Sub topic 15
Evaluating retrieval, grounding and agent behavior
This chapter assumes you can read basic Python, know what recall and precision mean at a high level, and have followed the earlier chapters on the agent loop, step budgets, and citing sources. You will learn to measure three things separately: whether the right passages were found, whether the answer is supported by them, and whether the agent behaved sensibly along the way.
Why one score is not enough
A final-answer score such as "was the answer correct?" hides where a failure came from. A wrong answer can come from a retriever that missed the passage, a model that ignored a good passage, or an agent that stopped too early. Each cause needs a different fix. So you evaluate three layers, each with its own data and metrics.
Build a small labeled test set
Start with 30 to 100 questions. Larger sets are better, but a small set that you trust beats a large one you never read. For each question, record:
- The question text, written the way real users write it.
- The ids of passages that contain the evidence. Multi-hop questions have several.
- A short reference answer, or the facts the answer must contain.
- A flag for questions that should trigger no search, such as greetings.
- A flag for questions the corpus cannot answer, where the right output is "the documentation does not say".
Include the last two kinds on purpose. An agent that always searches, or always answers, looks fine on a set made only of answerable questions.
Layer 1: retrieval quality
Measure retrieval on the passages the agent actually saw, taken from the trace, not on a separate call you make yourself. The agent rewrites queries, so only the trace shows what was retrieved.
Common metrics:
| Metric | Question it answers | Weakness |
|---|---|---|
| Recall@k | Did the needed passages appear among the results? | Ignores ranking and noise |
| Precision@k | How much of what came back was relevant? | Punishes returning extra context that is harmless |
| MRR | How high was the first relevant passage? | Looks only at the first hit |
| Evidence coverage | For multi-hop questions, were all required passages found across all steps? | Needs labels for every hop |
For agentic RAG, recall over the whole run (the union of all steps) matters most, because the agent can recover from a weak first query. Also record recall after the first search. The gap between the two shows how much the loop is helping.
def recall(retrieved_ids, relevant_ids):
relevant = set(relevant_ids)
if not relevant:
return None # unanswerable question: recall is undefined
return len(relevant & set(retrieved_ids)) / len(relevant)
def mrr(retrieved_ids, relevant_ids):
relevant = set(relevant_ids)
for rank, pid in enumerate(retrieved_ids, start=1):
if pid in relevant:
return 1.0 / rank
return 0.0
def retrieval_report(trace, relevant_ids):
# trace["searches"] is a list of {"query": str, "ids": [str, ...]}
first = trace["searches"][0]["ids"] if trace["searches"] else []
seen = []
for s in trace["searches"]:
for pid in s["ids"]:
if pid not in seen:
seen.append(pid)
return {
"recall_first_search": recall(first, relevant_ids),
"recall_whole_run": recall(seen, relevant_ids),
"mrr_whole_run": mrr(seen, relevant_ids),
}
trace = {"searches": [
{"query": "rate limit", "ids": ["d4", "d9"]},
{"query": "rate limit burst window", "ids": ["d2", "d4"]},
]}
print(retrieval_report(trace, ["d2", "d4"]))Running this prints a first-search recall of 0.5 and a whole-run recall of 1.0, which is the pattern you hope to see when rewriting works.
Layer 2: grounding
Grounding asks whether the answer's claims are supported by the passages the agent retrieved. Retrieval can be perfect and the answer still invented.
Check two things separately:
- Citation validity. Every cited id must exist in the trace. This is a cheap exact check. A cited id that was never retrieved is a fabricated citation.
- Claim support. Each factual claim must be entailed by the cited passage text. This is harder. Common approaches are a human reviewer on a sample, or a second model call acting as a judge that gets one claim and one passage and answers "supported", "contradicted" or "not mentioned".
import re
def citation_check(answer, retrieved_ids):
cited = set(re.findall(r"\[([A-Za-z0-9_\-]+)\]", answer))
retrieved = set(retrieved_ids)
return {
"cited": sorted(cited),
"invalid": sorted(cited - retrieved),
"has_citation": bool(cited),
}
answer = "The limit is 100 requests per minute [d4]. Bursts are allowed [d7]."
print(citation_check(answer, ["d2", "d4"]))This reports d7 as invalid. Note that a valid citation does not prove the claim is supported. It only proves the source was available.
Also score the abstention cases. For unanswerable questions, count an answer as correct only if it says the evidence is missing. Track the false-answer rate on these questions as its own number, since it measures hallucination under pressure.
Layer 3: agent behavior
The trace lets you check things that a final answer cannot show. Useful behavior metrics, all computed from logged steps:
- Steps used against the budget, as a distribution rather than an average. Look at the 95th percentile.
- Budget exhaustion rate: how often the loop hit the step limit and had to force an answer.
- Repeated queries: the same or near-identical query issued twice, which signals a stuck loop.
- Retrieval decision accuracy: searched when it should not have (waste), or skipped search when it should have searched (risk).
- Tool errors: calls with bad arguments or unknown tool names.
- Tokens and latency per question, since they tie to cost.
def behavior_report(trace, should_search, max_steps):
queries = [s["query"].strip().lower() for s in trace["searches"]]
return {
"steps": trace["steps"],
"hit_budget": trace["steps"] >= max_steps,
"repeated_queries": len(queries) - len(set(queries)),
"searched": bool(queries),
"wrong_decision": bool(queries) != should_search,
}
print(behavior_report(
{"steps": 5, "searches": [{"query": "refund policy"}, {"query": "Refund policy "}]},
should_search=True,
max_steps=5,
))Here the normalization catches the repeated query despite different casing and a trailing space, and the run is flagged as having hit the budget.
Reading the results together
Combine the layers to find the failing component.
| Retrieval | Grounding | Behavior | Likely cause |
|---|---|---|---|
| Low recall | Good on what was found | Few steps | Agent stopped too early, or query was too vague |
| Low recall | Good | Many repeats | Tool description or query advice needs work |
| High recall | Poor | Normal | Model ignores or misreads passages; tighten the answer prompt |
| High recall | Good | Hits budget often | Wasteful loop; lower the budget or improve grading |
| High recall | Poor on unanswerable | Normal | No abstention instruction, or it is too weak |
Practical rules
- Fix the test set and the metrics before you change the system, so that comparisons are fair.
- Compare against classic RAG on the same questions. Agentic RAG should win on multi-hop and ambiguous questions, and it need not win on simple lookups, where it mostly adds cost.
- Run each question more than once if sampling is on. Model behavior varies between runs, so report a spread, not one number.
- Store the full trace for every run. Without it you cannot tell which layer failed.
- Re-run the suite when you change the corpus, embedding model, tool description, or step budget. Each one can shift results in a different layer.
Exercise
An agentic RAG system scores whole-run recall of 0.92 and valid citations on every answer, yet reviewers find that many answers contain claims not in the cited passages. Which layer is failing, what extra check would you add, and why does the valid-citation check not catch the problem?
Show answer
Grounding is failing. Add a claim-support check, with a human reviewer on a sample or an LLM judge validated against hand labels, that tests whether each claim is entailed by the cited passage. The valid-citation check only confirms that a cited id was retrieved, so the model can cite a real passage and still state something it does not say.
Exercise
Your test set contains only questions that the corpus can answer. Name two kinds of questions to add and the behavior each one tests.
Show answer
Add questions that need no search, such as greetings, to test whether the agent skips retrieval and avoids wasted steps. Add unanswerable questions, where the corpus lacks the facts, to test whether the agent abstains and says the evidence is missing instead of inventing an answer.