Education › Evals & Harness › Stage 4: Safety, sandboxes & reliability

Tracing and debugging agents

Traces and spans for every step, replay, cost and latency accounting, and error analysis.

Advanced ~40 min read Module 15 of 20

When an agent fails, the question is always the same: what did it see, and what did it decide at each step? Without a trace, you are left guessing from the final answer. Observability for agents means recording every model call and tool call as a structured trace, with the inputs, outputs, tokens, latency and errors of each step, so you can replay a run, find where it went wrong, and aggregate behaviour across thousands of runs. This lesson covers trace structure, OpenTelemetry's generative AI conventions, what to record and redact, a debugging workflow, and the metrics worth charting.

After this module you can
  • Structure agent runs as traces with spans for model and tool calls
  • Instrument a harness with OpenTelemetry using generative AI attributes
  • Decide what to record, what to redact and how long to keep it
  • Debug a failed run step by step from its trace
  • Chart the aggregate metrics that reveal harness problems

Traces, spans and runs

A trace is one agent run. Inside it, each model call and each tool call is a span with a start time, duration, attributes and status. Spans nest: a sub-agent's work appears under the step that delegated to it. With this structure you can see the whole run as a timeline, open any step to read the exact messages the model received, and compare runs side by side.

SpanKey attributes
agent run (root)task ID, user or session ID (hashed), harness version, outcome
model callmodel, input and output tokens, latency, stop reason, tool calls requested
tool calltool name, arguments, result size, duration, error, permission decision
sub-agentbrief, nested spans, returned summary

Instrumenting with OpenTelemetry

OpenTelemetry defines semantic conventions for generative AI (attribute names prefixed gen_ai.), so traces from different harnesses and libraries can be read by the same backends. Open-source tools such as Langfuse and Arize Phoenix, and general tracing backends such as Jaeger or Grafana Tempo, can receive them. The conventions are still evolving, so pin the version you follow.

Spans around model and tool calls
python
from opentelemetry import trace

tracer = trace.get_tracer("my-harness")


def traced_model_call(messages, tools, model: str):
    with tracer.start_as_current_span(f"chat {model}") as span:
        span.set_attribute("gen_ai.operation.name", "chat")
        span.set_attribute("gen_ai.request.model", model)
        reply = call_llm(messages, tools=tools)
        span.set_attribute("gen_ai.usage.input_tokens", reply.usage.input_tokens)
        span.set_attribute("gen_ai.usage.output_tokens", reply.usage.output_tokens)
        span.set_attribute("harness.tool_calls", len(reply.tool_calls))
        return reply


def traced_tool_call(name: str, args: dict, run):
    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)
        try:
            result = run(**args)
            span.set_attribute("harness.result_chars", len(result))
            return result
        except Exception as e:
            span.record_exception(e)
            span.set_status(trace.Status(trace.StatusCode.ERROR))
            raise
spansOTLPmetricsalertsHarnessrun, chat, tool spansOTel SDKgen_ai attributesCollectorredact, sampleTrace backendJaeger, PhoenixDashboardsby harness versionEngineerreplay a run
The harness emits OpenTelemetry spans for every model and tool call; a collector redacts and samples them before a backend stores traces for replay, dashboards and alerts.

Instrument in one place. If every model call goes through a single client function and every tool call through a single dispatcher, two wrappers trace the whole harness, and nothing new can slip through untraced. Export through an OpenTelemetry Collector, which can batch, sample and apply redaction rules before data leaves your network, so you can switch backends without touching the harness code.

What to record and what to redact

  • Record full prompts and responses in development and evals, where replay is essential.
  • In production, record content only where you have a lawful basis and a retention limit; otherwise record metadata (sizes, tokens, tool names, outcomes) and sample content with consent.
  • Redact secrets, credentials and personal data before export, at the harness, not later in the backend.
  • Hash user identifiers so runs can be grouped without exposing identity.
  • Record the harness version, prompt hash and model with every trace, so behaviour changes can be tied to releases.

A debugging workflow

  1. Start at the outcome: what was wrong with the final state or answer?
  2. Find the first step where the run diverged from what a competent human would do.
  3. Read exactly what the model received at that step: was the needed information present, visible and unambiguous?
  4. Classify the cause: missing context, misleading tool result, bad tool choice, bad arguments, policy denial, budget hit, or a genuinely wrong decision with good inputs.
  5. Fix the harness layer responsible (tool, context, prompt, policy), add the run as an eval case, and re-run.

Most agent failures turn out to be harness failures: a truncated result cut off the important line, an error message gave no guidance, or the needed file was never offered. Only the trace shows that.

Aggregate metrics

Across many traces, chart the signals that reveal harness health: success rate by task type, steps and tokens per task (median and p90), cost per successful task, tool error rate and invalid-argument rate per tool, permission denials and approvals per task, loop detections, budget exhaustions, and latency per step. Break them down by harness version so a release that doubles steps per task is caught the same day.

Hands-on practice

Trace and debug an agent

  1. Run a tracing backend locally (for example Jaeger or Phoenix in Docker).
  2. Instrument your agent loop with spans for runs, model calls and tool calls using gen_ai attributes.
  3. Add redaction for a fake secret pattern before export and verify it never reaches the backend.
  4. Run ten benchmark tasks and open a failed trace; walk the debugging workflow to the first divergence.
  5. Classify the cause, fix the responsible layer and add the case to your eval set.
  6. Build a small chart of steps per task and tool error rate by harness version.
Cheat sheet

Tracing and debugging agents — at a glance

Main things to focus on

  • Trace = run; spans = model calls and tool calls, nested.
  • Use OpenTelemetry gen_ai attributes; pin the convention version.
  • Record version, prompt hash and model on every trace.
  • Redact at the harness; hash user IDs; limit retention.
  • Debug from the first divergent step; most failures are harness failures.
  • Chart steps, tokens, cost, tool errors and denials by version.

Span attributes

gen_ai.operation.namechat, execute_tool
gen_ai.request.modelModel used
gen_ai.usage.input_tokens / output_tokensTokens
gen_ai.tool.nameTool called
span.record_exception(e)Errors

Backends

Langfuse, Arize PhoenixLLM-focused, open source
Jaeger, Grafana TempoGeneral tracing
OTel CollectorRoute, redact, sample

Debug causes

missing contextInfo not offered
misleading resultTruncation, vague errors
bad tool or argumentsTool design
policy denial / budgetHarness limits

Metrics

steps, tokens per task (p50, p90)Efficiency
cost per successful taskEconomics
tool error rate per toolTool quality
denials, loops, budget hitsHarness health

Common pitfalls

  • Logging only the final answer.
  • Exporting raw prompts with secrets or personal data.
  • Traces without harness version or prompt hash.
  • Blaming the model before reading the step where it diverged.
  • Metrics averaged over all versions, hiding a bad release.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →