StackPractices
advanced By Mathias Paulenko

Complete Guide to RAG in Production

Take RAG to production: chunking strategies, vector store selection, hybrid retrieval, reranking, RAGAS evaluation, and deployment patterns.

Introduction

The failure that pushes teams into RAG usually looks like this: your support bot, trained on documentation from last quarter, confidently explains a refund policy that changed in March. The model isn’t malfunctioning — it’s doing exactly what LLMs do, answering from frozen training data plus whatever happens to sit in the prompt. When the knowledge you need lives in internal docs, ticket histories, and product databases that change weekly, the model’s memory is simply the wrong source.

Retrieval-Augmented Generation fixes that by splitting the job in two. A retriever searches an external knowledge base for documents relevant to the user’s question, and the LLM answers using those documents as context instead of its own recall. The pattern dates back to the original RAG paper by Lewis et al. (2020), and it’s now the standard way to ground LLMs on private or fast-changing knowledge.

This guide walks the whole production pipeline: how to ingest and chunk documents, which embedding models to pick, how to choose and operate a vector store, how to optimize retrieval with hybrid search and reranking, how to assemble context within a token budget, and how to evaluate and run the system in production. It assumes you’re comfortable with Python, have basic LLM API experience, and are past the “does RAG work” demo stage — the question here is how to make it reliable, measurable, and cheap enough to ship.

When to Use RAG — and When Not To

RAG earns its complexity when three conditions hold at once: the corpus is too large to fit in a prompt, it changes more often than you can retrain, and answers need to be traceable to sources. Customer support over a product knowledge base, internal search over engineering docs, and assistants over legal or medical corpora all fit. The OpenAI embeddings guide covers the embedding side of that stack in depth.

It stops earning its keep in three common situations:

  • The corpus is small. If all your reference material fits in a few thousand tokens, stuffing it into the system prompt or a long-context window is simpler, faster, and more accurate than maintaining an index.
  • Answers need the model’s judgment, not facts. RAG grounds what the model says; it doesn’t fix how it reasons. If your problem is style, tone, or task format, fine-tuning beats retrieval.
  • Freshness is measured in seconds. A vector index refreshed hourly can’t serve “what’s the price right now” questions. Those need live tool calls or APIs, possibly alongside RAG for the stable parts of the answer.

When the decision is genuinely open, this table is the honest comparison:

ApproachBest whenMain trade-off
RAGKnowledge changes often, corpus is large, citations requiredMore moving parts; retrieval can miss the right chunk
Fine-tuningBehavior, format, or domain style matters more than factsDoesn’t reliably inject new facts; retrain per update
Long context windowCorpus fits in the window and query volume is lowCost and latency scale with input size; “lost in the middle” recall issues

Many production systems end up hybrid: RAG for knowledge, a light fine-tune for behavior, and tools for live data. The sections below assume you’ve made that call for the knowledge half.

RAG Pipeline Overview

Every RAG system has the same two halves. Ingestion runs offline: documents get parsed, split into chunks, embedded into vectors, and stored in an index. The query path runs per request: the question gets embedded, the index returns candidate chunks, a reranker reorders them, and the survivors are assembled into a prompt for the LLM.

flowchart diagram: docs[Documents

Most of the engineering effort goes into the seams: chunk boundaries, embedding quality, index freshness, and how much context the prompt can afford. The LLM call at the end is the easy part.

Ingestion: Parsing Documents and Chunking

Ingestion starts before chunking: you need to extract text from PDFs, HTML, markdown, or databases, and that parsing step quietly determines your quality ceiling. A PDF that extracts tables as scrambled text will produce scrambled chunks no matter how good your splitter is. Budget real effort here — clean text with structure markers (headings, list boundaries, table delimiters) makes every downstream step easier.

Once you’ve got clean text, the chunking strategy decides what the retriever can actually find. There’s no universally correct answer; each strategy trades retrieval precision against context coherence:

Fixed-size chunking is the baseline. It splits text at a character or token boundary with overlap so a sentence that straddles the cut survives in at least one chunk. It’s fast, predictable, and easy to debug — which is why it’s the right default while you’re still evaluating whether RAG works for your data at all. The cost is that cuts land mid-sentence and mid-idea constantly, so retrieved chunks often start or end in the middle of a thought.

from typing import List

def fixed_size_chunks(text: str, chunk_size: int = 512, overlap: int = 50) -> List[str]:
    """Split text into fixed-size character chunks with overlap.

    chunk_size/overlap are in characters here — for token-accurate
    boundaries, count tokens with tiktoken instead.
    """
    chunks = []
    start = 0

    while start < len(text):
        end = start + chunk_size
        chunks.append(text[start:end])
        start = end - overlap  # overlap keeps straddling sentences recoverable

    return chunks

text = "This is a long document..." * 100
chunks = fixed_size_chunks(text, chunk_size=512, overlap=50)
print(f"Created {len(chunks)} chunks")

Sentence-based chunking respects linguistic boundaries. It packs whole sentences into chunks up to a size cap, so every chunk is at least readable. The failure mode is uneven density: a chunk of ten short sentences and a chunk of two long ones can carry very different amounts of information despite similar token counts. Use it when documents are already well-structured prose and you want boundaries that don’t cut mid-thought.

import re
from typing import List

def sentence_chunks(text: str, max_chunk_size: int = 512) -> List[str]:
    sentences = re.split(r'(?<=[.!?])\s+', text)

    chunks = []
    current_chunk = ""

    for sentence in sentences:
        candidate = f"{current_chunk} {sentence}".strip() if current_chunk else sentence
        if len(candidate) <= max_chunk_size:
            current_chunk = candidate
        else:
            if current_chunk:
                chunks.append(current_chunk)
            current_chunk = sentence

    if current_chunk:
        chunks.append(current_chunk)

    return chunks

Semantic chunking goes further: it embeds each sentence and starts a new chunk when the similarity between consecutive sentences drops below a threshold, so chunks break where the topic shifts rather than where characters run out. The results are cleaner on heterogeneous documents — a changelog that mixes API notes with marketing copy chunks sensibly instead of arbitrarily. The costs are real: you pay one embedding call per sentence at ingest (an O(n) cost that hurts on large corpora), you need to tune the threshold per document type, and it still produces chunks with no guaranteed size bounds.

import re
from typing import List

import numpy as np
from sentence_transformers import SentenceTransformer

# all-MiniLM-L6-v2 is a reasonable default; see sbert.net for alternatives
model = SentenceTransformer('all-MiniLM-L6-v2')

def semantic_chunks(text: str, threshold: float = 0.8) -> List[str]:
    """Group consecutive sentences while cosine similarity stays above threshold.

    threshold is a heuristic: 0.8 works for most English prose with
    MiniLM embeddings, but tune it on your own documents — values between
    ~0.7 and ~0.9 are common depending on document density.
    """
    sentences = [s.strip() for s in re.split(r'(?<=[.!?])\s+', text) if s.strip()]

    if len(sentences) <= 1:
        return sentences

    embeddings = model.encode(sentences)  # one embed call per sentence

    chunks = []
    current_chunk = [sentences[0]]

    for i in range(1, len(sentences)):
        sim = float(np.dot(embeddings[i], embeddings[i - 1]) /
                    (np.linalg.norm(embeddings[i]) * np.linalg.norm(embeddings[i - 1])))

        if sim > threshold:
            current_chunk.append(sentences[i])
        else:
            chunks.append(" ".join(current_chunk))
            current_chunk = [sentences[i]]

    chunks.append(" ".join(current_chunk))
    return chunks

Markdown-aware chunking suits documentation, README files, and anything with real heading structure. It splits on headers, keeps the header path as context for each chunk (so a chunk about “error codes” knows it lives under “Troubleshooting > API”), and falls back to sentence-level splitting for oversized sections. For docs sites and technical writing this is often the best quality-per-effort option, since the document author already did the semantic segmentation work.

import re
from typing import List

def sentence_chunks(text: str, max_chunk_size: int = 512) -> List[str]:
    sentences = re.split(r'(?<=[.!?])\s+', text)
    chunks, current = [], ""
    for sentence in sentences:
        candidate = f"{current} {sentence}".strip() if current else sentence
        if len(candidate) <= max_chunk_size:
            current = candidate
        else:
            if current:
                chunks.append(current)
            current = sentence
    if current:
        chunks.append(current)
    return chunks

def markdown_chunks(text: str, max_size: int = 512) -> List[str]:
    """Split markdown by headers; prepend header context to each chunk."""
    sections = re.split(r'(\n#{1,6}\s+.+)', text)

    chunks = []
    current_section = ""
    current_header = ""

    for part in sections:
        if re.match(r'\n#{1,6}\s+', part):
            if current_section.strip():
                section_text = (current_header + "\n" + current_section).strip()
                if len(section_text) > max_size:
                    chunks.extend(sentence_chunks(section_text, max_size))
                else:
                    chunks.append(section_text)
            current_header = part.strip()
            current_section = ""
        else:
            current_section += part

    if current_section.strip():
        chunks.append((current_header + "\n" + current_section).strip())

    return chunks

Whichever strategy you pick, store the source location (file, page, section, chunk index) in the chunk’s metadata — you’ll need it for citations and for debugging retrieval misses later. The vector database guide covers how metadata filters interact with vector search if your corpus needs per-source or per-permission filtering.

Embedding Models

The embedding model maps each chunk to a vector where semantic similarity becomes geometric distance. Two properties matter more than benchmark scores: dimensionality (each vector’s length — 384, 768, 1536, 3072 are common) and multilingual coverage if your corpus isn’t English-only.

Dimensionality is a storage-and-latency trade-off, not just a quality dial. OpenAI’s text-embedding-3-small produces 1536-dim vectors and text-embedding-3-large 3072 by default, but the large model accepts a dimensions parameter to truncate output — per the OpenAI embeddings documentation, you can request e.g. 1024 dims and keep most of the quality while cutting index size by two thirds. Matryoshka-style truncation isn’t free, though: validate retrieval quality at the reduced dimension before committing.

The API-vs-local decision is mostly about cost, latency, and data residency. API embeddings (OpenAI, Cohere, Voyage) are higher quality out of the box, require no GPU, and bill per token — cheap for moderate volumes, expensive at high ingest rates. Local models via sentence-transformers (all-MiniLM-L6-v2, bge, e5 families) are free after setup, keep data on-premise, and run fine on CPU for batch ingest — but you own model selection, versioning, and the hardware. For multilingual corpora, check each model’s language coverage explicitly; English-tuned embeddings degrade badly on other languages.

One rule that saves pain later: never change the embedding model without re-embedding the entire corpus. Vectors from different models aren’t comparable, so a model swap is a full index rebuild, not a config change.

import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI()

async def embed_batch(texts: list[str]) -> list[list[float]]:
    response = await client.embeddings.create(
        model="text-embedding-3-small",
        input=texts,
    )
    return [d.embedding for d in response.data]

async def batch_embed(texts: list[str], batch_size: int = 100) -> list[list[float]]:
    """Embed texts in batches, with batches in flight concurrently.

    Real concurrency matters at scale: sequential awaits make ingest
    latency-bound on round-trips. Stay under the API's per-request
    input limits (check current docs — limits change).
    """
    batches = [texts[i:i + batch_size] for i in range(0, len(texts), batch_size)]
    results = await asyncio.gather(*(embed_batch(b) for b in batches))
    return [emb for batch in results for emb in batch]

# assumes `chunks` from the ingestion step
chunks = ["chunk one text", "chunk two text", "chunk three text"]
embeddings = await batch_embed(chunks)

Vector Stores

The vector store holds embeddings plus metadata and answers “which vectors are closest to this query vector.” The choice is mostly operational: who runs the index, what it costs at your scale, and which query capabilities you need. For a deeper treatment of index internals (HNSW, quantization, filtering), see the vector databases guide.

StoreHostingBest forWatch out for
ChromaEmbedded library / self-hostedLocal dev, prototyping, small corporaNot built for multi-tenant production; durability is your problem
pgvectorSelf-hosted Postgres extensionTeams already on Postgres, moderate scaleYou tune recall/latency; ops burden grows with size
PineconeFully managed, serverlessProduction scale without vector opsCost at high query volume; less control over index internals
WeaviateSelf-hosted or managed cloudBuilt-in hybrid/BM25 search, multi-modalHeavier operational footprint than pgvector
QdrantSelf-hosted or managed cloudFiltering-heavy workloads, strong performanceSmaller ecosystem and fewer managed integrations

Chroma is the fastest way to a working prototype — it runs in-process and persists to disk. Pinecone removes all index operations but bills per vector and per query; its docs at docs.pinecone.io are the reference for index and query semantics. pgvector keeps vectors in Postgres next to your metadata — often the right call when the corpus is modest and you already run Postgres, and the pgvector-python README documents the psycopg3 integration shown below.

import chromadb

client = chromadb.PersistentClient(path="./vector_db")

collection = client.get_or_create_collection(
    name="documents",
    metadata={"hnsw:space": "cosine"}
)

# assumes `chunks`, `embeddings`, and `metadatas` (one dict per chunk)
collection.add(
    ids=[f"doc_{i}" for i in range(len(chunks))],
    documents=chunks,
    metadatas=metadatas,
    embeddings=embeddings,
)

# assumes `query_embedding` from the embedding step
results = collection.query(
    query_embeddings=[query_embedding],
    n_results=5,
    where={"source": "file1.pdf"}  # optional metadata filter
)

for doc, score, metadata in zip(
    results["documents"][0],
    results["distances"][0],
    results["metadatas"][0]
):
    print(f"Score: {score:.4f}, Source: {metadata['source']}, Text: {doc[:100]}")
from pinecone import Pinecone, ServerlessSpec

pc = Pinecone(api_key="your-api-key")

# Create the index once — dimension and metric are fixed at creation time
pc.create_index(
    name="documents",
    dimension=1536,
    metric="cosine",
    spec=ServerlessSpec(cloud="aws", region="us-east-1")
)

index = pc.Index("documents")

# assumes `chunks` and `embeddings` from earlier steps
vectors = [
    {
        "id": f"doc_{i}",
        "values": emb,
        "metadata": {
            "text": chunk,
            "source": f"file_{i}.pdf",
            "chunk_index": i,
        },
    }
    for i, (emb, chunk) in enumerate(zip(embeddings, chunks))
]

index.upsert(vectors=vectors)

# assumes `query_embedding`
query_result = index.query(
    vector=query_embedding,
    top_k=10,
    include_metadata=True,
    filter={"source": {"$eq": "file_1.pdf"}},
)

for match in query_result["matches"]:
    print(f"Score: {match['score']:.4f}, Text: {match['metadata']['text'][:100]}")
import psycopg
from pgvector.psycopg import register_vector
from psycopg.types.json import Json

# psycopg3 (not psycopg2) — register_vector adapts vectors for psycopg3
conn = psycopg.connect("postgresql://user:pass@localhost/db")
register_vector(conn)

with conn.cursor() as cur:
    cur.execute("""
        CREATE TABLE IF NOT EXISTS documents (
            id SERIAL PRIMARY KEY,
            content TEXT,
            embedding vector(1536),
            metadata jsonb
        )
    """)
    # HNSW index: m and ef_construction trade build cost vs recall
    cur.execute("""
        CREATE INDEX IF NOT EXISTS documents_embedding_idx
        ON documents USING hnsw (embedding vector_cosine_ops)
        WITH (m = 16, ef_construction = 64)
    """)
conn.commit()

# assumes `chunks` and `embeddings` from earlier steps
with conn.cursor() as cur:
    for chunk, emb in zip(chunks, embeddings):
        cur.execute(
            "INSERT INTO documents (content, embedding, metadata) VALUES (%s, %s, %s)",
            (chunk, emb, Json({"source": "file.pdf"}))
        )
conn.commit()

# assumes `query_embedding`; <=> is cosine distance (lower = more similar)
with conn.cursor() as cur:
    cur.execute(
        """
        SELECT content, metadata, embedding <=> %s AS distance
        FROM documents
        ORDER BY embedding <=> %s
        LIMIT 10
        """,
        (query_embedding, query_embedding)
    )
    for content, metadata, distance in cur.fetchall():
        print(f"Distance: {distance:.4f}, Content: {content[:100]}")

The pattern across all three: the store returns candidates, not answers. Start with top_k around 20–50 candidates and let reranking cut to 5 — paying for a wider recall pass is almost always cheaper than losing the right chunk in the first place. That principle is what the next two sections optimize.

Retrieval Optimization

Plain vector search has a known blind spot: exact-match queries. “Error code E-4471” or a product SKU embeds into a vector that sits far from the chunk containing it, because the embedding captures meaning, not tokens. Users will type identifiers constantly, and pure vector search will keep missing them.

Hybrid search fixes this by running keyword search (BM25 or equivalent) alongside vector search and merging the rankings. The classic merge is score normalization plus weighted sum — what the HybridSearch class below does — but the approach that holds up better in practice is Reciprocal Rank Fusion (RRF), which fuses rankings by rank position rather than raw scores and is far less sensitive to score-scale differences between the two retrievers. The hybrid search pattern in this repo uses RRF and is worth reading before you write your own fusion.

flowchart diagram: query[User query
from typing import List


class HybridSearch:
    """Combines vector and keyword results with weighted score fusion.

    Note: min-max normalization per query is simple but brittle — a bad
    result set still produces a 'best' score of 1.0. For production,
    prefer RRF (see the linked pattern) which fuses by rank position.
    """

    def __init__(self, vector_store, keyword_index, alpha: float = 0.5):
        self.vector_store = vector_store
        self.keyword_index = keyword_index
        self.alpha = alpha  # 0 = keyword only, 1 = vector only

    def search(self, query: str, query_embedding: list[float], top_k: int = 10) -> List[dict]:
        # assumes query_embedding comes from the embedding step
        vector_results = self.vector_store.query(
            query_embeddings=[query_embedding],
            n_results=top_k * 2,
        )
        keyword_results = self.keyword_index.search(query, top_k=top_k * 2)

        vector_scores = self._normalize_scores(
            [1 - d for d in vector_results["distances"][0]]  # distance -> similarity
        )
        keyword_scores = self._normalize_scores([r["score"] for r in keyword_results])

        combined = {}

        for i, doc in enumerate(vector_results["documents"][0]):
            doc_id = vector_results["ids"][0][i]
            combined[doc_id] = {
                "text": doc,
                "metadata": vector_results["metadatas"][0][i],
                "score": self.alpha * vector_scores[i],
            }

        for i, result in enumerate(keyword_results):
            doc_id = result["id"]
            contribution = (1 - self.alpha) * keyword_scores[i]
            if doc_id in combined:
                combined[doc_id]["score"] += contribution
            else:
                combined[doc_id] = {
                    "text": result["text"],
                    "metadata": result.get("metadata", {}),
                    "score": contribution,
                }

        return sorted(combined.values(), key=lambda x: x["score"], reverse=True)[:top_k]

    def _normalize_scores(self, scores: list[float]) -> list[float]:
        if not scores:
            return []
        min_s, max_s = min(scores), max(scores)
        if max_s == min_s:
            return [1.0] * len(scores)
        return [(s - min_s) / (max_s - min_s) for s in scores]

Tuning alpha is empirical: identifier-heavy corpora (logs, error docs, SKUs) want more keyword weight; conceptual corpora (policies, guides) want more vector weight. Measure both retrieval quality before generation — context precision and recall are retriever metrics, and conflating them with answer quality makes debugging miserable. The RAG evaluation checklist breaks down which metrics isolate which stage.

Reranking

The retriever is tuned for recall — it fetches candidates cheaply and lets some noise through. A reranker is tuned for precision: it scores each (query, document) pair jointly and reorders the shortlist. The two architectures differ in a key way:

  • Bi-encoders embed query and document independently and compare vectors. Fast enough to run over the whole corpus, which is why they power first-stage retrieval — but they never see the query and document together, so they miss subtle relevance signals.
  • Cross-encoders feed the concatenated query+document pair through a transformer and output a relevance score. They see the actual interaction, so they’re markedly more accurate — and markedly slower, because every candidate costs a forward pass. That’s why they rerank a shortlist of 20–50, not a corpus.

The trade-off is latency vs quality, and it’s a real budget decision: a cross-encoder adds tens to hundreds of milliseconds per query depending on model size and candidate count. Cohere’s hosted rerank API removes the GPU requirement entirely and is the pragmatic default; self-hosted cross-encoders via sentence-transformers are fine when data can’t leave your infrastructure. Check Cohere’s docs for the current model name — they ship new versions regularly and older names get deprecated.

from sentence_transformers import CrossEncoder
from typing import List

reranker = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')

def rerank_results(query: str, documents: List[str], top_k: int = 5) -> List[dict]:
    pairs = [(query, doc) for doc in documents]
    scores = reranker.predict(pairs)  # CPU-bound; wrap in asyncio.to_thread at runtime

    ranked = sorted(zip(documents, scores), key=lambda x: x[1], reverse=True)
    return [{"text": doc, "score": float(score)} for doc, score in ranked[:top_k]]

# assumes `vector_store` and `query_embedding` from earlier steps
initial_results = vector_store.query(query_embeddings=[query_embedding], n_results=20)
reranked = rerank_results(user_query, initial_results["documents"][0], top_k=5)
import cohere

co = cohere.Client("your-api-key")

def cohere_rerank(query: str, documents: List[str], top_k: int = 5) -> List[dict]:
    results = co.rerank(
        model="rerank-v5.0-fast",  # check Cohere docs for the latest model
        query=query,
        documents=documents,
        top_n=top_k,
    )
    return [
        {
            "text": documents[r.index],
            "score": r.relevance_score,
            "index": r.index,
        }
        for r in results.results
    ]

Skip reranking when your retrieval is already precise (small, clean corpus) or when latency budget is tighter than the quality gain justifies. Measure first: if your context precision is already above ~0.9 on the eval set, a reranker is solving a problem you don’t have.

Context Assembly

Before the LLM call, the reranked chunks become a prompt — and the prompt has a hard token ceiling shared with the system instructions, conversation history, and the answer’s output budget. Assembly is where you enforce that ceiling.

Two decisions matter. First, how much context: more retrieved text generally helps recall but dilutes attention and inflates cost; most production RAG systems land somewhere between 2k and 8k tokens of context, tuned per use case. Second, how to truncate: cutting mid-sentence produces confusing context, so prefer dropping whole lower-ranked chunks over slicing text — and when you must slice, truncate on token boundaries, not character counts. The code below uses tiktoken with the target model’s encoding so the budget is real tokens, not a len // 4 guess that drifts on code, non-English text, and emoji.

Keep source markers in the assembled context ([Source 1], [Source 2]). They cost a few tokens and buy you two things: the model can cite which document it used, and you can trace a wrong answer back to a specific retrieved chunk during debugging.

from typing import List

import tiktoken

# Match the tokenizer of the model that will consume the context
encoding = tiktoken.encoding_for_model("gpt-4o")

def assemble_context(
    retrieved_docs: List[dict],
    max_context_tokens: int = 4000,
    include_metadata: bool = True,
) -> str:
    context_parts = []
    current_tokens = 0

    for i, doc in enumerate(retrieved_docs):
        doc_tokens = len(encoding.encode(doc["text"]))

        if current_tokens + doc_tokens > max_context_tokens:
            # Drop the chunk entirely unless a meaningful slice still fits —
            # partial chunks tend to confuse the model more than they help.
            remaining = max_context_tokens - current_tokens
            if remaining > 100:
                truncated = encoding.decode(encoding.encode(doc["text"])[:remaining])
                context_parts.append(f"[Source {i + 1}]: {truncated} ...")
            break

        source_info = ""
        if include_metadata and "metadata" in doc:
            meta = doc["metadata"]
            source_info = f" (Source: {meta.get('source', 'unknown')})"

        context_parts.append(f"[Source {i + 1}]{source_info}: {doc['text']}")
        current_tokens += doc_tokens

    return "\n\n".join(context_parts)

def build_rag_prompt(query: str, context: str) -> list[dict]:
    return [
        {
            "role": "system",
            "content": (
                "Answer the user's question based on the provided context. "
                "If the context doesn't contain relevant information, say you don't know. "
                "Cite the source number for every claim drawn from the context."
            ),
        },
        {
            "role": "user",
            "content": f"Context:\n{context}\n\nQuestion: {query}",
        },
    ]

The Full RAG Pipeline

Putting it together: one class owns the index handle, embedder, and reranker, and answer() runs the whole query path. Two details matter in production code that demos skip: the embedder and reranker are CPU-bound, so in an async service they must run in a thread or they block the event loop for every concurrent request; and retrieval fetches top_k * 4 candidates so reranking has room to work.

import asyncio

from openai import AsyncOpenAI
from sentence_transformers import CrossEncoder, SentenceTransformer

client = AsyncOpenAI()
embedder = SentenceTransformer('all-MiniLM-L6-v2')
reranker = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')

# assumes `collection` is a configured Chroma collection with embeddings loaded

class RAGPipeline:
    def __init__(self, collection, embedder, reranker, llm_client):
        self.collection = collection
        self.embedder = embedder
        self.reranker = reranker
        self.llm_client = llm_client

    async def answer(self, query: str, top_k: int = 5) -> dict:
        # CPU-bound work goes through asyncio.to_thread so the event loop
        # stays free for concurrent requests
        query_embedding = (await asyncio.to_thread(self.embedder.encode, query)).tolist()

        # Over-retrieve: reranking needs a wider candidate pool than top_k
        results = self.collection.query(
            query_embeddings=[query_embedding],
            n_results=top_k * 4,
        )

        documents = results["documents"][0]
        pairs = [(query, doc) for doc in documents]
        scores = await asyncio.to_thread(self.reranker.predict, pairs)

        ranked = sorted(
            zip(documents, scores, results["metadatas"][0]),
            key=lambda x: x[1],
            reverse=True,
        )[:top_k]

        context_parts, sources = [], []
        for i, (doc, score, metadata) in enumerate(ranked):
            context_parts.append(f"[Source {i + 1}]: {doc}")
            sources.append({
                "source": metadata.get("source", "unknown"),
                "relevance_score": float(score),
            })

        messages = [
            {
                "role": "system",
                "content": (
                    "Answer based on the context. Cite source numbers. "
                    "If the context is insufficient, say you don't know."
                ),
            },
            {
                "role": "user",
                "content": f"Context:\n{'\n\n'.join(context_parts)}\n\nQuestion: {query}",
            },
        ]

        response = await self.llm_client.chat.completions.create(
            model="gpt-4o",
            messages=messages,
            temperature=0.3,  # low temperature: factual answering, not creativity
        )

        return {
            "answer": response.choices[0].message.content,
            "sources": sources,
            "retrieved_count": len(ranked),
        }

rag = RAGPipeline(collection, embedder, reranker, client)
result = await rag.answer("How do I configure authentication?")

Notice what this version does not do: no retries, no timeouts, no tracing, no evaluation hooks. Those aren’t optional in production — they’re the subject of the next two sections.

Evaluation

A RAG system has four places to fail independently: parsing can mangle documents, retrieval can miss the right chunk, the reranker can demote it, and the LLM can ignore or distort what it was given. A single “answer quality” number hides which stage broke, so evaluation has to measure stages separately — retrieval metrics on the retriever, generation metrics on the pipeline.

RAGAS is the standard open-source framework for the second half. Its four core metrics map cleanly onto failure modes:

MetricQuestion it answersTypical target (heuristic)
FaithfulnessIs every claim in the answer supported by the retrieved context?> 0.85
Answer relevancyDoes the answer actually address the question asked?> 0.80
Context precisionAre the retrieved chunks relevant to the question?> 0.75
Context recallDid retrieval fetch everything needed to answer?> 0.80

Treat those thresholds as starting points, not laws — a medical assistant needs faithfulness above 0.95 while an internal tooling bot tolerates 0.80. What matters is tracking them per version so a prompt change that silently hurts faithfulness shows up as a regression, not a support ticket.

# pip install ragas datasets openai
# API varies by version — this follows the classic ragas.metrics API;
# newer ragas versions expose a collections-based API in the docs.
from datasets import Dataset
from ragas import evaluate
from ragas.metrics import (
    faithfulness,
    answer_relevancy,
    context_precision,
    context_recall,
)

# Build the eval set from real questions + your pipeline's actual outputs.
# contexts must be the chunks YOUR retriever returned, not ideal answers.
eval_data = {
    "question": [
        "How do I configure SSO for the admin panel?",
        "What are the rate limits on the export API?",
    ],
    "answer": [
        "SSO is configured under Admin > Security > Identity providers.",
        "The export API allows 100 requests per minute per key.",
    ],
    "contexts": [
        ["Admin > Security > Identity providers lets you connect SAML or OIDC..."],
        ["Rate limits: export endpoints are limited to 100 req/min per API key..."],
    ],
    "ground_truth": [
        "SSO setup is done in Admin > Security > Identity providers via SAML/OIDC.",
        "Export API rate limit is 100 requests per minute per API key.",
    ],
}

dataset = Dataset.from_dict(eval_data)

results = evaluate(
    dataset,
    metrics=[faithfulness, answer_relevancy, context_precision, context_recall],
)

print(results)
# {'faithfulness': 0.91, 'answer_relevancy': 0.87,
#  'context_precision': 0.83, 'context_recall': 0.79}

Two practical notes. RAGAS scores are themselves LLM-judged under the hood, so they inherit judge noise — run enough samples (50+) before trusting a delta, and prefer relative comparisons between versions over absolute scores. And contexts must be what your system actually retrieved: evaluating against ideal contexts measures a pipeline you don’t have.

For the wider evaluation discipline — LLM-as-judge, hallucination checks, regression suites in CI — the LLM evaluation guide covers it in depth, and the AI RAG evaluation checklist gives a concrete pre-launch checklist.

Production Concerns

This is where “production” earns its name. The pipeline above works on your laptop; these are the concerns that decide whether it survives contact with real traffic.

Latency and cost budget per query. A RAG request chains embed → vector search → (optional keyword search) → rerank → LLM. Each stage adds latency and each embedding/rerank/LLM call adds cost. Set a p50/p95 budget (say 800ms/2s for a synchronous chat) and instrument each stage separately — when p95 blows up, you want to know whether it’s the reranker, the vector DB, or the LLM, not guess. Reranking 50 candidates on a large cross-encoder can cost more latency than the LLM call itself; that’s the knob to turn first.

Observability and tracing. You need per-request traces showing retrieved chunk IDs, scores, rerank positions, token counts, and the final answer — LangSmith, Langfuse, and OpenTelemetry-based tracing all cover this, and the generic requirement is the same: every query should be replayable after the fact. Log the retrieved context (or a hash plus IDs if privacy forbids content) because “why did it say that” is unanswerable without it.

Index versioning and re-embedding. The index is derived state — it must be reproducible from source documents plus an embedding model version. Store embedding_model, chunking_version, and index_version as metadata on every chunk; when you upgrade models or change chunking, rebuild the index alongside the old one and cut over, rather than mutating in place. The embedding cache pattern covers caching embeddings across rebuilds.

Document update pipeline. Knowledge bases aren’t static. You need incremental updates: document changed → re-parse → re-chunk → re-embed → upsert → (optionally) delete stale chunks by source ID. Deletion matters as much as insertion — a doc removed from the corpus must leave the index or the model keeps citing ghosts. For frequently changing sources, evaluate whether the refresh cadence (hourly? daily?) is acceptable before promising freshness.

Prompt injection via retrieved content. This one gets skipped and shouldn’t be. Retrieved documents are untrusted input — a malicious or compromised document can contain “ignore previous instructions and…” text that lands directly in your prompt. Mitigate with structural separation (delimit context clearly, keep instructions in the system role), content filtering on ingest, and output validation; for high-risk deployments, treat retrieved text as data, never as instructions.

Evaluation in CI. The eval set from the previous section should run on every prompt, model, or chunking change — the same regression-gate logic as the LLM evaluation guide describes, scoped to retrieval metrics plus end-to-end faithfulness.

Best Practices

  • Over-retrieve, then rerank. Fetch 3–4x your final top_k and let a cross-encoder or RRF decide — recall is cheap, precision is what the LLM sees.
  • Version everything that shapes vectors. Embedding model, chunking strategy, and index schema are part of the artifact; a silent model upgrade invalidates the whole index.
  • Measure retrieval separately from generation. Context precision/recall isolate the retriever; faithfulness isolates the generator. Conflating them turns every bug hunt into guesswork.
  • Preserve source metadata end-to-end. File, page, section, chunk index — citations and debugging both depend on it surviving the trip through the index.
  • Set explicit “I don’t know” behavior. Instruct the model to say when context is insufficient, and alert on answers with zero high-scoring retrieved chunks — that’s your retrieval-miss signal.
  • Start simple, add stages only on evidence. Fixed chunking + vector search + top-k works for a surprising amount; add semantic chunking, hybrid search, and reranking when eval numbers say they’re needed.

Common Mistakes

  • Evaluating end-to-end only. A faithfulness drop could be retrieval missing the chunk or the model ignoring it — without stage-level metrics you can’t tell which, and “make the prompt better” is the wrong fix half the time.
  • Embedding model swaps without re-indexing. Vectors from different models live in incompatible spaces; mixing old and new embeddings silently corrupts retrieval.
  • Giant chunks “to be safe.” A 4k-token chunk buries the relevant sentence in noise and inflates every prompt; retrieval precision degrades before context limits do.
  • Character-based token estimates. len(text) // 4 drifts badly on code, non-English text, and emoji — use the target model’s tokenizer for any budget that matters.
  • Ignoring reranker latency. A cross-encoder over 50 candidates on CPU can double your p95; benchmark it or use the hosted API.
  • Treating retrieved documents as trusted instructions. They’re user-adjacent input; a poisoned document is a prompt-injection vector into your system prompt’s neighborhood.
  • No deletion path in the update pipeline. Chunks from deleted or rewritten documents keep surfacing, and the model keeps citing content that no longer exists.

See Also

Frequently Asked Questions

What chunk size should I use?

There's no universal number — start around 300–500 tokens with modest overlap and tune on your eval set. Technical docs with dense facts usually want smaller chunks (200–400 tokens) so retrieval returns precise passages; narrative or conversational content tolerates larger ones. Whatever you choose, keep chunks under your context budget after reranking, and always measure context precision/recall per chunking config before shipping a change.

Should I use semantic chunking or fixed-size chunking?

Semantic chunking tends to produce cleaner boundaries — it breaks where topic similarity drops rather than where characters run out — but it costs one embedding per sentence at ingest and needs per-corpus threshold tuning. Fixed-size is nearly free and perfectly predictable. For most teams the pragmatic path is markdown-aware or sentence-based chunking first, semantic chunking only if eval shows boundary quality is actually hurting retrieval.

What is the difference between bi-encoders and cross-encoders?

Bi-encoders embed the query and each document independently, then compare vectors — fast enough for whole-corpus search, which is why they power first-stage retrieval. Cross-encoders process the query and document together in one pass and output a relevance score — more accurate because they see the actual interaction, but too slow for the full corpus, so they rerank shortlists. Use bi-encoders to recall, cross-encoders to rank.

How do I handle multi-turn conversations in RAG?

Rewrite the user's latest message into a standalone query before retrieval — "What about Python?" becomes "How does Python handle authentication?" using conversation history — because the retriever only sees the query string, not the chat. Decide per turn whether retrieval is even needed: follow-ups about the previous answer often don't require new context. Keep retrieved context scoped to the current turn's needs rather than accumulating it.

How do I evaluate my RAG system?

Separate the stages. For retrieval, measure context precision and recall against a labeled eval set; for generation, RAGAS metrics (faithfulness, answer relevancy) score whether answers stay grounded in what was retrieved. Build the eval set from real user questions plus production failures, run it on every prompt/model/chunking change, and watch scores as relative signals between versions rather than absolute truth.

Should I use a managed vector database or self-host?

Managed (Pinecone, Weaviate Cloud, Qdrant Cloud) when you want to skip index operations and your scale justifies per-query pricing; self-hosted (pgvector, Chroma, local Weaviate, Qdrant) for development, modest corpora, strict data residency, or cost control at high volume. If you already run Postgres, pgvector is the lowest-friction self-hosted option — the operational overhead is real but bounded, and the vector databases guide compares the trade-offs in detail.