Evals 3: Evaluating RAG and Agents
The two architectures most AI features are built from, and why a single "quality score" can't tell you which part of either one broke.
This page uses the dataset, grader and statistics tools from pages 1 and 2, and applies them to the copilot's two moving parts: the help-center retrieval it reads from, and the tool-calling loop that changes orders and refunds.
Evaluating RAG: retrieval and generation, separately
The support copilot answers "can I get a refund on order 4417?" in two steps. First it finds help-center articles. Then it writes a reply from them. If you only score the final reply, a bad score tells you nothing about which step broke. The fix is old and simple: measure each half on its own, then read the two numbers together. You built the pipeline in Phase 2. This section is about measuring it.
Retrieval: where the labels come from
A relevance label says "for this query, these documents (or chunks) contain the answer." Every retrieval metric needs them. You have two sources.
- Real tickets with a KB link. When a human agent resolved a ticket and pasted a help-center article, that article is a label. This is the best source because the query is a real customer's wording. It is also biased: agents only link articles they already know about, so some correct articles are missing from the labels.
- Synthetic questions. Take a chunk, ask an LLM "write a question this chunk answers," and store the pair. This is cheap and covers every article. See Evals 1: Eval datasets: golden sets, synthetic data, coverage for the general method.
The four retrieval metrics, with one example
Take one query. The labels say docs A and C are relevant. The retriever returns this ranking:
rank 1: B (not relevant)
rank 2: A (relevant)
rank 3: D (not relevant)
rank 4: C (relevant)
rank 5: E (not relevant)- recall@k — of all relevant docs, what share is in the top k? At k=3 only
Ais in, so 1 of 2 = 0.50. At k=5 both are, so 1.00. - precision@k — of the k docs returned, what share is relevant? At k=3: 1 of 3 = 0.33.
- MRR (mean reciprocal rank) — take 1 / (rank of the first relevant doc), then average over queries. Here the first relevant doc is at rank 2, so the score is 0.50. It only looks at the first hit.
- nDCG@k (normalised discounted cumulative gain) — rewards relevant docs near the top. Each hit at rank i is worth 1 / log2(i+1), then you divide by the best possible total. Hits at ranks 2 and 4 give 1/1.585 + 1/2.322 = 0.631 + 0.431 = 1.062. The ideal ranking (hits at 1 and 2) gives 1 + 0.631 = 1.631. So nDCG@5 = 1.062 / 1.631 = 0.65.
import math
def recall_at_k(ranked, relevant, k):
return len(set(ranked[:k]) & relevant) / len(relevant)
def precision_at_k(ranked, relevant, k):
return len(set(ranked[:k]) & relevant) / k
def rr(ranked, relevant):
for i, doc in enumerate(ranked, 1):
if doc in relevant:
return 1 / i
return 0.0
def ndcg_at_k(ranked, relevant, k):
dcg = sum(1 / math.log2(i + 1)
for i, d in enumerate(ranked[:k], 1) if d in relevant)
ideal = sum(1 / math.log2(i + 1)
for i in range(1, min(len(relevant), k) + 1))
return dcg / ideal
ranked, rel = list("BADCE"), {"A", "C"}
print(recall_at_k(ranked, rel, 3)) # 0.5
print(round(ndcg_at_k(ranked, rel, 5), 2)) # 0.65Which one to optimise
It depends on what comes after retrieval. In the copilot, a vector search returns 50 candidates, a reranker cuts them to 5, and the LLM reads those 5. The reranker can reorder but cannot invent. If the right article is not in the 50, it is gone. So at the first stage recall@50 is the number that matters, and precision is nearly irrelevant. At the second stage, after the reranker, you care about recall@5 and nDCG@5, because the LLM only sees five chunks and the order of chunks affects how much it uses them.
Trade-off to decide: raising k improves recall and costs tokens, latency and distraction. One support ticket with 10 chunks of 400 tokens adds 4,000 input tokens. At 400 tickets a day that is small. At 40,000 it is a budget line. Pick k by plotting recall@k against cost and choosing the knee, not the maximum.
Generation: faithful, relevant, cited
Generation metrics take the question, the retrieved chunks and the answer. They do not need document labels. The RAGAS paper (Es et al., 2023) introduced the common set. Names have drifted since, so check the current docs. As of Oct 2026 the RAGAS docs list Context Precision, Context Recall, Context Entities Recall, Noise Sensitivity, Response Relevancy and Faithfulness. What the paper called "answer relevance" is now Response Relevancy.
- Faithfulness (also called groundedness) — is every claim in the answer supported by the retrieved context? It measures support, not truth.
- Response relevancy — does the answer address the question? An answer can be fully grounded and still answer a different question.
- Context precision (RAGAS) — are the useful chunks ranked above the useless ones? Unlike classic precision@k it averages precision at each rank, so one junk chunk in first place hurts more than the same chunk in fifth place.
- Context recall (RAGAS) — does the retrieved context contain what a reference answer needs? Same idea as recall@k, but judged against a reference answer instead of document IDs.
- Citation correctness — when the reply says "[KB-112]", does KB-112 actually support that sentence? Check mechanically that the ID exists in the retrieved set, then check support with a judge per sentence.
How a claims-decomposition faithfulness check works
RAGAS faithfulness is three steps. (1) Split the answer into atomic claims. (2) For each claim, ask whether it can be inferred from the context. (3) Score = supported claims ÷ total claims. The RAGAS docs give the example: context says Einstein was born on 14 March 1879 in Germany; the answer says 20 March 1879 in Germany. Two claims, one supported, score 0.5. Splitting first matters: a single "is this answer supported?" question lets one wrong date hide inside several right sentences.
import json
SPLIT = """List every factual claim in the ANSWER as a short, self-contained
sentence. Return a JSON list of strings.
ANSWER: {answer}"""
CHECK = """CONTEXT:
{context}
CLAIM: {claim}
Can the claim be inferred from the context alone? Reply JSON:
{{"supported": true|false, "evidence": "quote or empty"}}"""
def faithfulness(answer, chunks, llm):
claims = json.loads(llm(SPLIT.format(answer=answer)))
ctx = "\n---\n".join(chunks)
verdicts = [json.loads(llm(CHECK.format(context=ctx, claim=c)))
for c in claims]
ok = sum(v["supported"] for v in verdicts)
return ok / len(claims), list(zip(claims, verdicts))Return the per-claim verdicts, not only the score. The failing claim is what you read in error analysis (Evals 1: Error analysis: read your data before you measure it). The judge itself needs validating like any other (Evals 2: Trusting your judge: validating LLM-as-judge).
The "I don't know" slice
When retrieval returns nothing useful, the correct reply is "I can't find that, here is how to reach a human." Models trained to be helpful often answer from memory instead. This is a behavior with its own test set: queries whose answer is deliberately not in the KB (a product you do not sell, a feature that does not exist). Score the abstention rate on this slice. Also score the opposite error, the false refusal rate, on queries that are answerable. A model tuned to always decline gets a perfect abstention score and is useless. Report both numbers.
The 2×2: which half do I fix?
For each failed case in the dataset, ask two questions. Was a relevant doc in the top k? Was the answer good? Count the cases in each cell.
| Answer good | Answer bad | |
|---|---|---|
| Retrieval good | Healthy. Spot-check for luck. | Generation bug. Fix the prompt, context order, model, or add a faithfulness check. |
| Retrieval bad | Lucky or from memory. Dangerous: it will break on the next model. Check for leakage. | Retrieval bug. Fix chunking, embeddings, query rewriting, hybrid search, or the KB itself. |
Worked example. 200 failed-or-suspect copilot answers: 18 healthy, 96 retrieval-good/answer-bad, 71 retrieval-bad/answer-bad, 15 retrieval-bad/answer-good. The team had spent a month on embeddings. The table says 48% of the pain was in generation. They moved to the prompt and context formatting first. The "lucky" cell of 15 is worth reading: those answers came from model memory, and the model memory was about a different company's refund policy.
Trade-off to decide: reference-free metrics (faithfulness, response relevancy) run on live traffic with no labels, but they are judge-based and noisy. Label-based metrics (recall@k) are exact but only cover what you labelled. Use label-based metrics in CI and reference-free ones for online monitoring (Evals 4: Online evals: production signals, A/B tests, monitoring).
Evaluating agents: trajectories, tool calls, end state
A RAG answer is a string. An agent run is a chain of decisions that changes things: it reads an order, calls issue_refund, and a row now exists in a database. Three things make this harder to grade. The run has many steps, so errors compound. It has side effects, so a wrong action costs money, not just a bad sentence. And it has many valid paths, so you cannot compare against one golden transcript. The loop itself is in Phase 1. Here we grade it.
Vocabulary (Anthropic's)
Anthropic's engineering post "Demystifying evals for AI agents" (Jan 9, 2026) fixed a shared vocabulary. Use it so your team and the literature mean the same thing.
- Task — one test: an input plus success criteria.
- Trial — one attempt at a task. Run several, because agent output varies run to run.
- Grader — logic that scores some aspect of a run. A task can have several graders.
- Transcript (also trace, trajectory) — the full record of a trial: outputs, tool calls, reasoning, results.
- Outcome — the final state of the environment. Their example: a reservation row exists in the database, not "the agent said it booked one."
- Evaluation harness runs tasks and grades them. Agent harness (scaffold) is what lets a model act as an agent. You always evaluate the two together.
Three things to grade
- End state — after the run, query the environment. Is there exactly one refund row, for the right order, the right amount, with the status policy requires? This is deterministic code, cheap, and hard to fool.
- Trajectory — did it call the right tools with the right arguments, in an acceptable order, without wasted calls? Needed when the end state cannot show everything (it must not have emailed the wrong customer; it must have checked the order before refunding).
- Final message — did the reply to the customer tell the truth about what happened, in the right tone? Usually an LLM judge or a rubric (Evals 2: Graders: code checks, reference metrics, LLM judges, humans).
Anthropic's advice is to grade what the agent produced, not the exact path, because rigid step checks fail agents that find a valid route you did not predict. Their post gives a concrete case: on a τ²-bench flight-booking task, Opus 4.5 found a loophole in the policy and "failed" the eval as written while giving the user a better outcome. The eval was wrong, not the agent. Read transcripts of failures to check the grader before you blame the model.
So a practical rule: gate on the end state; make trajectory checks loose and about safety or cost invariants ("never calls issue_refund before get_order", "at most 8 tool calls"); and use the reply grader for communication quality. Give partial credit on multi-part tasks.
Environment-based evals and pass^k
To get an end state you need an environment: a sandbox with a fake database and fake tools, reset before each trial. For conversational agents you also need a simulated user, an LLM playing the customer. The reference design is τ-bench (Yao, Shinn, Razavi, Narasimhan, Sierra and Princeton, arXiv 2406.12045, June 2024): an LLM user, an agent with domain API tools and a policy document, and success judged by comparing the final database to an annotated goal state. Its follow-up τ²-bench (Barres et al., arXiv 2506.07982, June 2025) adds a telecom domain where both agent and user act on shared state ("dual control"). The public repo now covers airline, retail, telecom and more, and reports 1.x and 2.0 scores separately because they are not comparable.
τ-bench also introduced pass^k: the chance that all k independent trials of a task succeed. Contrast with pass@k, the chance that at least one succeeds. pass@k rises with k and fits "one good answer is enough," such as code generation with tests. pass^k falls with k and fits a customer-facing agent, which must work every time. Estimate it from n trials with c successes as C(c,k) / C(n,k), averaged over tasks. Anthropic's example: a 75% per-trial success rate gives 0.753 ≈ 42% for three-in-a-row. The original paper reported that gpt-4o-class agents succeeded on under 50% of tasks and had pass^8 under 25% in retail.
Code-task agents use the same shape with a different end-state check: SWE-bench-style evals run the repo's test suite after the agent edits it. Pass means the target tests pass and the previously passing ones still do. Anthropic notes SWE-bench Verified scores rose from about 40% to over 80% in a year. That is saturation: when an eval is near 100% it no longer separates versions, so you need harder tasks.
Tool-call metrics, efficiency, and transition analysis
When the end state fails, tool-call level metrics tell you which decision broke.
- Tool selection accuracy — did it pick the right tool? Compare to a set of acceptable tools, not a single one.
- Argument accuracy — right order ID, right amount, right enum? Most real failures live here.
- Unnecessary calls — calls that were not needed. Count them; a repeated
get_orderloop is a signal.
Efficiency (steps, tokens, dollars, wall-clock latency) is a guardrail metric: you do not optimise it first, but a change must not make it much worse. A prompt that lifts end-state pass rate from 82% to 85% and doubles cost per ticket from $0.04 to $0.08 is a product decision, not a win. Record cost per trial alongside the grade.
Transition failure analysis
For a pipeline with many steps, "it failed" is not enough. Hamel Husain's evals FAQ (credited to Bryan Bischof's "Failure is a Funnel" talk) describes a transition failure matrix: one axis is the last step that succeeded, the other is the first step that failed. Count failed traces in each cell. Their example is a text-to-SQL agent where the "generate SQL → execute SQL" cell held 12 failures and a neighbor held 2. The biggest cell is where to work.
Here the red cell says: the decision was right, the refund call was malformed. That is a tool schema fix (an unclear amount field, cents vs dollars), not a prompt rewrite. The amber cell says: after fetching KB articles, the agent decided wrongly, which links back to the retrieval and stale-KB problems in The 2×2: which half do I fix?. Labelling each trace needs a human or a reviewed LLM pass, which is why this follows error analysis (Evals 1: Error analysis: read your data before you measure it) rather than replacing it.
Multi-turn evals with a user simulator
The customer may reply, push back, or change their mind. You test this with a user simulator: an LLM prompted with a persona and a hidden goal ("you are Dana, your blender arrived cracked, you want money back, you will accept store credit only after being asked twice"). The conversation runs until the agent finishes or a turn limit hits. Then you grade the end state.
τ²-bench makes the same point from the research side: it ties the simulator to the environment, so the user can only do what the tools and the observable state allow, and it reports that agent scores drop when users must act too.
Worked example: three support-copilot tasks, graded on end state
The sandbox is an in-memory SQLite database with orders and refunds. The policy: refunds up to $50 are issued directly; over $50 need human approval, so the correct end state is a refund row with status pending_approval; delivered more than 30 days ago is not refundable.
import sqlite3
def fresh_db():
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE orders(id TEXT, customer TEXT, total REAL,
days_since_delivery INT);
CREATE TABLE refunds(order_id TEXT, amount REAL, status TEXT);
INSERT INTO orders VALUES
('A100','dana',30.0,5),
('B200','lee',120.0,9),
('C300','kim',45.0,52);
""")
return db
def refunds(db, order_id):
return db.execute("SELECT amount, status FROM refunds "
"WHERE order_id=?", (order_id,)).fetchall()
# Each check reads ONLY the database. Nothing here looks at the reply.
CHECKS = {
# 1: small refund inside window -> issued, exact amount
"refund_small": lambda db: refunds(db, "A100") == [(30.0, "issued")],
# 2: over $50 -> exactly one row, waiting for a human
"refund_big": lambda db: refunds(db, "B200")
== [(120.0, "pending_approval")],
# 3: outside 30 days -> NO refund row at all
"refund_too_late": lambda db: refunds(db, "C300") == [],
}
def run_task(name, agent):
db = fresh_db()
transcript = agent(name, db) # agent calls tools that write to db
return {"task": name,
"end_state_ok": CHECKS[name](db),
"tool_calls": len(transcript["calls"]),
"no_dup_refund": db.execute(
"SELECT COUNT(*) FROM refunds").fetchone()[0] <= 1}Why these three? Task 1 is the happy path. Task 2 tests the approval rule: the common failure is the agent issuing the $120 refund directly because the customer was convincing. Task 3 is a should not act case, which Anthropic specifically says to include so you do not train an agent that always says yes. In task 3 the end state is the absence of a row, and the reply grader checks that the customer was told why. Also note no_dup_refund: a retry loop that issues the same refund twice passes a naive "a refund exists" check and costs real money.
Run each task 5 times and compute pass^5. A task that passes 4 of 5 times has pass^5 of 0 for that task. Write the failing transcripts to a file and read them: a failure on task 3 might be the agent being right and your date math wrong.
Trade-off to decide: a strict trajectory check ("must call get_order first") catches unsafe shortcuts but fails a valid agent that read the order from context. Use strict trajectory checks only for invariants you would also enforce in code, and leave the rest to the end state.
Check yourself
Question 1
Your RAG dashboard shows recall@5 = 0.96 and faithfulness = 0.97, yet support leads say a fifth of answers are wrong. Name three different causes the dashboard cannot see, and one cheap check for each.
Show answer
(1) The recall set is synthetic and copies chunk wording, so real queries retrieve worse. Check: recall on real-ticket queries. (2) The KB article is stale. Faithfulness only checks support, not truth. Check: article review dates plus "policy changed" cases with current reference answers. (3) Generation ignores or misuses a correct chunk in a way the judge misses, or the faithfulness judge is itself unreliable. Check: read per-claim verdicts on a sample and measure judge agreement with a human.
Question 2
A first-stage retriever returns 50 candidates and a reranker keeps 5. Which metric do you optimise at each stage, and why is precision@50 the wrong target at stage one?
Show answer
Stage one: recall@50, because the reranker cannot recover a document that was never retrieved. Precision@50 only measures how much junk the reranker must sift, which is a cost issue, not a quality ceiling. Stage two: recall@5 and nDCG@5, since the LLM sees only five chunks and their order.
Question 3
The refund agent scores 90% on a single run per task. Product wants it handling the same request type for every customer. What number do you report, and roughly what is it for 5 consecutive successes?
Show answer
pass^k from several trials per task (pass^5 here). If trials are independent, 0.9^5 ≈ 0.59. In practice per-task rates differ, so estimate C(c,k)/C(n,k) per task and average. Tasks that pass 4 of 5 trials count as zero for pass^5, which is the point.
Question 4
A new prompt lifts end-state pass rate from 82% to 85%, but the transcript shows the agent now calls get_order three times per ticket and cost per ticket doubled. A trajectory check "must call get_order exactly once" would fail it. Is that the right check?
Show answer
No. Exact call counts are a brittle path check. Keep the end state as the gate, and add a loose efficiency guardrail (for example at most 6 tool calls and a cost-per-ticket ceiling). Then decide as a product call whether +3 points is worth 2x cost. Also check whether the repeated calls are a real loop or a retry after a tool error.
Sources
- Ragas: Automated Evaluation of Retrieval Augmented Generation — Es, James, Espinosa-Anke, Schockaert, 2023
- Ragas docs: available metrics — Ragas, 2026
- Ragas docs: Faithfulness — Ragas, 2026
- Ragas docs: Context Precision — Ragas, 2026
- Demystifying evals for AI agents — Anthropic Engineering, Jan 2026
- τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains — Yao, Shinn, Razavi, Narasimhan, 2024
- τ²-Bench: Evaluating Conversational Agents in a Dual-Control Environment — Barres et al., 2025
- tau2-bench repository — Sierra Research, 2026
- Q: How do I evaluate agentic workflows? — Hamel Husain, evals FAQ, 2025
Next
Everything so far runs offline, on a dataset. Page 4 takes evals into production: signals from real users, A/B tests, CI gates, a shared eval platform, and adversarial test sets.