Build a RAG pipeline end to end
Answer questions over a document set with retrieved context injected into the prompt.
By Invicly Tech, , in AI Engineering with Python. About 13 minutes to read.
In short
Retrieval-augmented generation finds relevant passages from your documents and puts them in the prompt, so the model answers from your data instead of memory. It has an offline ingest stage and an online query stage.
Explained simply
A language model only knows what it saw during training. It has never read your company handbook, your product docs or last week's support tickets. Retrieval-augmented generation (RAG) fixes this without retraining the model. Before the model answers, your app looks up the most relevant passages and pastes them into the prompt. The model then answers like a student in an open-book exam.
RAG has two halves. The first half runs ahead of time: you load your documents, cut them into small pieces called chunks, turn each chunk into a list of numbers called an embedding, and save everything in a searchable store. The second half runs for every question: turn the question into an embedding, find the closest chunks, and send them to the model together with the question.
The model can only be as good as the passages it receives. If search returns the wrong pages, even the best model gives a wrong or vague answer. That is why most RAG work is really search work: clean documents, sensible chunks, useful metadata and a way to test retrieval.
A first version fits in under a hundred lines of Python. The real skill is testing it with questions real users ask, finding where it fails, and fixing the half that is actually broken.
Press Play on a diagram to walk through it one step at a time.
- Step 1Load documents
PDFs, web pages, docs
- Step 2Chunk
Split into passages with metadata
- Step 3Embed
Turn each chunk into a vector
- Step 4Store
Save vectors and text in a vector store
- User to RAG app: Ask a question1Ask a question
- RAG app to Vector store: Search with query embedding2Search with query embedding
- Vector store to RAG app: Top-k chunks3Top-k chunks
- RAG app to LLM: Prompt with question and chunks4Prompt with question and chunks
- LLM to RAG app: Grounded answer5Grounded answer
- RAG app to User: Answer with sources6Answer with sources
- Knowledge frozen at training time
- Has never seen your private docs
- Cannot point to a source
- Updating means retraining
- Reads current docs at question time
- Private data stays in your store
- Can cite the passages it used
- Updating means re-indexing
- Data
- Outdated or duplicate docs
- Contradicting versions
- Ingestion
- PDF text extracted badly
- Tables split mid-row
- Missing metadata
- Retrieval
- Right chunk not in top k
- Wording mismatch
- No relevance threshold
- Generation
- Ignores the context
- Fills gaps from memory
- Too many chunks
In depth
Ingestion is a repeatable job, not a one-off script
Documents change. Pages get edited, policies get replaced, files get deleted. If ingestion only ever adds chunks, your index fills up with old and contradicting text, and the model happily quotes last year's price. Treat ingestion as a job you can run again and again with the same result.
Give every document a stable ID (for example its path or URL) and store a hash of its content. On each run, skip documents whose hash did not change. For changed documents, delete all their old chunks and insert the new ones. For documents that disappeared, delete their chunks. Store metadata with every chunk: source, title, URL, section and last-updated date. You will need it for citations and filters later.
One more rule: if you switch embedding models, re-embed everything. Vectors from two different models live in different spaces and cannot be compared.
- Stable doc ID plus content hash makes re-runs cheap
- Delete old chunks before inserting new ones for a changed doc
- Keep source, URL and updated_at on every chunk
- 1Read document
Get its stable ID and text
- 2Hash content
sha256 of the text
- 3Compare hash
Same as stored? Skip it
- 4Delete old chunks
Remove every chunk with this doc ID
- 5Chunk and embed
Same embedding model as before
- 6Insert and save hash
In one transaction if possible
Retrieval: top-k, thresholds and the token budget
At query time you embed the question with the same model you used for the chunks, then ask the store for the k nearest chunks. A good starting point is k = 5 with chunks of a few hundred tokens. Tune both later with evals, not by feel.
Top-k always returns k results, even when nothing is relevant. A question about the office parking rules will still get five chunks back from a product manual. Add a similarity threshold so weak matches are dropped. The right value depends on the embedding model, so pick it by looking at scores for real questions.
The chunks also cost tokens. Five chunks of 400 tokens is about 2,000 tokens of context on every request. More context is not always better: extra loosely related text can distract the model and makes every call slower and more expensive.
- pgvector: ORDER BY embedding <=> query LIMIT 5 (cosine distance)
- Add an HNSW index so search stays fast as the table grows
- Log the retrieved chunk IDs and scores for every question
Building the prompt: order and structure
A RAG prompt has a clear shape. Rules come first: answer only from the context, cite sources, say you don't know when the answer is missing. Then the retrieved chunks, each wrapped with an ID, its source and maybe its date, inside clear delimiters such as context tags. The user's question comes last, right before the model starts writing.
Order inside the context matters too. Research on long contexts (often called lost in the middle) found that models use information at the start and end of a long prompt more reliably than information buried in the middle. Put the best-scoring chunk first, remove near-duplicate chunks, and keep the total short.
Including the document title and date with each chunk helps the model resolve conflicts, for example preferring the 2026 policy over the 2024 one.
- 1System rules
Use only the context, cite, admit gaps
- 2Context block
Numbered chunks with source and date
- 3Recent chat turns
Only if this is a conversation
- 4User question
Last, right before the answer
When you do not need RAG
RAG is not always the right tool. If your whole document set is small, say a 30-page handbook, it may fit in the model's context window. Sending all of it is simpler and avoids retrieval misses. Many providers offer prompt caching, which makes resending the same long prefix much cheaper.
Some questions are not search questions at all. How many tickets mentioned billing last month? needs counting over every record, so a SQL query (possibly written by the model) fits better than top-k chunks. Fine-tuning is another option people reach for, but it mostly changes style and format; it is a poor way to teach facts that change every week, and it cannot cite sources.
Use RAG when the knowledge is large, changes often, must stay private in your own store, or needs citations.
Testing with real questions
Before you tune anything, collect 20 to 30 questions that real users asked, from support tickets, chat logs or by watching someone use the system. For each question, write down which document should answer it. That label lets you test retrieval on its own: did the right document appear in the top k?
Then read the answers. When one is wrong, look at the logged chunks first. If the right chunk was missing, fix retrieval: chunking, metadata, hybrid keyword search or a reranker. If the right chunk was there and the answer was still wrong, fix the prompt or the model.
A very common retrieval failure is vocabulary mismatch: users write cancel my plan while the docs say terminate subscription. Keyword plus vector (hybrid) search and query rewriting both help with this.
Learn it in 5 short steps
About 1h each. Track them with a timer in your plan.
- 1Ingest and index a document set~1h
- 2Retrieve top-k chunks for a query~1h
- 3Inject context into the prompt~1h
- 4Generate grounded answers~1h
- 5Test with real questions~1h
Key points
- RAG lets models use private or recent data without retraining.
- Answer quality depends first on retrieval; wrong chunks mean wrong answers.
- Instruct the model to answer only from the provided context.
- Test with real user questions, not just ones you invented.
Key terms
Tap a card to flip it. 0/5 known
Examples
def build_prompt(question: str, chunks: list[dict]) -> str:
context = '\n\n'.join(
f"[{i}] ({c['source']})\n{c['text']}" for i, c in enumerate(chunks, 1)
)
return (
'Answer using only the context below. '
'If the answer is not there, say you do not know.\n\n'
f'<context>\n{context}\n</context>\n\nQuestion: {question}'
)
chunks = [{'source': 'faq.md', 'text': 'Refunds take 5 business days.'}]
print(build_prompt('How long do refunds take?', chunks))Inject numbered, sourced chunks into a grounded prompt.
A RAG table and query in Postgres with pgvector
You want to store chunks and search them without running a separate vector database. Step 1: enable the pgvector extension. Step 2: create a table with the chunk text, its source and an embedding column whose size matches your embedding model (1024 here is just an example). Step 3: add an HNSW index for fast approximate search with cosine distance. Step 4: at query time, pass the question's embedding as a parameter and order by distance. The <=> operator is cosine distance, so 1 minus it gives a similarity you can compare with a threshold.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
doc_id text NOT NULL,
source text NOT NULL,
content text NOT NULL,
embedding vector(1024) NOT NULL
);
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);
-- $1 = the question's embedding
SELECT source, content, 1 - (embedding <=> $1) AS similarity
FROM chunks ORDER BY embedding <=> $1 LIMIT 5;Debugging one wrong answer
A user asks: Can I get a refund after 30 days? The bot says yes, but the current policy says no. Step 1: open the log for that request and read the retrieved chunks, not the answer. Step 2: the top chunk comes from refund-policy-2023.pdf, which allowed 60 days. The 2026 policy is in the index but ranked seventh, outside the top 5. Step 3: the real bug is in ingestion: the old file was never removed. Delete it, add updated_at metadata, and re-run ingestion. Step 4: ask again. The 2026 chunk is now first and the answer is correct. Step 5: add this question and its expected source to your eval set so the bug cannot come back silently.
Quick reference
- Ingest offline: load, chunk, embed, store. Query online: embed, retrieve, build prompt, generate
- Embed questions and chunks with the same model; vectors from different models are not comparable
- Start with k = 5 and chunks of a few hundred tokens, then tune with evals
- pgvector operators: <=> cosine distance, <-> L2 distance, <#> negative inner product
- Context cost is about k times chunk size in tokens, paid on every request
- Prompt order: rules first, delimited numbered context next, question last
- When an answer is wrong, read the retrieved chunks before touching the prompt
- If the whole corpus fits in the context window, try sending it all before building RAG
Common mistakes
- Blaming the model when retrieval returned the wrong chunks.
- Stuffing too many chunks into the prompt and burying the answer.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write format_context(chunks, max_tokens) that numbers chunks as [1], [2] with their source, and stops adding chunks once an estimated token budget is reached (use about 4 characters per token).
- Exercise 2medium
Make ingestion idempotent. Given docs as {doc_id: text} and a store with get_hash, delete_chunks, add_chunks and set_hash methods, only re-index documents whose content changed.
- Exercise 3hard
Write a retrieval test. Each test case has a question and the expected source. Report the hit rate at k (share of cases whose expected source is in the top k) and print the misses.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is RAG better than fine-tuning?
- For answering from documents, usually yes. RAG uses current data, can cite sources and updates by re-indexing. Fine-tuning is better for changing style, format or behaviour.
- Do I need a dedicated vector database for RAG?
- Not to start. Postgres with pgvector, or even an in-memory array for a few thousand chunks, works well. Move to a dedicated store only when scale or features demand it.
- How many chunks should I retrieve?
- Start with about 5 and measure. Too few risks missing the answer; too many adds cost and can distract the model.
- Why does my RAG bot still make things up?
- Usually retrieval returned nothing useful and the model filled the gap from memory. Add a relevance threshold, clear grounding rules and a refusal path.