Building a RAG Pipeline with Vector Search
Retrieve relevant passages with embeddings, store them in a vector index, and ground LLM answers in cited context rather than guesses.
On this page
Introduction
Retrieval augmented generation (RAG) is the default architecture for answering questions over private data. A language model alone cannot know your support tickets, contracts or code, and asking it to answer anyway produces confident fabrications. RAG closes that gap by retrieving the handful of passages that actually contain the answer and placing them in the prompt so the model can cite instead of invent. The quality of the answer is bounded by the quality of retrieval, which is why most engineering effort belongs in chunking, embedding and evaluation rather than prompt wording.
Why Retrieval Beats a Bigger Model
A larger model knows more about the world but still knows nothing about yesterday documents that were never public. Retrieval gives the model access to facts at query time, so the same model can answer questions about data that changed five minutes ago. It also makes answers auditable: you can show the user the exact passage behind a claim and let them judge it. The practical consequence is that retrieval quality dominates answer quality. If the correct passage is never in the top results, no amount of prompt engineering recovers the answer, so you measure recall before you tune wording.
from openai import OpenAI
client = OpenAI()
def embed_batch(texts: list[str]) -> list[list[float]]:
# Batch to stay under the per-request token limit.
out: list[list[float]] = []
for i in range(0, len(texts), 64):
resp = client.embeddings.create(
model="text-embedding-3-small",
input=texts[i : i + 64],
)
out.extend(d.embedding for d in resp.data)
return out
def index_chunks(conn, doc_id: str, chunks: list[str]) -> None:
vectors = embed_batch(chunks)
with conn.cursor() as cur:
for offset, (chunk, vec) in enumerate(zip(chunks, vectors)):
cur.execute(
"INSERT INTO chunks (doc_id, offset, body, embedding) VALUES (%s, %s, %s, %s)",
(doc_id, offset, chunk, vec),
)
conn.commit()
Chunking the Corpus Before Embedding
A document is too large to embed as one vector because a single vector averages the meaning of everything in it and matches nothing precisely. You split the corpus into overlapping chunks of a few hundred tokens, keeping paragraphs intact and repeating a sentence or two at each boundary so a claim is not cut in half. Chunk size trades recall against precision: small chunks match narrowly but fragment context, large chunks carry context but dilute similarity. Store the source document id, the chunk offset and the heading path on every chunk so retrieved passages can be cited and reassembled in order.
def answer(conn, question: str, k: int = 8) -> dict:
qvec = embed_batch([question])[0]
with conn.cursor() as cur:
cur.execute(
"SELECT doc_id, offset, body FROM chunks "
"ORDER BY embedding <=> %s LIMIT %s",
(qvec, k),
)
rows = cur.fetchall()
context = "\n\n".join(f"[{r[0]}#{r[1]}] {r[2]}" for r in rows)
prompt = (
"Answer only from the context. Cite markers like [doc#offset]. "
"If the context is insufficient, say so.\n\n"
f"Context:\n{context}\n\nQuestion: {question}"
)
resp = client.chat.completions.create(
model="gpt-4o-mini", temperature=0,
messages=[{"role": "user", "content": prompt}],
)
return {"answer": resp.choices[0].message.content, "sources": [r[0] for r in rows]}
Embedding and Storing Vectors
An embedding model maps each chunk to a fixed length vector such that semantically similar text lands close together in the vector space. You embed every chunk once at ingestion time and persist the vector beside its text and metadata. Because a different embedding model produces an incompatible vector space, you must record which model and version produced each vector and never mix them in one index; changing models requires re-embedding the whole corpus.
Indexing for Fast Approximate Search
Brute force comparison against millions of vectors is too slow for interactive search, so vector stores build an approximate nearest neighbour index such as HNSW or IVF. These indexes trade a small amount of recall for large gains in latency by exploring only promising regions of the space. The recall you lose is invisible until it costs you an answer, so you must measure it against a known set of questions. Tune the index parameters, such as the number of neighbours explored at query time, until recall meets your target at an acceptable p99 latency.
Retrieval, Reranking and Prompt Assembly
At query time you embed the user question with the same model used at ingestion, ask the index for the top K candidates, optionally rerank them, and paste the best passages into the prompt with source markers. A reranker scores each candidate against the question directly and reorders the list, which recovers precision that the approximate index sacrificed. Assemble the prompt with a fixed instruction to answer only from the supplied context and to cite the markers, then pass the model temperature near zero so the answer stays close to the retrieved facts.
Evaluating and Monitoring Retrieval
You cannot improve what you do not measure. Build a golden set of questions with their known correct passages and assert that retrieval returns them, tracking recall at K as the primary metric. Add answer level checks that the response cites a retrieved passage and does not contradict it, and run these as automated tests on every prompt or index change. In production, log which chunks were retrieved, how often retrieval returned nothing useful, and watch for drift when the corpus grows or the embedding model is upgraded.
Common Failure Modes in Production
The failures that hurt most are quiet. A document updated in the source system keeps its stale chunks in the index because the ingestion job only inserts and never deletes, so the model cites superseded text. An embedding model upgrade changes the vector space while old vectors remain, so similarity scores become meaningless and results degrade without any error. Retrieved text that contains adversarial instructions can hijack the prompt, so retrieved content must be treated as data, never as trusted instructions. Finally, when retrieval returns nothing above a similarity threshold, the pipeline should refuse to answer rather than feed the model an empty context and invite a hallucination.
Sources
Sources: OpenAI embedding guide, pgvector, Pinecone documentation.
FAQ
- Do I need a managed vector database to start with RAG?
- No. A PostgreSQL table with the pgvector extension handles millions of vectors and keeps your text, metadata and vectors transactional. Move to a dedicated vector store only when index size or query latency demands it.
- Should I rerank results after retrieval?
- Reranking usually pays for itself when precision matters. A cross encoder scores each candidate against the question and reorders the top results, recovering the precision an approximate index trades away.
Report a problem with this articleOpens a pre-filled issue on GitHub.