Learning resourcesReviewed · Pydantic

Pydantic Evals: Custom Evaluators

Custom Evaluators is a Pydantic Evals guide for Python developers building output checks, but several examples contain simplified or placeholder validation logic. It explains functions and configurable evaluator classes, pass/fail assertions, numeric scores, labels, explanatory reasons and asynchronous integrations. Saved function evaluators retain names rather than captured state, so loading requires the intended function definitions.

Researched 26 Nov 2026

In short.

Custom Evaluators is a Pydantic Evals guide for Python developers evaluating task outputs, but several examples need stronger validation before real use. It covers function and dataclass evaluators, execution context, multiple result types, asynchronous calls and dataset serialization. Important constraints include finite numeric scores, unique function names and the loss of captured function state when saving datasets. Its SQL checks and local Python execution example have specific correctness and isolation limits. No examples were executed; runtime behavior, compatibility and performance remain unassessed.

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

Coverage includes the complete selected page at [https://pydantic.dev/docs/ai/evals/evaluators/custom/index.md], including its introductory documentation-index and query-parameter notices, code examples, best-practice guidance and next-step references. Linked pages and files are excluded. No examples were executed; runtime behavior, compatibility, performance and external-service reliability were not assessed. The selected page contains no pricing or license terms.

The overview

identity

Custom Evaluators is a feature guide in Pydantic's AI documentation for the Python pydantic_evals package. The resource is the complete documentation page at [https://pydantic.dev/docs/ai/evals/evaluators/custom/index.md].

It teaches how to define evaluation logic for individual task executions and attach that logic to datasets or cases. Its scope includes domain rules, specialized metrics and external validation services.

assessment

This is useful guidance when an evaluation needs application-specific checks, such as matching an expected answer, enforcing a keyword rule or consulting a validation API. It explains both the extension interface and operational details that can affect saved datasets.

The examples demonstrate implementation patterns rather than validated measures of quality. Developers must establish whether their chosen checks represent correctness for their application; the page provides no benchmarks or production results establishing that.

users

The guide suits Python developers maintaining evaluation datasets for AI applications or other tasks with inspectable inputs and outputs. It is particularly relevant when checks depend on expected answers, case metadata, recorded metrics or an external service.

Beginners can start with the short exact-match function. The later material assumes familiarity with dataclasses, type annotations, asynchronous functions and Python package imports; it does not provide a Python introduction or installation walkthrough.

capabilities

Evaluators can produce boolean assertions, integer or floating-point scores, string labels, and EvaluationReason values carrying explanations. Dictionaries, including nested dictionaries, allow one evaluator to return several results. An empty dictionary omits results for a case where the check does not apply.

EvaluatorContext exposes the case name, inputs, metadata, expected output, actual output, task duration in seconds, custom metrics and attributes. The page also describes access to an OpenTelemetry span tree when Logfire is configured. Both synchronous and asynchronous evaluators are supported, with configurable names and evaluator version labels.

Using it

requirements

The examples require Python and the pydantic_evals package. Class-based evaluators must use the dataclass decorator, inherit from Evaluator and implement evaluate. Checks without parameters can instead use plain synchronous or asynchronous functions accepting EvaluatorContext.

The HTTP examples import httpx, and the SQL parsing example imports sqlparse. Span-tree access is described for a Logfire-configured environment. The page does not specify an installation command, supported Python versions or a compatible package release. The exact-match and keyword examples contain no model calls.

mechanism

A check reads the task's execution context and returns a supported evaluation value. Boolean values become assertions, numbers become scores and strings become labels. EvaluationReason attaches an explanation. Dictionary keys name separate results. Numeric scores must be finite: NaN or either infinity produces an EvaluatorFailure for that case, including when contained in a reason or returned dictionary.

Function results use the function's name by default; FunctionEvaluator can override the evaluation name and attach a version. Dataclass fields provide parameters for class evaluators. Returning an empty dictionary suppresses results, but the evaluator is still invoked for every case and must perform its own applicability check.

setup

Define a function accepting EvaluatorContext for a check without parameters, or create a dataclass Evaluator subclass for configurable behavior. Add it to the evaluators list on a Dataset or Case. The basic demonstration evaluates a task using Dataset.evaluate_sync and reads named assertions and scores from the resulting report.

For saved datasets, supply custom functions and classes through custom_evaluator_types. Function names must be unique among the registered evaluators. Loading with Dataset.from_file requires supplying the intended definitions again; a saved dataset does not carry the function implementation or its captured state.

example

The page creates a dataset named shouting with input hello world and expected output HELLO WORLD. Its task converts the input to uppercase. The exact_match function compares actual and expected output, while an asynchronous word_count function counts output words. The documentation displays an assertion value of True and a score of 2; these are documented example outputs, and no code was executed.

For configurable checks, ContainsKeyword takes a keyword and a case_sensitive flag as dataclass fields. It optionally lowercases the keyword and output before checking containment. This demonstrates parameter handling, but keyword presence alone does not establish that an answer is correct.

Assessment & evidence

limitations

Function serialization stores the function name and any evaluation name or version, without captured state. Functions supplied when loading determine the resulting behavior. Duplicate names cause saving to fail, including collisions from factories or decorators. Lambdas, bound methods, functools.partial and other callable objects cannot be saved as function evaluators.

Several checks are illustrative. ComprehensiveCheck identifies JSON format using opening and closing braces. ValidSQL accepts a nonempty sqlparse result after substring filtering and does not use its dialect field. Other examples contain fixed placeholder scores. These implementations do not establish robust format validation, SQL correctness or meaningful quality measurement.

SafeEvaluator returns a passing boolean when expected_output is missing, despite describing the result as skipped. EfficiencyCheck treats a missing api_calls metric as zero. Either pattern can make absent evaluation data appear acceptable unless the developer deliberately chooses that behavior.

ExecutablePython writes ctx.output to a temporary file and launches it as a local Python subprocess. A timeout and cleanup are shown, but no sandbox is shown to restrict filesystem or network access. The example does not establish safe execution of untrusted generated code.

reasoning

The function interface is a practical starting point for checks without configuration. Dataclass subclasses make thresholds, keywords and endpoints explicit parameters. The guide recommends focused evaluators, while allowing grouped results when checks share substantial computation or one network request.

The main design decision is what each result actually measures. Exact matching measures equality, and the length score measures distance from a chosen length; neither establishes broader answer quality. Explanatory reasons help users distinguish the measured condition from the conclusions they might otherwise draw from a passing result.

alternatives

Within the documented interfaces, choose functions for checks without parameters and dataclass subclasses for configurable checks. Case-level evaluators can attach checks to particular cases, while returning an empty dictionary supports applicability decisions based on the actual output.

The page points to Report Evaluators for experiment-wide analyses and Span-Based Evaluation for checks using execution spans. Those linked pages are outside the supplied scope, so their implementation details and requirements are not assessed. The page provides no comparison with other evaluation libraries.

evidence

The evidence is the complete Custom Evaluators documentation page at [https://pydantic.dev/docs/ai/evals/evaluators/custom/index.md], retained as selected-page.txt. It includes interface descriptions, code examples, serialization rules, best practices and example printed outputs.

This is documentation evidence. It contains no independent benchmark, production reliability measurement or comparative evaluation. Linked API references and guides do not establish additional facts beyond the descriptions present on this page.

Access & freshness

costs

The page states no package prices, Logfire prices, external-service charges or usage totals. Costs are unknown.

API-backed evaluators make external requests, and the code-execution example uses local compute. Their resource consumption and any associated charges depend on the implementation and services used; the page does not quantify them.

rights

The selected page contains no license text or explicit redistribution grant for its documentation or embedded code examples. Those reuse rights, and the package's license, remain unknown from this page.

freshness

The supplied page was captured on 26 November 2026 at 12:40:34.075 UTC. The page provides no publication date, last-update date or package release identifying which installed versions support every documented feature.

Evaluator version labels shown in examples identify evaluator configurations rather than a package release. Compatibility with a particular installation and changes after the captured page remain unknown.

actions

Start with one check tied to a concrete application requirement, using a function unless configuration is needed. Define expected behavior for missing reference outputs, absent metrics and inapplicable cases. Add explanatory reasons and verify that numeric results remain finite.

Before relying on saved datasets, verify unique evaluator names and loading with the intended definitions. Replace placeholder validation with logic appropriate to the application. For external APIs, account for timeouts and the task output sent to the endpoint. Use the subprocess pattern only with trusted code or an execution environment providing appropriate isolation, and confirm compatibility with the installed package.

Evidence for this report

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