Sub topic 10
Grounding an agent with retrieval
This chapter assumes you can write Python, handle JSON, and have read the earlier chapters on tool calling and the agent loop. Here you will add retrieval so the agent answers from your documents instead of from memory.
Why grounding matters
A model only knows what was in its training data and what sits in its context window. It does not know your internal documents or events after its training cutoff. When it lacks a fact, it may still produce a confident but wrong answer.
Grounding means tying the answer to source text that you supply. Retrieval is the usual way to do it. The agent looks up relevant passages and places them in the context before it answers.
The retrieval pattern
Retrieval has three steps:
- Split your documents into chunks of a few hundred words.
- Index the chunks so you can search them by query.
- At question time, fetch the top few matching chunks and give them to the model.
Real systems often rank chunks by embeddings, which are number vectors that capture meaning. Keyword search or a mix of both also works. The agent does not care which one you use, as long as the tool returns relevant text.
Retrieval as a tool
The simplest design makes retrieval a tool. The model decides when to search and what to search for. This fits the loop you already built, because the search results come back as a tool message.
The example below uses simple word overlap so it runs with no extra libraries. It plugs into the TOOLS registry from the tool-calling chapter.
import json
DOCS = [
{"id": "refund-1", "text": "Refunds are issued within 14 days of purchase."},
{"id": "ship-1", "text": "Standard shipping takes 3 to 5 business days."},
{"id": "ship-2", "text": "Express shipping takes 1 business day."},
]
def search_docs(query: str, top_k: int = 2) -> str:
words = set(query.lower().split())
scored = []
for doc in DOCS:
overlap = len(words & set(doc["text"].lower().split()))
if overlap > 0:
scored.append((overlap, doc))
scored.sort(key=lambda pair: pair[0], reverse=True)
hits = [{"id": d["id"], "text": d["text"]} for _, d in scored[:top_k]]
return json.dumps({"results": hits})
TOOLS = {"search_docs": search_docs}
print(search_docs("how long does shipping take"))Each result carries an id. That lets the agent cite its source, and it lets you check the answer later.
Instructing the model to stay grounded
Retrieval alone does not stop the model from guessing. Add rules to the system prompt:
- Answer only from the retrieved passages.
- Cite the
idof each passage you use. - If the passages do not contain the answer, say so.
The last rule matters most. Without it, the model fills gaps from its own memory.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| Irrelevant results | Query is vague or chunks are too large | Let the model rewrite the query and shrink the chunks |
| Missing answer | Relevant text was split across chunks | Overlap chunks slightly |
| Context overflow | Too many or too long results | Lower `top_k` and truncate text |
| Confident wrong answer | No "say you don't know" rule | Add an explicit refusal instruction |
Exercise
The agent searches for "express delivery time" but your documents say "Express shipping takes 1 business day." The word-overlap search returns weak results. Name two changes that would improve retrieval.
Show answer
Use embedding-based search so that matching depends on meaning and not on exact words. Alternatively, let the model rewrite the query with terms like "shipping", or add synonyms to the index. Combining keyword and embedding search also helps.