What is RAG? Build a 'chat with your PDFs' app (with code)

By [PLACEHOLDER: Author name], [PLACEHOLDER: Author role] · Last updated: 22 November 2026

[DRAFT – trainer to review] This article is not published yet and is hidden from search engines.

Summary: RAG finds the most relevant passages in your documents and gives them to the model with the question, so it answers from your data and can cite sources. Below: a working PDF chatbot in about 60 lines of Python.

What is RAG?

RAG (retrieval-augmented generation) is a way to make a language model answer from your documents. When a question comes in, you search your documents for the most relevant passages and send them to the model together with the question and an instruction to answer only from those passages. The model's job changes from "remember the answer" to "read these pages and answer", which reduces invented answers and lets you show sources.

How it works, in four steps

  1. Load the documents (PDFs, web pages, database rows).
  2. Split them into chunks of a few hundred words, with a little overlap.
  3. Embed and store: turn each chunk into a vector (a list of numbers that captures its meaning) and save it in a vector database.
  4. Retrieve and generate: embed the question, find the closest chunks, and ask the model to answer using them.

Build it: chat with your PDFs

Install the packages (Python 3.10+):

pip install langchain-community langchain-openai langchain-chroma langchain-text-splitters pypdf fastapi uvicorn

Set OPENAI_API_KEY in your environment. Any chat and embedding model works; the structure stays the same.

1. Index the PDF (run once, or whenever the file changes)

# index.py
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_chroma import Chroma

pages = PyPDFLoader("handbook.pdf").load()            # one Document per page
splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100)
chunks = splitter.split_documents(pages)               # keeps page numbers in metadata

Chroma.from_documents(
    chunks,
    OpenAIEmbeddings(model="text-embedding-3-small"),
    persist_directory="chroma_db",
)
print(f"Indexed {len(chunks)} chunks")

2. Answer questions with sources

# rag.py
from langchain_chroma import Chroma
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI, OpenAIEmbeddings

store = Chroma(persist_directory="chroma_db",
               embedding_function=OpenAIEmbeddings(model="text-embedding-3-small"))
retriever = store.as_retriever(search_kwargs={"k": 3})

prompt = ChatPromptTemplate.from_messages([
    ("system",
     "Answer using only the context below. If the answer is not in the context, "
     "say you don't know. Cite page numbers like [p. 4].\n\nContext:\n{context}"),
    ("human", "{question}"),
])
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
chain = prompt | llm

def format_docs(docs):
    return "\n\n".join(f"[p. {d.metadata.get('page', 0) + 1}] {d.page_content}" for d in docs)

def ask(question: str) -> dict:
    docs = retriever.invoke(question)
    answer = chain.invoke({"context": format_docs(docs), "question": question})
    return {
        "answer": answer.content,
        "sources": sorted({d.metadata.get("page", 0) + 1 for d in docs}),
    }

3. Put it behind an API

# main.py
from fastapi import FastAPI
from pydantic import BaseModel
from rag import ask

app = FastAPI()

class Question(BaseModel):
    text: str

@app.post("/ask")
def ask_endpoint(q: Question):
    return ask(q.text)

# run: uvicorn main:app --reload

Making it good, not just working

  • Check retrieval first. Print the retrieved chunks for 20 real questions. If the right passage is missing, no prompt will fix the answer.
  • Tune chunk size. Too small loses context; too large dilutes the match. 500–1,000 characters is a common starting range.
  • Use hybrid search and re-ranking when exact terms (product codes, names) matter.
  • Measure. Keep a fixed set of questions with expected answers and track whether changes help.
  • Treat document text as untrusted. A document can contain instructions; your system prompt should tell the model to treat context as data.

FAQ

What is a vector database?

A database that stores embeddings (vectors) and quickly finds the ones closest to a query vector. FAISS, Chroma, Pinecone and Qdrant are common choices.

Does RAG stop hallucinations completely?

No. It reduces them when retrieval finds the right passages and the prompt tells the model to answer only from them. You still need evaluation.

Can I run RAG without paid APIs?

Yes. You can use open embedding models and a local chat model, for example through Ollama, with the same pipeline.