Make an agent's behaviour visible before releasing it
Agent observability records the complete execution trajectory—state transitions, model decisions, tool calls, observations, retries, approvals, latency, cost, and final outcome—so operators can understand and control a production run. Deployment adds explicit budgets, concurrency and rate limits, release controls, rollback, privacy-aware logging, and service objectives such as cost per successful task.
What You Will Learn
- Read a trace as nested spans for model, tool, handoff, and guardrail work.
- Interpret p50 and p95 latency and cumulative run cost.
- Distinguish observability evidence from evaluation judgments.
- Use budgets, controlled release, rollback, and privacy-aware logging.
Observability records; evaluation judges
A trace groups one complete task. Spans represent its individual operations, such as a model generation, tool call, handoff, approval, or guardrail check, and record timing, status, token use, and safe metadata. Observability supplies this evidence; evaluation applies success, quality, and safety criteria to it.
p50 latency is the median: half of runs are faster and half slower. p95 is a tail measure: 95% of runs are at or below it, while the slowest 5% take longer. Agents often have a much worse p95 because retries and extra tool steps accumulate.
Trace a run from the user request to its final outcome
Assign one trace ID across the task and record privacy-safe spans for model calls, tools, state transitions, retries, and approvals.
Set maximum elapsed time, cost, tokens, model calls, tool calls, and steps before execution; track each budget after every operation.
Measure task success, cost per successful task, step count, tool errors, p50/p95 latency, timeouts, safety events, and human overrides.
Control concurrency and provider rate limits, use smaller models or cached results for suitable steps, and stop or return partial progress when a budget is exhausted.
Release with offline gates, canary or shadow traffic, alerts, rollback, and production SLOs; feed incidents back into evaluation cases.
Instructional figure
One trace, many timed spans
How does a trace reveal where an agent spent time, tokens, and money?
Production metrics for agent systems
Budgets must change runtime behavior
Track time, tokens, money, model calls, tool calls, and steps after every operation. When a budget is nearly exhausted, switch from exploration to synthesis where appropriate. At exhaustion, stop, return a traceable partial result or abstain, and request approval before spending more—never continue silently.
Worked Example: Latency and cost accumulate across a run
One sequential trace contains three model calls and two tools. The measured values belong to these five spans.
- Latency = model 0.9 s + tool 0.4 s + model 1.1 s + tool 0.7 s + model 1.0 s = 4.1 s total.
- Cost = $0.006 + $0.002 + $0.007 + $0.001 + $0.006 = $0.022 total.
- Every additional sequential model or tool span adds to end-to-end latency; retries add another copy of the relevant span cost.
What the result means: Cost per successful task is more useful than cost per call because it includes the complete multi-step run and accounts for failed or retried runs that produced no useful outcome.
Instructional figure
Latency and cost accumulate step by step
Why can a short agent loop become slow and expensive?
Release controls
A Realistic Example: Diagnosing a looping research agent
Traces reveal that the same search was called six times because tool errors were summarized ambiguously. The run exceeded its latency and tool-call budgets without improving the answer. A retry classifier, duplicate-action guard, explicit budget, and release gate prevent recurrence before the corrected version enters a small canary release.
Read the Mechanism in Code
Use the label and note to understand what this block represents before reading each line.
with trace("research_task", task_id=task.id) as run:
for step in bounded_agent(task, max_steps=8, timeout_s=90):
with run.span(step.tool, safe_args=redact(step.args)):
result = execute(step)
budget.consume(tokens=result.tokens, cost=result.cost)
record_metrics(latency=result.latency, cost=result.cost)
if budget.exhausted:
return partial_result_with_trace(run)Hands-On Runnable Python Lab: Calculate Parallel Latency and Token Cost
A 400 ms planning call is followed by two tools starting at 400 ms: A lasts 300 ms and B lasts 500 ms. The final call starts at 900 ms and lasts 200 ms. Token-price fixtures are $1/million input and $3/million output, not current provider prices.
- List start and duration for each span, then compute its end time.
- Take the last completion minus the first start to get 1,100 ms wall-clock time.
- Compare with the 1,400 ms sum of child durations: it overcounts 300 ms of overlap.
- Calculate model cost $0.0029, then add tool cost $0.0010 to obtain $0.0039.
Parallel spans overlap: the slowest dependency controls the join
Each colored bar begins at its actual start time and shows its duration in milliseconds. The final model call waits until both tools finish at 900 ms.
spans = [
("plan", 0, 400),
("tool A", 400, 300),
("tool B", 400, 500),
("final", 900, 200),
]
for name, start, duration in spans:
print(f"{name}: {start} -> {start + duration} ms")
wall = max(start + duration for _, start, duration in spans) - min(start for _, start, _ in spans)
summed = sum(duration for _, _, duration in spans)
print("wall-clock latency:", wall, "ms")
print("sum of child durations:", summed, "ms")
input_tokens, output_tokens = 2000, 300
input_rate, output_rate = 1.0, 3.0 # illustrative USD per million tokens
model_cost = (input_tokens * input_rate + output_tokens * output_rate) / 1_000_000
tool_cost = 0.001
print(f"model cost: USD {model_cost:.4f}")
print(f"tool cost: USD {tool_cost:.4f}")
print(f"request cost: USD {model_cost + tool_cost:.4f}")
plan: 0 -> 400 ms
tool A: 400 -> 700 ms
tool B: 400 -> 900 ms
final: 900 -> 1100 ms
wall-clock latency: 1100 ms
sum of child durations: 1400 ms
model cost: USD 0.0029
tool cost: USD 0.0010
request cost: USD 0.0039What This Run Shows
- Tool A finishes at 700 ms, but the final call waits for tool B until 900 ms.
- The duration sum is useful as total child work, not as end-to-end latency.
- The example cost includes all listed usage; changing the number of retries requires changing both the trace and the usage totals.
Deploy with trace IDs, versioned prompts/tools/models, meaningful alerts and a rollback path. Observe safe task success alongside latency and cost so an optimization cannot silently reduce correctness.
From the Exercise to an Application
Experiment: Increase tool A to 600 ms while tool B stays at 500 ms.
A ends at 1,000 ms and becomes the critical dependency. The final span must start at 1,000 ms, so total latency becomes 1,200 ms. Updating only A’s duration without shifting the dependent final span would produce an inconsistent trace.
Summary / Key Takeaways
- Agent observability records the execution trajectory so operators can inspect model turns, tools, handoffs, guardrails, retries, approvals, latency, tokens, cost, and outcomes.
- Traces group one task while spans describe individual model/tool/agent operations, making bottlenecks and failures easier to locate.
- Multi-step agents accumulate latency and cost across every model and tool step, so budgets must be tracked throughout the run.
- Operational metrics should include task success, p50/p95 latency, cost per successful task, tool errors, retries, timeouts, human overrides, and safety events.
- Privacy-aware logging requires redaction, access controls, and retention limits rather than storing every raw prompt and tool result.
- New versions should pass offline gates and then use controlled release patterns such as shadowing or canaries with rollback plans.
- An agent is not production-ready unless operators can trace, budget, measure, stop, replay, canary, and roll back its behavior.
Verified Further Reading
These primary research papers and current official specifications support the concepts and implementation guidance in this lesson. The explanations, analogies, exercises, and code above remain original teaching material.
OpenTelemetry: Semantic Conventions for Generative AI Spans
Emerging conventions for tracing model, retrieval, memory, and tool operations; content capture requires privacy-aware configuration.
LangGraph: Overview
Current framework documentation for graph-based stateful workflows, persistence, interrupts, memory, and human-in-the-loop control.
OpenAI: A practical guide to building agents
Primary guidance on agent suitability, orchestration, tools, guardrails, and human intervention.