Sub topic 10
Grading results and trying again
This chapter assumes you can write the agent loop from the earlier chapters. It also assumes you have a retriever that returns passages as {"id": ..., "text": ...} and that you can call a model from Python.
Why retrieval needs a check
A vector search always returns something. Ask for the top 4 passages and you get 4, even if none of them mention your topic. The ranking only says which passages are nearest, not whether any of them is near enough.
In classic RAG, the model receives those passages and writes an answer anyway. In an agent loop, the same thing can happen: the model calls the tool once, sees plausible text, and answers. Grading adds a deliberate step between "results arrived" and "answer written". The step asks whether the evidence answers the question. If it doesn't, the agent tries something else or says the evidence is missing.
What a grader judges
Grade two separate things.
- Relevance: is each passage about the question?
- Sufficiency: do the passages together contain what is needed to answer?
Relevance does not imply sufficiency. Three passages about a product's rate limits are all relevant to "What is the rate limit for the free plan?" but may only describe the paid plans. Sufficiency is the check that matters most for the stop-or-retry decision.
Three ways to grade
| Method | How it works | Cost | Weakness |
|---|---|---|---|
| Score threshold | Compare the similarity score to a cutoff. | Almost free | Scores are not comparable across queries or embedding models. A good cutoff must be tuned on your data. |
| Model in the loop | The agent reads the tool result and decides for itself whether to search again. | No extra call | Nothing forces the check, and a model may accept weak evidence. |
| Separate grader call | A dedicated prompt returns a structured verdict. | One extra model call per attempt | Adds latency and can be wrong in either direction. |
Many systems combine them. A threshold removes obvious junk cheaply. The grader handles the cases that remain.
A grader with a structured verdict
Ask the grader for JSON with a fixed set of verdicts. Free-text opinions are hard to branch on.
import json
GRADER_PROMPT = """You check search results for a question.
Return only JSON: {{"verdict": "sufficient" | "partial" | "insufficient", "missing": "<what is still needed, or empty>"}}
- sufficient: the passages contain what is needed to answer fully.
- partial: some of the answer is present, some is not.
- insufficient: the passages do not help answer the question.
Question: {question}
Passages:
{passages}
"""
def grade_results(question, chunks, judge):
# judge(prompt) -> str is supplied by you (one model call).
passages = "\n\n".join(f"[{c['id']}] {c['text']}" for c in chunks) or "(no passages)"
raw = judge(GRADER_PROMPT.format(question=question, passages=passages))
try:
grade = json.loads(raw)
if grade.get("verdict") not in ("sufficient", "partial", "insufficient"):
raise ValueError("bad verdict")
grade.setdefault("missing", "")
return grade
except (ValueError, TypeError, AttributeError):
# An unreadable verdict must not pass as "sufficient".
return {"verdict": "partial", "missing": "grader output could not be parsed"}Note the fallback. If the grader's output is broken, the code treats the evidence as unproven, not as good. A silent default to sufficient would disable the whole check on the days the grader misbehaves.
Trying again with a different query
The missing field is the grader's most useful output. It tells the rewriter what to look for next, so the retry is not a repeat of the first search.
def retrieve_with_grading(question, search, judge, rewrite, max_attempts=3, k=4):
# search(query, k) -> list of {"id", "text"}; rewrite(question, tried, missing) -> str
tried, kept = [], {}
query, grade = question, {"verdict": "insufficient", "missing": ""}
for _ in range(max_attempts):
tried.append(query)
for chunk in search(query, k):
kept[chunk["id"]] = chunk # merge by id, no duplicates
grade = grade_results(question, list(kept.values()), judge)
if grade["verdict"] == "sufficient":
break
query = rewrite(question, tried, grade["missing"])
if query in tried: # the rewriter is stuck, so more attempts won't help
break
return list(kept.values()), gradeThree details matter here.
- Evidence accumulates across attempts. A
partialfirst result plus apartialsecond result may add up tosufficient. - The grader sees the question, not the latest query. Otherwise a drifting query could be judged against itself.
- The loop stops on a repeated query. Retrying the same text returns the same chunks.
Pass the list tried to the rewriter so it can avoid earlier queries. Here is a quick check with stubs:
def demo():
docs = {"a": "Paid plans allow 600 requests per minute.",
"b": "The free plan allows 60 requests per minute."}
def search(query, k):
hits = [d for d in docs if ("free" in query) == (d == "b")]
return [{"id": d, "text": docs[d]} for d in hits][:k]
def judge(prompt):
has_free = "free plan" in prompt.split("Passages:")[1]
return json.dumps({"verdict": "sufficient" if has_free else "partial",
"missing": "" if has_free else "free plan limit"})
def rewrite(question, tried, missing):
return f"{missing} requests per minute"
chunks, grade = retrieve_with_grading(
"What is the rate limit?", search, judge, rewrite)
print(grade["verdict"], [c["id"] for c in chunks])
demo()The first search finds only the paid-plan passage, so the verdict is partial. The rewritten query mentions the free plan, finds passage b, and the second verdict is sufficient.
The control flow
Admitting that the evidence is missing
The right exit for an exhausted budget is an honest answer, not a guess. When the loop ends with a verdict other than sufficient, pass the verdict and the missing text to the final prompt:
- If the verdict is
partial, answer the supported part and name the unsupported part. - If the verdict is
insufficient, say the documentation does not cover the question, and don't fill the gap from the model's memory.
A good "I could not find this" is a correct outcome. It is better than a fluent answer that no passage supports.
Common errors
- Grading relevance only. Passages on the right topic pass, and the answer is still incomplete. Ask about sufficiency.
- A lenient grader. Models tend to agree that evidence looks fine. Require the grader to name what is missing, and test it on cases where you know the evidence is thin.
- A strict grader. It rejects good evidence, and the loop burns its budget. Track how often attempt 2 changes the verdict.
- Rewriting without feedback. If the rewriter never sees
missingandtried, it produces paraphrases that return the same chunks. - Unbounded retries. Every retry costs a search and a grader call. Keep
max_attemptssmall, usually 2 or 3. - Grading text as instructions. The grader reads retrieved passages, which are untrusted. A later chapter covers injected text, but already keep the grader's output restricted to the fixed JSON schema.
Exercise
In retrieve_with_grading, why does the loop break when the rewritten query is already in tried, and what would you change if the rewriter regularly returned a repeat?
Show answer
A repeated query would return the same chunks and the same verdict, so another attempt spends a search and a grader call for nothing. The break saves that cost and ends the loop with the best evidence so far. If repeats are common, fix the cause: pass tried and missing to the rewriter prompt, and tell it explicitly not to reuse earlier queries or close paraphrases of them.
Exercise
A grader returns sufficient for passages that are all about the free plan, but the question asks about the enterprise plan. Which property did the grader fail to check, and how would you change the prompt?
Show answer
It checked relevance (the topic is plan limits) but not sufficiency (the specific enterprise answer is present). Change the prompt so the grader must state which passage supports each part of the question. It should return partial or insufficient with a missing entry when any part has no supporting passage.