RAG agent evaluation, sometimes called agentic RAG evaluation, checks whether an agent searched when needed, retrieved useful evidence and used that evidence to answer correctly.
We asked a handbook agent, "What Python version should I use for a new service?" The handbook says 3.12. The agent never called its search tool and answered: "As of October 2023, Python 3.11 is the latest stable release." In this trial, Ragas faithfulness had no retrieved context to score. Context recall was 0, but the retriever had never run.
The workflow below separates that decision failure from bad retrieval and bad use of good retrieval. We score four layers, inspect the corresponding traces in Laminar and compare three versions of the agent. These are results from a small handbook experiment, not a benchmark of models or evaluation libraries.
Why one RAG score hides where an agent failed
In a fixed retrieval pipeline, the system retrieves before answering. A row containing the question, retrieved contexts and answer describes the inputs to its RAG metrics. Ragas and DeepEval provide metrics for those inputs; the TruLens RAG triad covers context relevance, groundedness and answer relevance.
An agent with a search tool adds decisions:
- Whether to search. It can answer from outdated knowledge instead of checking the handbook.
- What to search for. One query may cover only part of a multi-part question.
- Whether to search again. After an empty result, it can rephrase or declare the topic undocumented.
- How to use the results. It can retrieve the right section and still misstate it.
Each path can end in a wrong answer, but the fixes differ. A missed search calls for a routing or prompt change. Missing sections require examining queries and the retriever. Misused evidence requires examining the answer against the context. Keep these scores separate so you know where to investigate.
The four layers of RAG agent evaluation
| Layer | Question | Needs | Score |
|---|---|---|---|
| 1. Search decision | Did it search when it should? | Tool calls, should_search label | Match or not |
| 2. Retrieval | Did searches return the right sections? | Retrieved ids, relevant ids | Context recall |
| 3. Evidence use | Is the answer supported by this run's results? | Answer, retrieved text | Faithfulness |
| 4. End task | Is the answer correct? | Reference answer | Correctness judge |
Start with the first failing layer, then check the trace before choosing a fix. After a missed search, recall is 0 and faithfulness is unscored in this workflow. Correctness still measures the damage. Conversely, an answer built from the wrong sections can be faithful to them.
Two additional retrieval checks help diagnose the failure:
- Reference-query recall runs the retriever on hand-written queries. If these find the sections and the agent's queries don't, investigate query formulation or sensitivity to phrasing.
- One-shot recall runs the retriever on the raw question, as a fixed pipeline would. It shows whether that query could have found the evidence.
Neither check generates an answer, so neither proves that forcing a search would improve correctness.
What standard RAG metrics do when the agent doesn't search
We tested Ragas 0.4.4 and DeepEval 4.3.7 with default metric settings and gpt-4.1-mini as judge. Both faithfulness metrics extract claims and compare them with retrieved context, but these examples produced different results. DeepEval 4.3.7 defaults penalize_ambiguous_claims to False.
| Case | Ragas Faithfulness | DeepEval FaithfulnessMetric |
|---|---|---|
| Answer from prior knowledge, no retrieved context | Raises ValueError | 1.0 |
| Answer from prior knowledge, unrelated context retrieved | 0.0 | 1.0 |
| Abstention with unrelated context | 0.0 | 1.0 |
Ragas measures the share of claims supported by the context. DeepEval's metric page describes truthfulness as not contradicting the context, which matches the observed outputs. Its documentation also uses stricter support language elsewhere. Treat this table as observed behavior for these versions and settings, not a guarantee about every configuration.
Neither faithfulness result identifies a skipped search. Context recall flags missing evidence with a 0, but cannot distinguish no search from a search that missed.
Ragas also offers agent metrics. Tool Call Accuracy compares tool names, arguments and sequence with reference calls. Our narrower should_search check records whether a search happened without prescribing a reference query.
Two other observations affected our scoring:
- Citation markers changed scores. A verbatim answer ending in [pg-backups] scored 0.67 in Ragas in three tests; without the marker, it scored 1.0 in all three. We strip markers before scoring faithfulness and check citation membership separately.
- Question details could appear unsupported. Restating the user's condition, "your migration locks a table with more than 10 million rows," scored 0.5 against the retrieved context. Inspect unsupported claims before treating a low score as an agent failure.
Build the eval: a handbook agent with a search tool
The example is an engineering-handbook assistant for fictional company Kestrel: 18 short sections, BM25 returning up to two sections per search, and a gpt-4o-mini tool loop using search_docs at temperature 0. We ran it on 2026-12-03 with lmnr 0.9.4 and self-hosted Laminar. The same evaluator structure can consume section ids and text from another retrieval system.
Return the retrieval trail from the executor
Laminar evaluations score the executor's output, so return every search alongside the answer. Wrapping the tool with observe records each call as a TOOL span in the trial's trace.
These blocks are excerpts from the tested script, not a standalone program. They omit the corpus (DOCS, DOC_IDS), index (BM25, TOKENIZE), OpenAI client, SEARCH_TOOL schema, SYSTEM_PROMPT and 19-row DATASET. The correctness evaluator is also omitted and described below.
import json
from lmnr import observe
def retrieve(query: str, k: int = 2) -> list[dict]:
scores = BM25.get_scores(TOKENIZE(query))
top = sorted(range(len(DOC_IDS)), key=lambda i: -scores[i])[:k]
return [{"id": DOC_IDS[i], "text": DOCS[DOC_IDS[i]]} for i in top if scores[i] > 0]
@observe(name="search_docs", span_type="TOOL")
def search_docs(query: str) -> list[dict]:
return retrieve(query)
@observe(name="handbook_agent")
def run_agent(question: str, system_prompt: str, max_turns: int = 6) -> dict:
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": question},
]
searches = []
for _ in range(max_turns):
msg = client.chat.completions.create(
model="gpt-4o-mini", messages=messages, tools=[SEARCH_TOOL], temperature=0
).choices[0].message
messages.append(msg)
if not msg.tool_calls:
return {"answer": msg.content, "searches": searches}
for call in msg.tool_calls:
query = json.loads(call.function.arguments)["query"]
results = search_docs(query)
searches.append({"query": query, "results": results})
messages.append(
{"role": "tool", "tool_call_id": call.id, "content": json.dumps(results)}
)
return {"answer": None, "searches": searches}
retrieve is separate from traced search_docs because the evaluators also call the retriever. Calling the traced tool from an evaluator would add those searches to the trace and inflate span-based counts of agent searches. We encountered that in an initial run.
Label the dataset for each layer
Each datapoint labels whether to search, which sections hold the answer, reference queries that retrieve them, and the reference answer.
{
"data": {"question": "I want to ship a payments change on Friday at 15:00 UTC. "
"Is that allowed, and how long would the canary stage last?"},
"target": {
"should_search": True,
"relevant_doc_ids": ["deploy-freeze", "canary"],
"reference_queries": ["deploy freeze friday", "canary release duration"],
"reference": "Not allowed without an exception: Friday after 14:00 UTC is a "
"freeze. The canary would run at 5% for 20 minutes.",
},
"task_id": "friday-canary",
}
The 19 questions include single-section lookups, multi-part requests and three questions that sound general but have handbook-specific answers. Two questions are unanswerable from the handbook, and two are general questions that need no search. A production golden dataset will have a different mix; include cases that exercise each layer.
Empty relevant_doc_ids does not imply should_search=False. An unanswerable handbook question still requires a search before the agent can claim the answer is undocumented.
Keep the corpus, labels and judge configuration fixed while comparing agent versions. If any of those change, record the change alongside the run; otherwise a score delta could reflect the test rather than the agent. The hand-written queries are diagnostics, not inputs passed to the agent.
Write one evaluator per layer
Evaluators receive executor output and targets. A returned dict adds score columns; an empty dict skips scores where the layer doesn't apply.
import re
from lmnr import evaluate
from openai import AsyncOpenAI
from ragas.llms import llm_factory
from ragas.metrics.collections import Faithfulness
judge = AsyncOpenAI()
faithfulness = Faithfulness(llm=llm_factory("gpt-4.1-mini", client=judge))
def executor(data):
out = run_agent(data["question"], SYSTEM_PROMPT)
out["question"] = data["question"]
return out
def retrieved_ids(output):
return {r["id"] for s in output["searches"] for r in s["results"]}
def search_decision(output, target):
searched = len(output["searches"]) > 0
return 1 if searched == target["should_search"] else 0
def retrieval(output, target):
gold = set(target["relevant_doc_ids"])
if not gold:
return {}
one_shot = {r["id"] for r in retrieve(output["question"])}
reference = {r["id"] for q in target["reference_queries"] for r in retrieve(q)}
return {
"context_recall": len(gold & retrieved_ids(output)) / len(gold),
"one_shot_recall": len(gold & one_shot) / len(gold),
"reference_query_recall": len(gold & reference) / len(gold),
}
async def faithful(output, target):
contexts = [r["text"] for s in output["searches"] for r in s["results"]]
if not contexts or not target["relevant_doc_ids"] or not output["answer"]:
return {}
result = await faithfulness.ascore(
user_input=output["question"],
response=re.sub(r"\s*\[[a-z0-9-]+\]", "", output["answer"]),
retrieved_contexts=contexts,
)
return {"faithfulness": result.value}
evaluate(
data=DATASET,
executor=executor,
evaluators={
"search_decision": search_decision,
"retrieval": retrieval,
"faithfulness": faithful,
"correctness": correctness,
},
name="handbook agent v3",
group_name="handbook-agent-rag",
trials=3,
)
correctness asks gpt-4.1-mini whether the answer agrees with every fact in the reference. Context recall uses section ids and needs no judge. Faithfulness uses results from every search, since this loop keeps them all in the conversation.
A separate citation check scored 1.0 in every v2 and v3 trial; v1 did not cite sections. That checks whether cited ids were retrieved, not whether each cited section supports its associated claim.
trials=3 repeats each question because the search decision was not stable.
Results: three versions, failures in three different layers
We ran 57 trials per version: 19 questions, three trials each.
- v1: a loose prompt, "You can call search_docs to look things up," and whitespace-tokenized BM25.
- v2: a stricter prompt requiring handbook searches, separate searches per topic, further searches when results don't answer, citations and abstention for undocumented answers. General questions can be answered directly.
- v3: v2 with stemmed BM25 and a rule requiring two searches with different terms that found nothing relevant before declaring something undocumented.
| Score (trials scored) | v1 | v2 | v3 |
|---|---|---|---|
| Search decision (57) | 0.895 | 0.947 | 0.947 |
| Context recall (45 labeled) | 0.967 | 0.867 | 0.933 |
| Faithfulness (45 / 42 / 42) | 0.924 | 0.948 | 0.929 |
| Correctness (57) | 0.930 | 0.842 | 0.895 |
Recall covers the 45 trials with relevant-section labels. Faithfulness covers those trials minus any with no retrieved context: v2 skipped Python twice and Alpine once; v3 skipped Python three times. General and unanswerable questions are excluded from both metrics in this implementation.
v2 had the highest faithfulness and lowest correctness. We grouped wrong answers by their first failing layer:
| First failing layer | v1 | v2 | v3 |
|---|---|---|---|
| Search decision (missed search) | 0 | 3 | 3 |
| Retrieval | 3 | 6 | 0 |
| Evidence use | 1 | 0 | 3 |
v1 searched unnecessarily on all six general-question trials without making their answers wrong. Its Friday query, "shipping schedule payments change," retrieved payments timeouts, not the freeze section. Reference-query recall was 1.0, showing that the required sections were reachable.
v2 eliminated unnecessary searches but skipped needed searches on Python twice and Alpine once. It also missed relevant evidence on Friday and Kafka questions. For Kafka, "replay missed events payments.ledger" returned nothing. A second query, "application logs access," retrieved log retention, and the answer claimed replay was undocumented while describing log availability.
These Kafka trials were scored for faithfulness. Across v2's six retrieval-failure answers, faithfulness ranged from 0.67 to 1.0 because many claims restated retrieved sections. The three missed-search trials were excluded, helping explain the high average despite poor correctness.
v3 resolved the two observed retrieval-failure cases. Its Friday query changed and retrieved the freeze section, an improvement under combined changes. For Kafka, the identical first query now returned the Kafka retention section, isolating the retriever change.
Python still failed all three trials without a search, despite one-shot recall of 1.0. The refund question exposed evidence misuse: v3 retrieved the right section but said refunds retry at most twice, then said non-idempotent calls such as refunds never retry. Faithfulness was 0.5; correctness failed.
Localize a failure from the trace
Walk each failing row through the layers, using the scores as pointers rather than automatic diagnoses:
- No search when required. Check the decision label, then routing, prompt and tool description. High one-shot recall makes a forced first search a candidate, not a proven fix. We did not test tool_choice="required"; it would also add searches to general questions. Rerun the evaluation before adopting it.
- Searches ran, recall is below 1. Inspect queries and reference-query recall. Good reference queries suggest checking the agent's formulation or retriever sensitivity. v2's reasonable payments.ledger query improved after the tokenizer change. If reference queries also miss, check labels and corpus coverage before changing indexing or chunking.
- Recall is 1, faithfulness is low. Inspect unsupported claims. Separate genuine evidence misuse from citation artifacts or facts repeated from the question.
- Only correctness fails. Compare answer completeness with the question, then inspect the reference and judge. In our initial runs, one question failed every trial because its reference demanded more facts than the question asked for.
In Laminar, open a failing row in the evaluation run to read its trace beside its scores. In the SQL editor, query evaluation_trials for trials with no search spans. trace_spans contains span names from the trial's trace:
SELECT
task_id,
simpleJSONExtractFloat(scores, 'correctness') AS correct,
arrayCount(s -> tupleElement(s, 'name') = 'search_docs', trace_spans) AS searches
FROM evaluation_trials
WHERE evaluation_id = '<evaluation_id>'
AND searches = 0
ORDER BY task_id
On v3, this returns six general-question trials with correct = 1 and three Python trials with correct = 0. The result depends on keeping evaluator retrieval calls out of search_docs spans.
Keep versions in one group_name. Run comparison then shows per-row changes, including the Python and payments.ledger regressions from v1 to v2.
When a fixed-pipeline RAG eval is enough
If the agent always retrieves once before answering, start with retrieval, faithfulness and correctness checks. Without an optional search decision, you do not need a separate decision score.
Conditional search needs an explicit decision check. Multiple searches require preserving queries, results and sequence. In this experiment, recall flagged retrieval failures and faithfulness flagged evidence-use failures, but the traces explained what happened.
For other tool and trajectory checks, see how to evaluate AI agents.
FAQ
Should I score faithfulness against the last search or all searches?
In this loop, all searches, because every result stays in the conversation. If your production agent truncates or summarizes earlier tool results, record what was available when it generated the answer. Score evidence use against that context, while retaining original search results for retrieval diagnostics.
Why can trials differ at temperature 0?
The Python question searched once and skipped twice in v2. Laminar groups each task's trials under one row with their average, so that variation stays visible. Don't rely only on the run average: inspect repeated trials for important questions, and distinguish changed agent behavior from changed judge scores.
How do I catch missed searches in production without labels?
Configure a Signal to look for suspicious trace patterns, such as a company-policy answer without search_docs, or an undocumented-answer claim after one empty search. Signals turn matching failures into structured events. These are review candidates, not measured search-decision accuracy without labels. For contradictions with tool results, see detecting hallucinations in AI agents.
Can I put these scores in CI?
Yes. When run as a script, evaluate() returns average scores that CI can compare with per-layer thresholds. Check scored and skipped counts too, so skipped faithfulness checks cannot look like an improvement. Our judge scored identical migration answers 1.0 and 0.67; allow for that variation rather than treating every small faithfulness change as a regression.