Sub topic 10
Grounding an agent with retrieval
This chapter assumes you have read the chapters on tool calling, the agent loop, and memory and context management. You should be comfortable with the run_tool registry and the loop that appends tool results to the message history. You also need basic Python and JSON.
Why an agent needs grounding
A language model only knows what was in its training data and what sits in its context window. It does not know your refund policy, last week's incident report, or the current version of your API. When it lacks a fact, it often produces a plausible guess. This is called hallucination.
Grounding means tying the model's answers to source material it can point to. The most common technique is retrieval: before or during a run, the program finds relevant passages in a document collection and puts them in the context. Combined with a generation step, this is called retrieval-augmented generation (RAG).
Retrieval also helps with the context window limit. You cannot paste a 5,000-page manual into every request, but you can fetch the three paragraphs that matter.
Two ways to wire retrieval into an agent
| Pattern | How it works | Strength | Weakness |
|---|---|---|---|
| Fixed retrieval | The program searches with the user's message and injects results before the first model call. | Predictable, one search per request. | The query is the raw user text, and the model cannot search again. |
| Retrieval as a tool | The model calls a `search_docs` tool whenever it decides it needs facts. | The model can rephrase, search several times, and skip search for simple questions. | Costs extra steps, and the model may skip search when it should have used it. |
For agents, retrieval as a tool is usually the better fit. It reuses the machinery you already built: a name, a description, an argument schema, and a result that goes back into the history.
The retrieval pipeline
Retrieval has an offline half and an online half.
- Chunk. Split documents into passages. Chunks that are too large dilute the match and waste context. Chunks that are too small lose the surrounding meaning. A few hundred tokens with a small overlap between neighbors is a common starting point. Splitting on headings or paragraphs usually beats splitting at a fixed character count.
- Index. Store each chunk with an id and metadata such as source file, section, and date.
- Search. Turn the query into a ranking over chunks.
- Return. Send the top few chunks back with their ids so the model can cite them.
Keyword search versus embeddings
Keyword search (such as BM25 or TF-IDF) scores chunks by shared words. It is fast, needs no model, and handles exact terms like error codes and product names well. It fails on synonyms: a query for "reimbursement" will not match a passage that says "refund".
Embedding search converts text into vectors, which are lists of numbers where similar meanings land close together. You rank by vector similarity. This handles paraphrases, but it can miss exact identifiers and needs an embedding model plus a vector store.
Many production systems combine both (hybrid search) and then rerank the merged top results with a stronger model. Start simple and add components only when your evaluation shows a retrieval problem.
A working retrieval tool
The example below uses only the standard library, so you can run it as is. It implements keyword scoring with inverse document frequency, which gives rare words more weight. It returns JSON in the same style as the earlier run_tool examples.
import json
import math
import re
from collections import Counter
DOCS = [
{"id": "refund-1", "text": "Refunds are issued within 14 days of purchase if the item is unused."},
{"id": "ship-1", "text": "Shipping takes 3 to 5 business days within the EU."},
{"id": "support-1", "text": "Support is available by email Monday to Friday, 9:00 to 17:00 CET."},
]
def tokenize(text: str) -> list[str]:
return re.findall(r"[a-z0-9]+", text.lower())
DOC_FREQ = Counter()
for doc in DOCS:
DOC_FREQ.update(set(tokenize(doc["text"])))
def score(query: str, doc: dict) -> float:
term_counts = Counter(tokenize(doc["text"]))
total = 0.0
for term in set(tokenize(query)):
if term in term_counts:
idf = math.log((1 + len(DOCS)) / (1 + DOC_FREQ[term])) + 1
total += term_counts[term] * idf
return total
def search_docs(query: str, top_k: int = 2) -> str:
ranked = sorted(((score(query, d), d) for d in DOCS), key=lambda p: p[0], reverse=True)
hits = [
{"id": d["id"], "score": round(s, 2), "text": d["text"]}
for s, d in ranked[:top_k]
if s > 0
]
if not hits:
return json.dumps({"results": [], "note": "No matching passages. Try different keywords."})
return json.dumps({"results": hits})
TOOLS = {"search_docs": search_docs}
print(search_docs("how many days for refunds"))
print(search_docs("reimbursement"))The first query returns refund-1 first, because it matches both "days" and "refunds". The second query returns no results, because "reimbursement" never appears in any document. That second case is a real limitation of keyword search, and the empty result carries a note so the model can retry with other words.
In the agent loop, register the tool and describe it clearly so the model knows when to use it:
SEARCH_DOCS_SPEC = {
"name": "search_docs",
"description": (
"Search the company policy documents. Use this before answering any "
"question about refunds, shipping, or support hours. Returns passages "
"with ids. Use short keyword queries, and call again with different "
"words if nothing relevant comes back."
),
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Keywords to search for."},
"top_k": {"type": "integer", "description": "Number of passages, 1 to 5."},
},
"required": ["query"],
},
}Making the model actually use what it retrieves
Retrieval gives the model evidence. Your system prompt determines whether it relies on that evidence. Useful instructions include:
- Answer factual questions only from retrieved passages.
- Cite the passage id after each claim, for example
[refund-1]. - If the passages do not contain the answer, say so. Do not guess.
- If the first search returns nothing useful, rephrase and search again before giving up.
Your step limit still applies. Each search costs one step, so an agent that is allowed to search repeatedly needs a max_steps that leaves room for it.
Common failures and edge cases
- Wrong chunks retrieved. The answer exists but ranks below irrelevant text. Fix this by improving chunk boundaries, adding hybrid search, or reranking. Log the query and the returned ids so you can see this happening.
- Answer split across chunks. Overlap between chunks and metadata such as section titles reduce this.
- Stale index. Documents change but the index does not. Store a date or version in the metadata and rebuild on a schedule or on change.
- Too many results. Ten passages of filler can crowd out the useful one and eat the context budget. Keep
top_ksmall and cap passage length. - Retrieved text as instructions. A passage might contain text such as "ignore your rules". Treat retrieved content as data, say so in the system prompt, and do not give a search-only agent powerful tools. The guardrails chapter returns to this.
- Answers that cite but do not follow. A model can attach a correct id to a claim the passage does not support. Check this in your evaluation by comparing each cited claim to the cited text.
Choosing when to add retrieval
Use retrieval when the facts are private, large, or changing. Do not add it for a small, stable body of knowledge that fits in the system prompt, because a plain prompt has no search to fail. If the model must combine facts across many documents, retrieval alone may not be enough, and you may need multi-step search or a planning pattern, which later chapters cover.
Exercise
A user asks your agent, "What is the reimbursement policy?" Your documents say "Refunds are issued within 14 days." The keyword search tool returns no results, and the agent answers with a confident policy it made up. Name two changes that would address this, one in the retrieval tool and one in the agent's instructions.
Show answer
In the retrieval tool, add embedding or hybrid search so that synonyms such as "reimbursement" and "refund" match, or return a note telling the model to retry with other keywords when results are empty. In the instructions, tell the model to answer only from retrieved passages, to rephrase and search again if nothing is found, and to say it cannot find the answer if the retry also fails.
Exercise
Why is retrieval as a tool often better for an agent than fixed retrieval that runs once before the first model call?
Show answer
With a tool, the model can write its own queries, search more than once with different wording, combine results from several searches, and skip searching when the question does not need it. Fixed retrieval is limited to one search built from the raw user message.