Learning resourcesReviewed · Pydantic

Pydantic Evals: Span-Based Evaluation

This Pydantic Evals guide teaches Python developers to check how AI agents run, but reliable conclusions depend on capturing the right spans and writing queries correctly. It covers OpenTelemetry capture through the Logfire SDK, HasMatchingSpan queries and custom SpanTree evaluators.

Researched 26 Nov 2026

In short.

This Pydantic Evals guide helps Python developers evaluate what AI agents did during execution, but incomplete traces or incorrectly scoped queries can produce misleading conclusions. It explains local span capture, boolean queries and custom trace analysis. HasMatchingSpan succeeds when any span matches, so checking that something never happened needs special care. Several examples establish presence or hierarchy rather than chronological order. No code was executed; runtime behavior and compatibility remain unverified, and costs are unknown.

Researched and written by an AI model and checked by a second AI model. How it works

Covers the complete captured page at [https://pydantic.dev/docs/ai/evals/evaluators/span-based/index.md], including requirements, query semantics, examples, custom interfaces and debugging guidance. Its documentation-index link and agent-query notice concern documentation access rather than span-evaluation prerequisites. Linked pages, package contents and external services are excluded. No code was executed; installation, runtime behavior, performance and compatibility remain unverified.

The overview

Identity

Span-Based Evaluation is a Pydantic Evals documentation guide at [https://pydantic.dev/docs/ai/evals/evaluators/span-based/index.md]. It teaches evaluation of AI system execution using OpenTelemetry spans, which are timed records of operations arranged into a tree.

The resource is a guide to a library feature. Its central interfaces are HasMatchingSpan, SpanQuery, SpanTree and SpanNode.

Assessment

The guide is useful when a correct final answer is insufficient evidence of acceptable behavior: a retrieval step may be missing, a forbidden tool may have been called, or delegation may have followed the wrong structure. It provides concrete ways to turn recorded behavior into evaluation assertions.

Its usefulness depends on instrumentation and query design. A passing span check establishes a condition about recorded telemetry; it does not independently establish answer quality, complete visibility into execution or prevention of dangerous operations.

Users

The examples suit Python developers maintaining retrieval-augmented generation systems, tool-calling agents and systems that delegate between agents. They are particularly relevant to regression testing when outputs remain acceptable while internal behavior changes.

Beginners will need familiarity with Python functions, dictionaries and evaluation cases, plus an understanding of how their application emits spans. Experienced developers can use the custom evaluator interfaces for application-specific metrics and behavioral checks.

Capabilities

SpanQuery supports exact, substring and regular-expression name matching; attribute values and keys; error status; duration limits; logical combinations; and relationships involving children, descendants and ancestors. It also supports depth constraints, child and descendant counts, and boundaries for recursive searches.

Custom evaluators can access ctx.span_tree, find or count matching nodes, inspect timestamps and attributes, and return multiple boolean or numeric results. The guide demonstrates counting tool spans and summing the durations of matching model spans.

The page also explains diagnostic details: successful spans typically have status unset rather than ok, and a model request attempt span indicates a failed or rejected attempt rather than necessarily a fallback to another model. Its gen_ai.request.model attribute identifies the attempted model.

Using it

Requirements

The Logfire SDK must be installed and configured to capture the OpenTelemetry spans used by these evaluators. The documented installation command is pip install 'pydantic-evals[logfire]'. A Pydantic Logfire account is not required for local capture.

The application must emit spans that represent the behavior being checked. Universal checks built around task_execution assume that all relevant work is enclosed by one root span with that name. Required Python versions, package versions and compatibility constraints are not specified on this page.

Mechanism

During task execution, the configured SDK captures emitted spans. Evaluators inspect the resulting span tree. HasMatchingSpan returns true if any span satisfies its query; conditions describe individual spans and their relationships.

This is an existence check. HasMatchingSpan(query={'not_': X}) succeeds if any span fails condition X, even when another span satisfies X. To establish that no captured span matches X, a custom evaluator can return not ctx.span_tree.any(X).

The built-in alternative is to match a task root and place the forbidden condition under no_descendant_has. That examines descendants of the matched root; a separate not_ condition is needed if the root itself could violate the rule.

Setup

Install the Logfire extra and configure capture before evaluation. The page uses logfire.configure(send_to_logfire='if-token-present'), making that example's export behavior conditional on token availability.

Ensure the task and tools emit the span names used in the queries. Add a task_execution root around all relevant work when using the root-scoped examples, then attach HasMatchingSpan evaluators to a Dataset containing Case inputs.

The basic snippet configures a dataset and evaluator but does not supply a complete task implementation and evaluation invocation. The page recommends inspecting the span tree and building queries incrementally.

Example

For a tool-calling task, HasMatchingSpan(query={'name_contains': 'search_tool'}, evaluation_name='used_search') checks whether a captured span name contains search_tool.

If all task work sits under a single task_execution root, query={'name_equals': 'task_execution', 'no_descendant_has': {'name_contains': 'delete_database'}} checks that no descendant has the forbidden name fragment. A missing root causes this check to fail; spans outside that root are not examined.

These assertions describe recorded operations. The search check does not establish that useful information was retrieved, and the forbidden-tool check does not block tool execution.

Assessment & evidence

Limitations

Checks cover captured spans, so missing instrumentation limits what they can establish. Root-scoped absence checks additionally exclude spans outside the selected root and depend on the assumption that one root contains all relevant work.

The Check Multiple Tools example verifies that operations appear, without comparing their order. The searched_before_answering example checks an ancestor relationship rather than chronological order. Verifying time order needs additional logic, such as custom comparisons of SpanNode timestamps.

The example labeled no loops limits direct child counts. That is neither a total tool-call limit nor proof that no loop occurred. Likewise, summing matching span durations should not be interpreted as elapsed task time when those spans overlap or nest.

Reasoning

The strongest reason to use this approach is that process failures can remain invisible in final outputs. A recorded retrieval operation, delegation relationship or retry gives a concrete target for a regression assertion.

Assertions should match the strength of the evidence. An attribute-key check for context_ids establishes that the key exists, not that the model used the referenced documents correctly. A name match establishes a recorded label, not the semantic success of the operation. Combining span checks with output validation addresses different parts of correctness.

Alternatives

For simple tasks where final output correctness is sufficient, the page says traditional input-output evaluation may be enough. Span checks can supplement those evaluators when execution behavior matters.

Within Pydantic Evals, custom SpanTree evaluators provide an alternative to declarative queries for more complex analysis. The page also points to MaxToolCalls for limiting total tool calls, but the linked implementation and detailed behavior are outside this page. No comparative evidence about other evaluation frameworks is provided.

Evidence

The evidence is the complete captured documentation page at [https://pydantic.dev/docs/ai/evals/evaluators/span-based/index.md]. It contains setup instructions, query definitions, practical examples, custom evaluator interfaces and debugging guidance.

The examples describe intended API usage and are not execution results. No code was executed. Runtime behavior, installation success, performance and compatibility have not been verified. Linked documentation provides references but contributes no assessed content.

Access & freshness

Costs

The page states that local span capture does not require a Pydantic Logfire account. It provides no prices for software, hosted telemetry, model requests or infrastructure, so total monetary cost is unknown.

No measurements quantify telemetry capture overhead, evaluation throughput or storage requirements.

Rights

The selected page supplies no explicit license or redistribution terms for its documentation or code examples. Permissions to redistribute either are unknown from this evidence.

Freshness

The page was captured on 26 November 2026 at 18:09:15.811 UTC. It does not identify a package release, minimum supported version or last-updated date.

The capture date establishes when this text was obtained, not when the feature last changed. Compatibility with a particular installed version remains unknown.

Actions

Before adoption, confirm compatibility with the intended Python and package versions. Instrument a representative task and inspect its actual span names, hierarchy, statuses and attributes before choosing assertions.

Start with a required-operation check, then add absence checks with explicit coverage boundaries. Validate queries against cases expected to pass and fail. Use timestamp comparisons when order matters, distinguish direct-child limits from total call limits, and combine behavioral assertions with output validation.

Review the example's send_to_logfire setting when local-only capture is required. The page supports local capture without an account, but its sample configuration allows conditional export.

Evidence for this report

selected-page.txtselected · checked 2026-11-26