ExAgent.Eval (ExAgent v3.0.0)

View Source

Measure an agent on a set of cases: run each case, score the result with evaluators and summarize pass rate, latency, usage and cost.

Stability — Stable.

cases = [
  ExAgent.Eval.Case.new("refund", "Refund order 7", expected: "refunded"),
  ExAgent.Eval.Case.new("lookup", "Where is order 9?", expected: "shipped")
]

report =
  ExAgent.Eval.run(agent, cases,
    evaluators: [
      ExAgent.Eval.contains(),
      ExAgent.Eval.tool_called("lookup_order")
    ],
    concurrency: 4,
    repeat: 3
  )

IO.puts(ExAgent.Eval.Report.format(report))
report.summary.pass_rate

Use it to compare prompts, models or tools before shipping a change (ExAgent.Eval.Report.compare/2 lists the cases that regressed), or in CI with a pass-rate threshold. Replay uses recorded model responses and usage. Live runs and explicit recordings can incur provider costs.

Targets

The target is an %ExAgent{} agent, run with ExAgent.run/3, or a function fn input, run_opts -> ExAgent.run(...) end returning {:ok, result} or {:error, reason}, for agents that need per-case setup.

For a multi-turn agent target, use a candidate ExAgent.Eval.Scenario as the case input. One attempt covers the whole conversation under the same timeout. The final turn provides :result and :output. Evaluators can inspect each turn in :trajectory, and tool_called/2 counts calls across all turns. A scenario with an ExAgent.Eval.Simulator also provides :simulation.

Evaluators

An evaluator has a name and a function of the case's outcome (outcome/0) that returns true, false, a score between 0 and 1, {score, reason} or :skip. Return {:error, reason} with a text reason if grading could not finish. This records a grading error and fails at every threshold. A result passes an evaluator when its score is at least the evaluator's threshold (default 1.0, so a boolean must be true). Build one with evaluator/3 or use the built-ins equals/1, contains/1, matches/2, tool_called/2 and tool_arguments/1. Model-based judge/1 is candidate. A case whose run fails, raises or times out gets no scores and does not pass. An evaluator that raises records a grading error. An attempt passes when it has at least one emitted grade and every check passes or skips. Coverage of emitted grades is available in report.summary.grading_coverage.

Grading usage

An evaluator that calls a model reports what it spent as a third element: {score, reason, usage} or {:error, reason, usage}, where usage is the %ExAgent.Result{} of a grading run, its %ExAgent.RunError{}, an %ExAgent.Message.Usage{} or a list of them. The report keeps it apart from the target's usage, in Result.grading and summary.grading. judge/1 reports its reviewer's runs. Build a model-calling evaluator with evaluator/3's :model option, so that a score without usage, an exception or a timeout leaves its grading unknown instead of none. The candidate calibration/3 measures an evaluator against human labels.

Summary

Types

What evaluators receive for one run of one case.

What a grading run reports: see the moduledoc's Grading usage.

Functions

Compare an evaluator's verdicts in report with human labels, to measure how far its grading can be trusted.

Look for the case's expected terms in the text output. Terms can be strings or numbers, individually or in a list. The score is the fraction of nonempty terms found. When all terms are empty after trimming, the evaluator skips. Set trim: false to match literal whitespace. With the default case-insensitive matching, terms are substrings of the Unicode case-folded output. For example, "SS" matches "ß". Other options: :case_sensitive (default false), :name, :threshold. Both text flags require booleans. Unknown or duplicate options raise ArgumentError at construction.

The output equals the case's :expected. For strings, trim: true (default) ignores surrounding whitespace and case_sensitive: false uses Unicode case folding, so "Straße" and "STRASSE" compare equal. Option :name (default "equals") names it in reports. Both text flags require booleans. Unknown or duplicate options raise ArgumentError at construction.

Build an evaluator from a name and a function of outcome/0. Return {:error, reason} when the evaluator cannot grade the outcome. The report retains the text reason, marks the score as an error and assigns zero. A score or :skip may carry one optional explanation in a pair. Nesting that pair inside another pair records a grading error. With :fixtures, the outcome carries the case's :fixture; an evaluator that calls a model passes it as fixture: to ExAgent.run/3 so its grading requests record and replay with the case, and returns the run's result as the third element so the report counts its usage

A reviewer model grades the answer against :criteria and replies PASS or FAIL with a reason.

Check whether the text output matches regex. The only option is :name (default "matches"). Unknown or duplicate options raise ArgumentError at construction.

Run every case and score it. Passing a scripted or simulated scenario as a case's input is candidate.

Score the application's observed tool arguments against case.metadata["expected_tool_calls"].

Counts calls to name emitted by the model, including calls with malformed arguments or failed execution. If an :args filter is supplied, only calls whose arguments decode to a map and pass the filter count. Absent arguments give the filter %{}. Supply a one-argument function for :args. Supply :version to identify that filter for baseline comparisons. With :status, count only calls whose first matching reply in the same response batch is a tool return with that status. A retry prompt consumes the call without recording a status. A user part closes the current batch. Replies before it still count. See ExAgent.Message.Part.ToolReturn.status/0. An argument filter checks the original request, before tool hooks. A non-negative integer for :times requires that exact count. With nil or no :times, at least one call must match. Use :name to label the score. Unknown or duplicate options raise ArgumentError at construction. By default this evaluator counts the target's :new_messages. A Composition or Flow requires an explicit step. Pass the candidate step: "id" to count calls in the retained :messages of that direct step or branch, including history from before a resume. A declared step that never started has an empty history. A function target using this option must supply a :steps list with exactly one matching :id and an ExAgent message list for that entry. Missing or ambiguous evidence records a grading error, including for times: 0. When a model response has omitted parts, visible matches give a lower bound. They can establish presence or disprove an exact count they already exceed. An undecidable count records a grading error at every threshold. A scenario supplies the new messages of every scripted turn, in order.

Types

outcome()

@type outcome() :: %{
  :case => ExAgent.Eval.Case.t(),
  :output => term(),
  :result => ExAgent.result() | nil,
  :error => term() | nil,
  optional(:fixture) => ExAgent.Fixture.t(),
  optional(:trajectory) => [map()],
  optional(:simulation) => map()
}

What evaluators receive for one run of one case.

score()

@type score() ::
  boolean()
  | number()
  | :skip
  | {boolean() | number() | :skip, String.t() | nil}
  | {boolean() | number() | :skip, String.t() | nil, usage()}
  | {:error, String.t()}
  | {:error, String.t(), usage()}

usage()

What a grading run reports: see the moduledoc's Grading usage.

Functions

calibration(report, evaluator, labels)

(candidate API)
@spec calibration(
  ExAgent.Eval.Report.t(),
  String.t(),
  %{optional(String.t() | {String.t(), pos_integer()}) => boolean()}
) :: {:ok, map()} | {:error, term()}

Compare an evaluator's verdicts in report with human labels, to measure how far its grading can be trusted.

labels maps a case name, or {case_name, attempt}, to true when the output should pass and false when it should fail. A case name labels every attempt of that case and an attempt key overrides it. Label the outputs that the report graded: live attempts each have their own output, so label attempts, or record the suite with :fixtures and label the replayed outputs.

Returns {:ok, calibration} for the labeled attempts, where a pass is the positive class:

  • tp, fp, tn, fn and their sum n — the attempts the evaluator passed or failed.
  • tpr (tp / (tp + fn)), tnr (tn / (tn + fp)) and balanced_accuracy, their mean; each is nil without labels on its side.
  • tpr_interval and tnr_interval — the 95% equal-tailed interval {low, high} of the posterior Beta(1 + hits, 1 + misses) of each rate (method: "beta_uniform_v1"), or nil.
  • abstained (the evaluator skipped), grading_errors (its score is a grading error) and unscored (no score: the target run failed).
  • disagreements — %{case, attempt, label, passed, reason} for each attempt where the evaluator and the label differ, by case and attempt.

Returns {:error, {:unknown_evaluator, name}} when the report has no definition or score for evaluator, and {:error, {:unknown_labels, keys}} when labels name cases or attempts that are not in the report. Labels that are not booleans keyed by a case name or {name, attempt} raise ArgumentError. Calibrate on labels the criteria were not tuned on, with a few dozen labels on each side before trusting the intervals.

contains(opts \\ [])

@spec contains(keyword()) :: ExAgent.Eval.Evaluator.t()

Look for the case's expected terms in the text output. Terms can be strings or numbers, individually or in a list. The score is the fraction of nonempty terms found. When all terms are empty after trimming, the evaluator skips. Set trim: false to match literal whitespace. With the default case-insensitive matching, terms are substrings of the Unicode case-folded output. For example, "SS" matches "ß". Other options: :case_sensitive (default false), :name, :threshold. Both text flags require booleans. Unknown or duplicate options raise ArgumentError at construction.

equals(opts \\ [])

@spec equals(keyword()) :: ExAgent.Eval.Evaluator.t()

The output equals the case's :expected. For strings, trim: true (default) ignores surrounding whitespace and case_sensitive: false uses Unicode case folding, so "Straße" and "STRASSE" compare equal. Option :name (default "equals") names it in reports. Both text flags require booleans. Unknown or duplicate options raise ArgumentError at construction.

A case with expected: nil skips this check. To require a nil output, use Eval.evaluator("nil output", &is_nil(&1.output)).

evaluator(name, fun, opts \\ [])

@spec evaluator(String.t(), (outcome() -> score()), keyword()) ::
  ExAgent.Eval.Evaluator.t()

Build an evaluator from a name and a function of outcome/0. Return {:error, reason} when the evaluator cannot grade the outcome. The report retains the text reason, marks the score as an error and assigns zero. A score or :skip may carry one optional explanation in a pair. Nesting that pair inside another pair records a grading error. With :fixtures, the outcome carries the case's :fixture; an evaluator that calls a model passes it as fixture: to ExAgent.run/3 so its grading requests record and replay with the case, and returns the run's result as the third element so the report counts its usage:

Eval.evaluator("faithful", fn outcome ->
  case ExAgent.run(grader, prompt(outcome), fixture: outcome[:fixture]) do
    {:ok, result} -> {result.output == "yes", nil, result}
    {:error, error} -> {:error, "grader failed", error}
  end
end, model: grader.model)

A third element that is not a usage (see usage/0) records a grading error.

Options: :threshold (default 1.0) and :model, the model the evaluator grades with, in any form ExAgent.new/1 accepts. With :model, a score without usage, an exception or a timeout leaves the attempt's grading unknown instead of none, and the report warns when it is the target's model (summary.warnings). Unknown or duplicate keys and a model that does not resolve raise ArgumentError when the evaluator is constructed.

Set :version to a non-secret UTF-8 identifier of 1 to 512 bytes for baseline comparisons or ExAgent.Eval.Online. Change it when the scoring code or configuration changes. Evaluators without a version can score cases and contribute to pass-rate summaries, with incomplete comparison provenance.

judge(opts)

(candidate API)
@spec judge(keyword()) :: ExAgent.Eval.Evaluator.t()

A reviewer model grades the answer against :criteria and replies PASS or FAIL with a reason.

Criteria must be valid UTF-8 and contain a non-whitespace character.

The reviewer sees the task, a transcript of the run (tool calls and results included, so facts the agent looked up count as supported) and the answer, each bounded by :max_transcript_bytes; images and files in the task appear as placeholders. The case's :expected, when present, is shown as the key content a correct answer must convey, not as the only acceptable wording. A function target may omit :messages for output-only evaluation. The reviewer is told that the target supplied no transcript. If provided, :messages must be a list of ExAgent messages. In imported histories, a notice identifies model response parts omitted by the runtime. For scenarios the first prompt describes the task and the transcript covers every scripted turn, including subsequent corrections.

Workflow results require :step. Pass step: "id" to review the overall answer using only that direct step's retained transcript. The task and expected answer still come from the case. A declared step with an empty history is identified in the prompt. A missing or duplicate ID or an invalid selected history records a grading error before the reviewer runs. The step history has the same shape as for tool_called/2.

The reviewer reasons before a final VERDICT: PASS or VERDICT: FAIL line. That last non-empty line may use Markdown emphasis, any letter case and a closing period (**Verdict: pass.**); other text on it is not a verdict. Set reasoning: false for the label-first format.

Options: :model and :criteria (required), :model_settings, :max_transcript_bytes (default 16_000, at least 1_024), :step, :name and :version for opaque or changing reviewer configuration. An unusable reply scores 0 with the error as reason. The reviewer's runs, including a format reminder or a failed review, count in the attempt's grading, not in the target's usage. Their agent is named "exagent.eval.judge", so telemetry and traces tell grading apart from the target. A reviewer on the target's model gives a {:judge_same_model, name} warning: a model tends to favour its own answers. Unknown or duplicate options raise ArgumentError before the reviewer is built.

matches(regex, opts \\ [])

@spec matches(Regex.t(), keyword()) :: ExAgent.Eval.Evaluator.t()

Check whether the text output matches regex. The only option is :name (default "matches"). Unknown or duplicate options raise ArgumentError at construction.

run(target, cases, opts \\ [])

@spec run(
  ExAgent.t() | (term(), keyword() -> term()),
  [ExAgent.Eval.Case.t()],
  keyword()
) ::
  ExAgent.Eval.Report.t()

Run every case and score it. Passing a scripted or simulated scenario as a case's input is candidate.

Options:

  • :evaluators — list of ExAgent.Eval.Evaluator.t/0 (default []: a case passes when its run succeeds).
  • :concurrency — runs (and scorings) at a time (default 4).
  • :timeout — milliseconds per run (default 120_000); a run that exceeds it is killed and its result's error is :timeout.
  • :evaluator_timeout — milliseconds to score one run with all evaluators (default 120_000); when exceeded, every evaluator of that run fails with a timeout reason. Scoring time is not part of the run's duration_ms.
  • :repeat — runs per case (default 1).
  • :fixtures — per-case cassette options including required :dir, optional :mode (defaults to :replay), :tool_stubs for strict tool dispatch, :stream_events for exact sequence capture and redaction callbacks for ExAgent.Fixture.open/2.
  • :run_opts — options for every run, merged under each case's own.

Unknown or duplicate suite options raise ArgumentError before any target runs. Pass options for the target in :run_opts. For an ExAgent target, Eval merges each case's overrides with the suite defaults and checks the option names and message history before starting the first case. Invalid options raise ArgumentError with the case name. A function target defines its own option contract. Both :timeout and :evaluator_timeout accept integers from 1 through 4_294_967_295 milliseconds.

Before either kind of target runs, every case must have a unique binary name, map metadata and a keyword list of run options. Evaluator names identify metrics in the report. Before starting any attempts, Eval checks that each evaluator has a binary name, a one-argument function, a numeric threshold from 0 through 1 and a valid identifier when versioned. Invalid evaluator definitions and repeated evaluator names raise ArgumentError: give each criterion its own :name.

Without evaluators, workers discard unused target history before completed cases wait for an earlier case. With evaluators, scoring starts after the target runs finish. Each grader sees the full result for its case. As the scores are collected in order, the runner releases fields that the report omits.

A target that raises, exits or throws produces a failed result; so does an evaluator, which then scores 0 and fails regardless of its threshold.

tool_arguments(opts \\ [])

@spec tool_arguments(keyword()) :: ExAgent.Eval.Evaluator.t()

Score the application's observed tool arguments against case.metadata["expected_tool_calls"].

Each expectation is a map with "tool" (name) and "args" (JSON object). Omit the metadata key to skip the evaluator. An empty list expects no calls. Calls are paired by tool name, in order within each name. Output schema submissions are excluded. Scenarios include calls from every target turn.

Each field in either side of a pair has equal weight: exact values earn 1, values equal after Unicode case folding, normalization and trimming string values (or equivalent JSON numbers) earn 0.5. Missing, extra, different and invalid arguments earn 0. An argument-free call gets one point when matched, and zero when missing or extra. The reason lists the result for each field without including its value.

Options are :name (default "tool_arguments"), :threshold (default 1.0) and the candidate :step option for a workflow. The step uses the same evidence as tool_called/2. Omitted response parts and argument-free Online observations provide insufficient evidence and produce a grading error.

tool_called(name, opts \\ [])

@spec tool_called(String.t(), keyword()) :: ExAgent.Eval.Evaluator.t()

Counts calls to name emitted by the model, including calls with malformed arguments or failed execution. If an :args filter is supplied, only calls whose arguments decode to a map and pass the filter count. Absent arguments give the filter %{}. Supply a one-argument function for :args. Supply :version to identify that filter for baseline comparisons. With :status, count only calls whose first matching reply in the same response batch is a tool return with that status. A retry prompt consumes the call without recording a status. A user part closes the current batch. Replies before it still count. See ExAgent.Message.Part.ToolReturn.status/0. An argument filter checks the original request, before tool hooks. A non-negative integer for :times requires that exact count. With nil or no :times, at least one call must match. Use :name to label the score. Unknown or duplicate options raise ArgumentError at construction. By default this evaluator counts the target's :new_messages. A Composition or Flow requires an explicit step. Pass the candidate step: "id" to count calls in the retained :messages of that direct step or branch, including history from before a resume. A declared step that never started has an empty history. A function target using this option must supply a :steps list with exactly one matching :id and an ExAgent message list for that entry. Missing or ambiguous evidence records a grading error, including for times: 0. When a model response has omitted parts, visible matches give a lower bound. They can establish presence or disprove an exact count they already exceed. An undecidable count records a grading error at every threshold. A scenario supplies the new messages of every scripted turn, in order.