Skip to content
01Home 02Capability Matrix 03Tools 04Benchmark Rankings 05Tracks 06About Us
Code Under Repair · AI coverage organised as a matrix of capability × stage. Not sorted by tool, but by where you are right now.
Updated every Wednesday

Build a Document Q&A App With Python and RAG

Build a document Q&A app with Python and RAG. Learn how to upload files, create a searchable vector store, retrieve relevant passages, and generate answers grounded in your own documents.

Nov 10, 2026
Build a Document Q&A App With Python and RAG LLM Apps & Agent Engineering

A chatbot can sound confident and still give you an answer that has nothing to do with your company's documents. The problem is not always the model. It may simply lack access to the information you're asking about.

Retrieval-Augmented Generation, or RAG, addresses this problem by retrieving relevant content from an external knowledge source and giving that content to the model as context. Instead of asking the model to answer from its general training, your application first searches your documents and then generates an answer grounded in the retrieved material.

In this tutorial, we'll build a document Q&A app with Python and the OpenAI API. We'll use a hosted vector store and the Responses API's file search tool, so you can focus on the retrieval workflow instead of building an embedding pipeline from scratch.


Table of Contents

  • What RAG Does

  • Prepare Your Python Project

  • Upload Documents to a Vector Store

  • Build the Document Q&A Endpoint

  • Test Retrieval Quality

  • Common RAG Problems


What RAG Does

RAG combines two operations: retrieval and generation. Retrieval finds relevant information from a knowledge base. Generation uses that information to produce a response.

A typical document Q&A workflow looks like this:

  1. A user uploads documents or uses an existing knowledge base.

  2. The application processes and indexes the documents.

  3. The user asks a question.

  4. The retrieval system searches for relevant passages.

  5. The model receives the question and retrieved context.

  6. The model generates an answer based on the available evidence.

RAG retrieval and generation workflow

For example, imagine a user asks, "How many days do I have to return an item?" A general model might answer with a common retail policy. A RAG application should instead retrieve the relevant return-policy section from your own document collection.

RAG does not guarantee that every answer is correct. It improves access to relevant information, but retrieval quality, document quality, and answer instructions still matter.


Prepare Your Python Project

Create a simple project:

document-qa/
├── app.py
├── upload_docs.py
├── documents/
│   └── return-policy.md
├── .env
└── requirements.txt

Install the packages:

pip install openai python-dotenv fastapi uvicorn

Configure your environment:

OPENAI_API_KEY=your_api_key_here
OPENAI_MODEL=your_supported_model
OPENAI_VECTOR_STORE_ID=

The vector store ID will be added after you create the knowledge base. Keep your API key and vector store configuration on the server rather than exposing them in frontend code.


Upload Documents to a Vector Store

A vector store provides a searchable container for your files. When files are added, the service processes them for retrieval, including chunking and embedding. You do not need to manually implement those steps for this hosted example.

Create upload_docs.py:

import os
import time
from pathlib import Path
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

store = client.vector_stores.create(
    name="Company Knowledge Base"
)

file_path = Path("documents/return-policy.md")

with file_path.open("rb") as file:
    uploaded = client.files.create(
        file=file,
        purpose="assistants"
    )

client.vector_stores.files.create(
    vector_store_id=store.id,
    file_id=uploaded.id
)

print("Vector store ID:", store.id)
print("File ID:", uploaded.id)

Run the script:

python upload_docs.py

Save the vector store ID printed by the script. Add it to your .env file.

Before using the document, make sure indexing has completed. A file that has been uploaded is not necessarily ready for retrieval immediately. Check the vector store file status through the SDK and handle failed indexing rather than assuming every upload succeeded.

Document upload to a vector store

Build the Document Q&A Endpoint

Now create a small FastAPI endpoint that accepts a question and searches the vector store. The Responses API can use the hosted file_search tool to retrieve relevant passages.

In app.py, start with the application setup:

import os
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from openai import OpenAI

load_dotenv()

client = OpenAI()
app = FastAPI()

MODEL = os.getenv("OPENAI_MODEL")
VECTOR_STORE_ID = os.getenv("OPENAI_VECTOR_STORE_ID")

if not MODEL or not VECTOR_STORE_ID:
    raise RuntimeError("Model or vector store ID is missing")

class QuestionRequest(BaseModel):
    question: str = Field(min_length=3, max_length=1000)

Next, add the endpoint:

@app.post("/ask")
def ask_document(request: QuestionRequest):
    try:
        response = client.responses.create(
            model=MODEL,
            instructions=(
                "Answer using the retrieved documents. "
                "If the documents do not contain enough information, "
                "say that you cannot find the answer. "
                "Do not invent policies or facts."
            ),
            input=request.question,
            tools=[
                {
                    "type": "file_search",
                    "vector_store_ids": [VECTOR_STORE_ID],
                    "max_num_results": 5
                }
            ]
        )

        if response.status != "completed":
            raise RuntimeError("The model response did not complete")

        return {
            "answer": response.output_text
        }

    except Exception as exc:
        raise HTTPException(
            status_code=502,
            detail="Unable to answer the question right now"
        ) from exc

The application now has a simple Q&A endpoint. The model can use file search to retrieve content from the configured vector store before generating its answer.

Python document Q&A API endpoint

Start the server:

uvicorn app:app --reload

Send a request to POST /ask with a JSON body:

{
  "question": "How many days do I have to return an item?"
}

The answer should reflect the policy document you uploaded, provided that the relevant content was indexed and retrieved.


Test Retrieval Quality, Not Just the Final Answer

One of the easiest mistakes in RAG development is evaluating only whether the final answer sounds reasonable. A fluent answer can hide a retrieval failure.

Test the system with questions whose answers you already know. Include several different types:

  • Direct questions: Ask for a fact stated clearly in one paragraph.

  • Paraphrased questions: Ask for the same information using different wording.

  • Multi-part questions: Ask for two details that appear in different sections.

  • Unanswerable questions: Ask about something that is not in the documents.

  • Conflicting information: Include documents with different dates or versions and check whether the app handles the conflict appropriately.

When debugging, inspect the retrieved passages as well as the generated answer. The Responses API supports including file search results in the response, which can help you see what the retrieval step actually returned.

For a production application, consider returning citations or document references to the user. A useful answer should make it possible to trace important claims back to their source.


Common RAG Problems

The right information is not retrieved

Check whether the document was indexed successfully, whether the question uses terminology found in the source, and whether the relevant passage is too fragmented. You may need to improve document structure or retrieval settings.

The answer combines unrelated passages

Retrieval can return several chunks that are individually relevant but do not support the same conclusion. Reduce irrelevant context, inspect the retrieved results, and make the answer instructions more explicit.

The model answers questions that the documents do not cover

Tell the model to say when the evidence is insufficient. Then test this behavior with questions that intentionally have no answer in the knowledge base. Instructions help, but they are not a substitute for evaluation.

Documents become outdated

RAG systems need a document lifecycle. Decide how files are updated, replaced, or removed. If an old policy remains searchable beside a new one, the model may retrieve conflicting information.


When to Move Beyond Hosted File Search

Hosted file search is a practical starting point, especially when you want to build a working prototype without managing every retrieval component yourself. But some applications need more control over chunking, embeddings, ranking, metadata filters, permissions, or hybrid search.

In those cases, you may choose to build a custom retrieval pipeline with a vector database and your own ingestion process. That adds engineering work, but it also gives you more control over how documents are processed and searched.

Start with the simplest system that meets your requirements. Measure retrieval quality with real questions before adding more infrastructure. A RAG application is only as useful as the evidence it can find.

Build it. Break it. Understand it. Fix it.

Reader responses

No responses on this piece yet.

Write what you observed