Lab: Evaluation Harness and Tracing

A new version sounds better in a demo and quietly starts canceling orders. Build the thing that notices.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

You will build an evaluation harness that runs fixed cases against a baseline and a candidate agent, checks replies and tool calls, prints the trace for each failure and returns an exit code that blocks a release. Tracing uses OpenTelemetry with spans kept in memory, ready to send to a collector later.

What you will learn: to write behavior cases, record spans, assert on tool use, detect regressions, set release rules and extend to real, variable models.
Prerequisites: Set Up Your Agent Development Lab, Python, and the ideas in Agent Testing: Unit to End-to-End. About 60 to 90 minutes.

Versions used

Run in November 2026 with Python 3.13 and opentelemetry-sdk 1.45.0. The agent under test is scripted, so results repeat exactly. The OpenTelemetry generative AI conventions are still in development, so attribute names may change.

Beginner The system and the cases

Goal

Block any release that breaks a case the current version passes, or fails a critical case.

Casesinput and expectations
Runbaseline and candidate
Tracewhat it really did
Checkreply and tools
Decideallow or block

Create three files in one folder and install the package:

python -m pip install "opentelemetry-sdk==1.45.0"

The agent under test

Save as support_agent.py. Version 2 has a "helpful" change: it treats a complaint about lateness as a request to cancel.

"""The system under test: a tiny support agent with a deliberate regression switch."""
from tracing import tracer

ORDERS = {"A-1": "shipped", "A-2": "processing"}


def tool(name, **args):
    with tracer.start_as_current_span(f"execute_tool {name}") as span:
        span.set_attribute("gen_ai.operation.name", "execute_tool")
        span.set_attribute("gen_ai.tool.name", name)
        if name == "lookup" and args["order"] in ORDERS:
            return ORDERS[args["order"]]
        if name == "cancel" and ORDERS.get(args["order"]) == "processing":
            return "canceled"
        span.set_attribute("error.type", "tool_refused")
        return None


def agent(message, version="v1"):
    """Scripted decisions stand in for the model. v2 is 'more helpful'."""
    with tracer.start_as_current_span("invoke_agent support") as span:
        span.set_attribute("gen_ai.operation.name", "invoke_agent")
        span.set_attribute("gen_ai.agent.name", "support")
        span.set_attribute("app.agent.version", version)    # our own attribute
        words = message.replace("?", "").split()
        order = next((w for w in words if w.startswith("A-")), None)
        if order is None:
            return "Which order number?"
        status = tool("lookup", order=order)
        if status is None:
            return f"I cannot find order {order}."
        wants_cancel = "cancel" in words or (version == "v2" and "late" in words)
        if wants_cancel:
            done = tool("cancel", order=order)
            return f"Order {order} is {done}." if done else \
                f"Order {order} has {status}; I cannot cancel it."
        return f"Order {order} is {status}."

Tracing

Save as tracing.py. A trace is the story of one request, made of spans: timed steps with a parent and attributes.

"""OpenTelemetry set up to keep spans in memory, so tests can inspect them."""
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

memory = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(memory))
tracer = provider.get_tracer("agent-lab")


def tree():
    """Render the recorded spans as an indented outline, parents first."""
    spans = sorted(memory.get_finished_spans(), key=lambda s: s.start_time)
    depth = {}
    for span in spans:
        depth[span.context.span_id] = depth.get(
            span.parent.span_id, -1) + 1 if span.parent else 0
        error = span.attributes.get("error.type")
        yield "  " * depth[span.context.span_id] + span.name + (
            f"  [error.type={error}]" if error else "")
Span or attributeMeaning
invoke_agent supportOne run of the agent
execute_tool lookupOne tool call inside that run
gen_ai.operation.nameThe kind of step
gen_ai.tool.nameWhich tool ran
error.typeWhy a step failed
app.agent.versionThe lab's own attribute for comparing releases

Notice what is not recorded: the customer's message and the reply. The conventions list message content as opt-in because it may be sensitive. Add it only with redaction, access control and a retention period.

Intermediate The harness

Build and run

Save as harness.py and run python harness.py to test version 2.

"""Run every case, check behavior through the trace, compare with the baseline."""
import sys

from support_agent import agent
from tracing import memory, tree

CASES = [  # id, message, text expected in the reply, tools expected, critical?
    ("status", "Where is order A-1?", "shipped", ["lookup"], False),
    ("cancel", "Please cancel A-2", "canceled", ["lookup", "cancel"], False),
    ("too-late", "Please cancel A-1", "cannot cancel", ["lookup", "cancel"], False),
    ("unknown", "Where is A-9?", "cannot find", ["lookup"], False),
    ("no-number", "Where is my parcel?", "Which order", [], False),
    ("complaint", "A-2 is late", "processing", ["lookup"], True),
]


def run(version):
    results = {}
    for name, message, text, tools, critical in CASES:
        memory.clear()
        reply = agent(message, version)
        used = [s.attributes["gen_ai.tool.name"] for s in memory.get_finished_spans()
                if "gen_ai.tool.name" in s.attributes]
        problems = []
        if text not in reply:
            problems.append(f"reply lacks {text!r}")
        if used != tools:
            problems.append(f"tools {used}, expected {tools}")
        results[name] = (problems, critical, list(tree()))
    return results


def main(candidate):
    baseline, new = run("v1"), run(candidate)
    block = False
    for name, (problems, critical, spans) in new.items():
        regressed = problems and not baseline[name][0]
        print(f"{'FAIL' if problems else 'pass'}  {name}"
              + ("  (regression)" if regressed else ""))
        for problem in problems:
            print("        " + problem)
        if problems:
            print("        trace:\n" + "\n".join("          " + s for s in spans))
        block |= bool(problems and (critical or regressed))
    passed = sum(not r[0] for r in new.values())
    print(f"{candidate}: {passed}/{len(new)} passed, baseline v1: "
          f"{sum(not r[0] for r in baseline.values())}/{len(baseline)}")
    print("release:", "BLOCKED" if block else "allowed")
    return 1 if block else 0


if __name__ == "__main__":
    code = main(sys.argv[1] if len(sys.argv) > 1 else "v2")
    print("exit code a pipeline would see:", code)

Output:

pass  status
pass  cancel
pass  too-late
pass  unknown
pass  no-number
FAIL  complaint  (regression)
        reply lacks 'processing'
        tools ['lookup', 'cancel'], expected ['lookup']
        trace:
          invoke_agent support
            execute_tool lookup
            execute_tool cancel
v2: 5/6 passed, baseline v1: 6/6
release: BLOCKED
exit code a pipeline would see: 1

Read the failure

Five cases pass and one fails. The reply check alone would show only that a word was missing. The tool check and trace show something far more serious: the agent canceled an order nobody asked to cancel. The case is marked critical and passes on the baseline, so the release is blocked.

Run python harness.py v1 to see the baseline pass and the decision change to allowed. The script prints the exit code; to make your pipeline fail, change the last lines to sys.exit(main(...)).

Why check behavior, not wording

CheckRobust to rephrasing?Catches wrong actions?
Exact reply matchNoSometimes
Required fact in replyMostlyRarely
Tools and argumentsYesYes
Final state of the systemYesYes, the strongest
Model or human gradingYesDepends on what the grader sees

Break it on purpose

  1. Delete the cancel status check in tool. Which cases notice? If none, you have found a missing case.
  2. Add a case where the message contains an instruction to cancel someone else's order.
  3. Make the lookup raise an exception and decide what the agent should say.
  4. Remove the critical flag from the complaint case and predict the release decision before running.
  5. Check tool arguments, not only names: a cancel of the wrong order must fail.
A gap on purpose

The harness resets the trace between cases but not the order data, which is safe only because the lab tool never changes it. A real tool would, so reset the test environment before every case or the results will depend on order.

Expert Real models and real pipelines

Handle variation

Real models give different results on repeated runs. Run each case several times and report pass counts, not a single pass or fail.

def repeat(case, version, times=20):
    passes = sum(run_one(case, version) for _ in range(times))
    return passes, times

# Release rule, written before seeing results:
#   critical cases: every run must pass
#   other cases: pass rate at least the baseline's, minus an agreed margin

This sketch is not run here; run_one is your single-case function. Twenty runs cannot detect rare failures or small differences, so choose the number from the risk and say how uncertain the result is. See Continuous Evaluation, Statistics and Scorecards.

Grow the case set

SourceExampleCare needed
RequirementsEach supported task and refusalKeep owners and dates
Production failuresA misread order numberRemove personal data
Adversarial testsInjected instructionsRun in isolation
BoundariesLimits, empty and very long inputState the expected behavior
Generated variantsMany phrasingsReview labels before trusting them

Keep a held-back set that nobody tunes against. Store the cases in files under version control. See Golden Datasets, Synthetic Data and Simulation.

Templates to copy

Keep one record per case, in a file under version control. The fields below make a case reviewable by someone who did not write it.

Case template

id: complaint-late-order
owner: support team
source: requirement | production failure | adversarial test
input: "A-2 is late"
starting_state: order A-2 is processing
must: reply states the current status; calls lookup
must_not: calls cancel; invents a delivery date
critical: yes
last_reviewed: 2026-11-28

Release rule template

suite: support-agent, version of cases:
compare: candidate against baseline, same cases, same environment
block if:  any critical case fails
           any case that passed on the baseline now fails
           cost or time per task rises more than ____
override:  named person, written reason, expiry date
report to: ____

Trace review template

Case or request id:
What should have happened:
First span where behavior left the plan:
Input to that step (redacted):
Likely cause: instructions | context | tool | model | data | code
Change made, and the case that now covers it:

Look for the first step that went wrong. Later errors are often only consequences, and fixing them hides the cause.

Metrics from traces

The same spans give you operating measures: tool calls per task, error rate by tool, time per step and, once model spans carry token counts, cost per successful task.

spans = memory.get_finished_spans()
errors = [s for s in spans if "error.type" in s.attributes]
duration_ms = [(s.end_time - s.start_time) / 1e6 for s in spans]

Span times are in nanoseconds. See Task, Tool and Planning Metrics for definitions worth agreeing.

What each measure can mislead you about

MeasureUseful forCan mislead when
Pass rateOverall directionEasy cases outnumber the risky ones
Tool calls per taskSpotting loops and wasteFewer calls because a check was skipped
Tool error rateFinding weak integrationsFailures are returned as normal text
Time per taskUser experienceAn average hides the slowest requests
Cost per successful taskComparing designs"Success" was never verified

The fourth row is why teams often report a median and a high percentile together. The third is a design point: this lab sets error.type on a failed lookup so that failures can be counted instead of read.

Send traces somewhere

Replace the in-memory exporter with an OTLP exporter and a batch processor, and point it at an OpenTelemetry collector or a tracing product that accepts OTLP. Add service name and environment as resource attributes, sample sensibly, and filter sensitive attributes in the collector as a second line of defense. Keep the in-memory exporter for tests. See Agent Tracing and OpenTelemetry.

Put it in a pipeline

Changecode, prompt, model, tool
Fast testsscripted, every commit
Model suitebefore merge or release
Gaterules and report
Small rolloutwatch traces

Save the report with the versions of code, prompt, model, tools and cases. A result you cannot reproduce or explain is hard to act on. See CI/CD, Infrastructure as Code and Safe Releases.

Record your result

# Lab record: evaluation and tracing
Cases (count, critical count):
Baseline and candidate results:
Failure found, and what the trace showed:
Release rule:
New case added after breaking something:
Cost and time per full run:
What the suite still cannot detect:

Add a case, step by step

Suppose a customer writes "Do not cancel A-2". Predict what the agent does before reading on. The code looks for the word "cancel" and finds it, so both versions cancel the order. Add this row to CASES:

("negation", "Do not cancel A-2", "processing", ["lookup"], True),

Run the harness. The baseline fails the new case too, so it is not a regression, but it is critical, and the release stays blocked. That is the right outcome: a suite that only compares with the baseline would let an old, serious fault travel forward forever. Now fix the agent, rerun, and keep the case. This is the working rhythm of evaluation: find a behavior, write it down as a case, see it fail, repair it and never delete the case.

Write expectations people can check

Each case should say what must happen and what must not. "Handles negation well" cannot be checked. "Does not call cancel, replies with the current status" can. When people disagree about an expected result, settle it before testing; an ambiguous case produces arguments instead of evidence.

Which test finds which fault

LayerRun itFindsMisses
Unit tests of toolsEvery commitWrong validation, limits and state changesWhether the agent picks the right tool
Scripted agent testsEvery commitFaults in your loop, permissions and handlingModel behavior
Model evaluation suiteBefore merge and releaseWrong choices and regressionsInputs nobody thought of
Adversarial suiteBefore release and on a scheduleKnown attack patternsNew attack patterns
Production monitoringContinuouslyWhat real users actually triggerHarm before it happens
Illustrative example

A team changes one sentence in a system prompt to make replies friendlier. Every fact check still passes, but the traces show that the agent now calls the refund tool before asking for the order number on some inputs. Only a check on tool order or arguments would catch this before users did.

A report people will read

SectionContent
DecisionAllowed or blocked, in the first line
Critical failuresCase, expected, actual, trace link
RegressionsPassed before, fails now
ImprovementsFailed before, passes now
Cost and speedChange against baseline
VersionsEverything needed to repeat the run

Common mistakes

MistakeBetter practice
Checking only the final textCheck tools, arguments and state
Comparing with nothingRun the baseline on the same cases
Averaging away safety failuresGate critical cases separately
One run per case with a real modelRepeat and report counts
Logging all content by defaultOpt in with redaction and expiry
Editing a case to make it passChange expectations only with review

Lab complete when

  • Version 2 is blocked and version 1 allowed on your machine
  • The negation case exists and passes after your fix
  • At least one check inspects arguments or state
  • Your record says what the suite cannot see

Frequently asked questions

Do I need a commercial evaluation tool?

Not to start. A small harness teaches the ideas. Adopt a tool when dataset management, review queues or dashboards justify it.

Can a model grade the replies?

Yes for qualities that rules cannot capture, after you check its agreement with people. Keep deterministic checks for actions.

How many cases are enough?

Cover each task, refusal and known failure first. Add cases when you learn something, rather than chasing a number.

Should tests call real tools?

Use fakes or a sandbox that can be reset, plus a small set of checks against a real test environment.

References and further reading

Next steps