# Testing and evaluations

Testing AI features shouldn't mean flaky CI runs, unpredictable token bills, or
skipping tests altogether. ExAgent treats testing as a first-class workflow:
start with deterministic in-process scripts, record real model replies into
cassettes for CI replay, turn real production bugs into redacted regression
cases, and score quality both offline (`mix exagent.eval`) and online
(`ExAgent.Eval.Online`).

**What ExAgent simplifies:**

- **100% offline ExUnit tests:** `ExAgent.Models.Test` and `use ExAgent.Case`
  exercise your real tools, Ecto schemas, permissions, streaming and approvals
  in milliseconds with zero network calls.
- **Recorded cassettes with tool stubs:** Record real provider interactions
  once with `ExAgent.Fixture`, substitute live side-effecting tools locally, and
  replay deterministically in CI.
- **Production-to-CI regressions:** Convert any run result or continuation into
  a redacted `Eval.Case` with `Eval.Case.from_run/2`.
- **Offline & online evaluation:** Run repeatable evaluation suites in CI
  (`ExAgent.Eval` / `mix exagent.eval`) and sample confirmed production runs
  asynchronously (`ExAgent.Eval.Online`) with optional OTLP log export.

> #### Need exact cassette v1 JSON schemas or online queue measurements? {: .info}
>
> For complete cassette matching rules, evaluator provenance fields and load
> numbers, see [Runtime & ops contracts](llm/runtime-and-ops-contracts.md).

## Assert on the public result

Start in ordinary ExUnit with `ExAgent.Models.Test`. Because `"test"` runs
through the exact same public loop as cloud and local models, you can assert on
`result.status`, `result.output`, tool returns and usage immediately:

```elixir
defmodule DocumentationAgentTest do
  use ExUnit.Case, async: true

  test "returns the validated final output" do
    agent = ExAgent.new(model: %ExAgent.Models.Test{label: "Ready"})
    assert {:ok, result} = ExAgent.run(agent, "Start")
    assert result.status == :succeeded
    assert result.output == "Ready"
    assert result.request_count == 1
  end
end
```

In your test modules, `use ExAgent.Case` adds helpful assertions
(`assert_output/2`, `assert_tool_called/3`, `assert_event/2`, `assert_usage/2`,
`assert_cost/2`) and `test_model/1` helpers.

## Script every expected request

Pass `script:` to script multi-step loops (`{:tool_calls, calls}`, plain
strings, explicit responses or `fn messages, params -> ... end` callbacks). A
nonempty script must cover every expected model request — if your agent makes
an unexpected extra call, the run fails explicitly instead of inventing an
answer:

```elixir
effects = :atomics.new(1, [])
tool = ExAgent.Tool.new(
  name: "record",
  parameters_json_schema: %{"type" => "object", "properties" => %{}},
  takes_ctx: false,
  call: fn _args ->
    :atomics.add(effects, 1, 1)
    {:ok, "recorded"}
  end
)
model = %ExAgent.Models.Test{script: [
  {:tool_calls, [%ExAgent.Message.Part.ToolCall{
    tool_name: "record", tool_call_id: "record-1", args: %{}}]}
]}
agent = ExAgent.new(model: model, tools: [tool])
{:error, %ExAgent.RunError{partial: partial}} = ExAgent.run(agent, "Record once.")
%{status: partial.status, requests: partial.request_count, effects: :atomics.get(effects, 1)}
```

## Script a conversation

For multi-turn tests, supply one script entry per turn and pass `result.model`
plus `result.messages` forward (or run through `ExAgent.Server`, which carries
the updated stateful model across turns automatically).

## Script explicit model finishes

Use `ExAgent.Message.new_response/2` when testing specific finish reasons
(`:stop`, `:tool_calls`, `:length`), usage accounting or commentary across both
buffered and streamed runs:

```elixir
alias ExAgent.{Message, Models.Test, Tool}
alias ExAgent.Message.Part.{Text, ToolCall}

tool = Tool.new(name: "inspect_chart", takes_ctx: false, call: fn _ -> "observed" end)
call = %ToolCall{tool_name: tool.name, tool_call_id: "inspect-1", args: %{}}
tool_reply = Message.new_response([call], finish_reason: :stop)
text_reply = Message.new_response([%Text{content: "Chart checked."}], finish_reason: :tool_calls)
model = %Test{script: [tool_reply, text_reply]}
agent = ExAgent.new(model: model, tools: [tool])

{:ok, buffered} = ExAgent.run(agent, "Inspect the chart.")
events = Enum.to_list(ExAgent.run_stream(agent, "Inspect the chart."))
{:result, streamed} = List.last(events)
{buffered, streamed}
```

## Script a streaming failure

Test how your UI and recovery logic behave when a provider disconnects
mid-stream using `ExAgent.Models.Test.stream/2`:

```elixir
alias ExAgent.{Message.Response, Models.Test, RequestError, RunError}

timeout = %RequestError{provider: :test, reason: :timeout, transport: :timeout}
item = Test.stream([text_delta: "half", usage: :unknown], {:error, timeout})
agent = ExAgent.new(model: %Test{script: [item]})
events = Enum.to_list(ExAgent.run_stream(agent, "Start"))
{:error, %RunError{partial: partial}} = List.last(events)
"half" = Response.text(partial.pending_response)
%{output: nil, usage_status: :unknown, usage: %{output_tokens: nil}} = partial
```

Notice `partial.pending_response` retains the provisional text while
`partial.output` stays `nil` and `usage_status` stays `:unknown` because no
final usage was confirmed.

## Declare a model profile

Test multimodal or capability-gated code paths offline by customizing the test
model's `%ExAgent.ModelProfile{}`:

```elixir
alias ExAgent.{Model, Models.Test}

profile = %{Model.profile(%Test{}) | supports_audio_input: true}
model = %Test{label: "Audio received", profile: profile}
%{supports_audio_input: true} = Model.profile(model)
```

### Settle a development Budget

To test spend-budget reservations and settlement offline, attach synthetic
estimated cents to `Test` responses with
`ExAgent.Message.Usage.with_estimated_cost(nil, 1)` (see
[Reserve a shared spend budget](models-and-limits.md#reserve-a-shared-spend-budget)).

## Exercise separate quota buckets

Give two `%ExAgent.Models.Test{}` structs distinct `system:` and `model_name:`
labels to test `ExAgent.RateLimiter` and `ExAgent.Models.Fallback` failover
deterministically:

```elixir
alias ExAgent.{Models.Fallback, Models.Test, RateLimiter}

primary = %Test{system: "primary", model_name: "small", label: "first"}
backup = %Test{system: "secondary", model_name: "large", label: "backup"}
{:ok, limiter} = RateLimiter.start_link(
  name: :review_test_quota,
  limits: %{{"primary", "small"} => [rpm: 1], {"secondary", "large"} => [rpm: 1]}
)

model = Fallback.new(models: [primary, backup], fallback_on_quota_denial: true)
agent = ExAgent.new(model: model, rate_limiter: limiter, model_settings: [max_tokens: 20])
{:ok, %{output: "first"}} = ExAgent.run(agent, "Review this.")
```

## Record and replay a stream

`ExAgent.Fixture` records real buffered or streamed model interactions into
JSON cassettes and replays them verbatim offline — letting you verify your
full request/response pipeline in CI without touching live APIs. In an ExUnit
test tagged `@tag :tmp_dir`, bind `path = Path.join(tmp_dir, "stream.json")`:

```elixir
alias ExAgent.{Fixture, Message, Models.Test}
alias ExAgent.Message.Part

terminal = Message.new_response([%Part.Text{content: "alpha beta"}], finish_reason: :stop)
chunks = [text_delta: "alp", text_delta: "ha beta"]
model = %Test{script: [Test.stream(chunks, {:finish, terminal})]}

for {mode, model} <- [{:record, model}, {:replay, %Test{script: [:invalid]}}] do
  agent = ExAgent.new(model: model)
  {:ok, fixture} = Fixture.open(path, mode: mode, stream_events: :verbatim, tool_stubs: %{})
  try do
    events = Enum.to_list(ExAgent.run_stream(agent, "Continue", fixture: fixture))
    ["alp", "ha beta"] = for {:text_delta, %{text: text}} <- events, do: text
    {:result, %{output: "alpha beta"}} = List.last(events)
  after
    {:ok, _} = Fixture.close(fixture)
  end
end
```

## Replay with tool substitutes

Pass `tool_stubs:` when opening a cassette so side-effecting tools (payments,
emails, external APIs) run safe local substitutes instead of live handlers:

```elixir
stubs = %{"write" => fn ctx, _args -> {:ok, "saved " <> ctx.tool_call_id} end}
{:ok, fixture} = ExAgent.Fixture.open(path, mode: :replay, tool_stubs: stubs)

try do
  ExAgent.run(agent, "Save the record.", fixture: fixture)
after
  {:ok, _} = ExAgent.Fixture.close(fixture)
end
```

## Match concurrent cassette requests

When a parallel `Flow` or multi-agent test dispatches requests concurrently,
v1 cassettes match each interaction by exact request content rather than
fragile call order. If two independent roots sharing the same cassette file
produce identical request fingerprints, replay fails with
`{:fixture_ambiguous, ...}` — pass `ExAgent.Fixture.with_label/2` on each root
to disambiguate them cleanly.

## Turn a production failure into a CI case

When a real user hits an agent bug, capture the terminal run with
`ExAgent.Eval.Case.from_run/2` and an explicit redactor, record a regression
cassette with substituted tools, and lock the fix into ExUnit:

```elixir
defmodule DocumentationRegressionTest do
  use ExAgent.Case, async: true
  alias ExAgent.{Eval, Tool}
  alias ExAgent.Message.Part.ToolCall

  @tag :tmp_dir
  test "routes the order for review", %{tmp_dir: dir} do
    observed = ExAgent.new(model: test_model(["APPROVE incident-order-842"]))
    terminal = ExAgent.run(observed, "Check incident-order-842")

    {:ok, regression} =
      Eval.Case.from_run(terminal,
        name: "order-review",
        expected: "Needs review",
        redact: fn _, text -> {:ok, String.replace(text, "incident-order-842", "example-order")} end
      )

    lookup = Tool.new(
      name: "lookup_order", takes_ctx: false,
      call: fn _ -> flunk("use the local substitute") end
    )
    call = %ToolCall{tool_name: "lookup_order", tool_call_id: "lookup-1", args: %{}}
    model = test_model([{:tool_calls, [call]}, regression.metadata.observed_output])
    agent = ExAgent.new(model: model, tools: [lookup])
    fixtures = [dir: dir, tool_stubs: %{"lookup_order" => fn _ -> "manual review" end}]
    eval_opts = [evaluators: [Eval.equals()]]

    before_fix =
      Eval.run(agent, [regression], eval_opts ++ [fixtures: [mode: :record] ++ fixtures])

    assert %{runs: 1, passed: 0, errors: 0} = before_fix.summary

    corrected = %{agent |
      model: test_model([fn _, _ -> flunk("the cassette must answer this request") end]),
      output_validators: [fn "APPROVE example-order", _ -> {:ok, "Needs review"} end]
    }

    target = fn input, opts ->
      events = corrected |> ExAgent.run_stream(input, opts) |> Enum.to_list()
      {:result, result} = assert_event(events, :result)
      assert_event(events, :tool_call_finished, &(&1.tool == "lookup_order"))
      assert_tool_called(result, "lookup_order", times: 1, status: :succeeded)
      assert_output(result, "Needs review")
      assert_usage(result, input: {:unknown, nil}, output: {:unknown, nil})
      assert_cost(result, :unknown)
      {:ok, result}
    end

    replay = Eval.run(target, [regression], eval_opts ++ [fixtures: fixtures])
    assert %{runs: 1, passed: 1, errors: 0} = replay.summary
  end
end
```

### Capture a persisted turn for CI

For bugs observed inside a durable continuation, fetch the authorized details
by logical execution `id` with `ExAgent.Continuation.get(scope, id, diagnostics: true)`
(where `record_id` is the separate lifetime CAS identity on the returned record)
and pass them to `Eval.Case.from_run/2` with your redactor and expected answer.

## Measure quality with evals

`ExAgent.Eval` runs a dataset of `ExAgent.Eval.Case` prompts against your agent
and grades every run with deterministic evaluators (`Eval.equals/1`,
`Eval.contains/1`, `Eval.tool_called/2`, custom functions), classifiers
(`Classifier.evaluator/3`) or LLM judges.

### Score a set of cases

Combine deterministic checks and an LLM judge in one concurrent suite:

```elixir
alias ExAgent.Eval

cases = [
  Eval.Case.new("total", "What is the total of order 7?", expected: "120"),
  Eval.Case.new("status", "Has order 9 shipped?", expected: "pending")
]

report =
  Eval.run(agent, cases,
    evaluators: [
      Eval.contains(),
      Eval.tool_called("lookup_order"),
      Eval.judge(model: reviewer_model, criteria: "Accurate, concise, no invented data.")
    ],
    repeat: 3,
    concurrency: 4
  )

IO.puts(Eval.Report.format(report))
```

### Check that a tool completed

Require not just that the model *asked* for a tool, but that the exact call
arguments succeeded:

```elixir
ExAgent.Eval.tool_called("lookup_order",
  args: &(&1["id"] == 9),
  status: :succeeded,
  times: 1,
  name: "order 9 looked up"
)
```

## Replay an evaluation suite in CI

Define an `ExAgent.Eval.Suite` module so pull requests run against recorded
cassettes with `mix exagent.eval` and fail immediately on regressions:

```elixir
defmodule SupportEval do
  use ExAgent.Eval.Suite, name: "support"
  def target(_opts), do: ExAgent.new(model: %ExAgent.Models.Test{label: "refund"})
  def cases, do: [ExAgent.Eval.Case.new("refund", "Return my order", expected: "refund")]
  def evaluators, do: [ExAgent.Eval.equals()]
end
```

```sh
# 1. Record cassettes & save a baseline locally in dev:
mix exagent.eval --suite support --record --save evals/baseline.json

# 2. Replay deterministically offline in CI against the baseline:
mix exagent.eval --baseline evals/baseline.json --min-pass-rate 0.9 --format junit \
  --output eval-junit.xml 2> eval-gate.log
```

Read saved JSON reports back into Elixir to inspect pass rates programmatically:

```elixir
map = report_path |> File.read!() |> Jason.decode!()
{:ok, report} = ExAgent.Eval.Report.from_map(map)
Map.take(report.summary, [:runs, :pass_rate])
```

### Compare runs when the suite changes

Save JSON reports from `ExAgent.Eval` across commits and compare pass rates,
latency, tool counts and token usage side by side to catch subtle quality or
cost regressions before deploying a prompt or model change.

### Simulate the user

Test multi-turn conversational flows by pairing your agent with a scripted or
simulated user persona across several turns to verify escalation, clarification
and tool recovery behavior.

## Sample confirmed terminals

In production, supervise `ExAgent.Eval.Online` to asynchronously grade a
bounded sample of confirmed runs (default 1%) without slowing down user
responses. Offers validate and check capacity immediately — returning
`{:error, :full}` cleanly under backpressure while leaving the user's response
untouched ([Online evaluation load](observability.md#online-evaluation-under-load)):

```elixir
alias ExAgent.Eval
alias ExAgent.Eval.Online

owner = self()
event = [:exagent, :eval, :online, :result]
handler = make_ref()

:ok = :telemetry.attach(handler, event, fn _, _, metadata, pid ->
  send(pid, {handler, metadata})
end, owner)

evaluator = Eval.evaluator("finished", &(&1.result.status == :succeeded), version: "1")
{:ok, pid} = Online.start_link(
  scope: "support", evaluator: evaluator, sample_rate: 1.0
)

try do
  agent = ExAgent.new(model: %ExAgent.Models.Test{label: "Ready"})
  {:ok, result} = terminal = ExAgent.run(agent, "Start")
  queue = Online.handle(pid)
  {:ok, :enqueued} = Online.offer(queue, {:run, terminal})
  {:ok, :duplicate} = Online.offer(queue, {:run, terminal})

  receive do
    {^handler, %{run_id: id, projection_version: 1, label: label, score: score}}
    when id == result.run_id ->
      {label, score}
  after
    2_000 -> raise "evaluation did not finish"
  end
after
  :telemetry.detach(handler)
  GenServer.stop(pid)
end
```

### Export evaluation logs

Pass an `:otel` callback to `Online.start_link/1` to export each
`gen_ai.evaluation.result` OTLP/HTTP log record directly to your Collector:

```elixir
alias ExAgent.Observability.OpenTelemetry

export_logs = fn request ->
  case Req.post(url, json: request, retry: false, redirect: false, receive_timeout: 1_000) do
    {:ok, %{status: status}} when status in 200..299 -> :ok
    {:ok, %{status: status}} -> {:error, {:collector_http_status, status}}
    {:error, _} = error -> error
  end
end

trace_context = OpenTelemetry.capture_context()
```

For `ExAgent.Server` turns, capture the trace context on the root run's stop
event and correlate it by `run_id` with the persistence-confirmed terminal
before calling `Online.offer/3`:

```elixir
alias ExAgent.{Eval.Online, Event, PubSub, Server}
alias ExAgent.Observability.OpenTelemetry

topic = Event.agent_topic(conversation_id, scope)
handler = make_ref()
:ok = PubSub.subscribe(pubsub, topic)

try do
  :ok = :telemetry.attach(handler, [:exagent, :run, :stop], fn
    _, _, %{agent: ^agent_name, parent_run_id: nil, status: :succeeded, run_id: id}, {pid, tag} ->
      send(pid, {tag, id, OpenTelemetry.capture_context()})

    _, _, _, _ ->
      :ok
  end, {self(), handler})

  with {:ok, %{run_id: run_id}} <- Server.send_message(server, prompt) do
    receive do
      {:exagent_event, %Event{
        type: :run_finished, namespace: ^scope, agent_id: ^conversation_id, run_id: ^run_id,
        payload: %{persistence: %{status: :confirmed}}
      } = terminal} ->
        receive do
          {^handler, ^run_id, context} ->
            Online.offer(queue, {:server, terminal}, trace_context: context)
        after
          2_000 -> {:error, :trace_context_not_observed}
        end
    after
      2_000 -> {:error, :confirmed_terminal_not_observed}
    end
  end
after
  :telemetry.detach(handler)
  PubSub.unsubscribe(pubsub, topic)
end
```

### Deliver grading with Jobs.Durable

When online grading calls a slower LLM judge and must survive node restarts,
back your evaluation pipeline with `ExAgent.Eval.Online.Durable` and Oban so
grading work persists cleanly outside request processes.

API: `ExAgent.Models.Test`, `ExAgent.Case`, `ExAgent.Fixture`,
`ExAgent.Eval`, `ExAgent.Eval.Case`, `ExAgent.Eval.Online`.
