AI & Data

5 min read

November 22, 2026

Building a RAG system with Python: architecture and code

How to build a retrieval-augmented generation (RAG) system in Python: ingestion, chunking, embeddings with pgvector, hybrid and permission-aware retrieval, cited answers, evaluation and production concerns.

By Parth Patel

Retrieval-augmented generation (RAG) lets a language model answer questions from your own documents instead of only its training data. The idea is simple: find the passages relevant to a question, give them to the model, and ask it to answer from them with citations. Building one that works reliably in production takes more care.

This guide walks through a RAG system in Python from ingestion to answers, with the decisions that most affect quality at each step.

The architecture

A production RAG system has two pipelines:

  1. Ingestion (offline): load documents, split them into chunks, compute embeddings, and store chunks, embeddings and metadata in an index.
  2. Query (online): take a question, retrieve the most relevant chunks, build a prompt, generate an answer with citations, and log everything for evaluation.

Keep them separate. Ingestion runs on a schedule or on document changes; the query path must be fast and observable.

Ingestion: load and clean

Most quality problems start here. Extract text carefully: PDFs with columns, tables and headers need a proper parser, and scanned documents need OCR. Strip navigation, boilerplate and repeated headers.

Keep metadata with every document: source, title, section, last updated, and who is allowed to see it. You will need it for filtering, citations and permissions.

Chunking

Chunk size is a trade-off. Small chunks retrieve precisely but lose context; large chunks keep context but dilute relevance. A good starting point is chunks of a few hundred tokens with some overlap, split on structural boundaries (headings, paragraphs) rather than at fixed character counts.

PythonPython
from dataclasses import dataclass

@dataclass
class Chunk:
    id: str
    doc_id: str
    text: str
    title: str
    section: str
    allowed_groups: list[str]

def chunk_document(doc, max_words: int = 220, overlap: int = 40) -> list[Chunk]:
    chunks, words = [], []
    for paragraph in doc.paragraphs:
        words.extend(paragraph.split())
        while len(words) >= max_words:
            text = " ".join(words[:max_words])
            chunks.append(Chunk(f"{doc.id}:{len(chunks)}", doc.id, text, doc.title, paragraph_section(paragraph), doc.allowed_groups))
            words = words[max_words - overlap:]
    if words:
        chunks.append(Chunk(f"{doc.id}:{len(chunks)}", doc.id, " ".join(words), doc.title, "", doc.allowed_groups))
    return chunks

Prefixing each chunk with its document title and section before embedding often improves retrieval noticeably, because the chunk carries its context.

Embeddings and the vector store

Compute an embedding for each chunk with an embedding model, and store it with the chunk text and metadata. For many teams PostgreSQL with pgvector is the simplest option: one database, transactions, and metadata filtering with ordinary SQL. Dedicated vector databases make sense at larger scale or when you need their specific features.

SQLSQL
CREATE TABLE chunks (
  id text PRIMARY KEY,
  doc_id text NOT NULL,
  content text NOT NULL,
  allowed_groups text[] NOT NULL,
  embedding vector(1536)
);
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);

Record which embedding model produced each vector. Changing models means re-embedding everything.

Retrieval: hybrid beats vector-only

Vector search finds passages with similar meaning; keyword search finds exact terms such as product codes, names and error messages. Combining them (hybrid search) is more robust than either alone. Merge the two result lists with reciprocal rank fusion, then optionally re-rank the top results with a cross-encoder for precision.

Filter by permission at retrieval time, not after generation. If a user may not see a document, its chunks must never reach the prompt.

PythonPython
def retrieve(question: str, user_groups: list[str], k: int = 8) -> list[Chunk]:
    vector_hits = vector_search(embed(question), user_groups, limit=30)
    keyword_hits = keyword_search(question, user_groups, limit=30)
    fused = reciprocal_rank_fusion([vector_hits, keyword_hits])
    return rerank(question, fused[:20])[:k]

Generation: answer from the sources, cite them

The prompt should give the model the retrieved passages with identifiers, instruct it to answer only from them, cite the passages it used, and say when the sources don't contain the answer.

PythonPython
SYSTEM = """Answer using only the numbered sources.
Cite sources like [2] after each claim.
If the sources do not contain the answer, say you don't know."""

def build_prompt(question: str, chunks: list[Chunk]) -> list[dict]:
    sources = "\n\n".join(f"[{i + 1}] {c.title} — {c.section}\n{c.text}" for i, c in enumerate(chunks))
    return [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": f"Sources:\n{sources}\n\nQuestion: {question}"},
    ]

Validate citations after generation: every cited number must exist, and you can drop or flag answers that cite nothing.

Frameworks: LangChain or plain Python?

LangChain and similar frameworks speed up prototyping with loaders, splitters and retriever integrations. For production, many teams keep the framework at the edges and write the core pipeline (retrieval, prompt building, citation checks) as plain, testable Python. Either way, own the parts that decide quality.

Evaluate before you launch

You cannot improve what you don't measure. Build a golden set of real questions with expected sources, then measure retrieval (recall at k) and answers (faithfulness, correctness, refusals) separately, and run the evaluation on every change. The RAG evaluation guide covers this in depth.

Production concerns

  • Observability: log the question, retrieved chunk IDs, prompt, answer, latency and token cost for every request.
  • Caching: cache embeddings for repeated questions and documents.
  • Freshness: re-ingest changed documents and delete chunks of removed ones.
  • Cost and latency budgets: track them per request and alert on drift.
  • Human review: route low-confidence answers or high-stakes questions to people.

Summary

A dependable RAG system in Python comes from careful ingestion, structure-aware chunking with metadata, hybrid and permission-aware retrieval, prompts that demand cited answers, and an evaluation set that tells you whether each change helped. The model is the easy part.

Next step

Working on something like this? Let’s talk it through.

Send a short brief. You’ll get a written reply from me within two business days — either a few clarifying questions, a suggested first step, or an honest “I’m not the right fit” with a pointer elsewhere.

Parth Patel

Senior full-stack engineer