Laminar logo
All blog posts

How to A/B Test AI Agent Changes in Production

Dec 1, 2026 · Laminar Team

A/B testing an AI agent change means comparing the current agent with a changed version on concurrent, randomly assigned traffic. In production, that comparison can break before you calculate a metric: a per-request coin flip can switch models between “here are your options” and “yes, book that one.”

Keep the conversation on one arm, then measure the whole task. A run can finish with status ok and a wrong answer. A cheaper model can make more calls. An automated judge can miss failures differently in each arm. This guide works through those problems using a synthetic two-arm rebooking test measured in Laminar. Its readout illustrates why the outcome definition matters before you declare a winner.

Illustrative readout of a synthetic A/B test of a rebooking agent. Per 1,000 passing tasks, gpt-5.4-nano costs $1.44 and gpt-5.4-mini $5.64. Judge-flagged share: 41.0% vs 53.0% with all findings, 39.9% vs 33.8% without hidden_error findings, 35.8% vs 23.6% on lookups.

Decide what needs a live test

Run offline evals first: they are repeatable and can reject poor candidates before users see them. How to Evaluate AI Agents covers trajectory and tool-call evals. Braintrust’s post “A/B testing can’t keep up with AI” argues for making evals the main optimization loop and reserving A/B tests for what evals cannot measure.

A live test helps answer questions your dataset leaves open:

  • Does the change hold up on the production task mix?
  • What does a completed task cost after turns, retries and tool calls?
  • Does the change affect user behavior, including abandonment and feedback?

A before/after comparison mixes the deployment’s effect with changes in traffic and provider behavior. AI Agent Drift covers investigating those shifts. Concurrent randomization reduces that confounding.

Shadow testing copies live requests to the new version and discards its output. Side-effecting tools require more care: a shadow rebooking agent that calls change_booking can move a real reservation. Stub write tools before shadowing. If you cannot isolate those effects, test in a sandbox before exposing a small production cohort.

Assign variants per user or session

Choose the assignment unit before launch and keep it sticky. Use the user or account when people return across conversations. Session assignment can work when conversations are independent and returning users are uncommon. Avoid switching variants between calls within a task.

GrowthBook’s LLM testing guide says assignment, exposure and metrics must use the same unit. In the rebooking example, the agent proposes a flight and the customer confirms on a later turn. Both turns need the same arm.

A salted hash provides sticky assignment without a lookup table. In production, an experimentation SDK usually replaces assign to manage exposure logging and the split:

import hashlib

from lmnr import Laminar, observe

Laminar.initialize()

EXPERIMENT = "rebooking-model-ab"
MODELS = {"control": "gpt-5.4-mini", "treatment": "gpt-5.4-nano"}


def assign(user_id: str) -> str:
    digest = hashlib.sha256(f"{EXPERIMENT}:{user_id}".encode()).hexdigest()
    return "treatment" if int(digest, 16) % 2 else "control"


def handle_turn(user_id: str, chat_id: str, messages: list) -> str:
    variant = assign(user_id)

    @observe(
        name="rebooking_agent",
        user_id=user_id,
        session_id=chat_id,
        metadata={"experiment": EXPERIMENT, "variant": variant},
    )
    def run():
        return run_agent(MODELS[variant], messages)

    return run()

run_agent is your existing agent loop. Keep the experiment name stable during the test. For a prompt or tool experiment, select that configuration instead and hold unrelated changes fixed.

Record assignment before agent work starts

Attach the experiment and variant as trace metadata, together with user and session IDs. Passing these fields to observe attaches them before the agent runs. In the example, all 11 sessions that crashed on a simulated 503 retained their variant metadata.

Record the task type too when your application knows it from an entry point or pre-response intent router. You will need that segment key later.

A release (LMNR_RELEASE) and agent versions, currently in beta, do not replace assignment metadata. Both arms can ship in one deployment. Agent versions track the stable system prompt and tool definitions, so a model-only change does not create a new version. Use release and version data to inspect what ran; use the variant field to identify the experimental arm.

Judge outcomes across the trajectory

A confident final message can contradict an earlier tool result. Trace status alone will not catch that mistake.

Signals read finished traces against your instruction and produce structured events when they match. Projects can start with Issues, a broad Signal for agent errors. An experiment benefits from a custom Signal tied to its outcome definition. The example used this instruction, shortened here:

Did the customer end this turn with a wrong outcome? Report wrong_information (a time, price or fare rule the tool results don’t support), wrong_choice (an option that breaks the customer’s constraints when a matching one existed), unauthorized_change, or hidden_error (a tool error the customer wasn’t told about). Tool calls from earlier turns in the LLM input count as having happened.

Check coverage before comparing verdicts. New Signals default to total tokens > 1000, which makes eligibility depend on agent behavior: a short, correct refusal can fall below the threshold. Replace it with a filter that every experimental trace satisfies, such as the root span name. Count completed analyses from signal_runs by arm and segment. Unanalyzed runs remain unknown.

Then inspect judgment accuracy in both arms. In an earlier run, Issues flagged 67 of 176 booking-change second turns for missing required lookups, although turn 1 contained those lookups in the recorded conversation: 38 of 85 for mini and 29 of 91 for nano. That motivated the custom instruction’s final sentence. Different judgment errors across arms can distort the comparison.

Carry user feedback as a separate outcome. How to Collect User Feedback on AI Agent Runs explains how to attach it after the run.

Measure cost per passing task within segments

A low cost per call can hide extra turns and retries. Roll traces up to the task, here the session, and compare end-to-end task duration.

The example defines cost per passing task as total arm spend, including crashed and unanalyzed tasks, divided by analyzed tasks with no flag and no crash. A judge’s pass is not confirmed success. At partial coverage, this is spend per observed pass; it does not estimate cost per successful task. Compare coverage alongside it.

Task segments also matter. A smaller model might handle booking changes well and struggle with flight lookups. Pooling them makes the result depend on the traffic mix.

Use a task key recorded before the response. Alternatively, Laminar’s task extraction stores the request in traces.agent_input. For multi-turn sessions, take argMin(agent_input, start_time): the confirmation turn’s input might only say “Yes, please go ahead with that one.”

Worked example: a cheaper rebooking model

This run used synthetic traffic on a local Laminar stack: 799 sessions from 450 simulated users, real OpenAI calls, and mock airline tools. Users were assigned to gpt-5.4-mini (control) or gpt-5.4-nano (treatment) for lookups, two-turn booking changes and cancellation questions. About 2% of booking lookups raised a simulated 503. The custom Signal ran on gpt-5.4.

Its initial token filter skipped 32 traces. Only 88% of mini’s booking-change sessions were fully analyzed, compared with 96% of nano’s. Of mini’s 18 skipped change traces, 14 were short, correct BASIC-fare refusals. After backfilling every skipped trace, mini’s change flagged share fell from 84.6% to 81.1%. The results below cover all 1,074 traces.

This SQL editor query aggregates traces into sessions, then compares arms by task:

WITH sessions AS (
    SELECT
        session_id,
        any(simpleJSONExtractString(metadata, 'variant')) AS variant,
        any(simpleJSONExtractString(metadata, 'task_type')) AS task,
        sum(total_cost) AS cost,
        countIf(status = 'error') > 0 AS errored,
        countIf(id IN (
            SELECT trace_id FROM signal_runs
            WHERE signal_id IN (SELECT id FROM signals WHERE name = 'Rebooking failure')
              AND status = 'COMPLETED'
        )) = count() AS analyzed,
        countIf(id IN (
            SELECT trace_id FROM signal_events
            WHERE signal_name = 'Rebooking failure'
        )) > 0 AS flagged
    FROM traces
    WHERE start_time >= now() - INTERVAL 7 DAY
      AND simpleJSONExtractString(metadata, 'experiment') = 'rebooking-model-ab'
    GROUP BY session_id
)
SELECT
    variant,
    task,
    count() AS tasks,
    round(countIf(analyzed) / tasks, 2) AS analyzed_share,
    round(countIf(analyzed AND (flagged OR errored)) / countIf(analyzed), 3) AS flagged_share,
    round(sum(cost) * 1000
        / countIf(analyzed AND NOT flagged AND NOT errored), 2) AS cost_per_1k_passing
FROM sessions
GROUP BY variant, task WITH ROLLUP
HAVING variant != ''
ORDER BY variant, task
TaskTasksAnalyzedFlagged shareCost per 1,000 passing
All423 / 376100% / 100%53.0% / 41.0%$5.64 / $1.44
Lookup182 / 165100% / 100%23.6% / 35.8%$2.27 / $0.77
Change148 / 134100% / 100%81.1% / 63.4%$21.77 / $4.01
Cancel93 / 77100% / 100%65.6% / 13.0%$6.13 / $0.63

Values are mini / nano. Flagged share counts analyzed sessions with a judge finding or a crash. It is not an audited failure rate. The strict instruction counts unsupported details, contributing to the high rates.

Pooled, nano was flagged less and cost 74% less per passing task despite using 12% more tokens per task: 3,489 versus 3,123. Median task duration was 2.27 s for mini and 2.23 s for nano. Three exploratory looks, none pre-registered, qualify that readout:

  • Segments disagree. Nano was flagged less on changes and cancellations, but more on lookups: 35.8% versus 23.6%, with clustered z = 2.65.
  • The outcome definition changes the direction. Both models sometimes passed an invalid value to get_fare_rules. Nano often disclosed the resulting error; mini often did not. There were 94 hidden_error findings for mini and four for nano. Excluding those findings gives flagged shares of 33.8% and 39.9%. The treatment-minus-control 95% interval spans −0.6 to +12.8 percentage points, so the reversal does not establish an advantage for either arm.
  • A deterministic check exposes missed errors. On two lookup templates with one correct flight, nano answered incorrectly in 12 of 113 runs and mini in three of 113. The Signal caught eight of those 15 errors. It also flagged 45 answers naming the correct flight; some may contain other faults, and a sample included clear judge errors. The checks measure different things.

This run does not establish that nano is better for users. Observed cost per passing task was lower under both definitions: mini cost 3.9 times as much with all findings and 2.8 times as much without hidden_error. Before rerunning, settle the outcome definition and audit judgments in both arms. Add the flight check as a guardrail and pre-register the lookup segment.

Plan sample size and inference before launch

Choose one primary outcome, guardrails and a stopping rule. Track crash rate across all assigned sessions even when judging fails.

Analyze at the assignment unit

When users are randomized, their sessions can be correlated. Treating every session as independent can understate uncertainty. Aggregate flagged and analyzed tasks per user, then compute uncertainty for the ratio across users. Statsig documents the delta method for this situation.

Add any(user_id) AS user_id to the first query’s sessions CTE. Replace its final SELECT with a comma followed by these CTEs and SELECT:

users AS (
    SELECT
        any(variant) AS variant,
        countIf(analyzed) AS n,
        countIf(analyzed AND (flagged OR errored)) AS y
    FROM sessions
    GROUP BY user_id
    HAVING n > 0
),
arms AS (
    SELECT
        variant,
        count() AS k,
        sum(y) / sum(n) AS p,
        (sum(y * y) - 2 * p * sum(y * n) + p * p * sum(n * n))
            / pow(sum(n), 2) * k / (k - 1) AS var
    FROM users
    GROUP BY variant
)
SELECT
    round(maxIf(p, variant = 'control'), 3) AS control,
    round(maxIf(p, variant = 'treatment'), 3) AS treatment,
    round(sqrt(sum(var)), 3) AS se_diff,
    round((maxIf(p, variant = 'treatment') - maxIf(p, variant = 'control'))
        / sqrt(sum(var)), 2) AS z
FROM arms

The result was 0.530 versus 0.410, standard error 0.034 and z = −3.51. Excluding hidden_error findings from the events subquery gave z = +1.79.

Clustered and naive standard errors were similar here: simulated users averaged about 1.8 sessions, without shared characteristics tying their outcomes together. Correlation between a real user’s sessions is what can widen uncertainty.

For cost per passing task, bootstrap users and recompute total spend divided by passing tasks in each resample. Preserve each user’s sessions together.

Size the test for the base rate

At 80% power and a two-sided 5% level, an approximate independent-task baseline is:

7.85 × (p1(1−p1) + p2(1−p2)) / (p1 − p2)²

Baseline flagged shareDetect a change toAnalyzed tasks per arm, independent baseline
20%16%About 1,440
10%8%About 3,210
5%4%About 6,740

Adjust for clustering. With similarly sized user clusters, an approximate design effect is 1 + (m − 1) × ICC, where m is analyzed tasks per user and ICC measures within-user outcome correlation. Estimate these from a pilot or A/A run. For uneven activity and ratio metrics, simulate the assignment and analysis using pilot data.

Then account for analysis coverage when estimating incoming traffic. Low-volume tests of rare failures can take months. Offline evals and a monitored staged rollout may be more practical for smaller changes.

Control duration and multiple comparisons

Run across business cycles. GrowthBook’s guide specifies at least seven full days. For a fixed-horizon test, do not stop when the result first crosses a significance threshold; use the planned horizon or a valid sequential method.

Five metrics across three segments create 15 comparisons. If they were independent under no effect, the chance of at least one p-value below 0.05 would be about 54%. Dependence changes that probability. Predeclare confirmatory comparisons and treat additional looks as exploratory.

Check the assignment split before reading outcomes. A mismatch can indicate assignment or logging problems. Here, 236 control users and 214 treatment users gave p ≈ 0.30, consistent with 50/50 assignment.

Separate measurement from experimentation

Laminar records trajectories and supports judged outcomes; it does not assign variants or calculate significance. An experimentation tool can own assignment, exposure logging and inference:

  • PostHog splits users between prompt versions and reports cost, latency and eval pass rate.
  • Statsig turns prompt or model configurations into experiments.
  • LaunchDarkly experiments on AI configuration variations through AgentControl.
  • GrowthBook documents prompt and model tests, including CUPED and sequential testing.
  • Datadog Experiments, formerly Eppo, offers prompt A/B testing in Preview with user-ID targeting.
  • Langfuse compares labeled prompt versions by latency, tokens, cost and scores; application code selects the label.

Record the assigned variant in Laminar metadata. Query Signal outcomes in SQL or send them back as experiment metrics, keeping the assignment unit consistent.

FAQ

Can I segment on something the variant changes?

Avoid it when estimating the treatment effect. Segment on information fixed before the first response, such as the initial request, entry point or customer plan. Turn count and tools used are outcomes of the variant; slicing by them can compare different tasks in each arm. Report them as outcomes instead.

Can I sample Signal analyses to reduce cost?

Yes. Use the same Signal and sampling policy across arms, then check actual coverage. Laminar applies sampling per user, as described in the Signals quickstart.

For multi-turn tasks, measure fully analyzed session coverage rather than assuming it equals the configured trace sampling rate. If 25% of complete tasks are analyzed, reaching a given analyzed-task count takes roughly four times the incoming traffic. The query above then reports spend per observed pass, not a sampling-adjusted success cost.

Is a canary rollout an A/B test?

A canary primarily limits exposure while checking safety. It supports an A/B comparison when you also specify assignment, outcomes and an inference plan. For prompt or tool canaries, setting a release lets Laminar’s agent versions attribute traces to the release that produced them. Keep variant metadata too.

Do I need an experimentation platform for one test?

You can implement a one-off test yourself, but you still need exposure records, assignment checks and a prespecified analysis. The SQL API provides access to the measurement data. A platform becomes useful when experiments overlap or you need managed exclusions and sequential statistics.