10B.5 DeepEval Tracing, Component-Level Evals and Agent Evaluation

ProductionLesson 5 of 1826,175 words14 parts
Module 10B · 0 of 7 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18

10B.2 taught DeepEval on finished, hand-written test cases. Real agents do not usually fail as one input and one output: the retriever returned nothing, the model chose the right tool with the wrong arguments, the planner looped, or a sub-agent never received the order id. This lesson is about evaluating that interior structure. In Part A you instrument an application with @observe, fill span and trace fields while the application runs, and evaluate individual components as well as the end-to-end result. In Part B you open up DeepEval's agent metrics: the trajectory judges that read the whole trace, the deterministic tool metrics, the multi-turn agent metrics and the MCP metrics. Every keyless sample in the lesson was run for real against deepeval 4.3.6 (the lesson was first written on 4.3.5 and every output reproduced unchanged) with the track's scripted FakeJudge and with network access blocked; several of them expose behaviour the documentation either does not mention or describes incorrectly. Each Output (real, ...) block sits directly under the code that produced it, so you can run every one of them yourself.

What you'll learn

  • What a DeepEval trace and span are, how they map to end-to-end, component-level and trajectory evaluation, and how they relate to the trajectory schema in 10A.7
  • How @observe records inputs, outputs, errors, tool calls, token counts, retriever settings, available tools and agent handoffs, including the exact keyword arguments accepted in 4.3.6
  • How update_current_span, update_current_trace, the typed update_*_span helpers, the next_*_span staging context managers, trace() and get_current_golden() work, and which documented parameters are silently ignored
  • How EvaluationDataset.evals_iterator() runs traced evaluations synchronously and asynchronously, what test cases DeepEval builds from spans and traces, how a failing component fails the golden, and how to recover the EvaluationResult from StopIteration.value
  • How traced assert_test(golden=...) behaves under deepeval test run, why span-only failures disappear from the console table and assertion message, and how to read them from .deepeval/.latest_test_run.json
  • How to browse a saved run with deepeval inspect, and why spans silently land in the wrong trace (or in none) when your code crosses an asyncio or thread boundary
  • Exactly what tracing does without a Confident AI key: nothing leaves the machine, export is a no-op, local evaluation still works, sampling affects export only, and masks receive raw Python objects
  • The OpenTelemetry architecture underneath modern DeepEval tracing, DEEPEVAL_AUTO_TRACE, framework integrations, and what DeepEval does not provide as a local observability backend
  • Every agent metric in 4.3.6: TaskCompletionMetric, StepEfficiencyMetric, PlanAdherenceMetric, PlanQualityMetric, ToolCorrectnessMetric, ArgumentCorrectnessMetric, ToolPermissionMetric, AgentLoopDetectionMetric, GoalAccuracyMetric, ToolUseMetric, TopicAdherenceMetric, the new ConversationToolCorrectnessMetric (4.3.6 only), MCPUseMetric, MultiTurnMCPUseMetric and MCPTaskCompletionMetric
  • How each metric computes its score, how many judge calls it makes, what prompt and which evidence the scoring call sees, which rubric anchors it is given, which numbers are not clamped, which metrics pass when no plan is visible, and which multi-turn units are silently skipped
  • What an exception inside a traced component does to evaluation (one case is a silent pass), and exactly where the deterministic loop detector goes blind
  • How nested agent spans represent multi-agent systems, what DeepEval can score per agent, what it cannot score about handoffs, and how that compares with 10A.12's handoff graders
  • How to choose, validate and defend these metrics rather than quoting a score because the package printed it

What you don't need

  • An API key. Every executable sample uses deterministic metrics or the shared FakeJudge from 10B.2, 3.5. That FakeJudge is not the function-style rag_eval.ScriptedJudge from 10A.6 or online.FakeJudge from 10A.9; those are evalkit teaching doubles with the same idea but a different interface.
  • A Confident AI account. Local tracing and local evaluation are the subject here. Production trace evaluation and dashboards are cloud features, surveyed rather than exercised; 10B.7 owns the platform and CI deep dive.
  • A running agent framework. The two framework integrations executed here (LangChain and LangGraph) use LangChain's fake chat model, not a provider. The integration table in Part 13 gives the verified import path and a wiring snippet for every other integration, marked as not executed; 10B.6 and later Inspect lessons do not depend on this one.
  • The basics of test cases, evaluate(), assert_test(), metric copying, judge construction, GEval, custom metrics or the built-in RAG metrics. Those belong to 10B.2, 10B.3 and 10B.4, and this lesson links rather than re-teaches them.
  • The theory of agent evaluation. 10A.7, Part 4 owns reference trajectories, constraints, pass rates and reliability; 10A.12 owns multi-agent handoff, attribution and simulator validity. Here those ideas are mapped onto DeepEval's implementation.

Setup

Continue in the track project created in 10B.1, or create a fresh project. DeepEval requires Python 3.10 or newer; the samples here ran on Python 3.13.

bash
uv init deepeval-lab --bare --python 3.13 && cd deepeval-lab   # first time only
uv add deepeval
uv add mcp langchain-core langgraph   # only for the MCP, LangChain and LangGraph samples
# or: pip install deepeval mcp langchain-core langgraph

Use the same .env line as the rest of the track:

bash
# .env
DEEPEVAL_TELEMETRY_OPT_OUT=1

Before the first sample, copy fake_judge.py unchanged from your 10B.2 work into the project folder; the samples import it as from fake_judge import FakeJudge. Also save the 19-line guard below as netguard.py in the same folder. Every sample in this lesson starts with import netguard; it makes any attempt to open a network connection raise an error, and prints a one-line count to stderr when the program exits. That count is the [netguard] total blocked attempts: 0 [] line at the end of each output: it is how this lesson proves that keyless tracing sends nothing anywhere.

python
"""Block and log every outbound network connection (proves keyless runs stay local)."""
import socket, sys
ATTEMPTS = []
_orig_connect = socket.socket.connect
_orig_gai = socket.getaddrinfo
def _connect(self, addr):
    ATTEMPTS.append(("connect", addr))
    print(f"[netguard] BLOCKED connect to {addr}", file=sys.stderr)
    raise OSError("netguard: network blocked")
def _gai(host, *a, **k):
    if host not in ("localhost", "127.0.0.1", None):
        ATTEMPTS.append(("dns", host))
        print(f"[netguard] BLOCKED DNS {host}", file=sys.stderr)
        raise socket.gaierror("netguard: dns blocked")
    return _orig_gai(host, *a, **k)
socket.socket.connect = _connect
socket.getaddrinfo = _gai
import atexit
atexit.register(lambda: print(f"[netguard] total blocked attempts: {len(ATTEMPTS)} {sorted(set(str(a[1]) for a in ATTEMPTS))}", file=sys.stderr))

If you do not want the guard, delete the import netguard line from a sample; only the last output line changes. If you run them outside a uv project, use uv run --no-project --with deepeval python -E -s <file>.py (add --with mcp, --with langchain-core or --with langgraph for those samples). -E -s keeps the script folder importable without the isolation surprises discussed in 10B.2.

Versions: the API facts in this lesson were first checked against deepeval 4.3.5 (24 November 2026) and every sample was then re-run on deepeval 4.3.6 (25 November 2026, with confident-trace 0.1.15, mcp and langchain-core as resolved by uv that day) with identical output, apart from one new field ("turn": null on tool calls in the 8.2 trace JSON). 4.3.6 adds ConversationToolCorrectnessMetric (covered in 11.5) and an assert_test classifiers parameter, adds flaky and evaluation_template parameters to the agent metrics, and moved red teaming back into DeepEval; 10B.7 owns that change. Statements below that say "in 4.3.5" were verified on 4.3.5 and re-verified on 4.3.6. DeepEval moves quickly; treat API details here as versioned facts, not permanent truth.


What you must be able to do after this lesson#

  • Explain the difference between a trace, a span and _trace_dict, and name the real span types
  • Instrument an app with @observe and fill test-case data with update_current_span and update_current_trace
  • Run a traced evaluation end to end and read its results
  • Design a component-level eval that scores one span instead of the whole trace
  • Choose a trajectory or tool metric such as Task Completion or Tool Correctness for an agent failure
  • Validate and defend an agent eval score before reporting it

Why this matters for an AI engineer#

This lesson is about scoring spans in an eval: turning the nested steps of one agent run into test cases, then grading them. It does not teach tracing itself. What a trace is for, how OpenTelemetry works and which vendor-neutral tools to send spans to are taught in 11A.1 (the GenAI span and attribute conventions are in sections 3.7 to 3.13, the backends and OTLP in sections 5.5 to 5.11). Read that first if spans are new to you. Here you learn what DeepEval adds on top: metrics that run on spans and fail the run.

You'll hear... You'll understand it after...
"The answer is right, but why did it take nine tool calls?" Part 9 and 10.4
"The retriever passed in isolation but the RAG eval fails." Part 4 and Part 7
"Can we evaluate just the LLM step inside the chain?" 2.4 and 5.1
"The trace looks fine, but Task Completion hallucinated what happened." 8.3
"Plan Adherence is 1.0, so the agent planned well." 9.4
"The pytest table passed, yet CI failed." 5.5
"We use LangGraph, CrewAI or the OpenAI Agents SDK. Do we rewrite tracing?" Part 13
"What leaves our network if we trace locally?" Part 6
"Which agent metric should I use, and when should I not trust it?" Part 14

Part 1: Traces, spans and the three scopes of evaluation#

1.1 The object model in one picture#

A trace is one end-to-end run of your application for one logical input. A span is one nested unit of work inside that run: an agent step, an LLM call, a retrieval, a tool invocation, or any custom operation you choose to name. Spans form a tree. The root is usually the agent or application entry point; children are the operations it invoked.

flowchart TD
    T["Trace: one user request"] --> A["agent span<br/>support_agent"]
    A --> L["llm span<br/>choose next action"]
    A --> R["retriever span<br/>search policy chunks"]
    A --> W["tool span<br/>lookup_order"]
    W --> DB["custom span<br/>orders database query"]
    A --> G["llm span<br/>write answer"]

For evaluation, the tree is more than a debugging picture. DeepEval turns it into test cases at three scopes:

Scope Where the metric is declared What the metric receives Typical question
End-to-end evals_iterator(metrics=...), trace(metrics=...), or ordinary evaluate(test_cases) Trace-level fields: input, output, retrieval context, tool list, golden metadata Did the whole run satisfy the user?
Component-level @observe(metrics=...), update_current_span(metrics=...), or next_*_span(metrics=...) One span's fields; trace-aware metrics also receive that span's subtree Did this retriever, model call, tool or sub-agent do its job?
Trajectory Trace level, using a metric whose class sets requires_trace = True Trace-level fields plus _trace_dict, the nested span tree as JSON Was the sequence of actions complete, efficient, planned and non-looping?

The crucial implementation fact is that component metrics are not annotations for later human review. They execute during the evaluation run and their failures roll up into the golden's pass/fail result. In the first full sample, one failed retriever span makes the whole golden fail even though every trace-level metric passes.

1.2 Why this lesson treats tracing as evaluation infrastructure#

In this lesson a trace is evaluation input, not a monitoring product. 11A.1 teaches tracing for production; this section only explains how scoring spans differs from grading a recorded run. The trace shapes for model, tool, retrieval and agent runs are in 11A.1, 3.11.

10A.7, 10.4 already taught the framework-neutral version: a trace has no world state, arguments may be redacted or hashed, and the tree must be adapted into a Trajectory before outcome and process graders can run. DeepEval's choice is different in three ways:

  1. The trace is captured in-process by decorators or framework instrumentation, not reconstructed from a separate JSONL log.
  2. Test-case fields are filled while the application runs, so retrieval context and expected tools can be attached exactly where they are produced.
  3. Some metrics read the raw nested tree (_trace_dict) rather than a flattened sequence of tool calls.

That is convenient, but it does not remove the limits from 10A.7. A span saying issue_refund returned success is evidence that the tool returned success, not independent proof that the refund row is correct in the system of record. For outcome correctness you still need state checks or goldens. Trajectory metrics answer process questions: did the agent use the right path, arguments, plan and number of steps.

1.3 The 4.x architecture: confident-trace, OpenTelemetry and the span bridge#

Since DeepEval 4.x, @observe is implemented on top of confident-trace, a small OpenTelemetry-first tracing package that DeepEval depends on. deepeval.tracing.otel.setup.ensure_confident_trace() initializes it once, installs span processors, and adds a DeepEval-specific span bridge. The bridge collects spans belonging to DeepEval traces in-process and converts them into DeepEval objects (AgentSpan, LlmSpan, RetrieverSpan, ToolSpan or plain BaseSpan). Those objects are what evaluation reads.

There are therefore two paths for a span:

flowchart LR
    A["your function or framework event"] --> B["confident-trace / OTel span"]
    B --> C["DeepEval span bridge<br/>in-process objects"]
    C --> D["local metrics and test-run JSON"]
    B --> E["RemoteSpanExporter"]
    E --> F{"Confident API key<br/>and export enabled?"}
    F -- no --> G["export returns success<br/>without network I/O"]
    F -- yes --> H["OTLP export to Confident AI"]

The distinction explains several behaviours that otherwise look magical:

  • Local evaluation does not need the exporter. It reads the bridge's in-memory spans.
  • Spans consumed by an evaluation are marked local and are not exported.
  • Framework integrations are not separate tracing systems. LangChain, LlamaIndex, CrewAI, OpenAI Agents, Pydantic AI and the OTel-based integrations all feed confident-trace spans into the same bridge, so update_current_span and next_*_span still work.
  • Without a Confident AI key the exporter returns success without opening a connection. In every runnable sample in this lesson, a socket-blocking guard reported zero connection attempts.

How DeepEval span types map to OpenTelemetry GenAI spans. One trace can serve both monitoring and evaluation when the two vocabularies line up. The OpenTelemetry GenAI semantic conventions name each kind of span with gen_ai.operation.name. The table shows the nearest match for each DeepEval span type.

DeepEval type Nearest OTel GenAI operation OTel span kind Related OTel attributes
agent invoke_agent (an LLM drives the loop through tool calls) or invoke_workflow (your code defines the control flow, such as a graph). Span name: invoke_agent {gen_ai.agent.name} INTERNAL (CLIENT for a remote agent service) gen_ai.agent.name, gen_ai.agent.id; available tools map loosely to the opt-in gen_ai.tool.definitions
llm chat (also generate_content, text_completion). Span name: chat {gen_ai.request.model} CLIENT gen_ai.provider.name, gen_ai.request.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens
retriever retrieval. Span name: retrieval INTERNAL opt-in gen_ai.retrieval.query.text; no standard attribute for top_k or chunk_size
tool execute_tool. Span name: execute_tool {gen_ai.tool.name} INTERNAL gen_ai.tool.name, gen_ai.tool.description, opt-in gen_ai.tool.call.arguments and gen_ai.tool.call.result
custom (the default) no standard operation any your own span name and attributes

Read the table as a correspondence of ideas, not as a promise about what DeepEval writes. This lesson did not verify which gen_ai.* attributes DeepEval's own spans carry (unverified), and the DeepEval type is only a label that does not change scoring. In practice, instrument your app with the OTel names for monitoring, and use DeepEval spans (or an OTel-based integration that feeds them) when you want the same steps scored.

1.4 The first evalkit mapping#

The precise mapping from the course's framework-free harness is:

evalkit concept DeepEval equivalent Important difference
Trajectory and StepRecord from 10A.7, 2.4 Nested _trace_dict generated from @observe spans DeepEval keeps a tree, not only an ordered step list
trace_adapter.py spans to Trajectory Automatic conversion through confident-trace and the span bridge DeepEval captures in-process; no JSONL adapter is needed for local evals
per-step deterministic graders Span-level metrics DeepEval metrics can also call judges
run-level outcome graders Trace-level end-to-end metrics Same concept, but goldens and trace fields are merged in DeepEval-specific ways
reference trajectory matchers such as trajectory_align ToolCorrectnessMetric plus custom metrics DeepEval has no general reference-trajectory scorer beyond tool correctness
LLM rubric over a trajectory summary Task Completion, Step Efficiency, Plan metrics DeepEval judges read nested JSON and are reference-free
mas_eval.py multi-agent spans Nested type="agent" spans and agent_handoffs DeepEval has no built-in routing, context-transfer or handoff-timing grader

Keep this map in mind. Much of Part B is not "new evaluation theory"; it is a specific implementation of process grading, with sharp edges that you need to know before relying on it.


Part 2: Instrumenting with @observe#

2.1 The decorator and its real signature#

The entry point is deepeval.tracing.observe. It can wrap synchronous functions, coroutines, generators and async generators, with or without arguments:

python
from deepeval.tracing import observe

@observe
def normal_function(x: str) -> str:
    return x.upper()

@observe(type="tool", description="Look up an order")
def lookup_order(order_id: str) -> dict:
    return {"order_id": order_id, "status": "delivered"}

The verified 4.3.5 signature is:

text
observe(_func=None, *, metrics=None, metric_collection=None, type=None,
        _drop_if_root=False, _internal=False, **observe_kwargs)

metrics attaches component-level metrics. metric_collection is accepted for compatibility but ignored in 4.3.5; it is a Confident AI platform setting, not a local metric list. _drop_if_root and _internal are private machinery used by DeepEval's own instrumentation. Everything else in observe_kwargs is interpreted according to the span type, and unrecognized keys are silently ignored. That last sentence is the source of the most common documentation migration bug.

2.2 The four real span types#

SpanType has exactly four members in 4.3.5: "agent", "llm", "retriever" and "tool". Anything else, including omitting type, becomes type "custom" and is stored as a plain BaseSpan. There is no SpanType.CUSTOM enum member. The type determines which keyword arguments are recorded:

type Accepted @observe kwargs Typed helper for later updates
agent available_tools=[], agent_handoffs=[] update_agent_span(available_tools=..., agent_handoffs=...)
llm model=None, provider=None, cost_per_input_token=None, cost_per_output_token=None update_llm_span(model=..., input_token_count=..., output_token_count=..., cost_per_input_token=..., cost_per_output_token=..., token_intervals=..., prompt=...)
retriever embedder=None update_retriever_span(embedder=..., top_k=..., chunk_size=...)
tool description=None update_tool_span(description=...)

name="checkout-agent" overrides the span name; otherwise the function name is used.

prompt is accepted on some LLM-related objects for platform compatibility but is ignored locally in 4.3.5. If you need the prompt in a local trace, put it in the span input or metadata deliberately.

2.3 What gets recorded automatically#

When a decorated function finishes, DeepEval records:

  • input: the function's keyword-bound arguments as a dictionary
  • output: the return value
  • start and end times
  • status SUCCESS or ERRORED; on exception, the error string is recorded and the exception still propagates
  • for an agent span, tools_called derived from descendant tool spans that are not owned by a nested agent

The input rule surprises people. If the function is called as retrieve("refund policy", top_k=4), the span input is a dict such as {"query": "refund policy", "top_k": 4}. When DeepEval later builds a span test case it stringifies that dict, so the metric sees "{'query': 'refund policy', 'top_k': 4}" rather than just the query. Call update_current_span(input=query) when the metric should see a clean user input. Values set explicitly with update_current_span win over automatic values.

The automatic agent derivation is genuinely useful. In the CI sample later, the agent span's ToolCorrectnessMetric sees a ToolCall built from the child lookup_policy tool span without the application manually constructing tools_called. Expected tools still have to come from the golden or update_current_span(expected_tools=...); DeepEval cannot know which tools should have been called.

2.4 Metrics on a span#

A metric passed to a span is evaluated against a test case built from that span. This is component-level evaluation:

python
from deepeval.metrics import AnswerRelevancyMetric
from deepeval.tracing import observe, update_current_span

@observe(type="llm", model="support-model",
         metrics=[AnswerRelevancyMetric(model=judge, threshold=0.7)])
def generate(query: str, chunks: list[str]) -> str:
    answer = write_answer(query, chunks)       # your application code
    update_current_span(input=query, output=answer)
    return answer

Putting metrics on the outermost function still makes them span metrics. They do not become trace-level metrics merely because the span is the root. Trace-level metrics come from evals_iterator(metrics=...), trace(metrics=...), update_current_trace(metrics=...), or assert_test(golden=..., metrics=...).

A span metric should answer a question that the span can answer honestly:

Span type Good component metrics Poor uses
retriever Non-empty context, deterministic top-k shape checks, Contextual Precision/Recall/Relevancy when goldens are available Faithfulness of the final answer (that belongs to the generation step or end-to-end case)
llm Answer Relevancy, a custom schema or format metric, a narrow G-Eval over input and output Step Efficiency (it needs the whole trajectory)
tool Exact output shape, allowed arguments, side-effect status, latency or cost custom metrics Task Completion (the tool does not know the user's whole task)
agent Tool Correctness, permissions, sub-agent output checks, trace-aware metrics on the agent subtree A metric whose required evidence is outside that agent's boundary
custom Domain-specific invariants: parser valid, SQL read-only, redaction applied Using custom spans as a dumping ground because no type was chosen

2.5 Errors and exceptions#

If an observed function raises, the span status becomes ERRORED, the error string is stored, and the exception continues to your caller. During evaluation DeepEval skips the metrics of an errored span, and of every span in a trace whose root errored. What "skipped" does to the golden's pass or fail depends on where the exception ends up, and one of the three cases is a silent pass: an errored component whose exception your agent catches does not fail the golden. 4.5 runs all three cases and shows how to catch the silent one.

A second subtlety is generator output. The decorator has separate wrappers for generators and async generators, so work is traced as iteration happens. If your application only partially consumes a generator, the span may end differently from what you expect. For evaluation code, prefer returning materialized results from tool and retriever spans unless streaming itself is the property under test.

2.6 Methods, generators and the cost fields#

@observe works on methods, and the first parameter is not special. Because the decorator records every bound argument, self becomes part of the span input. DeepEval does not dump the object: it records the placeholder '<ClassName>'. Generators are wrapped separately, and the span output for a generator is the last item it yielded, not the whole stream. For an llm span, cost_per_input_token and cost_per_output_token are stored next to the token counts, but 4.3.6 does not multiply them for you locally: the run file holds the two rates and the two counts, and the dollar figure is yours to compute (here 1000 * 0.000002 + 200 * 0.00001 = 0.004).

python
# observe_methods_cost.py: @observe on methods and generators, and the cost fields (lesson 10B.5)
import json
from pathlib import Path

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import ExactMatchMetric
from deepeval.tracing import observe, update_current_trace, update_llm_span


class SupportBot:
    prefix = "Answer: "

    @observe(type="llm", model="fake-llm", cost_per_input_token=0.000002,
             cost_per_output_token=0.000010)
    def generate(self, query: str):
        update_llm_span(input_token_count=1000, output_token_count=200)
        return self.prefix + "5 business days"

    @observe(type="tool")
    def stream_words(self, text: str):
        yield from text.split()


@observe(type="agent")
def agent(query: str):
    bot = SupportBot()
    answer = bot.generate(query)
    words = list(bot.stream_words(answer))
    update_current_trace(input=query, output=answer, expected_output=answer)
    return words


dataset = EvaluationDataset(goldens=[Golden(input="refund window?", expected_output="Answer: 5 business days")])
for golden in dataset.evals_iterator(
        metrics=[ExactMatchMetric()], async_config=AsyncConfig(run_async=False),
        display_config=DisplayConfig(print_results=False, show_indicator=False,
                                     inspect_after_run=False)):
    agent(golden.input)

trace = json.loads(Path(".deepeval/.latest_test_run.json").read_text())["testRunData"]["testCases"][0]["trace"]
llm = trace["llmSpans"][0]
print("method span input:", llm["input"])
print("llm cost fields:", {k: llm.get(k) for k in ("inputTokenCount", "outputTokenCount",
                                                  "costPerInputToken", "costPerOutputToken")})
tool = trace["toolSpans"][0]
print("generator span input:", tool["input"], "| output:", tool["output"])
print("run cost:", json.loads(Path(".deepeval/.latest_test_run.json").read_text())["testRunData"].get("evaluationCost"))
Output · real, DeepEval banner omitted5 lines
method span input: {'self': '<SupportBot>', 'query': 'refund window?'}
llm cost fields: {'inputTokenCount': 1000.0, 'outputTokenCount': 200.0, 'costPerInputToken': 2e-06, 'costPerOutputToken': 1e-05}
generator span input: {'self': '<SupportBot>', 'text': 'Answer: 5 business days'} | output: days
run cost: None
[netguard] total blocked attempts: 0 []

Three consequences follow. First, add update_current_span(input=query) in methods too, otherwise a judge-based component metric sees "{'self': '<SupportBot>', 'query': ...}". Second, never put a streaming tool on a span that a metric must read in full: materialize it (list(...)) and return the list. Third, compute cost from the recorded rates and counts in your own reporting; the local run file has no cost column for a trace.


Part 3: Filling test-case data at runtime#

3.1 The two update functions#

Automatic capture records what the function received and returned. Evaluation usually needs more: the retrieved chunks, the expected tool list, a cleaned input, a thread id, or an expected answer read from the golden. DeepEval's two principal runtime functions are:

text
update_current_span(input=None, output=None, retrieval_context=None, context=None,
                    expected_output=None, tools_called=None, expected_tools=None,
                    metadata=None, name=None, integration=None, provider=None,
                    test_case=None, metric_collection=None, metrics=None)

update_current_trace(name=None, tags=None, metadata=None, thread_id=None, user_id=None,
                     input=None, output=None, retrieval_context=None, context=None,
                     expected_output=None, tools_called=None, expected_tools=None,
                     test_case=None, confident_api_key=None, test_case_id=None,
                     test_run_id=None, turn_id=None, metric_collection=None, metrics=None)

The field names mostly match LLMTestCase from 10B.2, Part 2, with one renaming: the test-case field actual_output is called output on spans and traces. test_case= copies the usual seven fields (input, actual_output, expected_output, retrieval_context, context, tools_called, expected_tools) from an existing test-case object.

Two rules are more important than the long parameter list:

  1. Falsy values are ignored. The implementation is effectively if input: span.input = input. You cannot clear a field by passing "", [], {} or 0. This is not a typing accident; it is the runtime behaviour. If a metric requires the distinction between "empty retrieval" and "no retrieval field set", encode that distinction in metadata or use a non-empty sentinel.
  2. Outside a span or trace, the call is a silent no-op. There is no exception telling you that the decorator was forgotten or that the context was lost across an incorrect thread boundary. A missing update usually appears later as MissingTestCaseParamsError, or worse as a metric reading the wrong automatic input.

Several parameters are accepted but ignored in 4.3.5 because they are Confident AI platform settings: metric_collection on both functions, and user_id, confident_api_key, test_case_id, test_run_id and turn_id on update_current_trace. Treat them as dead compatibility surface. They are useful only when reading older examples, not when designing local evaluation.

3.2 The typed span helpers#

The type-specific helpers fill fields that generic test cases do not have:

python
from deepeval.tracing import (
    update_agent_span,
    update_llm_span,
    update_retriever_span,
    update_tool_span,
)

update_agent_span(available_tools=["lookup_order"], agent_handoffs=["billing-agent"])
update_llm_span(model="support-model", input_token_count=512, output_token_count=96)
update_retriever_span(embedder="text-embedding-local", top_k=4, chunk_size=800)
update_tool_span(description="Read-only order status lookup")

Use them for evidence, not for decoration. Token counts matter when you analyse cost; available_tools matters when Tool Correctness judges selection rather than mere recall; agent_handoffs matters when you inspect multi-agent structure. The helpers update the current span only if it is the matching type. Calling update_llm_span inside a tool span cannot retroactively make the tool an LLM.

3.3 next_*_span: staging values for code you do not own#

Sometimes the span is opened inside a library rather than inside your own decorated function. DeepEval's staging context managers let you attach data to the next span of a type before it starts:

python
from deepeval.metrics import AnswerRelevancyMetric
from deepeval.tracing import next_llm_span, next_tool_span

with next_llm_span(metrics=[AnswerRelevancyMetric(model=judge)]):
    answer = chain.invoke({"q": query}, config={"callbacks": [handler]})

with next_tool_span(metadata={"tenant": "acme"}):
    charge_card(...)

The available forms are next_span, next_llm_span, next_tool_span, next_retriever_span and next_agent_span. Each one accepts everything update_current_span takes plus its type's own fields. This is the correct way to put a component metric on a framework-created LLM span. It is also easy to misuse, and the 4.3.6 source (deepeval/tracing/context.py) spells out three rules that the probe below confirms:

  1. One-shot. The staged values are consumed by the first span of that type opened inside the block. A second model or tool call in the same with block receives nothing.
  2. More specific wins, field by field. When next_span(...) and a typed next_tool_span(...) are both active, the two payloads are merged with the typed one last. The merge replaces whole fields: a typed metadata={...} replaces the base metadata dict, it does not merge the keys.
  3. Discarded on exit. If no matching span opens inside the block, the staged values are silently dropped when the block ends.
python
# next_span_oneshot.py: next_*_span values go to the first matching span only (lesson 10B.5)
import json
from pathlib import Path

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import ExactMatchMetric
from deepeval.tracing import next_span, next_tool_span, observe, update_current_trace


@observe(type="tool")
def search(query: str):
    return [query]


@observe(type="agent")
def agent(query: str):
    with next_span(metadata={"staged_by": "next_span", "tier": "base"}), \
         next_tool_span(metadata={"staged_by": "next_tool_span"}):
        search("first call")
        search("second call")          # same with block, second tool span
    update_current_trace(input=query, output="ok", expected_output="ok")
    return "ok"


dataset = EvaluationDataset(goldens=[Golden(input="q")])
for golden in dataset.evals_iterator(
        metrics=[ExactMatchMetric()], async_config=AsyncConfig(run_async=False),
        display_config=DisplayConfig(print_results=False, show_indicator=False,
                                     inspect_after_run=False)):
    agent(golden.input)

trace = json.loads(Path(".deepeval/.latest_test_run.json").read_text())["testRunData"]["testCases"][0]["trace"]
for span in trace["toolSpans"]:
    print(span["input"]["query"], "->", span.get("metadata"))
Output · real, DeepEval banner omitted3 lines
first call -> {'staged_by': 'next_tool_span'}
second call -> None
[netguard] total blocked attempts: 0 []

The first tool span received the typed payload, which replaced the base metadata wholesale (the "tier" key is gone). The second tool span got nothing. When you control the calls, open one with next_llm_span(...) block per call. When a single framework call (one chain.invoke(...)) makes two model calls internally, only the first receives the staged metric; for the others, use an integration object that accepts metrics itself (13.3) or evaluate at trace level.

3.4 trace() and get_current_golden()#

Most examples in this lesson use evals_iterator, which opens a trace wrapper for each golden. You can also open or join a trace yourself:

python
from deepeval.tracing import trace

with trace(name="support-agent", tags=["production"], input=query):
    answer = support_agent(query)

trace() accepts the trace fields already listed (input, output, retrieval_context, context, expected_output, tools_called, expected_tools, metrics, and so on), plus two span-context objects for advanced use. If a trace is already open (as it is inside evals_iterator) it joins that trace instead of starting a new one, and its metrics= become trace-level metrics. It is a synchronous context manager, and it prints a warning when used inside an async def because manually scoped trace context and concurrent coroutines are easy to mix incorrectly. This sample shows both behaviours; note that the iterator itself is given no metrics, so trace(metrics=...) is the only metric source:

python
# trace_manual.py: trace() joins the golden's trace and declares trace metrics (lesson 10B.5)
import asyncio
import json
from pathlib import Path

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import ExactMatchMetric
from deepeval.tracing import observe, trace, update_current_trace


@observe(type="agent")
def support_agent(query: str):
    return "Refunds take 5 business days."


dataset = EvaluationDataset(goldens=[Golden(input="How long does a refund take?",
                                            expected_output="Refunds take 5 business days.")])
for golden in dataset.evals_iterator(
        async_config=AsyncConfig(run_async=False),          # no metrics=... here
        display_config=DisplayConfig(print_results=False, show_indicator=False,
                                     inspect_after_run=False)):
    with trace(name="support-agent", tags=["manual"], input=golden.input,
               expected_output=golden.expected_output, metrics=[ExactMatchMetric()]):
        update_current_trace(output=support_agent(golden.input))

run = json.loads(Path(".deepeval/.latest_test_run.json").read_text())["testRunData"]
case = run["testCases"][0]
print("traces recorded:", len(run["testCases"]))
print("trace name and tags:", case["trace"].get("name"), case["trace"].get("tags"))
print("trace metric:", [(m["name"], m["score"], m["success"]) for m in case["metricsData"]])


async def inside_async():
    with trace(name="async-misuse"):
        await asyncio.sleep(0)

asyncio.run(inside_async())
Output · real, DeepEval banner omitted9 lines
traces recorded: 1
trace name and tags: support-agent ['manual']
trace metric: [('Exact Match', 1.0, True)]
[Confident AI Trace Log]  Warning: Detected use of the synchronous 'trace' 
context manager within an async method: Wrapping an async method with the 
synchronous 'trace' context manager may lead to unexpected behavior. 
To disable dev logging, set CONFIDENT_TRACE_VERBOSE=0 as an environment 
variable.
[netguard] total blocked attempts: 0 []

One trace was recorded, not two: the with trace(...) block joined the golden's trace and renamed it. For evaluation datasets, prefer evals_iterator or traced assert_test with the metrics on the iterator; use trace() when you need to scope a trace by hand, for example around code you cannot decorate.

Inside an evaluation, get_current_golden() returns the golden currently being executed:

python
from deepeval.dataset import get_current_golden

@observe(type="agent")
def support_agent(query: str):
    golden = get_current_golden()
    expected = golden.expected_output if golden else None
    ...

This is how application code can copy gold standard evidence into the trace at the exact component boundary where it is needed. It is powerful and dangerous. If the application behaviour itself branches on get_current_golden(), you have contaminated the system under test with the answer key. Use it to attach expectations and reference context to spans, not to change retrieval, tool choice or generation.

3.5 A runtime-fields probe, run for real#

The following sample exercises the typed helpers, the falsy-update rule and get_current_golden(). It uses ExactMatchMetric, so no judge model is needed at all. Save it as runtime_fields.py; it reads the run file that evals_iterator writes into .deepeval/, so run it from the project folder.

python
# runtime_fields.py: typed span updates, falsy updates and get_current_golden (lesson 10B.5)
import json
from pathlib import Path

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden, get_current_golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import ExactMatchMetric
from deepeval.tracing import (observe, update_agent_span, update_current_span,
                              update_current_trace, update_llm_span,
                              update_retriever_span, update_tool_span)


@observe(type="retriever")
def retrieve(query: str):
    chunks = ["Refunds are issued within 5 business days."]
    update_current_span(input=query, retrieval_context=chunks)
    update_current_span(retrieval_context=[])       # falsy: ignored, does not clear the chunks
    update_retriever_span(top_k=1, chunk_size=240)
    return chunks


@observe(type="tool")
def lookup_order(order_id: str):
    update_tool_span(description="Read-only order status lookup")
    return {"order_id": order_id, "status": "delivered"}


@observe(type="llm")
def draft(query: str, chunks: list[str]):
    answer = chunks[0] if chunks else "I do not know."
    update_llm_span(model="fake-llm", input_token_count=21, output_token_count=8)
    update_current_span(input=query, output=answer)
    update_current_span(output="")                  # falsy: ignored, does not clear the answer
    return answer


@observe(type="agent", agent_handoffs=["billing-agent"])
def agent(query: str):
    golden = get_current_golden()
    print("golden visible inside agent:", golden.input if golden else None)
    lookup_order("A-1")
    answer = draft(query, retrieve(query))
    update_agent_span(available_tools=["lookup_order"], agent_handoffs=["billing-agent"])
    update_current_trace(input=query, output=answer,
                         expected_output=golden.expected_output)
    return answer


dataset = EvaluationDataset(goldens=[Golden(
    input="How long does a refund take?",
    expected_output="Refunds are issued within 5 business days.")])
for golden in dataset.evals_iterator(
        metrics=[ExactMatchMetric()],
        async_config=AsyncConfig(run_async=False),
        display_config=DisplayConfig(print_results=False, show_indicator=False, inspect_after_run=False)):
    agent(golden.input)

run = json.loads(Path(".deepeval/.latest_test_run.json").read_text())["testRunData"]
trace = run["testCases"][0]["trace"]
agent_span = trace["agentSpans"][0]
llm_span = trace["llmSpans"][0]
retriever_span = trace["retrieverSpans"][0]
tool_span = trace["toolSpans"][0]
print("agent handoffs:", agent_span.get("agentHandoffs"), "tools:", agent_span.get("availableTools"))
print("llm fields:", {k: llm_span.get(k) for k in ("model", "inputTokenCount", "outputTokenCount", "input", "output")})
print("retriever fields:", {k: retriever_span.get(k) for k in ("topK", "chunkSize", "retrievalContext")})
print("tool description:", tool_span.get("description"))
Output · real, DeepEval banner omitted7 lines
golden visible inside agent: How long does a refund take?

agent handoffs: ['billing-agent'] tools: ['lookup_order']
llm fields: {'model': 'fake-llm', 'inputTokenCount': 21.0, 'outputTokenCount': 8.0, 'input': 'How long does a refund take?', 'output': 'Refunds are issued within 5 business days.'}
retriever fields: {'topK': 1, 'chunkSize': 240, 'retrievalContext': ['Refunds are issued within 5 business days.']}
tool description: Read-only order status lookup
[netguard] total blocked attempts: 0 []

The two falsy updates did not clear the non-empty retrieval context or answer. If you need an explicit empty value to be semantically different, do not rely on update_current_span to preserve it.

3.6 Metadata and tags are not metric fields#

The tracing documentation has historically blurred this point. In 4.3.5 the test case built for a span contains the ordinary test-case fields only: input, actual output, expected output, context, retrieval context, tools called and expected tools. A custom metric cannot read span.metadata through test_case.metadata, because that field is not copied there. At trace level the metric's metadata comes from the golden's additional_metadata, not from update_current_trace(metadata=...).

That does not make metadata useless. It is stored in the trace and exported run, and it is invaluable for debugging. It just is not part of the metric evidence contract. If a metric must know a tenant, model version or prompt variant, put it in a field the metric contract actually receives, or use a custom metric that closes over the value when constructed. For run-level attribution use hyperparameters, covered in 10B.2, 7.1 and the pytest hooks in 10B.2, Part 5.


Part 4: A first traced evaluation end to end#

4.1 The application: a tiny support RAG agent#

The first complete sample is deliberately small, but its shape is the shape of a real support agent. A retriever span finds policy text, a tool span looks up an order, an LLM span writes the answer, and an agent span orchestrates them. Two component metrics are attached inside the application: a deterministic "did retrieval return anything?" metric on the retriever, and Answer Relevancy on the generation span. Three trace-level trajectory metrics are passed to the iterator.

The custom metric is a plain BaseMetric implementation. 10B.3, Part 6 owns that contract, so the important part here is not the class boilerplate: it is that a metric can be attached exactly to the component it understands.

python
# trace_component_eval.py: a keyless traced RAG agent with span and trace metrics (lesson 10B.5)

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import (AnswerRelevancyMetric, BaseMetric, PlanAdherenceMetric,
                              StepEfficiencyMetric, TaskCompletionMetric)
from deepeval.test_case import LLMTestCase
from deepeval.tracing import observe, update_current_span, update_current_trace

from fake_judge import FakeJudge


class NonEmptyContext(BaseMetric):
    """Deterministic component metric: did this retriever span return anything?"""

    def __init__(self, threshold=1.0):
        self.threshold = threshold

    def measure(self, test_case: LLMTestCase, *args, **kwargs):
        count = len(test_case.retrieval_context or [])
        self.score = 1.0 if count else 0.0
        self.reason = f"{count} chunks retrieved"
        self.success = self.score >= self.threshold
        return self.score

    async def a_measure(self, test_case, *args, **kwargs):
        return self.measure(test_case, *args, **kwargs)

    def is_successful(self):
        return self.success

    @property
    def __name__(self):
        return "Non-empty context"


DOCS = {
    "refund": "Refunds are issued within 5 business days.",
    "shipping": "Standard shipping takes 3-5 days.",
}

judge = FakeJudge(script={
    "TaskAndOutcome": [
        {"task": "Tell the user the refund window", "outcome": "Agent answered: 5 business days"},
        {"task": "Tell a joke", "outcome": "Agent said it did not know"},
    ],
    "TaskCompletionVerdict": [
        {"verdict": 0.9, "reason": "Outcome satisfies the task."},
        {"verdict": 0.9, "reason": "Outcome satisfies the task."},
    ],
    "Task": [
        {"task": "Tell the user the refund window"},
        {"task": "Tell the user the refund window"},
        {"task": "Tell a joke"},
        {"task": "Tell a joke"},
    ],
    "EfficiencyVerdict": [
        {"score": 0.75, "reason": "One redundant step."},
        {"score": 0.75, "reason": "One redundant step."},
    ],
    "AgentPlan": [{"plan": []}, {"plan": []}],
    "Statements": [
        {"statements": ["Refunds take 5 business days."]},
        {"statements": ["I don't know."]},
    ],
    "Verdicts": [
        {"verdicts": [{"verdict": "yes"}]},
        {"verdicts": [{"verdict": "yes"}]},
    ],
    "AnswerRelevancyScoreReason": [
        {"reason": "The answer is on-topic."},
        {"reason": "The answer is on-topic."},
    ],
})


@observe(type="retriever", embedder="fake-embedder", metrics=[NonEmptyContext()])
def retrieve(query: str):
    chunks = [text for key, text in DOCS.items() if key in query.lower()]
    update_current_span(input=query, retrieval_context=chunks)
    return chunks


@observe(type="tool", description="Look up an order")
def lookup_order(order_id: str):
    return {"order_id": order_id, "status": "delivered"}


@observe(type="llm", model="fake-llm", metrics=[AnswerRelevancyMetric(model=judge, threshold=0.5)])
def generate(query: str, chunks):
    answer = "Refunds take 5 business days." if chunks else "I don't know."
    update_current_span(input=query, output=answer)
    return answer


@observe(type="agent", available_tools=["lookup_order"])
def agent(query: str):
    lookup_order("A1")
    chunks = retrieve(query)
    answer = generate(query, chunks)
    update_current_trace(name="support-agent", tags=["lesson"], metadata={"version": 1},
                         input=query, output=answer)
    return answer


dataset = EvaluationDataset(goldens=[
    Golden(input="How long does a refund take?"),
    Golden(input="Tell me a joke"),
])
trace_metrics = [
    TaskCompletionMetric(model=judge),
    StepEfficiencyMetric(model=judge),
    PlanAdherenceMetric(model=judge),
]

count = 0
for golden in dataset.evals_iterator(
        metrics=trace_metrics,
        async_config=AsyncConfig(run_async=False),
        display_config=DisplayConfig(inspect_after_run=False)):
    agent(golden.input)
    count += 1

print("iterated", count)
print("judge calls:", judge.schemas())
for metric in trace_metrics:
    print(metric.__name__, metric.score, "|", metric.reason)
Output · real, golden 1 boxes and banner omitted33 lines
│  ❌ test_case_2                                                              │
│  ├──   Input:            Tell me a joke                                      │
│  │     Actual Output:    I don't know.                                       │
│  └── Metrics                                                                 │
│       Status ┃ Metric          ┃ Score ┃ Threshold ┃ Reason                  │
│      ━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━  │
│        PASS  │ Task Completion │ 0.90  │ 0.50      │ Outcome satisfies the   │
│              │                 │       │           │ task.                   │
│        PASS  │ Step Efficiency │ 0.75  │ 0.50      │ One redundant step.     │
│        PASS  │ Plan Adherence  │ 1.00  │ 0.50      │ There were no plans     │
│              │                 │       │           │ to evaluate within      │
│              │                 │       │           │ the trac...             │
│  ❌ retrieve                                                                 │
│  ├──   Input:            Tell me a joke                                      │
│  │     Actual Output:    []                                                  │
│  └── Metrics                                                                 │
│       Status  ┃ Metric            ┃ Score ┃ Threshold ┃ Reason               │
│      ━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━  │
│        FAIL   │ Non-empty context │ 0.00  │ 1.00      │ 0 chunks retrieved   │
│  Task Completion    │ 0.90          │ 100.00% | passed=2 | failed=0 │ 2      │
│  Step Efficiency    │ 0.75          │ 100.00% | passed=2 | failed=0 │ 2      │
│  Plan Adherence     │ 1.00          │ 100.00% | passed=2 | failed=0 │ 2      │
│  Answer Relevancy   │ 1.00          │ 100.00% | passed=2 | failed=0 │ 2      │
│  Non-empty context  │ 0.50          │ 50.00% | passed=1 | failed=1  │ 2      │
✓ Evaluation completed 🎉! (time taken: 0.09s | token cost: None)
» Test Results (2 total tests):
   » Pass Rate: 50.0% | Passed: 1 | Failed: 1
iterated 2
judge calls: ['TaskAndOutcome', 'TaskCompletionVerdict', 'Task', 'EfficiencyVerdict', 'Task', 'AgentPlan', 'Statements', 'Verdicts', 'AnswerRelevancyScoreReason', 'TaskAndOutcome', 'TaskCompletionVerdict', 'Task', 'EfficiencyVerdict', 'Task', 'AgentPlan', 'Statements', 'Verdicts', 'AnswerRelevancyScoreReason']
Task Completion 0.9 | Outcome satisfies the task.
Step Efficiency 0.75 | One redundant step.
Plan Adherence 1 | There were no plans to evaluate within the trace of your agent's execution. Please check if the agent's planning or reasoning or thinking is stored in any one of the trace attributes.
[netguard] total blocked attempts: 0 []

4.2 How to read that result#

The second golden fails even though Task Completion, Step Efficiency, Plan Adherence and Answer Relevancy pass. The reason is the retriever component: no document key occurs in "Tell me a joke", chunks is empty, and NonEmptyContext scores 0. DeepEval updates the enclosing test-case status for span metrics as well as trace metrics. This is the central value proposition of component-level evaluation: a failing internal component cannot hide behind a plausible final answer.

The result also reveals three things you should not over-read:

  1. The trace metrics were scripted to pass. In a real run they might fail too, but the rollup rule would be the same.
  2. The span boxes in the 4.3.5 console can show a red header even when all metrics inside them pass. Read the per-metric rows and the JSON, not the decorative glyph.
  3. The judge-call order shown here is an execution detail of this synchronous run, not a contract. What matters is the count, which you can read off the judge calls: line for one golden: Task Completion makes two calls (TaskAndOutcome, TaskCompletionVerdict), Step Efficiency two (Task, EfficiencyVerdict), Plan Adherence two (Task, AgentPlan: the plan came back empty, so there was no evaluation call, see 9.4) and Answer Relevancy three (Statements, Verdicts, AnswerRelevancyScoreReason). With a plan in the trace Plan Adherence makes three calls.

The pasted box lines come from the second golden's console output, and the Answer Relevancy summary row aggregates both goldens. The first golden's boxes are omitted because they only repeat the same pass rows.

4.3 What test cases DeepEval built#

For the trace-level metrics, DeepEval combines golden and trace fields approximately as follows:

text
LLMTestCase(
    input=golden.input,
    actual_output=str(trace.output),
    expected_output=trace.expected_output,
    context=trace.context,
    retrieval_context=trace.retrieval_context,
    tools_called=trace.tools_called,
    expected_tools=trace.expected_tools,
    metadata=golden.additional_metadata,
    comments=golden.comments,
    name=golden.name,
    expectations=golden.expectations,
)

For a span-level metric it uses the span's own fields:

text
LLMTestCase(
    input=str(span.input),
    actual_output=str(span.output),
    expected_output=span.expected_output,
    context=span.context,
    retrieval_context=span.retrieval_context,
    tools_called=span.tools_called,
    expected_tools=span.expected_tools,
)

Notice the str(...) conversion. A retriever input captured automatically as {"query": "Tell me a joke"} becomes the string representation of that dictionary unless you call update_current_span(input=query). This affects prompt wording for judge-based component metrics and exact matching for deterministic ones. Clean the input at the component boundary.

Now read the trace-level recipe again and notice which fields come from the golden: only input, additional_metadata, comments, name and expectations. The golden's expected_output, context, retrieval_context and expected_tools are not copied; the test case reads those from the trace (the 4.3.6 source builds it with expected_output=current_trace.expected_output in evaluate/execute/loop.py). A golden that carries an expected answer therefore does nothing for a reference-based metric until your code copies it:

python
# golden_fields.py: a golden's expected_output does not reach the trace test case by itself (lesson 10B.5)
import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden, get_current_golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import ExactMatchMetric
from deepeval.tracing import observe, update_current_trace


@observe(type="agent")
def agent(query: str, copy_expected: bool):
    answer = "Refunds take 5 business days."
    expected = get_current_golden().expected_output if copy_expected else None
    update_current_trace(input=query, output=answer, expected_output=expected)
    return answer


for copy_expected in (False, True):
    dataset = EvaluationDataset(goldens=[Golden(input="How long does a refund take?",
                                                expected_output="Refunds take 5 business days.")])
    metric = ExactMatchMetric()
    try:
        for golden in dataset.evals_iterator(
                metrics=[metric], async_config=AsyncConfig(run_async=False),
                display_config=DisplayConfig(print_results=False, show_indicator=False,
                                             inspect_after_run=False)):
            agent(golden.input, copy_expected)
        print(f"copy_expected={copy_expected}: Exact Match score={metric.score} success={metric.success}")
    except Exception as exc:
        print(f"copy_expected={copy_expected}: {type(exc).__name__}: {str(exc).splitlines()[0]}")
Output · real, DeepEval banner omitted3 lines
copy_expected=False: MissingTestCaseParamsError: 'expected_output' cannot be None for the 'Exact Match' metric
copy_expected=True: Exact Match score=1.0 success=True
[netguard] total blocked attempts: 0 []

This is the legitimate use of get_current_golden() from 3.4: copying expectations into the trace, never steering behaviour. The same applies at component level, where update_current_span(expected_tools=golden.expected_tools) is how a golden's tool expectations reach a span metric.

There is a quiet form of this trap. With ErrorConfig(skip_on_missing_params=True), a setting people add to silence exactly this error, a traced case whose golden expected_output was never copied does not stop the run: Exact Match is skipped on every case, metricsData is empty, and the run file still records the cases as passed. 10B.17, 4.7 runs it (three cases, three passed, zero scored metrics). Count scored metrics per case, not passed cases.

4.4 Why update_current_trace(output=...) is mandatory in the iterator#

The iterator itself opens a wrapper span. Your top-level application function is therefore not the trace root in the way intuition suggests, and the iterator does not treat your application's return value as the trace output. If you forget update_current_trace(output=...), a trace metric requiring ACTUAL_OUTPUT has no test case to evaluate. Save this as missing_trace_output.py; it does exactly that:

python
# missing_trace_output.py: the update_current_trace(output=...) pitfall (lesson 10B.5)

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import TaskCompletionMetric
from deepeval.tracing import observe

from fake_judge import FakeJudge

judge = FakeJudge(script={"TaskCompletionVerdict": [{"verdict": 1.0, "reason": "unused"}]})


@observe(type="agent")
def agent(query: str):
    return "Refunds take 5 business days."   # no update_current_trace(output=...)


dataset = EvaluationDataset(goldens=[Golden(input="How long does a refund take?")])
try:
    for golden in dataset.evals_iterator(
            metrics=[TaskCompletionMetric(model=judge)],
            async_config=AsyncConfig(run_async=False),
            display_config=DisplayConfig(print_results=False, inspect_after_run=False)):
        agent(golden.input)
except Exception as exc:
    print(type(exc).__name__)
    print(str(exc).splitlines()[0])
Output · real, progress display omitted3 lines
MissingTestCaseParamsError
'actual_output' cannot be None for the 'Task Completion' metric
[netguard] total blocked attempts: 0 []

This is the most common traced-evaluation failure. Every docs example calls update_current_trace for a reason. Treat it as part of the application-to-evaluation contract: the application must explicitly declare which value constitutes the user-visible result.

4.5 Errors roll up differently from missing data#

A missing output is a test-case construction failure. An application exception is different: the span is marked ERRORED and the metrics of the errored part of the tree are skipped. Neither should be converted into a pass, but one of them can be. The sample below raises inside a tool span in the three ways an exception can travel: the agent catches it, it escapes a synchronous loop body, or it escapes inside an async task. A deterministic HasStatus span metric sits on the tool and Exact Match sits on the trace:

python
# errored_spans.py: what an exception inside a traced run does to evaluation (lesson 10B.5)
import asyncio
import json
from pathlib import Path

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden, get_current_golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import BaseMetric, ExactMatchMetric
from deepeval.tracing import observe, update_current_trace

DISPLAY = DisplayConfig(print_results=False, show_indicator=False, inspect_after_run=False)
GOLDENS = [Golden(input="order BAD", expected_output="Your order is unknown."),
           Golden(input="order A-1", expected_output="Your order is delivered.")]


class HasStatus(BaseMetric):
    """Deterministic span metric: did the tool return a status field?"""
    def __init__(self):
        self.threshold = 1.0
    def measure(self, test_case, *args, **kwargs):
        self.score = 1.0 if "status" in (test_case.actual_output or "") else 0.0
        self.success, self.reason = self.score >= 1.0, "checked"
        return self.score
    async def a_measure(self, test_case, *args, **kwargs):
        return self.measure(test_case)
    def is_successful(self):
        return self.success
    @property
    def __name__(self):
        return "Has status"


@observe(type="tool", metrics=[HasStatus()])
def lookup_order(order_id: str):
    if order_id == "BAD":
        raise ValueError("order service timed out")
    return {"order_id": order_id, "status": "delivered"}


def body(query: str, catch: bool):
    try:
        status = lookup_order(query.split()[-1])["status"]
    except ValueError:
        if not catch:
            raise
        status = "unknown"                       # caught: the rest of the run continues
    answer = f"Your order is {status}."
    update_current_trace(input=query, output=answer,
                         expected_output=get_current_golden().expected_output)
    return answer


@observe(type="agent")
def agent(query: str, catch: bool):
    return body(query, catch)


@observe(type="agent")
async def async_agent(query: str):
    return body(query, catch=False)


def report(label):
    run = json.loads(Path(".deepeval/.latest_test_run.json").read_text())["testRunData"]
    print(f"{label}: {len(run['testCases'])} test case(s) recorded")
    for case in run["testCases"]:
        trace = case["trace"]
        tools = trace.get("toolSpans") or []
        span_m = [(m["name"], m.get("score"), m.get("success"))
                  for tool in tools for m in tool.get("metricsData") or []]
        trace_m = [(m["name"], m.get("score"), m.get("success")) for m in case.get("metricsData") or []]
        print(f"   {case['input']}: case success={case['success']}, trace {trace['status']}, "
              f"tool spans {[t['status'] for t in tools]}")
        print(f"      span metrics {span_m} | trace metrics {trace_m}")


# 1. sync, the agent catches the tool's exception
dataset = EvaluationDataset(goldens=list(GOLDENS))
for golden in dataset.evals_iterator(metrics=[ExactMatchMetric()], display_config=DISPLAY,
                                     async_config=AsyncConfig(run_async=False)):
    agent(golden.input, catch=True)
report("sync, caught")

# 2. sync, the exception escapes the loop body
dataset = EvaluationDataset(goldens=list(GOLDENS))
try:
    for golden in dataset.evals_iterator(metrics=[ExactMatchMetric()], display_config=DISPLAY,
                                         async_config=AsyncConfig(run_async=False)):
        agent(golden.input, catch=False)
except ValueError as exc:
    print("sync, uncaught: the for loop raised ValueError:", exc, "(golden 2 never ran)")


# 3. async, the exception escapes inside a task
async def main():
    dataset = EvaluationDataset(goldens=list(GOLDENS))
    for golden in dataset.evals_iterator(metrics=[ExactMatchMetric()], display_config=DISPLAY):
        dataset.evaluate(asyncio.create_task(async_agent(golden.input)))

asyncio.run(main())
report("async, uncaught in a task")
Output · real, the DeepEval banners between runs omitted12 lines
sync, caught: 2 test case(s) recorded
   order BAD: case success=True, trace SUCCESS, tool spans ['ERRORED']
      span metrics [('Has status', None, None)] | trace metrics [('Exact Match', 1.0, True)]
   order A-1: case success=True, trace SUCCESS, tool spans ['SUCCESS']
      span metrics [('Has status', 1.0, True)] | trace metrics [('Exact Match', 1.0, True)]
sync, uncaught: the for loop raised ValueError: order service timed out (golden 2 never ran)
async, uncaught in a task: 2 test case(s) recorded
   order BAD: case success=False, trace ERRORED, tool spans []
      span metrics [] | trace metrics [('Exact Match', None, False)]
   order A-1: case success=True, trace SUCCESS, tool spans ['SUCCESS']
      span metrics [('Has status', 1.0, True)] | trace metrics [('Exact Match', 1.0, True)]
[netguard] total blocked attempts: 0 []

Read the three cases carefully, because they behave very differently:

  1. Caught inside the agent: a silent pass. The tool span is recorded as ERRORED, its Has status metric was skipped (no score, no success value), and the golden passes. The console summary for that run said Pass Rate: 100.0%. A component that crashed and was papered over by a fallback answer is invisible unless you look for ERRORED spans yourself.
  2. Escaping a synchronous loop body: the run stops. The exception propagates out of your for loop. No later golden runs and no summary is produced, so one flaky tool aborts the whole suite.
  3. Escaping inside an async task: a recorded failure. The trace is marked ERRORED, the trace metric is recorded with no score and success=False, the golden fails, and the other goldens still run. The errored tool span itself is missing from the recorded trace; only the agent span keeps the error text.

The defensive pattern is to treat "errored" as its own outcome and fail CI on it. read_span_failures.py from 5.5 already prints a skipped metric (the entry has no success key, so not metric.get("success") is true), but an errored span that carries no metric leaves no entry at all, so also print every span whose status is "ERRORED". For regression analysis you want these categories distinct in reports:

  • application error: the agent could not run
  • missing instrumentation: the agent ran but evaluation evidence was not attached
  • metric error: the metric itself crashed or the judge response was invalid
  • metric failure: the metric ran and the score was below threshold

DeepEval's console compresses these into red failure rows in several places. When the distinction matters, inspect metricsData and error fields in .deepeval/.latest_test_run.json as 10B.2, Part 6 teaches for ordinary runs.


Part 5: evals_iterator, async evaluation and pytest mechanics#

Deep-dive

5.1 evals_iterator: the sync loop#

The verified signature is:

text
EvaluationDataset.evals_iterator(
    metrics=None,
    hyperparameters=None,
    identifier=None,
    display_config=None,
    cache_config=None,
    error_config=None,
    async_config=None,
) -> Iterator[Golden]

Conceptually it is a Python generator that lends you one Golden at a time. Your responsibility inside the loop is to run the application for that golden. DeepEval's responsibility when the generator regains control is to finish the trace, execute span and trace metrics, aggregate the result and write the local run record. Sync mode does that per golden before the next one is yielded; async mode queues traces and evaluates them after iteration.

In synchronous mode (AsyncConfig(run_async=False)) the loop shape is simple:

python
for golden in dataset.evals_iterator(
        metrics=trace_metrics,
        async_config=AsyncConfig(run_async=False)):
    agent(golden.input)

For each golden DeepEval opens a wrapper span, yields the golden, and treats everything decorated inside your application call as part of that golden's trace. After your iteration finishes, it evaluates the tree depth first. This is a good mode for teaching, debugging and small deterministic suites because failures surface in a predictable order.

The iterator is strict about the "metrics anywhere" rule. At least one metric must be declared in one of these places:

  • evals_iterator(metrics=[...]) for trace-level metrics
  • @observe(metrics=[...]) for a span
  • update_current_span(metrics=[...]) or update_current_trace(metrics=[...])
  • next_*_span(metrics=[...]) for a framework-created span

If none exists, DeepEval raises NoMetricsError after the loop rather than silently producing an empty success. This matters for integrations: in the LangChain probe (13.4), passing metrics only to CallbackHandler(metrics=[...]) does not register a metric source. Trace metrics belonged on the iterator and span metrics on next_llm_span.

The failure itself is easy to reproduce. This agent fills in its trace fields correctly but no metric is declared anywhere:

python
# no_metrics_error.py: an iterator with no metric anywhere ends in NoMetricsError (lesson 10B.5)
import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.tracing import observe, update_current_trace


@observe(type="agent")
def agent(query: str):
    update_current_trace(input=query, output="ok")   # trace fields, but no metric anywhere
    return "ok"


dataset = EvaluationDataset(goldens=[Golden(input="hello")])
try:
    for golden in dataset.evals_iterator(
            async_config=AsyncConfig(run_async=False),
            display_config=DisplayConfig(print_results=False, show_indicator=False,
                                         inspect_after_run=False)):
        agent(golden.input)
except Exception as exc:
    print(type(exc).__name__)
    print(str(exc).splitlines()[0][:150])
Output · real3 lines
NoMetricsError
evals_iterator was started but no metrics were declared anywhere. An evaluation run with zero metric sources cannot produce results.
[netguard] total blocked attempts: 0 []

The exception class is NoMetricsError. Notice that it is raised only after the loop body has run once, so a missing metric costs you a whole application run before you find out.

5.2 Async mode: dataset.evaluate(task) and StopIteration.value#

The default mode is asynchronous. You still iterate goldens synchronously, but each application run is scheduled as a task and passed back to the dataset object. Traces are queued and evaluated after the loop:

python
# async_iterator.py: async evals_iterator, dataset.evaluate(task), StopIteration.value (lesson 10B.5)
import asyncio

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import DisplayConfig
from deepeval.metrics import TaskCompletionMetric
from deepeval.tracing import observe, update_current_trace

from fake_judge import FakeJudge

judge = FakeJudge(script={
    "TaskAndOutcome": [
        {"task": "echo q0", "outcome": "echoed q0"},
        {"task": "echo q1", "outcome": "echoed q1"},
        {"task": "echo q2", "outcome": "echoed q2"},
    ],
    "TaskCompletionVerdict": [
        {"verdict": 0.6, "reason": "ok"},
        {"verdict": 0.6, "reason": "ok"},
        {"verdict": 0.6, "reason": "ok"},
    ],
})


@observe(type="agent", handoff_agents=["billing"])   # wrong kwarg: silently ignored in 4.3.5
async def agent(query: str):
    await asyncio.sleep(0.01)
    update_current_trace(input=query, output=f"echo {query}")
    return f"echo {query}"


async def main():
    dataset = EvaluationDataset(goldens=[Golden(input=f"q{i}") for i in range(3)])
    iterator = dataset.evals_iterator(
        metrics=[TaskCompletionMetric(model=judge)],
        display_config=DisplayConfig(print_results=False, show_indicator=False, inspect_after_run=False))
    try:
        golden = next(iterator)
        while True:
            dataset.evaluate(asyncio.create_task(agent(golden.input)))
            golden = iterator.send(None)
    except StopIteration as stop:
        result = stop.value
        print("EvaluationResult type:", type(result).__name__)
        print("test results:", [(t.name, t.success, [(m.name, m.score) for m in t.metrics_data])
                                for t in result.test_results])
        print("judge schemas:", judge.schemas())

asyncio.run(main())
Output · real, DeepEval banner omitted4 lines
EvaluationResult type: EvaluationResult
test results: [('test_case_0', True, [('Task Completion', 0.6)]), ('test_case_1', True, [('Task Completion', 0.6)]), ('test_case_2', True, [('Task Completion', 0.6)])]
judge schemas: ['TaskAndOutcome', 'TaskCompletionVerdict', 'TaskAndOutcome', 'TaskCompletionVerdict', 'TaskAndOutcome', 'TaskCompletionVerdict']
[netguard] total blocked attempts: 0 []

The generator detail is easy to miss: a Python for loop discards a generator's return value. evals_iterator returns the EvaluationResult there, so you must drive it manually with next() and send(None) and catch StopIteration, as above, or read the saved run file afterwards. This is ordinary Python generator behaviour, but it surprises people who expect evaluate()'s return-value shape.

The sample deliberately uses the documentation's wrong handoff_agents keyword. The run completes and no error complains, because unrecognized observe_kwargs are ignored. The resulting agent span has an empty agentHandoffs list. Use agent_handoffs.

5.3 Sync or async?#

Use sync mode when Use async mode when
You are debugging instrumentation and want immediate, ordered failures Your application is naturally async and makes concurrent model or tool calls
The suite is small or deterministic Wall-clock time matters and the runner can overlap work
You want the simplest possible mental model You are comfortable with queued traces and generator plumbing
You are teaching or printing prompts You are running a larger regression suite

Do not judge async mode by wall-clock numbers in this lesson. The fake judge returns instantly, so these runs measure machinery, not model cost. Real async behaviour also interacts with rate limits, retries and the copy rule for metric objects. 10B.2 owns those runner mechanics; this lesson's additional rule is that trace context must survive your task boundaries. If you spawn work yourself outside the pattern shown here, verify that child spans still land in the intended golden's trace.

Context propagation across tasks and threads

Spans find their parent through Python contextvars. Code that runs in the same task, or in a task made with asyncio.create_task or asyncio.gather, inherits the current context, so child spans attach to the right parent. Code that runs on a thread does not inherit it unless something copies the context: loop.run_in_executor(pool, fn) and ThreadPoolExecutor.submit(fn) copy nothing, while asyncio.to_thread(fn) does copy it. When there is no parent, the span has nowhere to attach, and DeepEval raises no error. This is the most common real-world tracing bug, so here is a probe with two goldens running concurrently, asyncio.gather children, and three kinds of thread hand-off:

python
# concurrency_context.py: where do spans land across asyncio and thread boundaries? (lesson 10B.5)
import asyncio
import contextvars
import json
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import BaseMetric
from deepeval.tracing import observe, update_current_trace


class Pass(BaseMetric):
    """A do-nothing metric so the iterator has a metric source."""
    def __init__(self):
        self.threshold = 0.5
    def measure(self, test_case, *args, **kwargs):
        self.score, self.success, self.reason = 1.0, True, "ok"
        return 1.0
    async def a_measure(self, test_case, *args, **kwargs):
        return self.measure(test_case)
    def is_successful(self):
        return True
    @property
    def __name__(self):
        return "Pass"


@observe(type="tool")
async def async_tool(name: str):
    await asyncio.sleep(0.01)
    return name


@observe(type="tool")
def thread_tool(name: str):
    return name


@observe(type="agent")
async def agent(query: str):
    await asyncio.gather(async_tool(f"{query}:gather-1"), async_tool(f"{query}:gather-2"))
    loop = asyncio.get_running_loop()
    with ThreadPoolExecutor(max_workers=1) as pool:
        # 1. a plain executor call: asyncio's run_in_executor copies no context
        await loop.run_in_executor(pool, thread_tool, f"{query}:plain-thread")
        # 2. the fix: run the callable inside a copy of the current context
        ctx = contextvars.copy_context()
        await loop.run_in_executor(pool, ctx.run, thread_tool, f"{query}:copied-context")
    # 3. asyncio.to_thread does that copy for you
    await asyncio.to_thread(thread_tool, f"{query}:to-thread")
    update_current_trace(input=query, output=f"done {query}")
    return query


async def main():
    dataset = EvaluationDataset(goldens=[Golden(input="g0"), Golden(input="g1")])
    iterator = dataset.evals_iterator(
        metrics=[Pass()],
        display_config=DisplayConfig(print_results=False, show_indicator=False,
                                     inspect_after_run=False))
    try:
        golden = next(iterator)
        while True:
            dataset.evaluate(asyncio.create_task(agent(golden.input)))
            golden = iterator.send(None)
    except StopIteration:
        pass


asyncio.run(main())

run = json.loads(Path(".deepeval/.latest_test_run.json").read_text())["testRunData"]
print("traces recorded:", len(run["testCases"]))
for case in run["testCases"]:
    trace = case["trace"]
    tools = [span["input"]["name"] for span in trace.get("toolSpans", [])]
    called = [call["name"] for call in trace["agentSpans"][0].get("toolsCalled", [])]
    print(case["name"], "tool spans:", sorted(tools))
    print("   agent toolsCalled:", len(called), "| plain-thread span present:",
          any("plain-thread" in t for t in tools))
Output · real, DeepEval banner omitted6 lines
traces recorded: 2
test_case_0 tool spans: ['g0:copied-context', 'g0:gather-1', 'g0:gather-2', 'g0:to-thread']
   agent toolsCalled: 4 | plain-thread span present: False
test_case_1 tool spans: ['g1:copied-context', 'g1:gather-1', 'g1:gather-2', 'g1:to-thread']
   agent toolsCalled: 4 | plain-thread span present: False
[netguard] total blocked attempts: 0 []

Read the result carefully. The gather children and the copied-context and to-thread calls landed in the correct golden's trace, even though two goldens ran at the same time. The plain-thread span is in neither trace and the agent span's toolsCalled lists four tools, not five. The evaluation ran, the metrics scored, and the missing tool call is invisible unless you look. The fixes are the two shown: contextvars.copy_context().run(fn, ...) or asyncio.to_thread. Put a planted-fault test like this beside any real agent that uses a thread pool.

5.4 What is stored locally#

After a run, .deepeval/.latest_test_run.json contains the test cases, their trace trees and per-span metricsData. This is not just a cache artifact. It is the most reliable local evidence for component failures, especially when the console compresses or omits them. 10B.2, Part 6 covers the file and SQLite store in detail.

deepeval inspect

deepeval inspect is a terminal UI (built on Textual, installed with pip install 'deepeval[inspect]') that opens a saved run as a span tree. The left pane is the tree of one trace; the right pane shows the selected span's input, output, fields, metric rows and raw JSON. Useful keys: j/k or the arrow keys to move, n/p or left/right to switch trace, / to filter spans by name, y to copy the selected node as JSON, Y to copy the whole trace, ? for help, q to quit. It is for people at a terminal: it is not a CI tool, and it cannot be driven from a script.

It finds a run in this order: the path you pass, then --folder or DEEPEVAL_RESULTS_FOLDER, then the SQLite store .deepeval/deepeval.db when DEEPEVAL_LOCAL_STORE=sqlite is set, then the rolling snapshot .deepeval/.latest_run_full.json. --list prints the runs in a SQLite store and --run-id N opens one of them. Real output of --list after running the 4.1 sample twice with the SQLite store enabled (the TUI itself needs an interactive terminal, so it was not run here):

text
$ DEEPEVAL_LOCAL_STORE=sqlite python trace_component_eval.py   # run it twice
$ deepeval inspect --list
                             .deepeval/deepeval.db                              
┏━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━┓
┃    ┃ created_at   ┃            ┃        ┃        ┃              ┃            ┃
┃ id ┃ (UTC)        ┃ identifier ┃ passed ┃ failed ┃ duration (s) ┃ cost (USD) ┃
┡━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━┩
│  2 │ 2026-11-28   │            │      1 │      1 │         0.06 │            │
│    │ 03:53:28     │            │        │        │              │            │
│  1 │ 2026-11-28   │            │      1 │      1 │         0.07 │            │
│    │ 03:53:27     │            │        │        │              │            │
└────┴──────────────┴────────────┴────────┴────────┴──────────────┴────────────┘
Open one with: deepeval inspect .deepeval/deepeval.db --run-id <id>

After an interactive evals_iterator or evaluate() run DeepEval may offer to open the TUI. The offer appears only when DisplayConfig.inspect_after_run is true, DEEPEVAL_NO_INSPECT_PROMPT is not truthy, stdout is a terminal, and the run contains at least one trace. The samples in this lesson turn it off with DisplayConfig(inspect_after_run=False); in scripts and CI set DEEPEVAL_NO_INSPECT_PROMPT=1.

5.5 Traced assert_test in pytest, and the invisible span failure#

The pytest pattern, as a complete file (test_agent_ci.py), is:

python
# test_agent_ci.py: traced component-level evaluation under deepeval test run (lesson 10B.5)
import netguard  # noqa: F401
import pytest
from deepeval import assert_test
from deepeval.dataset import EvaluationDataset, Golden
from deepeval.metrics import BaseMetric, TaskCompletionMetric, ToolCorrectnessMetric
from deepeval.test_case import LLMTestCase, ToolCall
from deepeval.tracing import observe, update_current_span, update_current_trace

from fake_judge import FakeJudge


class MentionsDays(BaseMetric):
    def __init__(self, threshold=1.0):
        self.threshold = threshold

    def measure(self, test_case: LLMTestCase, *args, **kwargs):
        self.score = 1.0 if "day" in (test_case.actual_output or "") else 0.0
        self.reason = "mentions a duration" if self.score else "no duration"
        self.success = self.score >= self.threshold
        return self.score

    async def a_measure(self, test_case, *args, **kwargs):
        return self.measure(test_case, *args, **kwargs)

    def is_successful(self):
        return self.success

    @property
    def __name__(self):
        return "Mentions days"


judge = FakeJudge(script={
    "TaskAndOutcome": [
        {"task": "answer the user's question", "outcome": "answered with available information"},
        {"task": "answer the user's question", "outcome": "answered with available information"},
    ] * 4,
    "TaskCompletionVerdict": [
        {"verdict": 0.8, "reason": "ok"},
        {"verdict": 0.8, "reason": "ok"},
    ] * 4,
})


@observe(type="tool")
def lookup_policy(topic: str):
    return {"refund": "5 business days", "shipping": "3-5 days"}.get(topic, "unknown")


@observe(type="llm", model="fake-llm", metrics=[MentionsDays()])
def answer(query: str, fact: str):
    output = f"It takes {fact}." if fact != "unknown" else "Sorry, I am not sure."
    update_current_span(input=query, output=output)
    return output


@observe(type="agent", metrics=[ToolCorrectnessMetric(model=judge)])
def agent(query: str):
    lowered = query.lower()
    topic = "refund" if "refund" in lowered else ("shipping" if "ship" in lowered else "other")
    fact = lookup_policy(topic)
    output = answer(query, fact)
    update_current_span(input=query, output=output, expected_tools=[ToolCall(name="lookup_policy")])
    update_current_trace(input=query, output=output)
    return output


dataset = EvaluationDataset(goldens=[
    Golden(input="How long do refunds take?"),
    Golden(input="Can I pay with crypto?"),
])


@pytest.mark.parametrize("golden", dataset.goldens)
def test_agent(golden: Golden):
    agent(golden.input)
    assert_test(golden=golden, metrics=[TaskCompletionMetric(model=judge)], run_async=False)

Run it with deepeval test run test_agent_ci.py, not plain pytest, when you want DeepEval's plugin and summary active. 10B.2, Part 5 owns the runner, flags and exit codes. The new tracing behaviour is in the failure reporting.

In this fixture, the agent span carries ToolCorrectnessMetric and the LLM span carries a deterministic MentionsDays metric. One golden asks "Can I pay with crypto?". The application answers "Sorry, I am not sure.", so the span metric fails because no duration is mentioned. The trace-level Task Completion metric passes. The real run exits 1 as it should, but the important lines are:

Output · real, ANSI colours removed, traceback and table trimmed6 lines
E               AssertionError: Metrics:  failed.
FAILED test_agent_ci.py::test_agent[golden1] - AssertionError: Metrics:  failed.
1 failed, 1 passed, 4 warnings in 0.11s
» Test Results (2 total tests):
   » Pass Rate: 50.0% | Passed: 1 | Failed: 1
[netguard] total blocked attempts: 0 []

The assertion does not name the failed span metric. The end-of-run table shows the trace-level metric passing for both tests and does not show MentionsDays. If you build a CI dashboard from that table, you will report nonsense: failure without a cause. Read the JSON instead:

python
# read_span_failures.py: find span metric failures in .latest_test_run.json (lesson 10B.5)
import json
from pathlib import Path

path = Path(".deepeval/.latest_test_run.json")
run = json.loads(path.read_text())["testRunData"]
span_lists = ("agentSpans", "llmSpans", "retrieverSpans", "toolSpans", "baseSpans")
for case in run["testCases"]:
    for span_list in span_lists:
        for span in (case.get("trace") or {}).get(span_list, []):
            for metric in span.get("metricsData") or []:
                if not metric.get("success"):
                    print(case["name"], span_list, span["name"], "->",
                          metric["name"], metric.get("score"), metric.get("reason"))
Output · real1 line
test_agent[golden1] llmSpans answer -> Mentions days 0.0 no duration

There is one more CI sharp edge. In the research probes, -n 2 (pytest-xdist) with traced assert_test preserved pytest's correct exit code but DeepEval's own summary and latest-run JSON contained only one of the two traced cases, with the surviving case varying between runs. Trust pytest's exit code for gating, but do not trust the traced DeepEval summary under xdist in 4.3.5. 10B.7, 2.5 owns the full CI design and shows an artifact_gate.py that compares the run file's test names with the junit counts and refuses a run file that lost cases.

5.6 The evaluation lifecycle in one picture#

sequenceDiagram
    participant D as EvaluationDataset
    participant Y as your test loop
    participant A as observed application
    participant B as span bridge
    participant M as metrics

    D->>Y: yield golden
    Y->>A: run agent(golden.input)
    A->>B: open and close spans
    A->>B: update_current_span or trace fields
    Y->>D: finish iteration
    D->>B: walk trace tree
    B->>M: build span test cases
    B->>M: build trace test case plus _trace_dict
    M->>D: scores, reasons, errors
    D->>Y: EvaluationResult as generator return value

The design consequence is that instrumentation is part of the eval harness, not merely part of the application. A change to span structure can change scores even when the application behaviour is unchanged. Treat instrumentation changes as evaluation-harness changes: review them, version them and include them in regression analysis.


Part 6: Local tracing, configuration, privacy and OpenTelemetry#

Deep-dive

6.1 What happens with no Confident AI key#

DeepEval tracing has two separate network questions that people often merge:

  1. Product telemetry: anonymous usage telemetry, disabled with DEEPEVAL_TELEMETRY_OPT_OUT=1 as 10B.1 and 10B.2 explain.
  2. Trace export: OpenTelemetry spans exported to Confident AI. Without a Confident API key, or with tracing disabled, the exporter returns success without sending anything.

The second point was verified rather than assumed. Every sample that executes DeepEval in this lesson imports netguard.py first, which monkey-patches socket connection and DNS functions to raise if anything attempts a network call. Every one of those outputs ends with zero blocked attempts. That includes samples run outside an evaluation, where export would have been the only possible reason to use the network.

The local behaviour is:

  • @observe works with no key.
  • evals_iterator and traced assert_test work with no key.
  • Spans consumed by evaluation are marked local and are not exported.
  • Outside evaluation, a traced function still completes with no key; its trace is not kept in memory after it ends.
  • flush_traces() returns normally because there is nothing to send.
  • Production observability, online metric collections, trace evaluation by UUID, thread evaluation and dashboards are Confident AI cloud features.

The cloud-only surface is small and explicit. These functions are exported from deepeval.tracing; each one posts a request to Confident AI for a trace or span that was already exported there, so none of them does anything useful in a keyless run (they were read from the 4.3.6 source, not executed):

Function What it asks Confident AI to do
evaluate_span(span_uuid, metric_collection, overwrite_metrics=False) run a saved metric collection on one exported span
evaluate_trace(trace_uuid, metric_collection, overwrite_metrics=False) run a saved metric collection on one exported trace
evaluate_thread(thread_id, metric_collection, overwrite_metrics=False, chatbot_role=None) run a saved conversation metric collection on a thread
a_evaluate_span, a_evaluate_trace, a_evaluate_thread the async twins of the three above

The metric_collection= keyword on observe, update_current_span and the integrations is the same idea: a name of a collection saved on the platform. Locally it is accepted and ignored, which is why a local metric must be passed as an object in metrics=[...].

This makes DeepEval suitable for local evaluation of sensitive systems, provided you configure masking correctly and do not accidentally install a key in the environment. It does not make it a complete local observability platform.

6.2 trace_manager.configure#

The verified signature is:

text
trace_manager.configure(
    mask=None,
    environment=None,
    sampling_rate=None,
    confident_api_key=None,      # deprecated, ignored
    anthropic_client=None,
    openai_client=None,
    tracing_enabled=None,
)

environment must be one of "production", "development", "staging" or "testing". The default comes from CONFIDENT_TRACE_ENVIRONMENT and is development; evaluation runs switch it to testing. sampling_rate must be in [0, 1], is read by default from CONFIDENT_TRACE_SAMPLE_RATE, and applies per whole trace. Crucially, sampling affects export only. Local evaluation still sees every trace. This is the right design for evaluation, but do not use a low sampling rate as evidence that volume is reduced locally.

openai_client and anthropic_client patch specific client instances so their model calls become LLM spans. The framework-wide integration imports in Part 13 use the same span bridge.

tracing_enabled=False disables export, not local evaluation. If your security posture is "nothing may leave this process", prefer the belt-and-braces approach: no CONFIDENT_API_KEY, DEEPEVAL_TELEMETRY_OPT_OUT=1, tracing_enabled=False, and a network guard in keyless test runs.

6.3 Masking: the raw-object pitfall#

mask is a function applied when an observed function finishes. It receives the raw input object and raw return object before storage or export. It is not a string-only convenience filter. In the real probe below, the mask handles strings but returns dictionaries unchanged:

python
# trace_local.py: local tracing, masking, sampling validation and next_tool_span (lesson 10B.5)
import json
import re

import netguard  # noqa: F401

from deepeval.tracing import (flush_traces, next_tool_span, observe, trace_manager,
                              update_current_trace)
from deepeval.tracing.trace_test_manager import trace_testing_manager


def mask(data):
    if isinstance(data, str):
        return re.sub(r"\b\d{4}-\d{4}-\d{4}-\d{4}\b", "[CARD]", data)
    return data


trace_manager.configure(mask=mask, environment="staging", sampling_rate=0.5)
print("environment:", trace_manager.environment, "| sampling:", trace_manager.sampling_rate)


@observe(type="tool", description="charge card")
def charge(card: str):
    return f"charged {card}"


@observe(type="agent", name="checkout-agent", available_tools=["charge"])
def checkout(message: str):
    update_current_trace(thread_id="thread-1", tags=["lesson"], metadata={"plan": "free"})
    with next_tool_span(metadata={"staged": True}):
        return charge("4111-1111-1111-1111")


trace_testing_manager.test_name = "lesson"
print("returned:", checkout("pay with 4111-1111-1111-1111"))
captured = trace_testing_manager.test_dict
print("captured keys:", sorted(captured.keys()))
print(json.dumps(captured, indent=1, default=str)[:2100])
trace_testing_manager.test_name = None
print("traces kept in memory after end:", len(trace_manager.get_all_traces()))
print("flush:", flush_traces(timeout=1))
for kwargs in ({"sampling_rate": 2}, {"environment": "prod"}):
    try:
        trace_manager.configure(**kwargs)
    except Exception as exc:
        print("validation:", exc)
Output · real, JSON cut at 2,100 characters by the print77 lines
environment: staging | sampling: 0.5
returned: charged 4111-1111-1111-1111
captured keys: ['agentSpans', 'baseSpans', 'endTime', 'environment', 'input', 'llmSpans', 'metadata', 'output', 'retrieverSpans', 'startTime', 'status', 'tags', 'threadId', 'toolSpans', 'uuid']
{
 "uuid": "9b9afbdb-655d-41ac-a4eb-cc128d55b460",
 "baseSpans": [],
 "agentSpans": [
  {
   "uuid": "05bd5f954801917b",
   "name": "checkout-agent",
   "status": "SUCCESS",
   "type": "agent",
   "startTime": "2026-11-28T03:48:22.058Z",
   "endTime": "2026-11-28T03:48:22.058Z",
   "input": {
    "message": "pay with 4111-1111-1111-1111"
   },
   "output": "charged [CARD]",
   "toolsCalled": [
    {
     "name": "charge",
     "type": "FUNCTION",
     "description": "charge card",
     "output": "charged [CARD]",
     "inputParameters": {
      "card": "4111-1111-1111-1111"
     }
    }
   ],
   "availableTools": [
    "charge"
   ],
   "agentHandoffs": []
  }
 ],
 "llmSpans": [],
 "retrieverSpans": [],
 "toolSpans": [
  {
   "uuid": "15053c2fd30c16a6",
   "name": "charge",
   "status": "SUCCESS",
   "type": "tool",
   "parentUuid": "05bd5f954801917b",
   "startTime": "2026-11-28T03:48:22.058Z",
   "endTime": "2026-11-28T03:48:22.058Z",
   "metadata": {
    "staged": true
   },
   "input": {
    "card": "4111-1111-1111-1111"
   },
   "output": "charged [CARD]",
   "description": "charge card"
  }
 ],
 "startTime": "2026-11-28T03:48:22.049Z",
 "endTime": "2026-11-28T03:48:22.058Z",
 "metadata": {
  "plan": "free"
 },
 "tags": [
  "lesson"
 ],
 "environment": "staging",
 "threadId": "thread-1",
 "input": {
  "message": "pay with 4111-1111-1111-1111"
 },
 "output": "charged [CARD]",
 "status": "SUCCESS"
}
traces kept in memory after end: 0
flush: True
validation: Invalid sampling rate: 2. Please use a value between 0 and 1
validation: Invalid environment: prod. Please use one of the following instead: "production", "development", "staging", "testing"
[netguard] total blocked attempts: 0 []

The output strings were masked in the captured trace. The input dictionaries were not, because the mask returned them unchanged. The derived toolsCalled[].inputParameters copy also kept the raw card number. The printed returned: line is still unmasked because masking changes what DeepEval stores, not the value your application returns. A correct mask must recursively walk dictionaries, lists, tuples and objects you actually pass:

python
import re

CARD = re.compile(r"\b\d{4}-\d{4}-\d{4}-\d{4}\b")

def recursive_mask(value):
    if isinstance(value, str):
        return CARD.sub("[CARD]", value)
    if isinstance(value, dict):
        return {key: recursive_mask(item) for key, item in value.items()}
    if isinstance(value, list):
        return [recursive_mask(item) for item in value]
    if isinstance(value, tuple):
        return tuple(recursive_mask(item) for item in value)
    return value

Two more boundaries matter. Values passed directly to update_current_span and update_current_trace are not masked in 4.3.5. Mask before you call those functions. And masking is not a substitute for minimization: if a span does not need a secret, do not put the secret in the span at all.

6.4 The environment variables that matter#

Variable Default in 4.3.5 Effect
CONFIDENT_TRACING_ENABLED "YES" anything else disables export
CONFIDENT_TRACE_ENVIRONMENT development default environment label
CONFIDENT_TRACE_SAMPLE_RATE 1.0 export sampling rate
CONFIDENT_TRACE_VERBOSE True controls trace-log console lines outside evaluation
CONFIDENT_TRACE_FLUSH unset eager flushing behaviour
CONFIDENT_TRACE_INTERNAL unset also trace DeepEval's own internal metric/model calls
DEEPEVAL_AUTO_TRACE True during evaluation, instrument supported installed libraries automatically
DEEPEVAL_GLOBAL_TRACER_PROVIDER False install confident-trace's provider globally when none exists
CONFIDENT_OTEL_URL https://otel.confident-ai.com export endpoint, still with Confident authentication semantics
DEEPEVAL_TELEMETRY_OPT_OUT unset opt out of product telemetry; separate from trace export

DEEPEVAL_AUTO_TRACE deserves special attention. During evals_iterator and deepeval test run, DeepEval can instrument every supported library installed in the environment, even if you did not add an integration callback. That is helpful when you want zero-code capture and confusing when duplicate or extra spans change the tree a trajectory judge sees. Set it to 0 when you need a controlled experiment with only explicit @observe spans.

6.5 OpenTelemetry without illusions#

DeepEval's use of OpenTelemetry is real, but the public integration surface is narrower than the words "OpenTelemetry support" might suggest. In 4.3.5:

  • There is no supported local DeepEval API that simply means "export all these spans to my collector".
  • CONFIDENT_OTEL_URL changes the endpoint but does not turn the exporter into a vendor-neutral exporter; it still expects Confident authentication.
  • ensure_confident_trace(exporter=..., tracer_provider=...) exists but is internal API and may change.
  • If confident-trace joins an existing application tracer provider, DeepEval's processors can coexist with it, but DeepEval-owned spans are not automatically exported through your application's exporters.
  • deepeval.instrument() and instrument_openinference() allow OpenInference instrumentors to feed DeepEval, useful when a framework already emits those events.

The idea in 1.3 is that one set of spans can serve monitoring and evaluation: DeepEval span types line up with OTel GenAI operations (invoke_agent, chat, retrieval, execute_tool), so an app instrumented for production can also feed an eval. The OTel names are at Development status (checked 2026-12-01), and the sharing is by convention, not by a supported export path in DeepEval (see the list above).

If your organization already has an observability platform, the clean separation is usually:

Concern Owner
Production traces, latency, operational dashboards, alerting your observability stack; see Module 11A
Evaluation-time capture, span metrics, trajectory judges DeepEval tracing in this lesson
Offline grading of historical production traces evalkit trace_adapter.py from 10A.7, 10.4 or a custom adapter
Confident AI trace analytics and online metric collections Confident AI, surveyed in 10B.7

This separation avoids the common mistake of making evaluation instrumentation depend on production export being enabled. Evaluation should work locally in a pull request with no key and no network.

6.6 Flushing and process lifetime#

flush_traces(timeout=...) and a_flush_traces(...) exist for applications that might exit before exporter batching finishes. In the keyless local path there is nothing to send, so flushing is trivially successful. In a keyed production deployment, call flush at shutdown rather than assuming process exit will drain spans. Even then, do not confuse flush success with evaluation success: one concerns export, the other concerns local metric results.


Part 7: Designing component-level evaluations#

7.1 Start with the failure, not with the decorator#

A component metric is useful only if it isolates a failure you actually expect. Do not begin by decorating every function and attaching every metric that sounds relevant. Begin with a failure inventory, as 10A.7, Part 1 does for agents:

Failure you fear Span to instrument Better component check Bad proxy
Retrieval returned no chunks retriever non-empty context, top-k shape, chunk metadata present final Answer Relevancy alone
Retrieval returned the wrong chunks retriever Contextual Recall/Precision against golden context whether the final answer sounds confident
The model ignored retrieved evidence generation span Faithfulness with that span's output and retrieval context retrieval recall
The wrong tool was selected agent or routing LLM Tool Correctness with available_tools Task Completion
The right tool received wrong arguments owning LLM/tool boundary Argument Correctness or exact expected parameters whether the final answer mentions the entity
A forbidden tool was called agent Tool Permission manual code review only
The agent looped trace Agent Loop Detection, budget checks average latency
A sub-agent was never handed the task parent and child agent spans custom handoff metric over _trace_dict final answer quality
The final claim is unsupported by state end-to-end trace outcome/state grader from 10A.7 any trajectory judge

Notice how many "best" checks are deterministic. They are cheaper, more reproducible and easier to debug than judge-based component metrics. Use judges where judgement is intrinsic: relevance, faithfulness, plan quality. Use code where truth is exact: schema shape, allow-lists, budgets, empty results, ordering constraints.

7.2 Choose span granularity deliberately#

A span should represent a boundary whose inputs and outputs you can name. Too few spans and every component metric becomes end-to-end in disguise. Too many spans and the tree becomes noise: the judge sees implementation detail, local metrics duplicate one another, and every refactor breaks evaluation.

A useful rule is:

  • one retriever span per logical retrieval decision, not per vector database client call
  • one llm span per model invocation whose prompt or output you may want to evaluate
  • one tool span per externally meaningful tool action, not per line of business logic
  • one agent span per autonomous responsibility boundary
  • custom spans for deterministic domain operations with their own invariants, such as SQL validation, redaction or parsing

For the docs_qa RAG application from Modules 06 and 07, a sensible tree is answer_question (agent or custom root), rewrite_query (llm), retrieve_chunks (retriever), rerank_chunks (custom or retriever), and write_grounded_answer (llm). A low-level embed_text span is useful while debugging retrieval cost but usually not a permanent eval boundary.

7.3 What evidence belongs on the span#

Each span should carry the minimum evidence required by its metrics:

Field Put it on the span when Do not use it for
input the metric should see a clean component input dumping entire prompts or secrets by default
output the component's meaningful return value large binary blobs or huge chunks of text
retrieval_context retrieval evidence for RAG metrics reranking scores unless represented as text or metadata deliberately
context golden facts or trusted reference context raw retrieved text that belongs in retrieval_context
tools_called / expected_tools tool metrics at the boundary that owns the decision duplicating every nested child's calls at every ancestor
metadata debugging and attribution metric evidence in 4.3.5, because it is not copied into the span test case

This is a data-minimization exercise as much as an evaluation exercise. A span is potentially exportable telemetry. Before adding a field, ask whether you would be comfortable seeing it in a trace export if a key were later configured.

7.4 Place metrics at the narrowest honest boundary#

The word "honest" matters. A component metric should not claim evidence outside the component's control. Faithfulness of a final answer does not belong on the retriever: retrieval can only supply evidence, not force the writer to use it. Conversely, retrieval recall does not belong on the writer: the writer cannot repair missing chunks except by abstaining.

A practical allocation for a support RAG agent is:

text
retrieve_chunks:
    deterministic non-empty and shape checks
    Contextual Recall or Precision when goldens provide expected evidence

rerank_chunks:
    deterministic ordering invariants or top-k overlap with a reference ranking

write_grounded_answer:
    Faithfulness against this span's retrieval_context
    Answer Relevancy against the user query

agent root:
    Tool Correctness, Tool Permission, budget or loop checks

trace:
    Task Completion, exact/expected output checks, end-to-end safety gates

Some duplication is deliberate. End-to-end Answer Relevancy and generation-span Answer Relevancy can coexist because they answer different questions: did the system satisfy the user, and did this particular model call stay on the prompt it was given? Accidental duplication is different: running the same expensive judge on every ancestor gives you correlated numbers that look like independent evidence but are not.

7.5 Goldens for components#

End-to-end goldens often contain only input and expected output. Component evaluation needs richer goldens:

  • expected retrieval facts or document ids for recall/precision
  • expected tools and arguments for tool correctness
  • forbidden tools or permission fixtures
  • expected sub-agent routing for multi-agent systems
  • metadata such as user tier, tenant or task type where behaviour should differ

In DeepEval, use Golden.additional_metadata for data a custom metric or harness needs, and copy selected values into span fields at runtime. Remember the metadata rule from Part 3: trace metadata is not automatically a metric field. The golden can also carry expected_output, context, retrieval_context and expected_tools directly where the field exists. 10B.6 owns dataset construction in detail; here the principle is that component expectations are part of the test design, not an afterthought.

7.6 Validate component metrics before trusting them#

The validation ladder is the same as in 10A.5, but the unit changes:

  1. Self-test with planted failures. Empty retrieval must fail the retriever metric. Wrong tool order must fail ordering. A forbidden tool must fail permission. If a planted bug does not light up its intended metric, the metric or instrumentation is wrong.
  2. Inspect the exact test case. Print or read the span input/output in JSON. Check for str(dict) inputs, missing fields, accidental truncation and leaked goldens.
  3. Inspect judge prompts. The fake judge in this lesson records every prompt. For a real judge, use the same technique in a staging run or log verbose output. Do not calibrate what you have not read.
  4. Label a small component dataset. For judge-based component metrics, humans label component outputs independently. Calculate agreement and error rates with evalkit judge_validation.py from 10A.5.
  5. Compare distributions, not one score. Use the statistical methods from 10A.8 before claiming a prompt or retrieval change improved a component.

A component metric that cannot be validated independently is a weak measurement. For example, if the only evidence for "correct argument" is the model's own final answer, Argument Correctness becomes circular. You need tool outputs, expected parameters or state checks.

7.7 Cost, latency and interference#

Every metric on a hot span is a cost multiplier. A retriever metric that calls a judge once per retrieved chunk can dominate the cost of the entire evaluation. Use these controls:

  • deterministic checks for CI on every commit
  • judge-based component checks on a sampled or nightly suite
  • cheaper component metrics during development, expensive trajectory judges before release
  • caching where appropriate, with the invalidation caveats from 10B.2, Part 6
  • tracing overhead measurement if the application is latency-sensitive, because decorators and span processors are not free

Also consider interference. Metrics execute after spans finish, but instrumentation itself can change timing and memory. For streaming systems, materializing outputs for evaluation can alter backpressure. For concurrency-heavy agents, context propagation bugs can drop spans or attach them to the wrong trace; the probe in 5.3 shows a thread-pool call whose span vanishes without any error. The evaluation harness must be tested under the same concurrency shape as production, not only in a synchronous demo.

7.8 A component-evaluation design checklist#

Before accepting a traced component eval, ask:

  1. Which component failure is this metric meant to isolate?
  2. Does this span contain all evidence the metric needs?
  3. Does the metric use evidence outside the component's control?
  4. Are expected values in the golden, and can the application see them only as expectations?
  5. Are inputs clean strings where judges expect strings, rather than stringified dictionaries?
  6. Are empty results representable despite the falsy-update rule?
  7. Are secrets masked before both automatic capture and explicit updates?
  8. Does a failing component fail the golden in the way CI expects?
  9. Is the failure visible in JSON, not only in the console table?
  10. Have planted bugs proved the metric fires?

If any answer is no, the number may still print. Printing is not evidence that the evaluation is meaningful.


Part 8: What trace-aware judges see#

Deep-dive

8.1 requires_trace and _trace_dict#

Some DeepEval metrics set requires_trace = True on the instance. During traced evaluation DeepEval attaches an extra private attribute to the test case:

text
test_case._trace_dict = trace_manager.create_nested_spans_dict(span)

The value is the span subtree as nested JSON. It includes names, types, inputs, outputs, tools called, available tools, handoffs, type-specific fields and children. It removes identifiers, exact timings, status and metadata. At trace level the root is the whole run; at component level it is that component's subtree.

This is the evidence the trajectory judges read. Custom metrics that need the same evidence must set self.requires_trace = True themselves; the attribute is opt-in, not inferred from the fact that measure() reads _trace_dict. _trace_dict is not the same as the full exported trace. A judge does not see your exact timestamps, span UUIDs or metadata unless those values are copied into input/output fields. That design keeps prompts smaller, but it also means important context can vanish silently if you stored it only in metadata.

8.2 A real trace inside a Task Completion prompt#

The sample below, saved as trace_prompt_view.py, runs a minimal agent and prints the trace JSON inside the first Task Completion judge prompt. (It also writes the whole prompt to task_completion_prompt.txt so you can read the instructions around the trace.) The application makes a questionable toy mistake: it uses the order status "delivered" as if it were a refund duration, producing "Refunds take delivered." That is useful because it shows the judge sees exactly the evidence you give it, including nonsense.

python
# trace_prompt_view.py: print the trace JSON inside TaskCompletion's first judge prompt (lesson 10B.5)

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import TaskCompletionMetric
from deepeval.tracing import observe, update_current_trace

from fake_judge import FakeJudge

judge = FakeJudge(script={
    "TaskAndOutcome": [{"task": "answer refund timing", "outcome": "answered 5 business days"}],
    "TaskCompletionVerdict": [{"verdict": 0.9, "reason": "complete"}],
})


@observe(type="tool", description="Look up an order")
def lookup_order(order_id: str):
    return {"order_id": order_id, "status": "delivered"}


@observe(type="llm", model="fake-llm")
def generate(query: str, fact: str):
    return f"Refunds take {fact}."


@observe(type="agent", available_tools=["lookup_order"])
def agent(query: str):
    fact = lookup_order("A1")["status"]
    answer = generate(query, fact)
    update_current_trace(input=query, output=answer)
    return answer


dataset = EvaluationDataset(goldens=[Golden(input="How long does a refund take?")])
for golden in dataset.evals_iterator(
        metrics=[TaskCompletionMetric(model=judge)],
        async_config=AsyncConfig(run_async=False),
        display_config=DisplayConfig(print_results=False, show_indicator=False, inspect_after_run=False)):
    agent(golden.input)

prompt = judge.prompt(0)
open("task_completion_prompt.txt", "w").write(prompt)
start = prompt.rfind("\ntrace:\n") + 1
print("--- the trace JSON in prompt 1 ---")
print(prompt[start:prompt.index("\n\nJSON:", start)])   # the trace block ends where the JSON-format instructions begin
Output · real, the trace block of the first prompt56 lines
trace:
{
  "name": "agent",
  "type": "agent",
  "input": {
    "query": "How long does a refund take?"
  },
  "output": "Refunds take delivered.",
  "tools_called": [
    {
      "name": "lookup_order",
      "type": "FUNCTION",
      "description": "Look up an order",
      "reasoning": null,
      "output": {
        "order_id": "A1",
        "status": "delivered"
      },
      "input_parameters": {
        "order_id": "A1"
      },
      "turn": null
    }
  ],
  "available_tools": [
    "lookup_order"
  ],
  "agent_handoffs": [],
  "children": [
    {
      "name": "lookup_order",
      "type": "tool",
      "input": {
        "order_id": "A1"
      },
      "output": {
        "order_id": "A1",
        "status": "delivered"
      },
      "description": "Look up an order",
      "children": []
    },
    {
      "name": "generate",
      "type": "llm",
      "input": {
        "query": "How long does a refund take?",
        "fact": "delivered"
      },
      "output": "Refunds take delivered.",
      "model": "fake-llm",
      "children": []
    }
  ]
}
[netguard] total blocked attempts: 0 []

Nothing in this JSON says that lookup_order was irrelevant to refund duration, that the agent should have searched policy text, or that the output is semantically malformed. A judge can infer some of that from names and values, but inference is not evidence. If you want the metric to know a tool was optional or forbidden, record available tools and use the deterministic tool metrics. If you want it to understand that order status is not policy evidence, make the retrieval and generation boundaries explicit.

8.3 Summarize, then grade: the extraction failure mode#

Task Completion does not ask one judge to compare the whole trace directly with the task in a single step. It first asks the judge to extract:

  1. the task expressed by the user in the root input
  2. a strictly factual outcome based only on the trace

The extraction prompt explicitly forbids subjective words such as "successfully", "efficiently" and "well" in the outcome summary. A second prompt then scores alignment between task and outcome.

This two-step design is sensible: it separates evidence compression from grading. It is also a failure amplifier. The verdict judge never sees the trace, only the extracted task and outcome. If extraction omits a forbidden tool call, invents a successful action, or misses that the answer was irrelevant, the verdict can be high and internally consistent. This is the same summarization risk taught framework-free in 10A.7, 4.5, implemented in a particular prompt pipeline.

Defences:

  • print extraction prompts with the fake judge during development
  • build adversarial traces where the correct outcome is easy to omit, such as a correct final answer after a forbidden action
  • pair reference-free trajectory judges with deterministic tool and state checks
  • inspect low and high outliers manually before accepting the metric
  • validate against human judgement using 10A.5's agreement workflow

8.4 Why trace-aware does not mean reference-aware#

A trace-aware metric knows what happened. It does not automatically know what should have happened. Task Completion, Step Efficiency, Plan Adherence and Plan Quality are reference-free unless you encode expectations in the input, expected output, tools or prompt. They can say whether the judge thinks the path was coherent, not whether it matches your reference trajectory.

That distinction is the main conceptual correction to make when moving from 10A.7, 4.1 to DeepEval. In evalkit you can compare against a reference sequence, use constraints, or score state. DeepEval gives you excellent plumbing for judge-read traces, but most of its trajectory metrics are opinions about that trace. Treat them as one layer in a battery, not as proof of correctness.


Part 9: The trajectory judges: task, efficiency and plans#

Deep-dive

9.1 The shared shape, and the unclamped-number rule#

The four single-turn trajectory judges in 4.3.5 are TaskCompletionMetric, StepEfficiencyMetric, PlanAdherenceMetric and PlanQualityMetric. They share the standard metric constructor shape from 10B.3: threshold=0.5, model=None, include_reason=True, async_mode=True, strict_mode=False, verbose_mode=False and related runner options. Newer eval_mode and system_one_model parameters belong to Confident's paid Jev/System One surface; this course uses ordinary llm mode with an explicit judge.

The most important implementation fact is not in the constructor: judge numbers are not clamped to [0, 1]. A scripted verdict of 1.4 produces score=1.4 and counts as a pass; a malformed custom judge that returns 8 can produce 8.0. Save this as standalone_trace_metrics.py. It calls the trace judges directly on a plain LLMTestCase (which is why they receive a null trace, see 9.5) and scripts an out-of-range verdict:

python
# standalone_trace_metrics.py: trace judges used outside a trace, and the unclamped rule (lesson 10B.5)
import netguard  # noqa: F401

from deepeval.metrics import (AgentLoopDetectionMetric, PlanAdherenceMetric,
                              PlanQualityMetric, StepEfficiencyMetric, TaskCompletionMetric)
from deepeval.test_case import LLMTestCase, ToolCall

from fake_judge import FakeJudge


def show(name, metric, judge=None):
    calls = judge.schemas() if judge else []
    print(f"{name}: score={metric.score!r} success={metric.success} calls={calls}")


case = LLMTestCase(
    input="What's the weather in Paris and convert 20C to F?",
    actual_output="It is 20C (68F) in Paris.",
    tools_called=[ToolCall(name="get_weather", input_parameters={"city": "Paris"}),
                  ToolCall(name="convert", input_parameters={"c": 20})],
)

judge = FakeJudge(script={
    "TaskAndOutcome": [{"task": "weather+convert", "outcome": "reported 20C/68F"}],
    "TaskCompletionVerdict": [{"verdict": 1.0, "reason": "done"}],
})
metric = TaskCompletionMetric(model=judge, async_mode=False)
metric.measure(case, _show_indicator=False)
show("TaskCompletion fallback", metric, judge)

judge = FakeJudge(script={
    "TaskAndOutcome": [{"task": "unused", "outcome": "unused"}],
    "TaskCompletionVerdict": [{"verdict": 1.4, "reason": "over-range"}],
})
metric = TaskCompletionMetric(model=judge, task="Report weather", async_mode=False)
metric.measure(case, _show_indicator=False)
show("TaskCompletion unclamped", metric, judge)

scripts = {
    StepEfficiencyMetric: {
        "Task": [{"task": "weather+convert"}],
        "EfficiencyVerdict": [{"score": 0.5, "reason": "cannot audit a null trace honestly"}],
    },
    PlanAdherenceMetric: {
        "Task": [{"task": "weather+convert"}],
        "AgentPlan": [{"plan": ["get weather", "convert"]}],
        "PlanAdherenceScore": [{"score": 0.8, "reason": "scripted"}],
    },
    PlanQualityMetric: {
        "Task": [{"task": "weather+convert"}],
        "AgentPlan": [{"plan": ["get weather", "convert"]}],
        "PlanQualityScore": [{"score": 0.6, "reason": "scripted"}],
    },
}
for cls in (StepEfficiencyMetric, PlanAdherenceMetric, PlanQualityMetric):
    judge = FakeJudge(script=scripts[cls])
    metric = cls(model=judge, async_mode=False)
    metric.measure(case, _show_indicator=False)
    show(cls.__name__ + " with TRACE null", metric, judge)

metric = AgentLoopDetectionMetric(async_mode=False)
metric.measure(case, _show_indicator=False)
show("AgentLoopDetection without trace", metric)
print("  reason:", metric.reason)
Output · real8 lines
TaskCompletion fallback: score=1.0 success=True calls=['TaskAndOutcome', 'TaskCompletionVerdict']
TaskCompletion unclamped: score=1.4 success=True calls=['TaskAndOutcome', 'TaskCompletionVerdict']
StepEfficiencyMetric with TRACE null: score=0.5 success=True calls=['Task', 'EfficiencyVerdict']
PlanAdherenceMetric with TRACE null: score=0.8 success=True calls=['Task', 'AgentPlan', 'PlanAdherenceScore']
PlanQualityMetric with TRACE null: score=0.6 success=True calls=['Task', 'AgentPlan', 'PlanQualityScore']
AgentLoopDetection without trace: score=0.0 success=False calls=[]
  reason: No trace data found. This metric requires trace data from @observe.
[netguard] total blocked attempts: 0 []

A real judge can misread its schema or instructions in the same way. Before aggregating trajectory scores, validate ranges. DeepEval does not provide the calibration and interval layer from 10A.5 or the statistical comparison layer from 10A.8; you still need evalkit or equivalent code around it.

What each judge is shown, and on what scale

Two questions decide whether you can defend a trajectory score: what evidence did the scoring call see, and what scale was the judge told to use? The extraction calls see the trace, but the final call is where the number is produced, and it does not always see the trace. This sample runs all four judges on one traced agent that wrote a plan, then checks which evidence appears in each metric's final prompt:

python
# judge_inputs.py: what evidence reaches each trajectory judge's final scoring prompt (lesson 10B.5)
import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import (PlanAdherenceMetric, PlanQualityMetric, StepEfficiencyMetric,
                              TaskCompletionMetric)
from deepeval.tracing import observe, update_current_span, update_current_trace

from fake_judge import FakeJudge

TASK = [{"task": "Tell the customer the refund window for order A-1042"}]
PLAN = ["look up the order", "read the refund policy", "tell the customer the refund window"]
judges = {
    TaskCompletionMetric: FakeJudge(script={
        "TaskAndOutcome": [{"task": TASK[0]["task"], "outcome": "Looked up A-1042; replied 5 days."}],
        "TaskCompletionVerdict": [{"verdict": 0.9, "reason": "scripted"}]}),
    StepEfficiencyMetric: FakeJudge(script={
        "Task": TASK, "EfficiencyVerdict": [{"score": 0.75, "reason": "scripted"}]}),
    PlanAdherenceMetric: FakeJudge(script={
        "Task": TASK, "AgentPlan": [{"plan": PLAN}],
        "PlanAdherenceScore": [{"score": 0.5, "reason": "scripted"}]}),
    PlanQualityMetric: FakeJudge(script={
        "Task": TASK, "AgentPlan": [{"plan": PLAN}],
        "PlanQualityScore": [{"score": 0.75, "reason": "scripted"}]}),
}


@observe(type="llm", model="fake-planner")
def make_plan(query: str):
    plan = "Plan: 1. look up the order. 2. read the refund policy. 3. tell the customer."
    update_current_span(input=query, output=plan)
    return plan


@observe(type="tool", description="Look up an order")
def lookup_order(order_id: str):
    return {"order_id": order_id, "status": "delivered"}


@observe(type="agent")
def agent(query: str):
    make_plan(query)
    lookup_order("A-1042")
    update_current_trace(input=query, output="Refunds take 5 business days.")
    return "Refunds take 5 business days."


metrics = [cls(model=judge) for cls, judge in judges.items()]
dataset = EvaluationDataset(goldens=[Golden(input="How long does a refund on order A-1042 take?")])
for golden in dataset.evals_iterator(
        metrics=metrics, async_config=AsyncConfig(run_async=False),
        display_config=DisplayConfig(print_results=False, show_indicator=False,
                                     inspect_after_run=False)):
    agent(golden.input)

MARKERS = {"task": "refund window for order", "plan": "read the refund policy",
           "trace JSON": '"name": "lookup_order"', "raw user input": "How long does a refund"}
print(f"{'metric':<16} {'final call':<22}", "  ".join(MARKERS))
for metric, judge in zip(metrics, judges.values()):
    final = judge.prompt(len(judge.schemas()) - 1)          # the scoring prompt
    seen = [("yes" if text in final else "no").ljust(len(name)) for name, text in MARKERS.items()]
    print(f"{metric.__name__:<16} {judge.schemas()[-1]:<22} " + "  ".join(seen).rstrip())
Output · real, DeepEval banner omitted6 lines
metric           final call             task  plan  trace JSON  raw user input
Task Completion  TaskCompletionVerdict  yes   no    no          no
Step Efficiency  EfficiencyVerdict      yes   yes   yes         yes
Plan Adherence   PlanAdherenceScore     yes   yes   yes         yes
Plan Quality     PlanQualityScore       yes   yes   no          no
[netguard] total blocked attempts: 0 []

(Step Efficiency shows plan: yes only because the plan text is inside the trace JSON, in the planning span's output; it is not given the extracted plan.) Put that beside the scoring instructions in the 4.3.6 templates (deepeval/metrics/<metric>/templates/):

Metric Scoring call sees Scale the judge is given Tie-break instruction
Task Completion extracted task and extracted outcome only continuous 0 to 1; only the endpoints are defined (1 = "perfectly achieves", 0 = "does not achieve at all"), plus one worked example at 0.85 none
Step Efficiency extracted task and the trace JSON five anchors: 1.0 perfectly efficient, 0.75 one small redundant step, 0.5 noticeable inefficiency, 0.25 multiple irrelevant actions, 0.0 most actions unnecessary; "enrichment" steps cap the score at 0.25 or below "When uncertain, always assign the lower score"
Plan Adherence extracted task, extracted plan and the trace JSON five anchors from 1.0 perfect to 0.0 no adherence; 0.5 "should be the highest score possible when there are any deviations" "err toward the lower score"; also says one missing step means "lowest possible"
Plan Quality extracted task and extracted plan only five anchors: excellent, good, adequate but flawed, weak, inadequate "When in doubt, assign the lower score"

Four consequences for how you use these numbers:

  • Two of the four final calls never see the trace. Task Completion's verdict and Plan Quality's score are computed from summaries the judge wrote in an earlier call. Validating them means validating the extraction too (8.3): label the extracted task, outcome and plan for correctness, not just the final score.
  • Three of the four are ordinal scales, not measurements. Step Efficiency, Plan Adherence and Plan Quality ask for one of five anchors, so real judges cluster on 0, 0.25, 0.5, 0.75 and 1.0. A mean of 0.62 is an average of category labels. Report the distribution across anchors, and when you calibrate against human labels use an ordinal agreement statistic such as weighted kappa from 10A.5, 3.4, not raw agreement on the decimals.
  • The default threshold of 0.5 means "Moderate efficiency" or "Partial adherence" passes. For Plan Adherence, 0.5 is the anchor the prompt reserves for runs with deviations, so a 0.5 threshold accepts deviating runs by design. Choose thresholds from labelled data, not from the default.
  • The Plan Adherence prompt contradicts itself. One instruction says a single missing step makes the score "lowest possible"; the scale then defines 0.5 as "some steps clearly match, but others are missing". Different judge models will resolve that conflict differently, which is one more reason to validate per judge model rather than reuse thresholds across models.

9.2 TaskCompletionMetric: extract outcome, then score alignment#

TaskCompletionMetric(task=None) requires input and actual_output, sets requires_trace=True, and normally reads the whole trace. Its algorithm is:

  1. Extract the task and outcome. With a trace, the judge receives the nested trace JSON. Without a trace, standalone measure() falls back to input, output and tool calls. If you pass task=, the extraction call still runs because the outcome is needed; your supplied task replaces the extracted task.
  2. Ask for TaskCompletionVerdict{verdict: float, reason} where the instructions define verdict 1 as perfectly achieving the task and 0 as not achieving it.
  3. Use the verdict as the score, subject to strict-mode zeroing but not range clamping.

That is two judge calls per case, plus no reference answer. A high score means "the judge's own outcome summary aligns with the task as the judge re-read it". It does not mean a golden expected output was matched, a tool actually changed state, or the agent followed policy.

Use it for:

  • broad end-to-end outcome screening when no exact expected output exists
  • comparing whether an agent even attempted the requested task
  • catching loops or incomplete runs when paired with process metrics

Do not use it alone for:

  • refund issued yes/no correctness
  • exact answer correctness in RAG
  • regression gates where a deterministic oracle exists
  • safety or permission compliance

The task= parameter is most useful when the user input is ambiguous or when the same input should be evaluated against a precise operational objective. It does not turn the metric into a reference-based grader; it only removes one extraction degree of freedom.

9.3 StepEfficiencyMetric: an adversarial auditor with no budget#

StepEfficiencyMetric also requires a trace. It makes two judge calls: extract the task, then ask for EfficiencyVerdict{score, reason}. The prompt is deliberately adversarial. It describes the judge as an efficiency auditor, defines efficiency as achieving the user's goal with the fewest, simplest and most direct actions, instructs zero tolerance for unnecessary actions, and says that if it is unclear whether an action was required, assume it was unnecessary. It even warns that the metric is adversarial and the lowest defensible score should be assigned. The opening of the real prompt is printed in 9.4.

This framing is useful because LLM judges are often generous. It is also dangerous because "minimal" is not defined by a budget, reference trajectory or cost model. The metric explicitly ignores correctness. A fast wrong answer can look efficient; a necessary retry can look wasteful if the trace does not show why it was necessary.

Use Step Efficiency when:

  • you have evidence that agents waste tool calls and want a pressure metric
  • you pair it with Task Completion and deterministic budget checks
  • traces include enough reasoning or tool output to explain why a step was needed

Do not use it as a latency or cost metric. It is neither. Measure latency and cost separately; use trajectory budgets from 10A.7, 4.3 when you need exact limits.

9.4 PlanAdherence and PlanQuality: the empty-plan pass#

Both plan metrics require a trace and make up to three judge calls:

  1. extract the task
  2. extract an explicit or clearly evidenced plan as AgentPlan{plan: list[str]}
  3. evaluate adherence or quality

When extraction returns an empty plan, 4.3.5 short-circuits before the third call and assigns the empty-plan result described below.

The extraction prompt is conservative. It accepts evidence from reasoning or thought fields inside tool calls and explicit plan-like statements in trace content, and instructs the judge not to invent steps. If no plan is evidenced, the correct extraction is {"plan": []}.

Here is the sharp edge: in 4.3.5, an empty plan scores 1.0 for both metrics. The reason says there were no plans to evaluate and asks you to check whether planning or reasoning is stored in a trace attribute. In the first traced sample, Plan Adherence passed at 1.0 for exactly this reason. A plan-less agent therefore appears perfectly plan-adherent.

To make these metrics meaningful, put plans in the trace deliberately. Options include:

  • a planning LLM span whose output is the plan
  • ToolCall(reasoning=...) where the tool-call object carries reasoning
  • a custom span whose output is a structured plan
  • copying plan text into span input or output, because metadata is not included in _trace_dict

Here is the first option working end to end. The agent below writes a three-step plan in a planning llm span, then performs steps 1 and 3 and skips step 2 (reading the refund policy). The judges are scripted, so the numbers are not a verdict on any real model; what the sample proves is the mechanics: the plan is found in the trace, extracted as AgentPlan{plan: [...]}, and both plan metrics make their third call. It also prints where in the prompt the judge found the plan, and the opening of the Plan Adherence and Step Efficiency prompts:

python
# plan_real_trace.py: plan metrics on a trace that really contains a plan (lesson 10B.5)
import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import PlanAdherenceMetric, PlanQualityMetric, StepEfficiencyMetric
from deepeval.tracing import observe, update_current_span, update_current_trace

from fake_judge import FakeJudge

PLAN = ("Plan: 1. look up the order. 2. read the refund policy. "
        "3. tell the customer the refund window.")
STEPS = [{"task": "Tell the customer the refund window for order A-1042"}]
PLAN_STEPS = ["look up the order", "read the refund policy", "tell the customer the refund window"]

adherence_judge = FakeJudge(script={
    "Task": STEPS, "AgentPlan": [{"plan": PLAN_STEPS}],
    "PlanAdherenceScore": [{"score": 0.4, "reason": "Step 2 (read the refund policy) never happened."}],
})
quality_judge = FakeJudge(script={
    "Task": STEPS, "AgentPlan": [{"plan": PLAN_STEPS}],
    "PlanQualityScore": [{"score": 0.8, "reason": "Complete and non-redundant."}],
})
efficiency_judge = FakeJudge(script={
    "Task": STEPS,
    "EfficiencyVerdict": [{"score": 0.9, "reason": "Two actions, both needed."}],
})


@observe(type="llm", model="fake-planner")
def make_plan(query: str):
    update_current_span(input=query, output=PLAN)
    return PLAN


@observe(type="tool", description="Look up an order")
def lookup_order(order_id: str):
    return {"order_id": order_id, "status": "delivered"}


@observe(type="agent", available_tools=["lookup_order"])
def agent(query: str):
    make_plan(query)
    lookup_order("A-1042")               # step 1
    answer = "Refunds take 5 business days."   # step 3, with step 2 skipped
    update_current_trace(input=query, output=answer)
    return answer


metrics = [PlanAdherenceMetric(model=adherence_judge), PlanQualityMetric(model=quality_judge),
           StepEfficiencyMetric(model=efficiency_judge)]
dataset = EvaluationDataset(goldens=[Golden(input="How long does a refund on order A-1042 take?")])
for golden in dataset.evals_iterator(
        metrics=metrics, async_config=AsyncConfig(run_async=False),
        display_config=DisplayConfig(print_results=False, show_indicator=False,
                                     inspect_after_run=False)):
    agent(golden.input)

for metric, judge in zip(metrics, (adherence_judge, quality_judge, efficiency_judge)):
    print(f"{metric.__name__}: score={metric.score} calls={judge.schemas()}")
    print("  reason:", metric.reason)

plan_prompt = adherence_judge.prompt(1)          # the AgentPlan extraction prompt
print("\n--- AgentPlan prompt: where the judge found the plan ---")
print(plan_prompt[plan_prompt.index('"name": "make_plan"'):][:420])
for title, prompt in [("PlanAdherence prompt, first 560 characters", adherence_judge.prompt(2)),
                      ("StepEfficiency prompt, first 560 characters", efficiency_judge.prompt(1))]:
    print(f"\n--- {title} ---")
    print(prompt[:560])
Output · real, DeepEval banner omitted50 lines
Plan Adherence: score=0.4 calls=['Task', 'AgentPlan', 'PlanAdherenceScore']
  reason: Step 2 (read the refund policy) never happened.
Plan Quality: score=0.8 calls=['Task', 'AgentPlan', 'PlanQualityScore']
  reason: Complete and non-redundant.
Step Efficiency: score=0.9 calls=['Task', 'EfficiencyVerdict']
  reason: Two actions, both needed.

--- AgentPlan prompt: where the judge found the plan ---
"name": "make_plan",
      "type": "llm",
      "input": "How long does a refund on order A-1042 take?",
      "output": "Plan: 1. look up the order. 2. read the refund policy. 3. tell the customer the refund window.",
      "model": "fake-planner",
      "children": []
    },
    {
      "name": "lookup_order",
      "type": "tool",
      "input": {
        "order_id": "A-1042"
      },
      "output": {
        "or

--- PlanAdherence prompt, first 560 characters ---
You are an **adversarial plan adherence evaluator**. Your goal is to assign the **lowest justifiable score** based on how strictly the agent's actions in the execution trace align with its declared plan.

INPUTS:

- **User Task:** The original request or objective.
- **Agent Plan:** The explicit step-by-step plan the agent was supposed to follow.
- **Execution Trace:** A detailed record of all agent actions, reasoning, tool calls, and outputs.

EVALUATION OBJECTIVE:

Determine whether the agent **exactly and exclusively** followed its plan.  
You are not

--- StepEfficiency prompt, first 560 characters ---
You are an **efficiency auditor** evaluating how economically an AI agent executed a task.

OBJECTIVE:

Determine how **efficiently** the agent executed the given task based on its full execution trace.
Efficiency means achieving the user's goal using the **fewest, simplest, and most direct** actions possible.

You must assign a score from **0.0 to 1.0** that reflects how close the execution came to the *minimal necessary sequence of actions*.

**Important:** You are not evaluating correctness, completeness, creativity, or helpfulness — only the *efficie
[netguard] total blocked attempts: 0 []

Three things to read in that output. First, all three metrics ran with the call counts from 14.2: Plan Adherence and Plan Quality made three calls (Task, AgentPlan, then the score), where the empty-plan trace in 4.1 stopped after two. Second, the plan came from the planning span's output text; nothing told DeepEval that span was "the plan", the extraction prompt found it in the nested JSON. If your planner span were missing, you would be back to the empty-plan 1.0. Third, the Plan Adherence prompt opens with an adversarial framing ("assign the lowest justifiable score", "exactly and exclusively followed its plan"), just as the Step Efficiency prompt opens as an "efficiency auditor". Expect real judges to score harshly on both, and calibrate thresholds against human labels (10A.5) rather than keeping 0.5.

The fourth option in the list, ToolCall(reasoning=...), is a field on the tool-call object (ToolCall(name="lookup_order", reasoning="Step 1 of the plan: find the order")). Tool spans do not fill it automatically, so it is useful when you build tools_called yourself; with plain @observe spans, prefer a planning span.

PlanAdherenceMetric asks whether execution followed the evidenced plan. Its anchors penalize deviations strongly; a score above 0.5 should be rare when there are real deviations. PlanQualityMetric asks whether the plan itself was complete, efficient and non-redundant. They answer different questions: an agent can follow a bad plan perfectly or abandon a good plan halfway.

Neither metric validates that planning is desirable. For simple tasks, planning may be overhead. For long-horizon tasks, explicit plans are useful evidence but can be performative: the model writes a plausible plan because the architecture expects one. Validate against outcomes before interpreting plan quality as agent quality.

9.5 The standalone TRACE: null behaviour#

The documentation describes Step Efficiency, Plan Adherence and Plan Quality as trace-only metrics that must be used in evals_iterator or through @observe. In 4.3.5 standalone measure() does not raise. It sends prompts with TRACE: null or Execution Trace: null and returns whatever the judge says. Task Completion falls back to its input/output prompt. Only AgentLoopDetectionMetric guards properly and returns 0 with "No trace data found".

This is a documentation-versus-code disagreement. The lesson teaches the stricter rule: never run these metrics standalone. If you see a score, you have asked a judge to grade a missing trace and the score is meaningless. A future version may enforce the documented behaviour; your harness should not depend on the current permissive bug.

9.6 How to combine the trajectory judges#

Question Metric Pair it with Why
Did the run achieve the user's objective? Task Completion exact outcome or state grader the judge can miss extraction errors
Did it waste actions? Step Efficiency explicit step/token/tool budgets "minimal" is subjective and correctness-blind
Did it follow the plan it wrote? Plan Adherence instrumentation that records a plan empty plans pass at 1.0
Was the written plan any good? Plan Quality human review of sample traces plan quality is not outcome quality
Did it choose the correct tools? Tool Correctness available-tools selection and permissions task success can hide bad routing
Did it get stuck? Agent Loop Detection Step Efficiency loop detection is deterministic; efficiency is judgement

A defensible agent evaluation usually uses one outcome measure, one or two deterministic process measures, and at most one judge-based process measure unless you have calibrated them. More red and green numbers can create false confidence without adding independent evidence.


Part 10: Tool-centred metrics and loop detection#

Deep-dive

10.1 ToolCorrectness beyond the deterministic core#

10B.4, 5.2 introduced the deterministic core. The agent context adds several operational details.

The next sample builds the ToolCall objects once and runs every variant. ToolCall is a Pydantic model with the fields name, type (default FUNCTION), description, reasoning, output, input_parameters and turn (used only by the multi-turn metric in 11.5). Only name, type, input_parameters and output take part in matching. Save it as tool_metrics.py; it also contains the Tool Permission and Argument Correctness probes that 10.2 and 10.3 discuss.

python
# tool_metrics.py: Tool Correctness variants, Tool Permission, Argument Correctness (lesson 10B.5)
import netguard  # noqa: F401

from deepeval.metrics import (ArgumentCorrectnessMetric, ToolCorrectnessMetric,
                              ToolPermissionMetric)
from deepeval.test_case import LLMTestCase, ToolCall, ToolCallParams

from fake_judge import FakeJudge


def show(name, metric, judge=None):
    calls = judge.schemas() if judge else []
    print(f"{name}: score={metric.score!r} success={metric.success} calls={calls}")


def run(case, judge=None, **kwargs):
    metric = ToolCorrectnessMetric(model=judge or FakeJudge(), async_mode=False, **kwargs)
    metric.measure(case, _show_indicator=False)
    return metric


case = LLMTestCase(
    input="What's the weather in Paris and convert 20C to F?",
    actual_output="It is 20C (68F) in Paris.",
    tools_called=[
        ToolCall(name="get_weather", input_parameters={"city": "Paris"}, output="20C"),
        ToolCall(name="convert", input_parameters={"c": 20}, output="68F"),
        ToolCall(name="web_search", input_parameters={"q": "paris weather"}),
    ],
    expected_tools=[
        ToolCall(name="convert", input_parameters={"c": 20}),
        ToolCall(name="get_weather", input_parameters={"city": "Paris"}),
    ],
)

try:
    ToolCorrectnessMetric()
except Exception as exc:
    print("ToolCorrectnessMetric() without model:", type(exc).__name__, str(exc).splitlines()[0])

print("\n== ToolCorrectness variants")
show("default", run(case))
show("ordering", run(case, should_consider_ordering=True))
show("exact", run(case, should_exact_match=True))
show("INPUT_PARAMETERS", run(case, evaluation_params=[ToolCallParams.INPUT_PARAMETERS]))

judge = FakeJudge(script={"ToolSelectionScore": [{"score": 1.0, "reason": "The right tools were chosen."}]})
metric = run(case, judge, available_tools=[ToolCall(name="get_weather"), ToolCall(name="convert"),
                                          ToolCall(name="web_search"), ToolCall(name="send_email")])
show("with available_tools", metric, judge)

print("\n== Partial credit on arguments, and the empty-expected edge")
half = LLMTestCase(
    input="Weather in Paris in Celsius?", actual_output="20C",
    tools_called=[ToolCall(name="get_weather",
                           input_parameters={"city": "Paris", "units": "kelvin"})],
    expected_tools=[ToolCall(name="get_weather",
                             input_parameters={"city": "Paris", "units": "celsius"})],
)
show("one of two keys matches", run(half, evaluation_params=[ToolCallParams.INPUT_PARAMETERS]))
show("same case, names only", run(half))
none_expected = LLMTestCase(
    input="Say hello", actual_output="Hello!",
    tools_called=[ToolCall(name="web_search")], expected_tools=[],
)
show("expected_tools=[] but one call", run(none_expected))
show("strict_mode on a 0.5 score", run(case, should_consider_ordering=True, strict_mode=True))

print("\n== ToolPermission")
metric = ToolPermissionMetric(allowed_tools=["get_weather", "convert"], denied_tools=["send_email"])
metric.measure(case, _show_indicator=False)
show("ToolPermission", metric)
print("  reason:", metric.reason)

print("\n== ArgumentCorrectness")
judge = FakeJudge(script={
    "Verdicts": [{"verdicts": [
        {"verdict": "yes"}, {"verdict": "yes"},
        {"verdict": "no", "reason": "search query redundant"},
    ]}],
    "ArgumentCorrectnessScoreReason": [{"reason": "Two of three argument sets were relevant."}],
})
metric = ArgumentCorrectnessMetric(model=judge, async_mode=False)
metric.measure(case, _show_indicator=False)
show("ArgumentCorrectness", metric, judge)
Output · real22 lines
ToolCorrectnessMetric() without model: DeepEvalError OpenAI API key is not configured. Set OPENAI_API_KEY in your environment or pass `api_key` to OpenAIModel(...).

== ToolCorrectness variants
default: score=1.0 success=True calls=[]
ordering: score=0.5 success=True calls=[]
exact: score=0.0 success=False calls=[]
INPUT_PARAMETERS: score=1.0 success=True calls=[]
with available_tools: score=1.0 success=True calls=['ToolSelectionScore']

== Partial credit on arguments, and the empty-expected edge
one of two keys matches: score=0.5 success=True calls=[]
same case, names only: score=1.0 success=True calls=[]
expected_tools=[] but one call: score=0.0 success=False calls=[]
strict_mode on a 0.5 score: score=0 success=False calls=[]

== ToolPermission
ToolPermission: score=0.6666666666666666 success=False calls=[]
  reason: 1 of 3 tool call(s) were unauthorized: ['web_search']. Allowed=['convert', 'get_weather'], Denied=['send_email'].

== ArgumentCorrectness
ArgumentCorrectness: score=0.6666666666666666 success=True calls=['Verdicts', 'ArgumentCorrectnessScoreReason']
[netguard] total blocked attempts: 0 []

What that output teaches, line by line:

  • The constructor wants a model even though no call is made. ToolCorrectnessMetric() without a key or explicit model raises DeepEvalError before any measurement. The keyless workaround is to pass any DeepEvalBaseLLM, including the track's FakeJudge; it is constructed but called only when available_tools is supplied.
  • default: 1.0. The default score is recall over the expected tools, in any order: each expected tool takes its best unused match among the calls. The extra web_search call is not penalized, but only because something was expected.
  • ordering: 0.5. should_consider_ordering=True scores a weighted longest common subsequence of expected and called tools, divided by the number of expected tools. Required tools in the wrong order lose credit.
  • exact: 0.0. should_exact_match=True requires the same length, the same order and matching names, so one extra call is a failure.
  • INPUT_PARAMETERS: 1.0, then 0.5 in the partial-credit block. Adding ToolCallParams.INPUT_PARAMETERS does not make parameters all-or-nothing. A tool's match is scored by key overlap: matched keys / union of keys, recursing into nested dicts. With {"city": "Paris", "units": "kelvin"} against {"city": "Paris", "units": "celsius"}, one of two keys matches and the score is 0.5; the same case compared by names only scores 1.0. With should_exact_match=True the parameter dicts must be equal. ToolCallParams.OUTPUT compares outputs when the expected tool has one, and a ToolCall.type mismatch scores the pair 0.
  • expected_tools=[] with one call: 0.0. So the rule "extra calls are free" holds only when at least one tool was expected. A case that expects no tool at all fails the moment any tool is called, which is exactly the behaviour you want for "do not call a tool for this question".
  • strict_mode: 0. With strict_mode=True the threshold becomes 1 and any score below it, here 0.5, is forced to 0.
  • with available_tools: 1.0 and one call. Supplying available_tools=[ToolCall(...), ...] adds a judge-scored tool-selection assessment (ToolSelectionScore) for over-selection, under-selection and mis-selection, and the final score is the minimum of the deterministic calling score and the judge's selection score. Remember the type note from 2.2: here the list holds ToolCall objects, not names.

Finally, tracing changes where tools_called comes from. On an agent span, DeepEval derives the list from descendant tool spans that are not owned by a nested agent. In the pytest fixture, Tool Correctness on the agent span saw child lookup_policy calls without manual construction. You still must provide expected_tools, usually from the golden or with update_current_span(expected_tools=...). Automatic derivation tells you what happened, not what should have happened.

10.2 ArgumentCorrectness: relevance, ownership and a silent missing-LLM trap#

ArgumentCorrectnessMetric is LLM-based. It requires input and tools called. For each tool call, the judge answers whether the input parameters relevantly and correctly address the original input; the score is the fraction of yes verdicts, followed by a reason call. No tool calls score 1.0 with the reason "No tool calls provided". In the tool_metrics.py sample from 10.1, scripted yes/yes/no over three calls produced 0.6666666666666666 and two judge calls (Verdicts, then the reason schema). Setting include_reason=False drops the second call; see 14A.8.

This metric judges relevance to the user input, not schema validity or exact correctness. A call can be relevant but invalid, or valid but irrelevant. Use schema validation, tool-side tests or Tool Correctness with INPUT_PARAMETERS for exactness.

Trace-aware attribution is more subtle. When a span metric receives no explicit tools_called but has a trace subtree, DeepEval attributes a tool call to the LLM span that chose its arguments: the tool's parent if that parent is an LLM span, otherwise the latest earlier LLM sibling. Tool calls without an owning LLM span are left out. In plain @observe code where tools hang directly under an agent, the metric may see no attributable calls at all.

The argument_attribution.py sample below demonstrates both cases. Without an LLM span, the tool metric errored because tools_called was missing. With the tool nested under an LLM span, the judge received the LLM span's clean input and correctly scored the wrong order id as 0:

python
# argument_attribution.py: which LLM span ArgumentCorrectness blames (lesson 10B.5)

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import ArgumentCorrectnessMetric
from deepeval.tracing import observe, update_current_span, update_current_trace

from fake_judge import FakeJudge


def run_once(with_llm: bool, judge: FakeJudge):
    metric = ArgumentCorrectnessMetric(model=judge, async_mode=False)

    @observe(type="tool", metrics=[metric])
    def lookup(order_id: str):
        return {"order_id": order_id, "status": "delivered"}

    @observe(type="llm", model="fake-llm")
    def choose(query: str):
        update_current_span(input=query, output="call lookup")
        return lookup("WRONG-ORDER")

    @observe(type="agent")
    def agent(query: str):
        if with_llm:
            choose(query)
        else:
            lookup("WRONG-ORDER")
        update_current_trace(input=query, output="The order is delivered.")
        return "The order is delivered."

    dataset = EvaluationDataset(goldens=[Golden(input="Where is order A-1042?")])
    iterator = dataset.evals_iterator(
        metrics=[], async_config=AsyncConfig(run_async=False),
        display_config=DisplayConfig(print_results=False, show_indicator=False, inspect_after_run=False))
    try:
        golden = next(iterator)
        while True:
            agent(golden.input)
            golden = iterator.send(None)
    except StopIteration:
        pass
    return metric


no_call_judge = FakeJudge(script={})
try:
    metric = run_once(False, no_call_judge)
    print("no llm span:", metric.score, metric.success, "judge calls:", no_call_judge.schemas(), "|", metric.reason)
except Exception as exc:
    print("no llm span error:", type(exc).__name__, str(exc).splitlines()[0])

yes_no_judge = FakeJudge(script={
    "Verdicts": [{"verdicts": [{"verdict": "no", "reason": "wrong order id"}]}],
    "ArgumentCorrectnessScoreReason": [{"reason": "The chosen id does not appear in the user input."}],
})
metric = run_once(True, yes_no_judge)
print("tool owned by llm span:", metric.score, metric.success, "judge calls:", yes_no_judge.schemas(), "|", metric.reason)
print("input the judge saw:", yes_no_judge.prompt(0).split("Input:")[-1].strip().splitlines()[0])
Output · real, DeepEval banner omitted5 lines
no llm span error: MissingTestCaseParamsError 'tools_called' cannot be None for the 'Argument Correctness' metric

tool owned by llm span: 0.0 False judge calls: ['Verdicts', 'ArgumentCorrectnessScoreReason'] | The chosen id does not appear in the user input.
input the judge saw: Where is order A-1042?
[netguard] total blocked attempts: 0 []

The design rule is: if you want Argument Correctness, model the decision point honestly. Put an llm span around the model call that chooses the action and invoke the tool inside or after that decision span in a way DeepEval can attribute. Do not attach the metric blindly to every tool span and assume the package will know which model chose the arguments.

10.3 ToolPermissionMetric: a deterministic allow/deny gate#

ToolPermissionMetric(allowed_tools=None, denied_tools=None, threshold=1.0, ...) is deterministic. A call is unauthorized if its name is in denied_tools, or if allowed_tools is set and the name is absent. Score is authorized calls divided by total calls; no calls score 1.0. The sample below (tool_permission.py) allows [get_weather, convert], denies [send_email], and makes a call to web_search, which is in neither list:

python
# tool_permission.py: the deterministic allow/deny gate (lesson 10B.5)
import netguard  # noqa: F401

from deepeval.metrics import ToolPermissionMetric
from deepeval.test_case import LLMTestCase, ToolCall

case = LLMTestCase(
    input="Weather in Paris, then convert 20C to F.",
    actual_output="It is 20C (68F) in Paris.",
    tools_called=[ToolCall(name="get_weather"), ToolCall(name="convert"),
                  ToolCall(name="web_search")],
)
metric = ToolPermissionMetric(allowed_tools=["get_weather", "convert"], denied_tools=["send_email"])
metric.measure(case, _show_indicator=False)
print(f"ToolPermission: score={metric.score!r} success={metric.success}")
print("reason:", metric.reason)
Output · real3 lines
ToolPermission: score=0.6666666666666666 success=False
reason: 1 of 3 tool call(s) were unauthorized: ['web_search']. Allowed=['convert', 'get_weather'], Denied=['send_email'].
[netguard] total blocked attempts: 0 []

This is one of the most valuable metrics in the whole agent catalogue because it is simple, cheap and security-relevant. It still has limits: it sees names, not argument-level effects. delete_records(table="audit_log") and delete_records(table="scratch") are the same tool name. Argument policy belongs in tool design and deterministic custom metrics, with Module 12 owning the security depth.

10.4 AgentLoopDetection: a deterministic health score#

AgentLoopDetectionMetric requires a trace but makes no judge call. Its constructor exposes the meaningful knobs:

text
AgentLoopDetectionMetric(
    threshold=0.5,
    repetition_threshold=3,
    similarity_threshold=0.85,
    check_tool_repetition=True,
    check_reasoning_stagnation=True,
    check_call_graph_cycles=True,
    ...
)

It computes up to three sub-scores:

  1. Tool repetition. Every tool span in the trace is keyed by its name plus its whole recorded input (all keyword arguments, sorted). The most repeated key decides the score: 0.0 when it occurs at least 2 * repetition_threshold times (6 by default), 0.5 at repetition_threshold (3), otherwise 1.0. The count is over the whole trace, not consecutive calls.
  2. Reasoning stagnation. Each LLM span's output is compared with the next LLM span's output only. Both are lowercased and reduced to "meaningful" words (longer than two characters and not on a built-in stop list); if either has fewer than 20 meaningful words, the pair is skipped. The similarity of a pair is the maximum of bigram Jaccard (shared word pairs divided by all word pairs) and difflib.SequenceMatcher(...).ratio() on the cleaned text. The highest pair similarity decides the score: 0.0 above 0.95, 0.5 at or above similarity_threshold (0.85), otherwise 1.0.
  3. Call-graph cycles. Each span gets the label type:name: plus the first 64 characters of its input (the source calls this an "input hash", but it is a prefix, not a hash). A label that appears twice on one root-to-leaf path is a cycle and scores 0.0; otherwise 1.0. Repeated siblings are not cycles; check 1 handles them.

The combined score is a weighted mean over enabled checks with weights 0.40, 0.35 and 0.25 respectively, divided by the sum of the enabled weights, so turning a check off renormalizes the others. strict_mode=True forces any score below the threshold to 0. The sample below (agent_loop_detection.py) creates six identical reasoning spans and six identical empty searches:

python
# agent_loop_detection.py: deterministic loop detection over a real @observe trace (lesson 10B.5)

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import AgentLoopDetectionMetric
from deepeval.tracing import observe, update_current_trace

REPEATED_THOUGHT = (
    "I still do not have enough evidence, so I should search the same policy again, "
    "read the same result carefully, and then decide whether another identical search "
    "might reveal a different answer for the user"
)


@observe(type="tool")
def search_policy(query: str):
    return []


@observe(type="llm", model="fake-llm")
def think(query: str):
    return REPEATED_THOUGHT


@observe(type="agent")
def looping_agent(query: str):
    for _ in range(6):
        think(query)
        search_policy("refund policy")
    answer = "I am still checking."
    update_current_trace(input=query, output=answer)
    return answer


metric = AgentLoopDetectionMetric(async_mode=False)
dataset = EvaluationDataset(goldens=[Golden(input="How long do refunds take?")])
iterator = dataset.evals_iterator(
    metrics=[metric], async_config=AsyncConfig(run_async=False),
    display_config=DisplayConfig(print_results=False, show_indicator=False, inspect_after_run=False))
try:
    golden = next(iterator)
    while True:
        looping_agent(golden.input)
        golden = iterator.send(None)
except StopIteration:
    pass

print("score:", metric.score)
print("success:", metric.success)
print("breakdown:", metric.score_breakdown)
print("reason:", metric.reason)
Output · real, DeepEval banner omitted5 lines
score: 0.25
success: False
breakdown: {'tool_repetition': 0.0, 'reasoning_stagnation': 0.0, 'call_graph_cycles': 1.0}
reason: Tool 'search_policy' called 6 times with identical arguments. Identical reasoning outputs at steps 0 and 1.
[netguard] total blocked attempts: 0 []

Read the breakdown before interpreting the score. Here 0.25 is not a vague "25% looping" measure. It is the weighted combination of two failed checks and one passed check: 0.40*0 + 0.35*0 + 0.25*1 = 0.25. The metric's own docstring lists two limitations (input-prefix collisions can create false cycles, and paraphrases can evade stagnation detection). The rules above imply more blind spots than that, and because the metric is deterministic you can map them exactly. This probe runs one fixture per edge:

python
# loop_detection_internals.py: where AgentLoopDetection's deterministic checks go blind (lesson 10B.5)
import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import AgentLoopDetectionMetric
from deepeval.tracing import observe, update_current_trace

SHORT = "No result yet, so I will search the refund policy again."          # 7 meaningful words
LONG_A = ("The refund policy search returned nothing useful, so the sensible next action is "
          "querying the policy index again with identical keywords, reading every returned "
          "paragraph carefully, comparing each clause against the customer question, and then "
          "deciding whether another identical query might finally surface the refund window")
LONG_B = ("Customer satisfaction matters greatly here, therefore drafting a polite holding reply "
          "explaining that refund timelines vary by payment method, region, merchant category, "
          "bank processing schedules and public holidays seems wise while waiting for further "
          "information from internal finance colleagues about this specific order")
LONG_A1 = LONG_A.replace("carefully", "attentively")                    # one word changed
LONG_A2 = LONG_A.replace("finally", "eventually")                       # a different word changed
LONG_A3 = (LONG_A.replace("carefully", "attentively").replace("sensible", "obvious")
           .replace("finally", "eventually").replace("comparing", "checking"))   # four words changed
PREFIX = "Customer asks about order A-1042. Full conversation so far follows here: "   # 74 characters


@observe(type="llm", model="fake-llm")
def think(text: str):
    return text


@observe(type="tool")
def search(query: str):
    return []


@observe(type="agent", name="worker")
def worker(task: str):
    if "first" in task:                                          # one legitimate sub-delegation
        worker(PREFIX + "second request: issue a refund")       # differs only after char 64
    return "ok"


FIXTURES = {
    "short identical thoughts x6": lambda: [think(SHORT) for _ in range(6)],
    "long thoughts A,B,A,B,A,B": lambda: [think(LONG_A if i % 2 == 0 else LONG_B) for i in range(6)],
    "long thought, 'carefully' changed": lambda: [think(LONG_A), think(LONG_A1)],
    "long thought, 'finally' changed": lambda: [think(LONG_A), think(LONG_A2)],
    "long thought, four words changed": lambda: [think(LONG_A), think(LONG_A3)],
    "identical search x3": lambda: [search("refund policy") for _ in range(3)],
    "same 64-char input prefix": lambda: worker(PREFIX + "first request: check status"),
}


def run(label, behaviour):
    @observe(type="agent", name="root")
    def agent(query: str):
        behaviour()
        update_current_trace(input=query, output="done")
        return "done"

    metric = AgentLoopDetectionMetric(async_mode=False)
    dataset = EvaluationDataset(goldens=[Golden(input="How long do refunds take?")])
    for golden in dataset.evals_iterator(
            metrics=[metric], async_config=AsyncConfig(run_async=False),
            display_config=DisplayConfig(print_results=False, show_indicator=False,
                                         inspect_after_run=False)):
        agent(golden.input)
    print(f"{label}: score={metric.score:.2f} breakdown={metric.score_breakdown}")
    if metric.score < 1:
        print("   reason:", metric.reason)


for label, behaviour in FIXTURES.items():
    run(label, behaviour)
Output · real, DeepEval banners omitted12 lines
short identical thoughts x6: score=1.00 breakdown={'tool_repetition': 1.0, 'reasoning_stagnation': 1.0, 'call_graph_cycles': 1.0}
long thoughts A,B,A,B,A,B: score=1.00 breakdown={'tool_repetition': 1.0, 'reasoning_stagnation': 1.0, 'call_graph_cycles': 1.0}
long thought, 'carefully' changed: score=0.65 breakdown={'tool_repetition': 1.0, 'reasoning_stagnation': 0.0, 'call_graph_cycles': 1.0}
   reason: Identical reasoning outputs at steps 0 and 1.
long thought, 'finally' changed: score=0.82 breakdown={'tool_repetition': 1.0, 'reasoning_stagnation': 0.5, 'call_graph_cycles': 1.0}
   reason: High reasoning overlap (0.89) at steps 0 and 1.
long thought, four words changed: score=1.00 breakdown={'tool_repetition': 1.0, 'reasoning_stagnation': 1.0, 'call_graph_cycles': 1.0}
identical search x3: score=0.80 breakdown={'tool_repetition': 0.5, 'reasoning_stagnation': 1.0, 'call_graph_cycles': 1.0}
   reason: Tool 'search' called 3 times with identical arguments.
same 64-char input prefix: score=0.75 breakdown={'tool_repetition': 1.0, 'reasoning_stagnation': 1.0, 'call_graph_cycles': 0.0}
   reason: Cycle detected in execution path: agent:worker -> agent:worker.
[netguard] total blocked attempts: 0 []

What each line proves:

  • Short repeated thoughts are never compared. Six identical seven-word thoughts score a perfect 1.0, because every pair falls under the 20-meaningful-word minimum. Terse agents (and most ReAct "Thought:" lines are terse) are invisible to the stagnation check.
  • Only neighbours are compared. An agent that alternates between two long thoughts, A, B, A, B, is never compared with itself, so it scores 1.0.
  • The near-duplicate band is narrow and position-sensitive. Changing carefully gives similarity above 0.95 (0.0, "identical"); changing finally gives 0.89 (0.5); changing four words drops below 0.85 and the check passes. The four-word result is lower than intuition suggests because of a difflib default: when the second string has 200 or more characters, SequenceMatcher's "autojunk" heuristic ignores every character that makes up more than 1% of it while looking for matching blocks, and in English text that is most of the alphabet, which sharply lowers the ratio for long texts. Recomputed with autojunk=False, the same pair scores about 0.93 and would have landed in the 0.5 band. In practice, the check fires only for near-verbatim repetition of long reasoning.
  • Three identical calls halve the tool score. repetition_threshold=3 means the third identical call already costs 0.20 of the total score. A legitimate poll that retries a status check three times with the same arguments is penalized; raise repetition_threshold for agents that poll by design.
  • Long inputs that share a prefix look like a cycle. The worker legitimately delegated a different request to a second worker, but both inputs share their first 64 characters once serialized, so the labels match and the metric reports a cycle. Prompts and task descriptions that start with the same boilerplate are exactly this shape.

It is a tripwire, not a proof of termination. Plant faults that match how your agent loops before trusting its silence.

Use it in CI because it is deterministic and cheap. Pair it with a hard step or wall-clock budget, since a non-repetitive but endlessly diverse agent can still fail to stop. 10A.7's budget graders remain the more explicit reliability mechanism.

10.5 A minimal tool-evaluation battery#

For most single-turn tool agents, start with this battery:

Layer Metric or check Cost Failure it catches
expected routing Tool Correctness, usually any-order zero judge calls unless available_tools required tool missing
forbidden routing Tool Permission zero dangerous or out-of-scope tool used
argument exactness Tool Correctness with INPUT_PARAMETERS, schema checks, or a custom metric zero or low wrong entity/id/payload
argument relevance Argument Correctness judge calls plausible but irrelevant arguments
loop health Agent Loop Detection zero repeated identical actions or stagnant reasoning
outcome exact state/output grader, then Task Completion if needed low to high the user goal was not achieved

Only after this baseline is green should you spend money on broader trajectory judges. The deterministic metrics are narrower but much easier to defend.


Part 11: Multi-turn agent metrics#

Deep-dive

11.1 The unit-interaction preprocessing step#

GoalAccuracyMetric, ToolUseMetric, TopicAdherenceMetric, ConversationToolCorrectnessMetric and the multi-turn MCP metrics operate on ConversationalTestCase objects, not traced trees. (ConversationToolCorrectnessMetric is the exception to the unit-splitting rule below: it scores turns directly, see 11.5.) Before scoring, DeepEval splits the turns into unit interactions. A unit starts at a user turn that follows an assistant turn; a trailing unit is kept only when it contains more than one turn and ends with an assistant turn. The details matter because a short or incomplete conversation can silently produce few or no scorable units.

This is one of the places where the documentation's language and the implementation need careful reading. "Multi-turn" does not mean every turn is always scored in context, and it does not mean tracing. DeepEval's multi-turn evaluation documentation says tracing is not supported there yet. These metrics read the conversation object you construct or capture; they do not receive _trace_dict.

The general conversation metrics (Knowledge Retention, Role Adherence, Conversation Completeness, Turn Relevancy and the Turn RAG metrics) belong to 10B.4, Part 6. The four here are agent-specific because they ask about goals, tool use and topical control.

11.2 GoalAccuracyMetric: goal and plan means averaged#

GoalAccuracyMetric builds goal and step descriptions in code for each unit: user messages form the goal; assistant messages and tools called form the steps. Unlike Task Completion there is no initial judge extraction call for the goal. Per unit it asks for a GoalScore and a PlanScore, then makes a final free-text reason call. The score is:

text
(mean goal score across units + mean plan score across units) / 2

Save the sample below as multiturn_agent_metrics.py. It builds one conversation and runs Goal Accuracy, Tool Use and Topic Adherence on it, so this section reads its first lines and 11.3 and 11.4 read the rest. The scripts feed Goal Accuracy goal scores [1.0, 0.5] and plan scores [1.0, 1.0], so the score is (0.75 + 1.0) / 2 = 0.875:

python
# multiturn_agent_metrics.py: GoalAccuracy, ToolUse and TopicAdherence (lesson 10B.5)

import netguard  # noqa: F401

from deepeval import evaluate
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import GoalAccuracyMetric, ToolUseMetric, TopicAdherenceMetric
from deepeval.test_case import ConversationalTestCase, ToolCall, Turn

from fake_judge import FakeJudge


def show(name, metric, judge):
    print(f"{name}: score={metric.score!r} success={metric.success} calls={judge.schemas()}")
    print("  reason:", str(metric.reason).replace("\n", " ")[:220])


conversation = ConversationalTestCase(
    scenario="User wants weather then a unit conversion",
    turns=[
        Turn(role="user", content="Weather in Paris?"),
        Turn(role="assistant", content="20C and sunny.",
             tools_called=[ToolCall(name="get_weather", input_parameters={"city": "Paris"})]),
        Turn(role="user", content="In Fahrenheit? Also, who won the football?"),
        Turn(role="assistant", content="68F. I can only help with weather."),
    ],
)

judge = FakeJudge(script={
    "GoalScore": [{"score": 1.0, "reason": "goal met"}, {"score": 0.5, "reason": "partly met"}],
    "PlanScore": [{"score": 1.0, "reason": "direct"}, {"score": 1.0, "reason": "direct"}],
    "": ["unit goals and plan reviewed"],
})
metric = GoalAccuracyMetric(model=judge, async_mode=False)
metric.measure(conversation, _show_indicator=False)
show("GoalAccuracy", metric, judge)

judge = FakeJudge(script={
    "ToolSelectionScore": [{"score": 1.0, "reason": "right tool"}, {"score": 0.5, "reason": "missing conversion"}],
    "ArgumentCorrectnessScore": [{"score": 1.0, "reason": "arguments fit"}],
    "Reason": [{"reason": "selection was inconsistent"}, {"reason": "arguments were fine"}],
})
metric = ToolUseMetric(available_tools=[ToolCall(name="get_weather"), ToolCall(name="convert")],
                       model=judge, async_mode=False)
metric.measure(conversation, _show_indicator=False)
show("ToolUse standalone", metric, judge)

judge = FakeJudge(script={
    "QAPairs": [
        {"qa_pairs": [{"question": "Weather in Paris?", "response": "20C"}]},
        {"qa_pairs": [{"question": "F?", "response": "68F"},
                      {"question": "football?", "response": "only weather"}]},
    ],
    "RelevancyVerdict": [
        {"verdict": "TP", "reason": "on topic answered"},
        {"verdict": "TP", "reason": "on topic answered"},
        {"verdict": "TN", "reason": "refused off-topic"},
    ],
    "TopicAdherenceReason": [{"reason": "All pairs were handled correctly."}],
})
metric = TopicAdherenceMetric(relevant_topics=["weather"], model=judge, async_mode=False)
metric.measure(conversation, _show_indicator=False)
show("TopicAdherence", metric, judge)

judge = FakeJudge(script={
    "ToolSelectionScore": [{"score": 0.2, "reason": "poor"}, {"score": 0.2, "reason": "poor"}],
    "ArgumentCorrectnessScore": [{"score": 0.2, "reason": "poor"}],
    "Reason": [{"reason": "poor selection"}, {"reason": "poor arguments"}],
})
result = evaluate([conversation], [ToolUseMetric(available_tools=[ToolCall(name="get_weather")], model=judge)],
                  async_config=AsyncConfig(run_async=False),
                  display_config=DisplayConfig(print_results=False, show_indicator=False, inspect_after_run=False))
md = result.test_results[0].metrics_data[0]
print("ToolUse inside evaluate:", md.score, md.success, "test success:", result.test_results[0].success)
Output · real, DeepEval banner omitted9 lines
GoalAccuracy: score=0.875 success=True calls=['GoalScore', 'GoalScore', 'PlanScore', 'PlanScore', None]
  reason: "unit goals and plan reviewed"
ToolUse standalone: score=0.75 success=None calls=['ToolSelectionScore', 'ToolSelectionScore', 'ArgumentCorrectnessScore', 'Reason', 'Reason']
  reason: selection was inconsistent arguments were fine
TopicAdherence: score=1.0 success=True calls=['QAPairs', 'QAPairs', 'RelevancyVerdict', 'RelevancyVerdict', 'RelevancyVerdict', 'TopicAdherenceReason']
  reason: All pairs were handled correctly.

ToolUse inside evaluate: 0.2 False test success: False
[netguard] total blocked attempts: 0 []

The None in the call list is the schema-less final reason call. The probe also exposes an implementation quirk: the step string accumulates, so later step descriptions repeat earlier assistant messages. That is not automatically wrong, but it changes prompt length and may bias the judge towards earlier context.

Use Goal Accuracy for multi-turn tasks where the user's intent evolves or is refined. Do not interpret it as a task-completion proof. It is still judge-scored and reference-free unless you encode goals externally. It also averages goal and plan equally, a design choice you may or may not agree with. If outcomes matter more than process, weight them accordingly in your own reporting.

11.3 ToolUseMetric: minimum of selection and argument quality#

ToolUseMetric(available_tools=[...]) requires the list of tools the assistant could use, as ToolCall objects rather than names (see the note in 2.2). Per unit it asks for a ToolSelectionScore; for units that used tools it asks for an ArgumentCorrectnessScore; two final reason calls explain the dimensions. The score is:

text
min(mean selection score, mean argument correctness score)

Taking the minimum is strict: correct arguments cannot compensate for choosing the wrong tool, and correct tool choice cannot compensate for bad arguments. The sample in 11.2 scripted selection [1.0, 0.5] and argument correctness [1.0], so the standalone score is min(0.75, 1.0) = 0.75. The ToolUse lines of that output are:

Output · real, ToolUse lines of the 11.2 run2 lines
ToolUse standalone: score=0.75 success=None calls=['ToolSelectionScore', 'ToolSelectionScore', 'ArgumentCorrectnessScore', 'Reason', 'Reason']
ToolUse inside evaluate: 0.2 False test success: False

The two ToolUse lines use different scripted verdicts (selection [1.0, 0.5] in the standalone run, all 0.2 inside evaluate()), so ignore the score difference and compare only the success field: None standalone, False inside evaluate().

Notice success=None after standalone measure(). This is a verified 4.3.5 quirk in the synchronous path. Inside evaluate() the success value is computed and recorded correctly. Use metric.is_successful() where supported, or evaluate through the runner; do not read the raw attribute in standalone scripts.

As with single-turn argument correctness, this is relevance and quality judgement, not proof that arguments match an exact schema. It is best for assistants whose tool use unfolds over several user requests, for example a support chat that gathers an order id, looks up status, then offers a replacement.

11.4 TopicAdherenceMetric: a confusion-matrix judge#

TopicAdherenceMetric(relevant_topics=[...]) extracts question/answer pairs per unit, then classifies each pair as:

Verdict Meaning
TP on-topic question answered
TN off-topic question correctly not answered
FP off-topic question answered
FN on-topic question not answered

The score is (TP + TN) / (TP + TN + FP + FN), with zero pairs scoring 0. This is accuracy in the machine-learning sense, computed over judge-labelled pairs. The 11.2 sample scripted two true positives and one true negative and scored 1.0:

Output · real, TopicAdherence lines of the 11.2 run2 lines
TopicAdherence: score=1.0 success=True calls=['QAPairs', 'QAPairs', 'RelevancyVerdict', 'RelevancyVerdict', 'RelevancyVerdict', 'TopicAdherenceReason']
  reason: All pairs were handled correctly.

The confusion-matrix framing is useful because topical control is not just "answer in scope". A good scoped assistant also refuses or redirects out-of-scope requests. But the labels are judge-produced, so all the usual judge-validation concerns apply. In particular, accuracy can be misleading when most user requests are on-topic. If off-topic resistance is the risk, report FP and TN counts separately rather than only the aggregate.

11.5 ConversationToolCorrectnessMetric: the deterministic multi-turn tool metric#

ConversationToolCorrectnessMetric is new in deepeval 4.3.6 (it is absent from 4.3.5, where hasattr(deepeval.metrics, "ConversationToolCorrectnessMetric") is False) and is documented at deepeval.com/docs/metrics-conversation-tool-correctness. It is the multi-turn counterpart of Tool Correctness and the missing deterministic spine for conversations: it makes no judge call and takes no model argument. What the 4.3.6 source does:

  • Expected tools live on the conversation. You set ConversationalTestCase(expected_tools=[ToolCall(...)]). The actual calls are Turn.tools_called on assistant turns.
  • ToolCall.turn pins an expected tool to a turn index. A pinned index must point at an assistant turn, otherwise the metric raises MissingTestCaseParamsError. Each pinned turn is one check.
  • Unpinned expected tools (turn=None) form one more check against the assistant tool calls left over after the pinned ones were matched, labelled Any turn (or Conversation when nothing is pinned).
  • Each check reuses the Tool Correctness scorer, with the same should_exact_match, should_consider_ordering and evaluation_params options, and the final score is the plain mean of the check scores.
  • Constructor: threshold=0.5, evaluation_params, should_exact_match, should_consider_ordering, include_reason, async_mode, strict_mode, verbose_mode, flaky.

The sample (save as conversation_tool_correctness.py; it needs deepeval>=4.3.6) pins one tool that happened and one that did not:

python
# conversation_tool_correctness.py: the deterministic multi-turn tool metric, new in 4.3.6 (lesson 10B.5)
import netguard  # noqa: F401

from deepeval import evaluate
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import ConversationToolCorrectnessMetric
from deepeval.test_case import ConversationalTestCase, ToolCall, Turn

turns = [
    Turn(role="user", content="Where is order A-1042?"),                       # turn 0
    Turn(role="assistant", content="Let me check.",                            # turn 1
         tools_called=[ToolCall(name="lookup_order", input_parameters={"order_id": "A-1042"})]),
    Turn(role="user", content="Can I get a refund?"),                          # turn 2
    Turn(role="assistant", content="Refunds take 5 business days.",            # turn 3
         tools_called=[ToolCall(name="search_policy", input_parameters={"topic": "refund"}),
                       ToolCall(name="web_search", input_parameters={"q": "refund"})]),
]
expected = [
    ToolCall(name="lookup_order", turn=1),      # pinned: must happen on turn 1
    ToolCall(name="issue_refund", turn=3),      # pinned: must happen on turn 3, did not
]


def case(expected_tools):
    return ConversationalTestCase(turns=turns, expected_tools=expected_tools)


def show(label, metric, test_case):
    metric.measure(test_case, _show_indicator=False)
    print(f"{label}: score={metric.score}")
    for check in metric.check_scores:
        print(f"   {check['check']}: {check['score']}")


show("pinned, default", ConversationToolCorrectnessMetric(async_mode=False), case(expected))
show("unpinned (any turn)", ConversationToolCorrectnessMetric(async_mode=False),
     case([ToolCall(name="lookup_order"), ToolCall(name="search_policy")]))
show("pinned, exact match", ConversationToolCorrectnessMetric(should_exact_match=True, async_mode=False),
     case([ToolCall(name="lookup_order", turn=1), ToolCall(name="search_policy", turn=3)]))

result = evaluate([case(expected)], [ConversationToolCorrectnessMetric()],
                  async_config=AsyncConfig(run_async=False),
                  display_config=DisplayConfig(print_results=False, show_indicator=False,
                                               inspect_after_run=False))
data = result.test_results[0].metrics_data[0]
print("inside evaluate():", data.name, data.score, data.success, "| no judge model was passed")
metric = ConversationToolCorrectnessMetric(async_mode=False)
metric.measure(case(expected), _show_indicator=False)
print("reason:", metric.reason)
Output · real, DeepEval banner omitted13 lines
pinned, default: score=0.5
   Turn 1: 1.0
   Turn 3: 0.0
unpinned (any turn): score=1.0
   Conversation: 1.0
pinned, exact match: score=0.5
   Turn 1: 1.0
   Turn 3: 0.0

inside evaluate(): Conversation Tool Correctness 0.5 True | no judge model was passed
reason: The score is 0.50: 1 of 2 checks passed.
- Turn 3 (0.00): Incomplete tool usage: missing tools ['issue_refund']; expected ['issue_refund'], called ['search_policy', 'web_search']. See more details above.
[netguard] total blocked attempts: 0 []

The pinned run scores 0.5: turn 1 called lookup_order as expected (1.0), turn 3 never called issue_refund (0.0), and the extra web_search is ignored by the default scorer. Dropping the pins makes the same conversation score 1.0 because the tools were called somewhere; that is the trade-off of pinning. should_exact_match=True on the second pinned turn gives 0.0 for that check because two calls were made where one was expected. It needs no judge, so it is the multi-turn check to put in CI before Tool Use.

11.6 Multi-turn methodology: what these scores do not know#

These metrics do not know whether the conversation state in your application is correct. They only know the recorded Turn objects. If the application forgets to record a tool call, omits an assistant message, or writes a cleaned rather than actual user turn, the metric grades the edited story. This is the simulator and trace fidelity problem from 10A.12, Part 7 in miniature.

Before trusting multi-turn metrics:

  1. Verify turn construction. Compare a sample with real logs.
  2. Include tool calls on turns where your schema supports them.
  3. Preserve refusals and clarifying questions; do not reduce every assistant turn to a final answer.
  4. Validate judge labels on a small human-labelled conversation set.
  5. Pair the metrics with memory and leakage checks from 10A.11 when long context is the risk.

Also remember the statistical shape. A mean over a handful of multi-turn conversations is fragile. Conversation length, unit splitting and judge variance all affect the score. Use the interval and regression methods from 10A.8, and report conversation counts alongside means.


Part 12: MCP metrics#

Reference

For what MCP is, read 08E.1 first, then 08E.2 for the protocol in depth. This part covers only how DeepEval scores MCP tool use.

12.1 What DeepEval means by an MCP test case#

08E.1 owns the Model Context Protocol itself: tools, resources, prompts, transports, security and client behaviour. DeepEval does not need a live MCP server for the keyless evaluation samples in this lesson. It needs test-case objects describing what the server offered and what the agent called.

The relevant types are imported from deepeval.test_case:

  • MCPServer(server_name, transport=None, available_tools=None, available_resources=None, available_prompts=None)
  • MCPToolCall(name, args, result)
  • MCPResourceCall(uri, result)
  • MCPPromptCall(name, result)

The result objects are not plain dictionaries. MCPToolCall expects an mcp.types.CallToolResult; resources and prompts expect the corresponding MCP SDK result types. Therefore even keyless metric construction requires the mcp package. Without it, importing or constructing these objects fails with ModuleNotFoundError: No module named 'mcp'. The samples install mcp but never start a server or open a socket.

This distinction is important: you are evaluating recorded MCP use, not testing the MCP transport. If you need protocol conformance or a live server test, that belongs to the application tests in Module 08E. DeepEval's MCP metrics answer whether the agent chose and used MCP primitives appropriately.

12.2 MCPUseMetric for a single turn#

MCPUseMetric requires input, actual_output and mcp_servers. It makes two judge calls:

  1. MCPPrimitivesScore: were the right MCP primitives used? For example, should the agent have called a tool, read a resource or used a prompt?
  2. MCPArgsScore: were the arguments appropriate?

The score is the minimum of the two. As in Tool Use, the minimum prevents good arguments from compensating for the wrong primitive. In the sample printed in full in 12.3, scripted primitive score 1.0 and argument score 0.5 produced:

Output · real, MCPUse lines of the 12.3 run2 lines
MCPUse: score=0.5 success=True calls=['MCPPrimitivesScore', 'MCPArgsScore']
  reason: [ 	right primitive 	partly right args ] 

The success value is true because the default threshold is 0.5, even though the score reveals a significant argument problem. This is a threshold-design warning. For infrastructure-sensitive MCP calls, use a higher threshold, inspect both sub-scores in verbose output, or build deterministic argument validators for high-risk tools.

A minimal test case looks like this:

python
from deepeval.test_case import LLMTestCase, MCPServer, MCPToolCall
from mcp.types import CallToolResult, TextContent, Tool

server = MCPServer(
    server_name="weather-mcp",
    transport="stdio",
    available_tools=[Tool(
        name="get_weather",
        description="weather by city",
        inputSchema={"type": "object", "properties": {"city": {"type": "string"}}},
    )],
)
result = CallToolResult(content=[TextContent(type="text", text="20C")])
case = LLMTestCase(
    input="Weather in Paris?",
    actual_output="20C",
    mcp_servers=[server],
    mcp_tools_called=[MCPToolCall(
        name="get_weather",
        args={"city": "Paris"},
        result=result,
    )],
)

No MCP server is contacted. The objects are evidence records for the metric.

12.3 MultiTurnMCPUseMetric and the three-turn rule#

MultiTurnMCPUseMetric evaluates a ConversationalTestCase with mcp_servers. Per unit interaction it asks for a ToolScore and an ArgsScore; the final score is the minimum of the two means. MCPTaskCompletionMetric asks for a TaskScore per unit and averages them.

The sharp edge is verified and easy to hit: both multi-turn MCP metrics skip units with two or fewer turns. A conversation shaped as [user, assistant(with MCP call)] produces no scorable task and returns 0.0 after only a reason call. The expected shape is at least three turns:

text
user asks
assistant turn carries the MCP call
assistant turn uses the result in an answer

Here is the whole sample (mcp_metrics.py, needs pip install mcp). It builds an MCPServer, a tool result and both conversation shapes, then runs the three MCP metrics. ConversationalTestCase(mcp_servers=[server], turns=[Turn(role=..., content=..., mcp_tools_called=[...])]) is the construction to copy for your own multi-turn MCP cases:

python
# mcp_metrics.py: MCPUse, MultiTurnMCPUse and MCPTaskCompletion, keyless (lesson 10B.5)
import netguard  # noqa: F401

from deepeval.metrics import MCPTaskCompletionMetric, MCPUseMetric, MultiTurnMCPUseMetric
from deepeval.test_case import (ConversationalTestCase, LLMTestCase, MCPServer,
                                MCPToolCall, Turn)
from mcp.types import CallToolResult, TextContent, Tool

from fake_judge import FakeJudge


def show(name, metric, judge):
    print(f"{name}: score={metric.score!r} success={metric.success} calls={judge.schemas()}")
    print("  reason:", str(metric.reason).replace("\n", " ")[:220])


server = MCPServer(
    server_name="weather-mcp", transport="stdio",
    available_tools=[Tool(name="get_weather", description="weather by city",
                          inputSchema={"type": "object", "properties": {"city": {"type": "string"}}})])
tool_result = CallToolResult(content=[TextContent(type="text", text="20C")])
mcp_case = LLMTestCase(
    input="Weather in Paris?", actual_output="20C", mcp_servers=[server],
    mcp_tools_called=[MCPToolCall(name="get_weather", args={"city": "Paris"}, result=tool_result)])
judge = FakeJudge(script={
    "MCPPrimitivesScore": [{"score": 1.0, "reason": "right primitive"}],
    "MCPArgsScore": [{"score": 0.5, "reason": "partly right args"}],
})
metric = MCPUseMetric(model=judge, async_mode=False)
metric.measure(mcp_case, _show_indicator=False)
show("MCPUse", metric, judge)

two_turn = ConversationalTestCase(mcp_servers=[server], turns=[
    Turn(role="user", content="Weather in Paris?"),
    Turn(role="assistant", content="20C",
         mcp_tools_called=[MCPToolCall(name="get_weather", args={"city": "Paris"}, result=tool_result)]),
])
three_turn = ConversationalTestCase(mcp_servers=[server], turns=[
    Turn(role="user", content="Weather in Paris?"),
    Turn(role="assistant", content="Calling weather tool",
         mcp_tools_called=[MCPToolCall(name="get_weather", args={"city": "Paris"}, result=tool_result)]),
    Turn(role="assistant", content="It is 20C in Paris."),
])

for cls, script in [
    (MultiTurnMCPUseMetric, {
        "ToolScore": [{"score": 1.0, "reason": "right tool"}],
        "ArgsScore": [{"score": 0.8, "reason": "mostly right args"}],
        "Reason": [{"reason": "multi-turn use reviewed"}],
    }),
    (MCPTaskCompletionMetric, {
        "TaskScore": [{"score": 0.9, "reason": "task mostly completed"}],
        "Reason": [{"reason": "task completion reviewed"}],
    }),
]:
    judge = FakeJudge(script={key: list(value) for key, value in script.items()})
    metric = cls(model=judge, async_mode=False)
    metric.measure(two_turn, _show_indicator=False)
    show(cls.__name__ + " two-turn unit", metric, judge)
    judge = FakeJudge(script={key: list(value) for key, value in script.items()})
    metric = cls(model=judge, async_mode=False)
    metric.measure(three_turn, _show_indicator=False)
    show(cls.__name__ + " three-turn unit", metric, judge)
Output · real11 lines
MCPUse: score=0.5 success=True calls=['MCPPrimitivesScore', 'MCPArgsScore']
  reason: [ 	right primitive 	partly right args ] 
MultiTurnMCPUseMetric two-turn unit: score=0.0 success=False calls=['Reason']
  reason: multi-turn use reviewed
MultiTurnMCPUseMetric three-turn unit: score=0.8 success=True calls=['ToolScore', 'ArgsScore', 'Reason']
  reason: multi-turn use reviewed
MCPTaskCompletionMetric two-turn unit: score=0.0 success=False calls=['Reason']
  reason: task completion reviewed
MCPTaskCompletionMetric three-turn unit: score=0.9 success=True calls=['TaskScore', 'Reason']
  reason: task completion reviewed
[netguard] total blocked attempts: 0 []

The two-turn and three-turn lines show the cliff exactly.

This is not a semantic judgement that two-turn MCP use is bad. It is an implementation unit-splitting rule. If your conversation representation puts the call and final answer in the same assistant turn, the metric may never evaluate the call. Represent the call and the answer as separate assistant turns, or treat the score as invalid.

12.4 What MCP metrics can and cannot prove#

They can help answer:

  • Did the agent choose an MCP tool when a tool was appropriate?
  • Did it use resources or prompts when those primitives were more appropriate?
  • Were arguments plausible and relevant across a multi-turn task?
  • Did the MCP-backed unit appear to complete the user's task?

They cannot prove:

  • that the server executed the call correctly
  • that the transport was secure or authorized correctly
  • that returned content is true in the external system
  • that the agent respected server-side instructions or avoided malicious tool output
  • that the sequence would robustly pass a real protocol conformance test

MCP outputs are untrusted tool output. DeepEval's metrics are not injection defences, and Module 12 owns the security model. Treat MCP metrics as one functional layer beside the protocol tests and security controls from 08E.1.

12.5 Designing MCP eval cases#

A good MCP eval fixture records five things explicitly:

  1. the server name and transport label
  2. the primitives available to the agent
  3. the exact primitive calls and arguments
  4. the structured result objects returned
  5. the assistant's use of those results in later turns

Then write cases for negative as well as positive behaviour:

  • no MCP call when a direct answer is sufficient
  • correct refusal when required arguments are missing
  • correct resource read rather than a tool call when the primitive type matters
  • wrong argument unit or identifier
  • result-present but answer ignores it
  • multi-turn clarification before the call

For high-value tools, deterministic argument validators usually beat judge scores. A judge can tell you {"city": "Paris"} looks plausible; only code can enforce that account_id belongs to the active tenant or that a mutation payload satisfies the server schema.


Part 13: Multi-agent systems and framework integrations#

Reference

For when and why to split work across agents, read 08D.1 and 08D.3. For framework-neutral multi-agent evaluation (handoff, attribution, simulators), see 10A.12. This part covers how DeepEval represents and scores multi-agent runs.

13.1 Nested agent spans as the DeepEval multi-agent model#

DeepEval does not model organizations, messages or handoffs as first-class evaluation objects. Its multi-agent representation is structural: one type="agent" span can contain another agent span, and each agent span records available_tools and agent_handoffs. Tool calls under a nested agent are attributed to that nested agent, not flattened blindly into the supervisor.

That maps naturally onto a bounded orchestrator design from 08D.3:

flowchart TD
    S["agent span<br/>support supervisor"]
    S --> T1["tool span<br/>lookup_customer"]
    S --> B["agent span<br/>billing specialist"]
    S --> R["agent span<br/>retention specialist"]
    B --> BT["tool span<br/>issue_refund"]
    R --> RT["tool span<br/>offer_credit"]

This structure lets you attach metrics per agent. A billing specialist span can carry Tool Correctness for refund tools; a retention specialist can carry a narrower permission metric; the supervisor can carry routing or output checks. DeepEval's tracing guide correctly notes that trace-level metrics are optional in this shape because component metrics already live on sub-agent spans.

What it does not give you is the interaction evaluation from 10A.12. There is no built-in metric for routing confusion, handoff timing, context transfer, delegation brief quality, ping-pong, orphaned results or escalation correctness. agent_handoffs is a recorded list, not a grader.

13.2 Writing a handoff metric yourself#

A custom handoff metric can read _trace_dict when attached as a trace-aware custom metric or when you deliberately replicate that pattern. At minimum it should inspect:

  • whether the chosen child agent is the expected route
  • whether the child received the entities it needed in its input
  • whether the child actually opened a span
  • whether the child returned to the supervisor or the result was dropped
  • whether the same task ping-pongs between agents

Then compare it with evalkit's graders from 10A.12, Part 3: routing_confusion, context_transfer, schema_valid, pingpong, cycles, repeated_delegations and return_path. evalkit is stricter because it models handoffs explicitly. DeepEval gives you convenient capture; the evaluation semantics remain yours.

A minimal deterministic start, with a tiny two-route fixture (handoff_metric.py), is:

python
# handoff_metric.py: verify a custom trace-aware handoff-presence metric (lesson 10B.5)

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import BaseMetric
from deepeval.test_case import LLMTestCase
from deepeval.tracing import observe, update_current_trace


class ExpectedChildAgent(BaseMetric):
    def __init__(self, expected_name: str, threshold: float = 1.0):
        self.expected_name = expected_name
        self.threshold = threshold
        self.requires_trace = True       # ask the runner to attach test_case._trace_dict

    def measure(self, test_case: LLMTestCase, *args, **kwargs):
        trace = getattr(test_case, "_trace_dict", None) or {}
        children = trace.get("children") or []
        names = [child.get("name") for child in children if child.get("type") == "agent"]
        self.score = 1.0 if self.expected_name in names else 0.0
        self.success = self.score >= self.threshold
        self.reason = f"child agents: {names}; expected {self.expected_name!r}"
        return self.score

    async def a_measure(self, test_case, *args, **kwargs):
        return self.measure(test_case, *args, **kwargs)

    def is_successful(self):
        return self.success

    @property
    def __name__(self):
        return "Expected child agent"


@observe(type="agent", name="billing-specialist")
def billing(order_id: str):
    return f"billing looked up {order_id}"


@observe(type="agent", name="retention-specialist")
def retention(order_id: str):
    return f"retention looked up {order_id}"


@observe(type="agent", name="support-supervisor")
def supervisor(query: str):
    if "refund" in query:
        answer = billing("A-1042")
    else:
        answer = retention("A-1042")
    update_current_trace(input=query, output=answer)
    return answer


dataset = EvaluationDataset(goldens=[
    Golden(input="refund order A-1042"),
    Golden(input="keep me as a customer"),
])
metric = ExpectedChildAgent("billing-specialist")
for golden in dataset.evals_iterator(
        metrics=[metric],
        async_config=AsyncConfig(run_async=False),
        display_config=DisplayConfig(print_results=False, show_indicator=False,
                                     inspect_after_run=False)):
    supervisor(golden.input)

print("score:", metric.score)
print("success:", metric.success)
print("reason:", metric.reason)
Output · real, DeepEval banner omitted4 lines
score: 0.0
success: False
reason: child agents: ['retention-specialist']; expected 'billing-specialist'
[netguard] total blocked attempts: 0 []

The first golden routes to billing-specialist and passes; the second routes to retention-specialist and fails. The printed metric fields are the final state of the reused sync-mode metric object, so use the per-test JSON for case-by-case reporting.

The instance-level requires_trace = True line is essential: without it DeepEval treats the class like an ordinary custom metric and never attaches _trace_dict. This metric checks presence only. It does not grade timing or context transfer. That is deliberate: a small deterministic check you understand is better than a broad "multi-agent quality" judge that hides every decision in one number. Build up gradually, and use the failure taxonomy in 10A.12, 1.3 as the checklist.

13.3 Framework integrations are tracing front-ends#

DeepEval's framework integrations are not separate evaluation engines. They are instrumentation adapters that feed confident-trace spans into the same bridge as @observe. Once inside the bridge, update_current_span, update_current_trace, span metrics and next_*_span behave the same way.

Verified import paths and entry points in 4.3.6. The last column says what was actually run in this lesson:

Framework or library Verified entry point What it adds to the trace Run here
OpenAI SDK from deepeval.openai import OpenAI, AsyncOpenAI re-exports OpenAI's classes and instruments model calls as llm spans; trace_manager.configure(openai_client=client) is the narrower alternative import only
Anthropic SDK from deepeval.anthropic import Anthropic, AsyncAnthropic same pattern; needs the anthropic package import only
LangChain from deepeval.integrations.langchain import CallbackHandler, tool the chain as an agent span, model calls as llm spans, other steps as base spans (13.4); tool(...) wraps LangChain tools and accepts metrics executed (13.4)
LangGraph the same CallbackHandler one agent span for the graph, llm spans for model calls, a base span per node (13.5) executed (13.5)
LlamaIndex from deepeval.integrations.llama_index import instrument_llama_index LlamaIndex's dispatcher events plus the provider SDK calls beneath them (openai, anthropic, google_genai, bedrock, litellm) import only
CrewAI from deepeval.integrations.crewai import instrument_crewai, Crew, Agent, LLM, tool crews, tasks, agents, tools and model calls, plus a span per knowledge retrieval; the Crew, Agent, LLM and tool shims accept metrics not importable without crewai
OpenAI Agents SDK from deepeval.openai_agents import DeepEvalTracingProcessor, Agent, function_tool agent runs through OpenInference's processor; the processor adds trace settings and the settings a DeepEval Agent gives its spans not importable without openai-agents
Pydantic AI from deepeval.integrations.pydantic_ai import DeepEvalInstrumentationSettings the framework's own OpenTelemetry spans, tagged with your trace defaults. instrument_pydantic_ai() still works but emits a DeprecationWarning import only
Strands from deepeval.integrations.strands import instrument_strands the telemetry Strands emits, converted by confident-trace import only
Bedrock AgentCore from deepeval.integrations.agentcore import instrument_agentcore the same, for AgentCore telemetry import only
Google ADK from deepeval.integrations.google_adk import instrument_google_adk the same, for ADK telemetry import only
OpenInference from deepeval.integrations.openinference import instrument_openinference, or deepeval.instrument(...) spans from any community OpenInference instrumentor, for example OpenAIInstrumentor import only
Hugging Face Trainer from deepeval.integrations.hugging_face import DeepEvalHuggingFaceCallback not tracing: a Trainer callback that generates and scores outputs during training; needs transformers not importable without transformers

The minimal wiring for each, as fragments (not run here: the frameworks are not installed in the keyless setup, and the code uses placeholders). Run a sample, print one captured trace, and only then attach metrics:

python
# --- OpenAI / Anthropic SDKs: change the import, use the client as usual
from deepeval.openai import OpenAI
client = OpenAI()

# --- LangChain / LangGraph: a callback on the invoke config (executed in 13.4 and 13.5)
from deepeval.integrations.langchain import CallbackHandler
result = chain.invoke(inputs, config={"callbacks": [CallbackHandler(name="my-chain", tags=["eval"])]})

# --- LlamaIndex and CrewAI: instrument once at start-up
from deepeval.integrations.llama_index import instrument_llama_index
instrument_llama_index()
from deepeval.integrations.crewai import instrument_crewai
instrument_crewai()

# --- OpenAI Agents SDK: register DeepEval's processor with the SDK
from agents import add_trace_processor
from deepeval.openai_agents import DeepEvalTracingProcessor
add_trace_processor(DeepEvalTracingProcessor())

# --- Pydantic AI: pass settings to the agent (instrument_pydantic_ai() is deprecated)
from pydantic_ai import Agent
from deepeval.integrations.pydantic_ai import DeepEvalInstrumentationSettings
agent = Agent("openai:your-model", instrument=DeepEvalInstrumentationSettings(name="support", tags=["eval"]))

# --- Strands, AgentCore, Google ADK: call once before creating agents
from deepeval.integrations.strands import instrument_strands
instrument_strands(name="support", tags=["eval"], environment="testing")

# --- OpenInference: start DeepEval's tracer, then the community instrumentor you want
import deepeval
from openinference.instrumentation.openai import OpenAIInstrumentor
deepeval.instrument(name="support")
OpenAIInstrumentor().instrument()

Signatures worth knowing (read from the 4.3.6 source):

  • instrument_strands, instrument_agentcore, instrument_google_adk and instrument_openinference share the trace-default keywords name, thread_id, metadata, tags and environment; update_current_trace(...) overrides them at runtime. instrument_openinference also takes integration.
  • api_key, user_id, metric_collection, test_case_id and turn_id appear on several of these signatures but are deprecated Confident AI platform settings that are ignored locally. They should not affect your local evaluation design.
  • instrument_llama_index(dispatcher=None) takes no trace keywords; the dispatcher is accepted for compatibility only.
  • CallbackHandler(name, tags, metadata, thread_id, user_id, metrics, metric_collection, test_case_id, turn_id). Its metrics argument does not register a metric source on its own; the probe in 5.1 and 13.4 shows the resulting NoMetricsError.
  • DeepEvalHuggingFaceCallback(trainer, evaluation_dataset=None, metrics=None, tokenizer_args=None, aggregation_method="avg", show_table=False).

Only LangChain and LangGraph produced spans in this lesson. The other rows are verified import and signature facts, plus the module documentation, not claims that every framework version will produce the same span tree. Because framework instrumentation is version-sensitive, always print a captured trace before designing metrics around it.

What happens when the framework package is missing is itself worth knowing. This sample imports every entry point with only deepeval installed:

python
# integration_imports.py: which integration entry points import, with only deepeval installed (lesson 10B.5)
import importlib

import netguard  # noqa: F401

ENTRY_POINTS = [
    ("deepeval.openai", "OpenAI"),
    ("deepeval.anthropic", "Anthropic"),
    ("deepeval.integrations.langchain", "CallbackHandler"),
    ("deepeval.integrations.llama_index", "instrument_llama_index"),
    ("deepeval.integrations.crewai", "instrument_crewai"),
    ("deepeval.openai_agents", "DeepEvalTracingProcessor"),
    ("deepeval.integrations.pydantic_ai", "instrument_pydantic_ai"),
    ("deepeval.integrations.strands", "instrument_strands"),
    ("deepeval.integrations.agentcore", "instrument_agentcore"),
    ("deepeval.integrations.google_adk", "instrument_google_adk"),
    ("deepeval.integrations.openinference", "instrument_openinference"),
    ("deepeval.integrations.hugging_face", "DeepEvalHuggingFaceCallback"),
]
for module, name in ENTRY_POINTS:
    try:
        getattr(importlib.import_module(module), name)
        print(f"ok       {module}.{name}")
    except ModuleNotFoundError as exc:
        print(f"missing  {module}.{name} -> {str(exc)[:70]}")
    except Exception as exc:
        message = str(exc).split(" (")[0]          # drop the local file path some errors append
        print(f"error    {module}.{name} -> {type(exc).__name__}: {message[:90]}")
Output · real, only deepeval installed13 lines
ok       deepeval.openai.OpenAI
missing  deepeval.anthropic.Anthropic -> Please install anthropic to use this feature: 'pip install anthropic'
error    deepeval.integrations.langchain.CallbackHandler -> NameError: name 'BaseCallbackHandler' is not defined
ok       deepeval.integrations.llama_index.instrument_llama_index
error    deepeval.integrations.crewai.instrument_crewai -> ImportError: cannot import name 'DeepEvalCrew' from 'deepeval.integrations.crewai.subs'
error    deepeval.openai_agents.DeepEvalTracingProcessor -> RuntimeError: openai-agents is required for this integration. Please install it.
ok       deepeval.integrations.pydantic_ai.instrument_pydantic_ai
ok       deepeval.integrations.strands.instrument_strands
ok       deepeval.integrations.agentcore.instrument_agentcore
ok       deepeval.integrations.google_adk.instrument_google_adk
ok       deepeval.integrations.openinference.instrument_openinference
ok       deepeval.integrations.hugging_face.DeepEvalHuggingFaceCallback
[netguard] total blocked attempts: 0 []

The ok rows import cleanly because they only need deepeval's own dependencies. Anthropic, CrewAI and OpenAI Agents fail with a clear message or an ImportError. The LangChain row is the surprising one: without langchain-core the import fails with a bare NameError: name 'BaseCallbackHandler' is not defined, not a "please install" message. If you see that, install langchain-core.

13.4 The keyless LangChain probe#

The executed integration sample (langchain_integration.py) uses FakeListChatModel, so LangChain runs without a provider. It attaches the DeepEval callback to the chain, stages Answer Relevancy onto the next LLM span, and passes Task Completion to the iterator. It then prints which spans the integration created, and repeats the loop with the metric passed only to CallbackHandler:

python
# langchain_integration.py: DeepEval tracing inside a LangChain chain, keyless (lesson 10B.5)
import json
from pathlib import Path

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.integrations.langchain import CallbackHandler
from deepeval.metrics import AnswerRelevancyMetric, TaskCompletionMetric
from deepeval.tracing import next_llm_span
from langchain_core.language_models.fake_chat_models import FakeListChatModel
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

from fake_judge import FakeJudge

model = FakeListChatModel(responses=["Refunds take 5 business days.", "I can't help with crypto."])
chain = (ChatPromptTemplate.from_messages([("system", "You are a support bot."), ("human", "{q}")])
         | model | StrOutputParser())

judge = FakeJudge(script={
    "TaskAndOutcome": [
        {"task": "answer refunds", "outcome": "answered 5 business days"},
        {"task": "answer crypto payment", "outcome": "refused crypto help"},
    ],
    "TaskCompletionVerdict": [
        {"verdict": 0.7, "reason": "mostly complete"},
        {"verdict": 0.7, "reason": "mostly complete"},
    ],
    "Statements": [
        {"statements": ["Refunds take 5 business days."]},
        {"statements": ["I can't help with crypto."]},
    ],
    "Verdicts": [
        {"verdicts": [{"verdict": "yes"}]},
        {"verdicts": [{"verdict": "yes"}]},
    ],
    "AnswerRelevancyScoreReason": [
        {"reason": "on-topic"}, {"reason": "on-topic"},
    ],
})

dataset = EvaluationDataset(goldens=[Golden(input="How long do refunds take?"), Golden(input="Pay with crypto?")])
for golden in dataset.evals_iterator(
        metrics=[TaskCompletionMetric(model=judge)],
        async_config=AsyncConfig(run_async=False),
        display_config=DisplayConfig(print_results=False, show_indicator=False, inspect_after_run=False)):
    with next_llm_span(metrics=[AnswerRelevancyMetric(model=judge)]):
        answer = chain.invoke({"q": golden.input}, config={"callbacks": [CallbackHandler(name="lc-probe")]})
    print("chain said:", answer)
print("judge calls:", judge.schemas())

# which spans did the integration create for the last golden?
trace = json.loads(Path(".deepeval/.latest_test_run.json").read_text())["testRunData"]["testCases"][-1]["trace"]
for key in ("agentSpans", "llmSpans", "baseSpans"):
    print(f"{key}:", [span["name"] for span in trace.get(key, [])])
llm = trace["llmSpans"][0]
print("llm span integration and provider:", llm.get("integration"), "|", llm.get("provider"))

# the negative finding: metrics passed only to CallbackHandler do not count as a metric source
try:
    for golden in dataset.evals_iterator(
            async_config=AsyncConfig(run_async=False),
            display_config=DisplayConfig(print_results=False, show_indicator=False, inspect_after_run=False)):
        chain.invoke({"q": golden.input},
                     config={"callbacks": [CallbackHandler(metrics=[TaskCompletionMetric(model=judge)])]})
except Exception as exc:
    print("CallbackHandler(metrics=...) only:", type(exc).__name__)
Output · real, DeepEval banners omitted10 lines
chain said: Refunds take 5 business days.
chain said: I can't help with crypto.

judge calls: ['TaskAndOutcome', 'TaskCompletionVerdict', 'Statements', 'Verdicts', 'AnswerRelevancyScoreReason', 'TaskAndOutcome', 'TaskCompletionVerdict', 'Statements', 'Verdicts', 'AnswerRelevancyScoreReason']
agentSpans: ['RunnableSequence']
llmSpans: ['FakeListChatModel']
baseSpans: ['ChatPromptTemplate', 'StrOutputParser']
llm span integration and provider: LangChain | fakelistchatmodel
CallbackHandler(metrics=...) only: NoMetricsError
[netguard] total blocked attempts: 0 []

The span lists show what the integration made of a three-step chain: the chain itself (RunnableSequence) became an agent span, the chat model an llm span tagged with the LangChain integration and the fake provider, and the prompt template and output parser untyped base spans. Task Completion ran at trace level and Answer Relevancy ran on the staged LLM span, as the judge-call order shows. Two practical consequences: an agent-span metric such as Tool Correctness would attach to the RunnableSequence span, and a metric staged with next_agent_span would land on the first chain you invoke, not on your conceptual agent.

The last line is the negative finding, now reproduced: passing metrics only as CallbackHandler(metrics=[...]) inside evals_iterator does not register a metric source, and the loop ends in NoMetricsError (the same error as 5.1). Use the documented split:

  • trace-level metrics on evals_iterator(metrics=...)
  • component metrics on next_*_span(metrics=...) or integration objects that explicitly support them

13.5 The same on LangGraph#

LangGraph runs on LangChain's runnables, so the same CallbackHandler traces it. This sample (langgraph_integration.py, needs pip install langgraph) builds a two-node graph, classify then respond, where respond calls the fake chat model. It passes metrics=[] to the iterator because the only metric is staged on the framework-created LLM span with next_llm_span, then prints which span lists the run produced:

python
# langgraph_integration.py: DeepEval tracing a two-node LangGraph, keyless (lesson 10B.5)
import json
from pathlib import Path
from typing import TypedDict

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.integrations.langchain import CallbackHandler
from deepeval.metrics import AnswerRelevancyMetric
from deepeval.tracing import next_llm_span, update_current_trace
from langchain_core.language_models.fake_chat_models import FakeListChatModel
from langgraph.graph import END, START, StateGraph

from fake_judge import FakeJudge

judge = FakeJudge(script={
    "Statements": [{"statements": ["Refunds take 5 business days."]}],
    "Verdicts": [{"verdicts": [{"verdict": "yes"}]}],
    "AnswerRelevancyScoreReason": [{"reason": "on-topic"}],
})
model = FakeListChatModel(responses=["Refunds take 5 business days."])


class State(TypedDict):
    question: str
    answer: str


def classify(state: State):
    return {"question": state["question"].strip()}


def respond(state: State):
    return {"answer": model.invoke(state["question"]).content}


graph = StateGraph(State)
graph.add_node("classify", classify)
graph.add_node("respond", respond)
graph.add_edge(START, "classify")
graph.add_edge("classify", "respond")
graph.add_edge("respond", END)
app = graph.compile()

dataset = EvaluationDataset(goldens=[Golden(input="How long do refunds take?")])
for golden in dataset.evals_iterator(
        metrics=[], async_config=AsyncConfig(run_async=False),
        display_config=DisplayConfig(print_results=False, show_indicator=False,
                                     inspect_after_run=False)):
    with next_llm_span(metrics=[AnswerRelevancyMetric(model=judge)]):
        result = app.invoke({"question": golden.input, "answer": ""},
                            config={"callbacks": [CallbackHandler(name="graph-probe")]})
    update_current_trace(input=golden.input, output=result["answer"])
print("graph said:", result["answer"])

trace = json.loads(Path(".deepeval/.latest_test_run.json").read_text())["testRunData"]["testCases"][0]["trace"]
for key in ("agentSpans", "llmSpans", "retrieverSpans", "toolSpans", "baseSpans"):
    print(f"{key}:", [span["name"] for span in trace.get(key, [])])
print("judge calls:", judge.schemas())
Output · real, DeepEval banner omitted8 lines
graph said: Refunds take 5 business days.
agentSpans: ['LangGraph']
llmSpans: ['FakeListChatModel']
retrieverSpans: []
toolSpans: []
baseSpans: ['classify', 'respond']
judge calls: ['Statements', 'Verdicts', 'AnswerRelevancyScoreReason']
[netguard] total blocked attempts: 0 []

The graph became one agent span named LangGraph, the model call became an llm span named after the model class, and each node that is not itself a model call became a base (custom) span named after the node. Two practical points follow. A component metric on "the respond node" has to be staged on the LLM span inside it, not on the node, because the node is an untyped base span. And a handoff or routing metric over a LangGraph run reads node names, so rename nodes for evaluation the way you would name @observe spans.

13.6 Integration evaluation checklist#

Framework instrumentation can change shape across versions. Before writing a large suite:

  1. Capture one trace and print the span tree.
  2. Identify which span is actually typed llm, agent, tool or custom/base.
  3. Check whether tool arguments and outputs appear where you expect.
  4. Attach one deterministic metric first, not a judge.
  5. Add next_*_span staging for framework spans you do not control.
  6. Set DEEPEVAL_AUTO_TRACE=0 in controlled tests if automatic instrumentation adds duplicate spans.
  7. Version your framework, DeepEval and integration expectations together.

This is especially important for LangGraph and CrewAI, where graph nodes and framework agents may or may not correspond to your conceptual agents. Do not let the framework's runtime vocabulary silently redefine your evaluation boundary.


Part 14: Choosing, validating and defending agent evals#

14.1 The metric decision table#

If your question is... Start with Add only if needed Avoid
Did the final answer satisfy this exact case? exact/expected-output or state grader from 10A.3/10A.7 Task Completion for open-ended tasks treating Task Completion as an oracle
Did the right tool fire? Tool Correctness ordering, exact match, input parameters relying on final answer fluency
Did a forbidden tool fire? Tool Permission custom argument-level policy checks default Tool Correctness alone
Were arguments appropriate? deterministic schema/entity checks Argument Correctness assuming relevance means validity
Did the agent loop? Agent Loop Detection plus hard budgets Step Efficiency for a judge opinion interpreting weighted sub-scores as percentages of loops
Did it follow a written plan? Plan Adherence after instrumenting plans Plan Quality reading empty-plan 1.0 as success
Was retrieval the problem? retriever-span deterministic and RAG metrics end-to-end RAG metrics Faithfulness on the retriever span
Was generation the problem? generation-span Faithfulness or Answer Relevancy custom schema/format checks blaming retrieval without a retrieval metric
Did the assistant call the right tool on the right turn? Conversation Tool Correctness (4.3.6+, no judge) with pinned turns Tool Use for judged selection and arguments pinning every turn when order does not matter
Did a multi-turn assistant stay on goal? Goal Accuracy with validated units Topic Adherence for scope control using tiny two-turn units blindly
Was MCP use correct? deterministic call/argument fixtures MCPUse or multi-turn MCP metrics live-server assumptions from a metric score
Was the handoff correct? evalkit handoff graders or custom _trace_dict metric per-agent component metrics waiting for a built-in DeepEval handoff metric (there is none in 4.3.6)

14.2 Judge calls and formulas in one table#

Measured or source-verified for 4.3.6 (the counts are unchanged from 4.3.5):

Metric Input shape Judge calls per case/unit Score rule
Task Completion trace, or input/output fallback 2 judge verdict, unclamped
Step Efficiency trace 2 judge score, unclamped
Plan Adherence trace up to 3; 2 when no plan found judge score; 1.0 when no plan found
Plan Quality trace up to 3; 2 when no plan found judge score; 1.0 when no plan found
Tool Correctness tools_called, expected_tools 0, plus 1 with available_tools matched expected / expected; minimum with selection score
Argument Correctness input plus attributable tool calls 2 yes verdicts / tool calls
Tool Permission tools_called 0 authorized / calls
Agent Loop Detection trace 0 weighted mean: tool repetition 0.40, reasoning stagnation 0.35, cycles 0.25
Goal Accuracy conversation 2 per unit plus 1 reason (mean goal + mean plan) / 2
Tool Use conversation plus available tools 1-2 per unit plus 2 reason calls min(mean selection, mean argument correctness)
Topic Adherence conversation plus topics 1 per unit plus 1 per QA pair plus 1 (TP + TN) / all pairs
Conversation Tool Correctness (4.3.6+) conversation plus expected_tools 0 mean of the per-turn tool checks
MCP Use single-turn plus mcp_servers 2 min(primitives, arguments)
Multi-turn MCP Use conversation units of 3+ turns 2 per valid unit plus 1 min(mean tool, mean args)
MCP Task Completion conversation units of 3+ turns 1 per valid unit plus 1 mean task score

Use this table for cost estimation before running a suite. A hundred traced cases with Task Completion, Step Efficiency, Plan Adherence and one Answer Relevancy span metric can imply up to 1,000 judge calls in the scripted shapes shown here: (2 + 2 + 3) * 100 for the trajectory metrics and 3 * 100 for Answer Relevancy. When plans are absent, as in the 4.1 sample where the plan came back empty, Plan Adherence stops after two calls and the total is 900. Real counts depend on retrieval size, conversation units, whether a plan was found and whether reasons are enabled.

Two constructor switches change the counts or the score, and this sample measures them on two metrics (save as call_counts.py):

python
# call_counts.py: what include_reason=False and strict_mode do to judge-call counts (lesson 10B.5)
import netguard  # noqa: F401

from deepeval.metrics import ArgumentCorrectnessMetric, TaskCompletionMetric
from deepeval.test_case import LLMTestCase, ToolCall

from fake_judge import FakeJudge

case = LLMTestCase(
    input="Where is order A-1042?", actual_output="Delivered.",
    tools_called=[ToolCall(name="lookup", input_parameters={"order_id": "A-1042"})],
)


def argument_judge():
    return FakeJudge(script={
        "Verdicts": [{"verdicts": [{"verdict": "yes"}]}],
        "ArgumentCorrectnessScoreReason": [{"reason": "relevant"}],
    })


def task_judge(verdict):
    return FakeJudge(script={
        "TaskAndOutcome": [{"task": "find the order", "outcome": "reported delivered"}],
        "TaskCompletionVerdict": [{"verdict": verdict, "reason": "scripted"}],
    })


for label, kwargs in [("ArgumentCorrectness default", {}),
                      ("ArgumentCorrectness include_reason=False", {"include_reason": False})]:
    judge = argument_judge()
    metric = ArgumentCorrectnessMetric(model=judge, async_mode=False, **kwargs)
    metric.measure(case, _show_indicator=False)
    print(f"{label}: score={metric.score} calls={judge.schemas()} reason={metric.reason!r}")

for label, kwargs in [("TaskCompletion default", {}),
                      ("TaskCompletion include_reason=False", {"include_reason": False}),
                      ("TaskCompletion strict_mode, verdict 0.9", {"strict_mode": True})]:
    judge = task_judge(0.9)
    metric = TaskCompletionMetric(model=judge, async_mode=False, **kwargs)
    metric.measure(case, _show_indicator=False)
    print(f"{label}: score={metric.score} success={metric.success} threshold={metric.threshold} calls={judge.schemas()}")
Output · real6 lines
ArgumentCorrectness default: score=1.0 calls=['Verdicts', 'ArgumentCorrectnessScoreReason'] reason='relevant'
ArgumentCorrectness include_reason=False: score=1.0 calls=['Verdicts'] reason=None
TaskCompletion default: score=0.9 success=True threshold=0.5 calls=['TaskAndOutcome', 'TaskCompletionVerdict']
TaskCompletion include_reason=False: score=0.9 success=True threshold=0.5 calls=['TaskAndOutcome', 'TaskCompletionVerdict']
TaskCompletion strict_mode, verdict 0.9: score=0 success=False threshold=1 calls=['TaskAndOutcome', 'TaskCompletionVerdict']
[netguard] total blocked attempts: 0 []

include_reason=False removes the separate reason call for metrics that make one: Argument Correctness drops from two calls to one and reason becomes None. Task Completion's reason arrives inside the verdict call, so its count stays at two. strict_mode=True sets the threshold to 1 and forces any score below it to 0, here 0.9 becoming 0, with no change in the call count. Check any other metric before budgeting by printing judge.schemas() exactly as the sample does.

To script the keyless FakeJudge for any metric in this lesson you need the schema names it asks for. These are the names that appeared in the real runs above (a name repeated per case or unit is scripted once per call):

Metric FakeJudge script keys, in call order
Task Completion TaskAndOutcome, TaskCompletionVerdict
Step Efficiency Task, EfficiencyVerdict
Plan Adherence / Plan Quality Task, AgentPlan, then PlanAdherenceScore / PlanQualityScore
Argument Correctness Verdicts, ArgumentCorrectnessScoreReason
Tool Correctness with available_tools ToolSelectionScore
Goal Accuracy GoalScore, PlanScore, and the key "" for the free-text reason
Tool Use ToolSelectionScore, ArgumentCorrectnessScore, Reason
Topic Adherence QAPairs, RelevancyVerdict, TopicAdherenceReason
MCP Use MCPPrimitivesScore, MCPArgsScore
Multi-turn MCP Use / MCP Task Completion ToolScore, ArgsScore, Reason / TaskScore, Reason
Answer Relevancy Statements, Verdicts, AnswerRelevancyScoreReason

14.3 A validation workflow that survives scrutiny#

Use this sequence before putting any of these metrics in a gate:

  1. Range-check every score. Reject or flag values below 0 or above 1 before aggregation. DeepEval does not clamp them.
  2. Plant faults. Wrong tool, wrong argument, forbidden tool, empty retrieval, loop, missing plan, missing MCP result and dropped handoff. Each fault should light the intended metric and not be invisible.
  3. Print the evidence. Read _trace_dict, span JSON and at least one judge prompt per metric family.
  4. Label a small gold set. Human reviewers label task completion, correct tool, correct arguments and looping independently. Do not label by reading the metric's own reason first.
  5. Measure judge agreement. Use evalkit/judge_validation.py from 10A.5: confusion rates for binary judgements, agreement and disagreement examples for ordinal scores.
  6. Tune thresholds with base rates. A 0.5 default is not a safety threshold and may not even be a good quality threshold. Use the cost of false passes and false failures.
  7. Repeat for variance. Non-deterministic agents need repeated trials, pass rates and intervals as 10A.7, Part 5 teaches.
  8. Compare paired runs. For prompt or architecture changes, use paired per-case comparisons and confidence intervals from 10A.8, not two aggregate means.
  9. Slice the report. Tool-heavy, retrieval-heavy, multi-turn, multi-agent and MCP cases should not be averaged into one opaque number.
  10. Version instrumentation. A span-tree refactor is a measurement-instrument change. Record it beside prompt and model versions in hyperparameters.

14.4 The complete evalkit ↔ DeepEval mapping for this lesson#

evalkit concept and owner DeepEval 4.3.5 equivalent What changes
StepRecord, Trajectory in 10A.7, 2.4 nested span tree and _trace_dict tree structure rather than one flat sequence; capture is in-process
trace_adapter.py in 10A.7, 10.4 confident-trace bridge and framework integrations no local JSONL production adapter included; DeepEval is strongest when instrumented at runtime
outcome graders in 10A.7, Part 3 trace-level ordinary metrics and Task Completion DeepEval's judge outcome metric is reference-free unless you supply references separately
reference trajectory and tool precision/recall in 10A.7, Part 4 Tool Correctness and Tool Permission no general reference-trajectory alignment scorer beyond tools
loop and budget checks in 10A.7, 4.3 Agent Loop Detection DeepEval detects patterns but does not impose execution budgets
judge-scored trajectory dimensions in 10A.7, 4.5 Step Efficiency, Plan Adherence, Plan Quality DeepEval implements them as fixed prompts over nested trace JSON
pass rates, pass@k and intervals in 10A.7, Part 5 none built in repeat runs and statistics remain your job
evalkit runner and compare in 10A.8 evals_iterator, assert_test, local run JSON DeepEval runs metrics but does not replace paired regression statistics
mas_eval.py in 10A.12 nested agent spans plus custom metrics DeepEval captures structure but does not grade routing, context transfer, ping-pong or attribution
simulator validation in 10A.12, Part 7 none here multi-turn metrics score conversations; they do not validate whether simulated users resemble real users

14.5 What DeepEval does not do in this area#

As of 4.3.6, keep these boundaries explicit:

  • no general reference-trajectory metric beyond tool correctness
  • no built-in handoff-correctness, context-transfer or multi-agent attribution metric
  • no judge calibration, human-label agreement, confidence intervals or paired statistical comparison
  • no score clamping for judge-returned trajectory numbers
  • no tracing support for multi-turn evaluation in the same sense as single-turn evals_iterator
  • no fully supported local OTLP backend story for arbitrary collectors
  • no production online evaluation without Confident AI
  • no execution budgets or sandboxing: those belong to the agent harness, and Inspect lessons later in this track approach the problem differently

These absences do not make DeepEval weak. They define where the package ends and your evaluation engineering begins.

14.6 A defensible report paragraph#

When you report an agent evaluation, write in this shape:

text
We ran N seeded trials per case across C cases (counts by slice). Instrumentation version X
produced span trees shaped as Y. Deterministic gates were Tool Correctness (ordering variant),
Tool Permission and Agent Loop Detection; judge-based metrics were Task Completion and Plan
Adherence using judge J. Judge validation on H human-labelled traces produced TPR/TNR/agreement
values A, with disagreement examples linked. Scores are means over valid cases only; errored
traces are reported separately. Pairwise comparison against baseline B uses paired bootstrap
intervals. Known limitations: reference-free judges, no handoff metric, plan absent in Z% of
traces, MCP units shorter than three turns excluded.

If you cannot fill those blanks, the right response is not to hide them. It is to narrow the claim. "Tool Correctness improved on the 40 single-turn routing cases" is defensible. "The agent is better" usually is not.


Symptom What is usually happening Fix
MissingTestCaseParamsError: 'actual_output' cannot be None in a traced eval the iterator wrapper is the trace root and your application return value was not copied to the trace call update_current_trace(input=..., output=...)
A span metric sees "{'query': '...'}" instead of the query automatic input capture stores keyword arguments as a dict and DeepEval stringifies it call update_current_span(input=query)
handoff_agents produces an empty handoff list docs keyword does not match 4.3.5 source and is silently ignored use agent_handoffs
Setting output="" or retrieval_context=[] never appears falsy updates are ignored use a sentinel, metadata, or redesign the empty-state test
Plan Adherence passes every run no plan is present, and empty plans score 1.0 instrument explicit plans before using plan metrics
Step Efficiency is high for a wrong answer the metric ignores correctness by design pair it with outcome metrics
Task Completion describes actions that never happened extraction hallucinated or compressed the trace badly inspect extraction prompts and pair with deterministic evidence
Tool Correctness passes although a forbidden tool fired default scoring is recall over expected tools and ignores extras add Tool Permission or exact-match
Argument Correctness sees no calls no owning llm span exists for the tool call instrument the decision-making model call as an LLM span
Multi-turn MCP score is 0 for a correct short interaction units with two or fewer turns are skipped represent call and answer as separate assistant turns or do not use the metric
ToolUseMetric.success is None after measure() verified standalone-path quirk run through evaluate() or use the success API rather than raw attribute
CI fails but no metric is named span failures are missing from the pytest assertion and console table parse .deepeval/.latest_test_run.json
Traces appear different after installing framework packages DEEPEVAL_AUTO_TRACE automatically instruments supported libraries disable auto tracing for controlled experiments or design for the extra spans
Masked output still leaks in input mask only handles strings; automatic inputs are dicts write recursive masks and mask explicit updates yourself
Trace metrics pass but the test fails a component metric failed and rolled up into the golden inspect per-span metricsData
A tool call is missing from toolsCalled and no error appears the work ran on a thread that did not inherit the context (run_in_executor, ThreadPoolExecutor.submit), so its span joined no trace run under contextvars.copy_context().run(...) or use asyncio.to_thread (5.3)
NoMetricsError after the loop body ran no metric was declared on the iterator, a span, a trace update or next_*_span (CallbackHandler(metrics=...) does not count) declare one metric source (5.1)
NameError: name 'BaseCallbackHandler' is not defined on a DeepEval import langchain-core is not installed pip install langchain-core (13.3)
ImportError or ModuleNotFoundError for ConversationToolCorrectnessMetric the installed deepeval is older than 4.3.6 upgrade, or use ToolCorrectnessMetric per turn
Async result object is None generator return values are discarded by ordinary for loops capture StopIteration.value or read the saved run file
A tool crashed but the run shows a 100% pass rate the agent caught the exception; the errored span's metrics were skipped and a skipped metric does not fail the golden fail CI on any span with status == "ERRORED" (4.5)
One tool exception aborts the whole synchronous suite the exception escaped the for loop body, so no later golden ran catch at the agent boundary and record the error, or use async mode where an errored task fails only its own golden
MissingTestCaseParamsError: 'expected_output' cannot be None although the golden has one golden expected fields are not copied to the trace test case update_current_trace(expected_output=get_current_golden().expected_output) (4.3)
A metric staged with next_llm_span scored only the first model call next_*_span values are one-shot one with block per call, or an integration object that accepts metrics (3.3)
An obviously looping agent scores 1.0 on Agent Loop Detection its thoughts are under 20 meaningful words, alternate between two texts, or are paraphrased; or its repeated calls vary one argument budgets and planted-fault fixtures that match how your agent loops (10.4)
Agent Loop Detection reports a cycle for a legitimate delegation two inputs share their first 64 characters, so the cycle labels match put the varying part of the input first, or disable check_call_graph_cycles and use your own check

What this means for you#

As an AI engineer, you should treat tracing as part of the evaluation harness, not as free observability. Instrument boundaries that correspond to real responsibilities, attach expectations deliberately, and make failures visible in machine-readable output. For agent metrics, use deterministic checks as the spine and judge-based trajectory metrics as calibrated supporting evidence. DeepEval gives you strong plumbing and a useful metric catalogue, but the meaning of the number still depends on your test design, instrumentation and validation discipline.


Common misconceptions#

Misconception Reality
"Tracing is only for debugging production systems." In DeepEval, traces are evaluation inputs. Spans become component test cases and _trace_dict becomes judge evidence.
"A metric on the root span is a trace-level metric." It is still a span metric. Trace metrics come from evals_iterator, trace(), update_current_trace or assert_test.
"The agent's return value automatically becomes the trace output in evals_iterator." You must call update_current_trace(output=...); otherwise trace metrics can fail with missing actual output.
"DeepEval local tracing sends data to Confident AI." Without a key, export is a no-op. The keyless samples in this lesson blocked sockets and saw zero attempts.
"Sampling reduces local evaluation cost." Sampling affects export only. Local evaluation still sees every trace.
"A mask function receives strings." It receives raw objects. If it does not recurse into dicts and lists, inputs can leak while outputs look masked.
"Task Completion compares with the golden answer." It extracts task and outcome, then judges their alignment. No golden reference is used unless you build one into the evaluation separately.
"Step Efficiency measures cost or latency." It is a judge's adversarial opinion about action minimality, with correctness explicitly ignored.
"Plan metrics measure planning even when no plan is in the trace." In 4.3.5, no evidenced plan yields score 1.0 with a warning-like reason. You must instrument plans.
"Tool Correctness is enough for tool safety." Its default ignores extra calls. Permissions, exact arguments and state policy need additional checks.
"MCP metrics test a live MCP server." They score recorded MCP evidence objects. Protocol and server behaviour need separate tests.
"Nested agent spans mean DeepEval evaluates handoffs." The structure is captured, but handoff correctness metrics are yours or evalkit's.
"A green pytest table means all span metrics passed." Span failures can be invisible in the table and assertion string. Read the run JSON.
"If a component throws, the golden fails." Only if the exception escapes. A caught exception leaves an ERRORED span whose metrics are skipped, and the golden can still pass.
"The golden's expected answer is used automatically in traced evaluation." The trace test case reads expected output, context and expected tools from the trace. Copy them from get_current_golden().
"Plan Quality judges the plan against what the agent did." Its scoring call sees only the task and the extracted plan; execution is Plan Adherence's job.

Key takeaways#

  • A DeepEval trace is a tree of typed spans. It feeds three evaluation scopes: end-to-end, component-level and trajectory.
  • @observe records function arguments and returns automatically, but meaningful evaluation usually requires explicit update_current_span and update_current_trace calls.
  • In 4.3.5 the real span types are agent, llm, retriever and tool; everything else is custom. The implemented handoff keyword is agent_handoffs, not handoff_agents.
  • Falsy updates are ignored, some documented parameters are accepted but ignored, and metadata is not automatically part of a metric's test case.
  • evals_iterator supports sync and async patterns. The async result is the generator's return value, available through StopIteration.value.
  • A failing span metric fails the golden. In pytest, that failure may be invisible in the console table, so parse the latest-run JSON.
  • Keyless local tracing is real tracing. Without Confident credentials, export sends nothing; local evaluation remains fully available.
  • Masks receive raw Python objects and explicit updates are not masked. Recursive masking and data minimization are mandatory for sensitive systems.
  • Trace-aware judges read _trace_dict. Task Completion extracts then grades; Step Efficiency is deliberately adversarial; plan metrics pass at 1.0 when no plan is evidenced.
  • Tool Correctness, Tool Permission and Agent Loop Detection form a strong deterministic spine. Argument Correctness and the trajectory judges need validation because they are judge-dependent.
  • Multi-turn agent metrics operate on conversation units, not traces. MCP multi-turn metrics skip units of two or fewer turns.
  • Framework integrations are tracing front-ends. Verify the actual span tree before attaching metrics, and use next_*_span for framework-created spans.
  • DeepEval does not replace evalkit's judge validation, statistics, reference trajectory design or multi-agent handoff graders.
  • Spans depend on contextvars: copy the context (or use asyncio.to_thread) when you hand work to a thread, or the span silently disappears.
  • 4.3.6 adds ConversationToolCorrectnessMetric, a judge-free multi-turn tool check with per-turn pinning; use it as the deterministic spine for conversations.
  • Errors are a third outcome, not a failure: a caught component exception leaves an ERRORED span, skips its metrics and can still pass the golden. Gate on errored spans explicitly.
  • Trajectory judges score on five-anchor ordinal scales (Task Completion excepted), and two of them never see the trace in their scoring call. Validate extraction as well as scores, and use ordinal agreement statistics.
  • Agent Loop Detection is precise but narrow: it ignores short thoughts, compares only neighbouring thoughts and labels cycles by a 64-character input prefix.

Terms introduced in this lesson#

Term Meaning in this lesson
trace One end-to-end application run, represented as a tree of spans
span One nested unit of work inside a trace, such as an agent, LLM call, retrieval, tool or custom operation
component-level evaluation Metrics attached to individual spans and scored against test cases built from those spans
trajectory evaluation Metrics that read a whole run or subtree as ordered/nested process evidence
_trace_dict The nested JSON representation of a span subtree passed to trace-aware DeepEval metrics
@observe DeepEval's decorator for capturing functions as spans
update_current_span Runtime function that writes test-case and metadata fields onto the active span
update_current_trace Runtime function that writes trace-level fields such as input, output, tags and metrics
next_*_span Context managers that stage values or metrics for the next framework-created span
span bridge DeepEval machinery that converts confident-trace/OpenTelemetry spans into in-process DeepEval span objects
confident-trace The OpenTelemetry-first tracing dependency underneath DeepEval 4.x tracing
evals_iterator EvaluationDataset generator that yields goldens while collecting traced application runs
agent handoff field agent_handoffs, the implemented 4.3.5 agent-span field recording possible handoff targets
unit interaction A conversational unit constructed by multi-turn metrics before scoring
MCP primitive A Model Context Protocol tool, resource or prompt available to or used by an agent
Tool Permission Deterministic allow/deny metric for unauthorized tool names
Agent Loop Detection Deterministic trace metric combining tool repetition, reasoning stagnation and call-graph cycle checks
ConversationToolCorrectnessMetric 4.3.6 deterministic multi-turn tool metric: scores Turn.tools_called against ConversationalTestCase.expected_tools, optionally pinned to turns with ToolCall.turn, with no judge call
context propagation How a span finds its parent through Python contextvars; it survives asyncio.gather and asyncio.to_thread but not a plain thread-pool call
deepeval inspect Textual terminal UI that opens a saved run as a span tree; interactive only, installed with the inspect extra
base span The untyped (custom) span class; frameworks such as LangGraph produce one per graph node
errored span A span whose function raised; its status is ERRORED, its metrics are skipped, and it fails the golden only if the exception escaped the trace
rubric anchor A named score level in a judge prompt (for example 0.75 "Strong adherence"); anchored scores are ordinal labels, not continuous measurements

Exercises#

These exercises are keyless. Use DEEPEVAL_TELEMETRY_OPT_OUT=1, the shared FakeJudge, and deterministic fixtures. Do not log in to Confident AI.

  1. Recursive masking. Starting from the trace_local.py sample in 6.3, replace the string-only mask with a recursive mask for dicts, lists, tuples and strings. Prove with captured trace JSON that card numbers are redacted in automatic span input, automatic output and derived toolsCalled.inputParameters (hint: write a helper that lists the JSON path of every value that still contains the card number). Then pass a card number explicitly through update_current_span and explain what happens.
  2. The missing-output bug. Run the 4.1 sample after deleting update_current_trace(output=answer). Capture the exact exception class and message, then fix it. Write one sentence explaining why the application return value is not enough inside evals_iterator.
  3. Planted component bugs. Extend the support RAG agent from 4.1 with three goldens: one that retrieves nothing, one that calls the wrong tool and one that calls a forbidden tool. Attach the smallest deterministic metric for each failure. Verify that each golden fails for the intended reason in .deepeval/.latest_test_run.json.
  4. Async result recovery. Modify the 5.2 async iterator sample so it runs five goldens. Recover the EvaluationResult with StopIteration.value and print per-test success plus metric names. Then rerun with an ordinary for loop and explain what happened to the result object.
  5. A handoff presence metric. Start from the handoff_metric.py sample in 13.2 (supervisor, billing and retention agent spans). Make one golden route to billing and one route incorrectly to retention. Extend the metric so it also checks that the child input contains the order id, add a case where the supervisor routes correctly but drops the id, and compare your design with context_transfer in 10A.12, 3.4.
  6. Loop-detection breakdown. Starting from the agent_loop_detection.py sample in 10.4, build three loop fixtures: repeated identical tool calls, repeated semantically similar but differently worded reasoning, and a call-graph cycle (an agent span that calls another agent span that calls the first with the same input). Record the score and the score_breakdown for each. Explain one false positive and one false negative that the metric's own algorithm permits.
  7. MCP unit shape. Starting from the mcp_metrics.py sample in 12.3, build two conversational MCP cases for the same behaviour: one with the call and answer in a single assistant turn, one with separate assistant turns. Run MultiTurnMCPUseMetric on both with scripted scores and report the score and the judge-call list for each. Explain the difference without blaming the judge.
  8. Defend a number. Choose Task Completion or Step Efficiency. Write a one-paragraph evaluation report using the template in 14.6, including judge validation status, planted-fault results, known limitations and exactly which claims the metric supports.
Answers
  1. The recursive mask redacts strings wherever they occur inside nested dicts and lists, so all three locations show [CARD]: the leak list is empty. A value passed directly to update_current_span is not masked in 4.3.6, so the card number is back in the agent span's input unless you mask it before calling the update function. The solution (solution_1_recursive_mask.py) and its real output:
python
# solution_1_recursive_mask.py: exercise 1, a recursive mask and the explicit-update leak (lesson 10B.5)
import json
import re

import netguard  # noqa: F401

from deepeval.tracing import (observe, trace_manager, update_current_span,
                              update_current_trace)
from deepeval.tracing.trace_test_manager import trace_testing_manager

CARD = re.compile(r"\b\d{4}-\d{4}-\d{4}-\d{4}\b")


def recursive_mask(value):
    if isinstance(value, str):
        return CARD.sub("[CARD]", value)
    if isinstance(value, dict):
        return {key: recursive_mask(item) for key, item in value.items()}
    if isinstance(value, (list, tuple)):
        return type(value)(recursive_mask(item) for item in value)
    return value


def leaks(node, path="trace"):
    """Yield the JSON path of every value that still contains the card number."""
    if isinstance(node, dict):
        for key, item in node.items():
            yield from leaks(item, f"{path}.{key}")
    elif isinstance(node, list):
        for index, item in enumerate(node):
            yield from leaks(item, f"{path}[{index}]")
    elif isinstance(node, str) and "4111" in node:
        yield path


trace_manager.configure(mask=recursive_mask)


@observe(type="tool")
def charge(card: str):
    return f"charged {card}"


@observe(type="agent", name="checkout-agent")
def checkout(message: str, explicit: bool):
    if explicit:                                   # an explicit update bypasses the mask
        update_current_span(input=message)
    update_current_trace(input="checkout", output="done")
    return charge("4111-1111-1111-1111")


for explicit in (False, True):
    trace_testing_manager.test_name = "mask"
    checkout("pay with 4111-1111-1111-1111", explicit)
    paths = sorted(leaks(trace_testing_manager.test_dict))
    trace_testing_manager.test_name = None
    print(f"explicit update_current_span={explicit}: leaked paths = {paths}")
Output · real3 lines
explicit update_current_span=False: leaked paths = []
explicit update_current_span=True: leaked paths = ['trace.agentSpans[0].input']
[netguard] total blocked attempts: 0 []
  1. The exception is MissingTestCaseParamsError, with 'actual_output' cannot be None for the 'Task Completion' metric. The iterator opens the trace wrapper; the application function's return value is a span output but not automatically the trace-level output needed to build the trace test case.
  2. The retrieval failure should fail the retriever span's empty-context metric, the wrong tool should fail Tool Correctness or a routing metric, and the forbidden tool should fail Tool Permission. The JSON should show the failing metric name, score and reason under the relevant span's metricsData. If the only evidence is the final test status, the report is not good enough. One way to do it (solution_3_planted_bugs.py) keeps a passing control golden, plants one bug per remaining golden, attaches NonEmptyContext to the retriever and Tool Correctness plus Tool Permission to the agent span, and copies each golden's expected_tools onto the agent span with get_current_golden() (expectations only, never behaviour). It then prints every failing span metric per test case from the run JSON:
python
# solution_3_planted_bugs.py: exercise 3, one planted bug per golden, one deterministic metric each (lesson 10B.5)
import json
from pathlib import Path

import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden, get_current_golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import BaseMetric, ToolCorrectnessMetric, ToolPermissionMetric
from deepeval.test_case import ToolCall
from deepeval.tracing import observe, update_current_span, update_current_trace

from fake_judge import FakeJudge


class NonEmptyContext(BaseMetric):
    def __init__(self, threshold=1.0):
        self.threshold = threshold

    def measure(self, test_case, *args, **kwargs):
        count = len(test_case.retrieval_context or [])
        self.score, self.reason = (1.0 if count else 0.0), f"{count} chunks retrieved"
        self.success = self.score >= self.threshold
        return self.score

    async def a_measure(self, test_case, *args, **kwargs):
        return self.measure(test_case)

    def is_successful(self):
        return self.success

    @property
    def __name__(self):
        return "Non-empty context"


DOCS = {"refund": "Refunds are issued within 5 business days.",
        "shipping": "Standard shipping takes 3-5 days."}


@observe(type="retriever", metrics=[NonEmptyContext()])
def retrieve(query: str):
    chunks = [text for key, text in DOCS.items() if key in query.lower()]
    update_current_span(input=query, retrieval_context=chunks)
    return chunks


@observe(type="tool")
def lookup_order(order_id: str):
    return {"order_id": order_id, "status": "shipped"}


@observe(type="tool")
def track_parcel(order_id: str):                  # planted bug 2: the wrong tool
    return {"carrier": "unknown"}


@observe(type="tool")
def issue_refund(order_id: str):                  # planted bug 3: a forbidden tool
    return {"refunded": True}


@observe(type="agent", metrics=[ToolCorrectnessMetric(model=FakeJudge()),
                                ToolPermissionMetric(denied_tools=["issue_refund"])])
def agent(query: str):
    q = query.lower()
    if "parcel" in q:
        track_parcel("A-1042")
    else:
        lookup_order("A-1042")
    if "refund my order" in q:
        issue_refund("A-1042")
    chunks = retrieve(query)
    answer = chunks[0] if chunks else "Sorry, I could not find that."
    golden = get_current_golden()                  # expectations only, never behaviour
    update_current_span(input=query, output=answer, expected_tools=golden.expected_tools)
    update_current_trace(input=query, output=answer)
    return answer


EXPECTED = [ToolCall(name="lookup_order")]
dataset = EvaluationDataset(goldens=[
    Golden(input="Where is my order, and what is the shipping time?", expected_tools=EXPECTED),
    Golden(input="Tell me a joke about my order", expected_tools=EXPECTED),            # bug 1
    Golden(input="What is the shipping time for my parcel?", expected_tools=EXPECTED),  # bug 2
    Golden(input="Refund my order. What is the refund time?", expected_tools=EXPECTED), # bug 3
])
for golden in dataset.evals_iterator(
        async_config=AsyncConfig(run_async=False),
        display_config=DisplayConfig(print_results=False, show_indicator=False,
                                     inspect_after_run=False)):
    agent(golden.input)

run = json.loads(Path(".deepeval/.latest_test_run.json").read_text())["testRunData"]
for case in run["testCases"]:
    failures = [f"{span['name']}: {metric['name']} {metric['score']:.2f} | "
                + " ".join(str(metric["reason"]).replace("[", " ").replace("]", " ").split())
                for key in ("agentSpans", "retrieverSpans")
                for span in case["trace"].get(key, [])
                for metric in span.get("metricsData") or [] if not metric["success"]]
    print(f"{case['input']:<50} success={case['success']}")
    for failure in failures:
        print("    FAIL", failure[:100])
Output · real, DeepEval banner omitted8 lines
Where is my order, and what is the shipping time?  success=True
Tell me a joke about my order                      success=False
    FAIL retrieve: Non-empty context 0.00 | 0 chunks retrieved
What is the shipping time for my parcel?           success=False
    FAIL agent: Tool Correctness 0.00 | Tool Calling Reason: Incomplete tool usage: missing tools 'lookup_ord
Refund my order. What is the refund time?          success=False
    FAIL agent: Tool Permission 0.50 | 1 of 2 tool call(s) were unauthorized: 'issue_refund' . Allowed=ANY, D
[netguard] total blocked attempts: 0 []

Each planted bug lit exactly one metric, and the control passed. Notice that the forbidden-tool golden still passes Tool Correctness (the expected lookup_order was called and extras are ignored), which is the "recall is not permission" point from 10.1 shown on your own fixture.

  1. The manual next()/send(None) loop receives an EvaluationResult in StopIteration.value. An ordinary for loop discards generator return values, so the object is unavailable afterwards unless you read the saved run file.
  2. The metric passes when the expected child agent name appears among child agent spans and fails otherwise. The order-id extension inspects the child span's input, not the supervisor input, because context transfer is about what the receiver actually saw. The solution (solution_5_handoff_context.py) awards 0.5 for routing and 0.5 for the child seeing the id, so the three scenarios score 1.0, 0.5 and 0.0. This is still weaker than evalkit's full handoff grading: it does not score timing, ping-pong, return path or dropped results.
python
# solution_5_handoff_context.py: exercise 5, route check plus context transfer (lesson 10B.5)
import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import BaseMetric
from deepeval.tracing import observe, update_current_trace


class ChildAgentWithOrderId(BaseMetric):
    """Pass only if the expected child agent exists AND its input carries the order id."""
    def __init__(self, expected_name: str, must_contain: str):
        self.expected_name, self.must_contain = expected_name, must_contain
        self.threshold = 1.0
        self.requires_trace = True

    def measure(self, test_case, *args, **kwargs):
        children = (getattr(test_case, "_trace_dict", None) or {}).get("children") or []
        agents = [c for c in children if c.get("type") == "agent"]
        match = next((c for c in agents if c.get("name") == self.expected_name), None)
        routed = match is not None
        informed = routed and self.must_contain in str(match.get("input"))
        self.score = (0.5 if routed else 0.0) + (0.5 if informed else 0.0)
        self.success = self.score >= self.threshold
        self.reason = (f"routed={routed} child_saw_order_id={informed} "
                       f"children={[c.get('name') for c in agents]}")
        return self.score

    async def a_measure(self, test_case, *args, **kwargs):
        return self.measure(test_case)

    def is_successful(self):
        return self.success

    @property
    def __name__(self):
        return "Child agent with order id"


@observe(type="agent", name="billing-specialist")
def billing(request: str):
    return f"billing handled: {request}"


@observe(type="agent", name="retention-specialist")
def retention(request: str):
    return f"retention handled: {request}"


@observe(type="agent", name="support-supervisor")
def supervisor(query: str, pass_order_id: bool):
    request = "refund for A-1042" if pass_order_id else "refund please"   # context dropped
    answer = billing(request) if "refund" in query else retention(request)
    update_current_trace(input=query, output=answer)
    return answer


scenarios = [("routes to billing, passes the id", "refund order A-1042", True),
             ("routes to billing, drops the id", "refund order A-1042", False),
             ("routes to retention (wrong)", "keep me as a customer", True)]
results = []
for label, query, pass_id in scenarios:
    metric = ChildAgentWithOrderId("billing-specialist", "A-1042")
    dataset = EvaluationDataset(goldens=[Golden(input=query)])
    for golden in dataset.evals_iterator(
            metrics=[metric], async_config=AsyncConfig(run_async=False),
            display_config=DisplayConfig(print_results=False, show_indicator=False,
                                         inspect_after_run=False)):
        supervisor(golden.input, pass_id)
    print(f"{label}: score={metric.score} | {metric.reason}")
Output · real, DeepEval banner omitted6 lines
routes to billing, passes the id: score=1.0 | routed=True child_saw_order_id=True children=['billing-specialist']

routes to billing, drops the id: score=0.5 | routed=True child_saw_order_id=False children=['billing-specialist']

routes to retention (wrong): score=0.0 | routed=False child_saw_order_id=False children=['retention-specialist']
[netguard] total blocked attempts: 0 []
  1. Identical tool calls fire tool_repetition (score 0.6 here, because the other two checks passed: 0.40*0 + 0.35*1 + 0.25*1). The paraphrased fixture scores a perfect 1.0 for an agent that is plainly looping: that is the false negative. Be precise about why. These paraphrases have fewer than 20 meaningful words each, so the stagnation check skipped every pair without comparing anything (10.4). Had they been long enough to compare, they would still evade it, because the similarity is lexical (bigram Jaccard and SequenceMatcher), not semantic; the four-word edit in the 10.4 probe already falls below the 0.85 threshold. Repeating the same (type, name, input hash) along one root-to-leaf path fires call_graph_cycles (0.75 here: 0.40*1 + 0.35*1 + 0.25*0). A false positive can arise from an input-prefix collision (two different inputs that share their first 64 characters, as in the 10.4 probe) or a legitimate repeated poll with identical arguments; a false negative can also arise when the agent varies one irrelevant argument each time, as refund policy attempt {i} does in the second fixture. The solution (solution_6_loop_fixtures.py):
python
# solution_6_loop_fixtures.py: exercise 6, which loop-detection check fires for which fixture (lesson 10B.5)
import netguard  # noqa: F401

from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import AgentLoopDetectionMetric
from deepeval.tracing import observe, update_current_trace

PARAPHRASES = [
    "Let me try searching the refund policy once more to find the answer.",
    "I should look at the refund rules again because the answer is still missing.",
    "Perhaps checking the policy documents one further time will reveal the window.",
    "Another pass through the refund guidelines may finally surface the number.",
    "Time to consult the returns policy yet again in search of the duration.",
    "Reading the policy text a sixth time could still produce the missing detail.",
]


@observe(type="tool")
def search(query: str):
    return []


@observe(type="llm", model="fake-llm")
def think(text: str):
    return text


def identical_calls():
    for i in range(6):
        search("refund policy")                       # identical (name, arguments) six times


def paraphrased_reasoning():
    for i in range(6):
        think(PARAPHRASES[i])                         # different words, same idea
        search(f"refund policy attempt {i}")          # arguments vary


def call_graph_cycle():
    visits = []

    @observe(type="agent", name="planner")
    def planner(task: str):
        visits.append("planner")
        return worker(task)

    @observe(type="agent", name="worker")
    def worker(task: str):
        visits.append("worker")
        return planner(task) if len(visits) < 3 else "ok"   # planner -> worker -> planner

    planner("refund")                                 # the second planner call has the same input


def run(label, behaviour):
    @observe(type="agent", name="root")
    def agent(query: str):
        behaviour()
        update_current_trace(input=query, output="still checking")
        return "still checking"

    metric = AgentLoopDetectionMetric(async_mode=False)
    dataset = EvaluationDataset(goldens=[Golden(input="How long do refunds take?")])
    for golden in dataset.evals_iterator(
            metrics=[metric], async_config=AsyncConfig(run_async=False),
            display_config=DisplayConfig(print_results=False, show_indicator=False,
                                         inspect_after_run=False)):
        agent(golden.input)
    print(f"{label}: score={metric.score} breakdown={metric.score_breakdown}")


run("identical tool calls", identical_calls)
run("paraphrased reasoning", paraphrased_reasoning)
run("call-graph cycle", call_graph_cycle)
Output · real, DeepEval banner omitted6 lines
identical tool calls: score=0.6 breakdown={'tool_repetition': 0.0, 'reasoning_stagnation': 1.0, 'call_graph_cycles': 1.0}

paraphrased reasoning: score=1.0 breakdown={'tool_repetition': 1.0, 'reasoning_stagnation': 1.0, 'call_graph_cycles': 1.0}

call-graph cycle: score=0.75 breakdown={'tool_repetition': 1.0, 'reasoning_stagnation': 1.0, 'call_graph_cycles': 0.0}
[netguard] total blocked attempts: 0 []
  1. The compact two-turn shape is skipped because the implementation ignores units of two or fewer turns: the real run in 12.3 scored 0.0 after a single Reason call. The three-turn shape is judged: it scored 0.8 (min(1.0, 0.8)) and made ToolScore, ArgsScore and Reason calls. The difference is unit construction, not the judge's opinion of MCP quality.
  2. A strong paragraph names case and trial counts, instrumentation shape, deterministic gates, judge identity, human-label validation, planted-fault results, aggregation and limitations. It claims only what was measured, for example improved routing on the specified cases, not universal agent improvement.

Check yourself#

  1. What is the difference between a trace, a span and _trace_dict?
  2. Which four real span types exist in DeepEval 4.3.5, and what happens if you omit type?
  3. Why is handoff_agents dangerous in code written against the documentation?
  4. What are two consequences of the falsy-update rule?
  5. Why must you call update_current_trace(output=...) in evals_iterator?
  6. How do you recover the EvaluationResult from the asynchronous iterator?
  7. Why can pytest exit 1 while its DeepEval table appears to show only passing trace metrics?
  8. What does trace sampling affect, and what does it not affect?
  9. Why did the simple card mask fail in the real probe?
  10. What evidence does Task Completion's verdict judge see, and why is that a failure mode?
  11. Why is an empty-plan score of 1.0 misleading?
  12. What are the three sub-scores and weights in Agent Loop Detection?
  13. Why can Argument Correctness ignore a tool call in a plain traced agent?
  14. Why does a two-turn MCP interaction score 0.0 in the multi-turn MCP metrics?
  15. What can DeepEval capture about multi-agent systems, and what can it not grade built in?
  16. Why can a tool span vanish from a trace when work is handed to a thread pool, and what are two fixes?
  17. What does ConversationToolCorrectnessMetric need that ToolCorrectnessMetric gets from the span, and does it call a judge?
  18. An observed tool raises, your agent catches the exception and returns a fallback answer. What happens to the tool's span metric and to the golden, and how do you make CI notice?
  19. Why can six identical "I will search the policy again" thoughts score 1.0 on reasoning stagnation?
  20. Which two trajectory judges produce their final score without seeing the trace, and what does that change about how you validate them?
  21. Your golden has an expected_output, yet Exact Match raises MissingTestCaseParamsError inside evals_iterator. Why, and what is the fix?

Further resources#

Official DeepEval documentation, checked for the research underlying this lesson on 24 November 2026 (the Conversation Tool Correctness page on 28 November 2026):

Within this course: 10A.7 for the framework-free agent harness, trajectory metrics and reliability statistics; 10A.12 for handoffs, attribution and simulator validity; 10B.2 for test cases and runners; 10B.3 for judges and custom metrics; 10B.4 for the non-agent metric catalogue; 10B.6 for datasets and simulation; and 10B.7 for CI/CD and Confident AI.

← 10B.4: DeepEval's Built-in Metrics, Opened Up: RAG, Safety, Conversations and More | Module 10B overview | 10B.6: DeepEval Datasets, Synthetic Data, Conversation Simulation and Benchmarks →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close