Building a RAG Q&A System from Scratch: LangChain, FAISS, and Structured Output

    This article walks through building a working knowledge Q&A application: organizing the pipeline with LangChain, storing vectors in FAISS, constraining model output with a structured schema, and evaluating retrieval with a fixed set of questions. Each step includes runnable code and the reasoning behind the choices.

    The Short Version

    To build a usable knowledge Q&A application, you can use LangChain to organize the flow, FAISS to store vectors, structured output to constrain the model’s return format, and a fixed set of questions to evaluate retrieval quality. Every step below comes with runnable code and the reasoning behind it.

    1. Environment Setup

    1. python -m venv .venv
    2. source .venv/bin/activate
    3. pip install -U langchain-core langchain-community langchain-openai langchain-text-splitters faiss-cpu pydantic
    4. export OPENAI_API_KEY="your-key"

    Keep the key in an environment variable only — never in the code, and never committed to the repository. Pin dependency versions in requirements.txt, because the interfaces of the sub-packages change between versions. Without pinning, the same code may start failing after a while.

    2. Overall Architecture

    Offline stage (run once whenever documents change):
    document → split by headings and paragraphs → embed → write to the FAISS index

    Online stage (run on every question):
    question → embed → retrieve the 4 closest chunks → build the prompt → LLM → structured output → validate → return if valid, retry on failure, fall back to a default answer once retries are exhausted

    Offline and online are kept separate because the index only needs rebuilding when documents change. Online requests do nothing but retrieval and generation, which makes responses faster and cheaper.

    3. Step 1: Split Documents and Build the Index

    Paragraphs in policy documents are usually short. A chunk size of around 500 characters keeps a passage semantically intact without making chunks so large that retrieval precision drops. An overlap of 80 characters between adjacent chunks prevents a single rule from being cut in half across two chunks. Separators are tried in order: level-1 heading, level-2 heading, blank line, newline, period.

    ingest.py:

    1. import os
    2. from langchain_community.document_loaders import TextLoader
    3. from langchain_community.vectorstores import FAISS
    4. from langchain_openai import OpenAIEmbeddings
    5. from langchain_text_splitters import RecursiveCharacterTextSplitter
    6. assert "OPENAI_API_KEY" in os.environ, "Set the OPENAI_API_KEY environment variable first"
    7. docs = TextLoader("docs/expense_policy.md", encoding="utf-8").load()
    8. splitter = RecursiveCharacterTextSplitter(
    9. chunk_size=500,
    10. chunk_overlap=80,
    11. separators=["\n## ", "\n### ", "\n\n", "\n", "."],
    12. )
    13. chunks = splitter.split_documents(docs)
    14. print(f"Split into {len(chunks)} chunks")
    15. embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
    16. store = FAISS.from_documents(chunks, embeddings)
    17. store.save_local("index/expense")

    Two things are worth remembering. First, the index and the embedding model must be used as a pair. After switching embedding models, the old index has to be rebuilt entirely; otherwise the vector spaces do not match and retrieval results become meaningless. Second, this script must be re-run after every document change.

    4. Step 2: Retrieval and the Prompt Template

    Set the retrieval count k to 4. Policy questions usually need only one or two rules, and 4 chunks cover cross-section cases without stuffing large amounts of irrelevant content into the context. If evaluation shows that answers frequently miss information, raise k to 5 or 6. If there is too much irrelevant content, add a reranking model to score the candidate chunks again.

    The prompt template asks the model to do three things: answer only from the provided material; explicitly state “not found” when the material contains no answer; and quote original sentences from the material as evidence. The third requirement is the basis for the validation step that follows.

    5. Step 3: Structured Output and Retry on Failure

    If you let the model return free-form natural language, the program has a hard time telling whether it followed the instructions. Here a Pydantic model defines the return structure, the model outputs fixed fields, and the program validates them. If validation fails, retry; after repeated failures, return a fallback answer instead of handing a malformed result to the user.

    qa.py:

    1. import logging
    2. from pydantic import BaseModel, Field
    3. from langchain_community.vectorstores import FAISS
    4. from langchain_core.prompts import ChatPromptTemplate
    5. from langchain_openai import ChatOpenAI, OpenAIEmbeddings
    6. logging.basicConfig(level=logging.INFO)
    7. log = logging.getLogger("qa")
    8. class Answer(BaseModel):
    9. found: bool = Field(description="Whether evidence was found in the material")
    10. answer: str = Field(description="Answer based on the material; state that no relevant rule was found if absent")
    11. sources: list[str] = Field(description="Sentences copied verbatim from the material as evidence; empty list if none")
    12. embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
    13. # Load only indexes you generated yourself. allow_dangerous_deserialization runs deserialization code — do not load files of unknown origin.
    14. store = FAISS.load_local(
    15. "index/expense", embeddings, allow_dangerous_deserialization=True
    16. )
    17. retriever = store.as_retriever(search_kwargs={"k": 4})
    18. PROMPT = ChatPromptTemplate.from_messages([
    19. ("system",
    20. "You are a company policy Q&A assistant. Answer only from the [Material] and do not use knowledge outside it. "
    21. "When the material contains no answer, set found to false, write 'No relevant policy found' in answer, and leave sources empty. "
    22. "When an answer is found, fill sources with sentences from the material, copied verbatim."),
    23. ("human", "[Material]\n{context}\n\n[Question]\n{question}"),
    24. ])
    25. # Replace the model name with one available to your account. temperature=0 makes output for the same question more stable.
    26. llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
    27. structured_llm = llm.with_structured_output(Answer)
    28. FALLBACK = Answer(
    29. found=False,
    30. answer="The system cannot provide a reliable answer right now. Please contact Human Resources.",
    31. sources=[],
    32. )
    33. def format_docs(docs):
    34. return "\n---\n".join(d.page_content for d in docs)
    35. def ask(question: str, max_retries: int = 2) -> Answer:
    36. docs = retriever.invoke(question)
    37. context = format_docs(docs)
    38. messages = PROMPT.format_messages(context=context, question=question)
    39. for attempt in range(max_retries + 1):
    40. try:
    41. result = structured_llm.invoke(messages)
    42. if result.found and not result.sources:
    43. raise ValueError("found is true but sources is empty")
    44. return result
    45. except Exception as exc:
    46. log.warning("Attempt %s failed: %s", attempt, exc)
    47. return FALLBACK