The full pipeline: retrieve, build the prompt, answer with sources
RAG & Vector Search · 10 questions
Short notes
Key idea
The full pipeline joins the pieces: retrieve the top chunks, build a prompt that tells the model to answer only from them, generate, and return the answer with its sources.
Syntax
def answer(question: str) -> dict:
hits = search(question, k=5)
context = "\n\n".join(f"[{i+1}] ({h.source}) {h.text}" for i, h in enumerate(hits))
prompt = (
"Answer the question using only the numbered sources below. "
"Cite sources like [2]. If the answer isn't there, say you don't know.\n\n"
f"{context}\n\nQuestion: {question}"
)
r = client.models.generate_content(model=MODEL, contents=prompt)
return {"answer": r.text, "sources": [h.source for h in hits]}
Example
"Can I return a phone after 10 days?" Sources [1] (Returns, electronics: 7 days) and [3] (Exceptions: damaged on arrival, 30 days). Answer: "Usually no: electronics have a 7-day window [1], unless it arrived damaged, which allows 30 days [3]."
Traps
- No "don't know" instruction and the model fills gaps from its own memory.
- Citations can be invented; check that cited numbers exist in the context.
- Too many chunks add cost and noise; 3–8 is typical.
- Put the question after the context so it's fresh when the model answers.
Want the full lesson with step-by-step examples, a project and a certificate? RAG & Vector Search course, ₹180 →
- Question 1easy
Which work should happen once (and again only when documents change), not on every question?
- Question 2medium
How many times is the model called?
from practice_llm import ScriptedModel model = ScriptedModel(["Answer A [1]", "Answer B [1]"]) def answer(hits): if not hits: return "I'll check with the team." return model.generate([{"role": "user", "content": "..."}]).text answer([{"chunk_id": "7-3"}]) answer([]) answer([]) print(len(model.calls)) - Question 3hard
Find the source numbers cited in
text(like [2]), keep only numbers between 1 andlen(hits), sort them, and store the matchingchunk_ids inresult.Store your answer in
result. - Question 4medium
Why ask for the answer and its sources as validated JSON in production, instead of parsing [n] from text?
- Question 5medium
Each chunk is about 200 tokens. How many context tokens do you save per question by cutting k from 10 to 4?
print(10 * 200 - 4 * 200)
The full pipeline: retrieve, build the prompt, answer with sources
The full pipeline: retrieve, build the prompt, answer with sources
The full pipeline: retrieve, build the prompt, answer with sources
The full pipeline: retrieve, build the prompt, answer with sources
The full pipeline: retrieve, build the prompt, answer with sources
5 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.