Observability Architecture for AI Agents: A Practical Guide to Tracing Slow, Costly, and Failing Tasks
Debugging a single agent run is easy; operating a fleet of agents is not. This guide presents a practical observability architecture for AI agent tasks, using an open-source coding agent framework as the reference system. It defines the three core operational questions—where tasks are slow, where they are expensive, and where they fail—and shows how to answer them with a five-layer call tree (Session, Turn, Step, Action, and fine-grained events) built from trace_id, span_id, parent_id, and timing data. You will learn how to collect telemetry without touching business code through a plugin-based, zero-intrusion design, the trade-offs between per-event streaming and batched export, and how to store and query traces, metrics, and logs. The article closes with a step-by-step rollout path from metric definitions to dashboards, alerts, and a failure-analysis feedback loop.
Observability Architecture for AI Agents: A Practical Guide
Introduction: Why Logs Stop Working at Scale
When you debug a single agent task, scanning the conversation transcript by eye is usually enough. But once agents become part of the daily development workflow and concurrent task volume grows, the nature of the problem changes. You are no longer asking “was this one output correct?” You are asking “is this entire batch of tasks healthy?”
Operating an agent cluster is, in essence, similar to operating a microservices system. You will be asked the same three questions again and again: where is it slow, where is it expensive, and where is it wrong? Answering them requires reconstructing every task as a call tree with parent-child relationships and time intervals, and aggregating and retaining that data across sessions and machines over the long term. This article uses an open-source coding agent framework (internally abbreviated as H, with a CLI tool named h) as the observed system and lays out a general, actionable approach.
1. Define the Problem First: Slow, Expensive, Wrong
Where is it slow? A single task takes two minutes—is the time spent in model inference or in tool execution? Is time-to-first-token (TTFT) hurting the perceived latency? In a multi-turn “reason—call tool—observe” loop, which turn becomes the bottleneck?
Where is it expensive? Which sessions and which models concentrate token consumption? Is the cache hit rate dropping? Is the input/output ratio out of balance?
Where is it wrong? Does the failure originate on the model side or the tool side? How many retries were attempted? At which step did the interruption occur? Can a failure from several days ago be fully reconstructed?
Reading transcripts cannot answer these questions. You need call-chain data that is structured, aggregatable, and storable for the long term.
2. Understand the Observed System: Architecture Determines Data Shape
H is an open-source coding agent framework whose goal is to let a model autonomously complete full tasks in a controlled environment: reading and writing files, executing commands, and calling external services, with each step deciding the next based on the previous result. Its architecture has three key characteristics:
- Microkernel plus full plugin architecture. The kernel contains no business capabilities; it only assembles plugins by profile and manages their lifecycle. Model adapters, tool sets, sandbox policies, and session persistence are all plugins, and multiple interaction modes share the same kernel. Observability can therefore also be implemented as a plugin, with no changes to the framework itself.
- ReAct execution model, with structure unknown before runtime. One user task is one turn, and each internal round of “reason → call tool → observe” is one step. The exact number of rounds and which tools get called cannot be determined before execution, which means the call tree must be built dynamically.
- Multiple modes share one kernel. The CLI, the terminal UI, and headless mode share the same execution path, so placing collection points at the kernel layer covers all modes.
3. Overall Design: A Five-Layer Call Tree
Reconstruct runtime events into a five-layer structure:
- L1 Session: a context container spanning turns, carrying long-term cost attribution.
- L2 Turn: the full lifecycle of one user request.
- L3 Step: one round of reasoning and tool calling.
- L4 Action: a concrete action such as a model call, tool execution, or retrieval.
- L5 Fine-grained events: token counts, cache hits, retries, error codes, and so on.
Every node carries trace_id, span_id, parent_id, start/end times, status, and attributes uniformly. Example structure:
{"trace_id": "t-1", "span_id": "s-2", "parent_id": "s-1","name": "step.3.tool.exec", "start": 1710000000000, "end": 1710000002300,"status": "ok", "attrs": {"tool": "shell", "retry": 0}}
With parent-child relationships and time intervals, you can pinpoint where it is slow (which layer takes longest) and where it is wrong (which node has an abnormal status).
4. Zero-Intrusion Collection: The Plugin Mechanism
The core idea is to build observability as a plugin at the same layer as business plugins, subscribing to events through lifecycle hooks exposed by the kernel, without modifying business code. Key points:
- Mount points: register listeners at the create, start, end, and exception callbacks of turn/step/action.
- Context propagation: use the framework’s session context object to pass trace information implicitly, avoiding changes to function signatures at every layer.
- Sampling and switches: support configuring sampling rate and whether to record input/output summaries per profile, with the ability to disable dynamically in production.
- Redaction: summarize or hash file contents and command arguments to keep sensitive information out of trace storage.
Example (pseudocode):
def on_step_start(ctx, step):span = tracer.start("step", parent=ctx.span, attrs={"index": step.index})ctx.span = spandef on_step_end(ctx, step, error=None):ctx.span.finish(status="error" if error else "ok")
5. Engineering Trade-offs of Batched Direct Export
How collected data egresses is a key engineering decision.
- Per-event direct export: best real-time behavior, but under high-frequency events it puts heavy pressure on the network and backend and can cause jitter.
- Batched aggregation: trigger batch sends in memory by count, bytes, or time, with controllable retries and backpressure and high throughput; the cost is second-level latency and a data-loss window if the process crashes.
- Recommendation: call-chain data is not strongly real-time, so prefer batching; error events can go through a separate immediate channel; local disk persistence serves as a fallback, with re-upload after process restart.
Also handle out-of-order and duplicate data: deduplicate idempotently by trace_id + span_id, and rebuild the tree by sorting on start.
6. Storage and Query
- Trace storage: storage oriented toward trace-based retrieval and tree display, with tiered retention (hot/warm/cold).
- Metric aggregation: pre-aggregate latency, tokens, and error rate into time-series metrics to support dashboards and alerting.
- Log correlation: correlate structured logs by trace_id, enabling drill-down from metrics to an individual trace.
7. Implementation Steps
- Define the metric definitions for the three core question categories (TTFT, per-layer latency, token distribution, retry rate, failure-step distribution).
- Integrate collection via a plugin, first validating tree-structure correctness in a staging environment.
- Configure batching and sampling policies, then roll out gradually.
- Build dashboards and alerts, periodically review failure samples, and form an optimization feedback loop.
Conclusion
The essence of agent observability is reconstructing an unknown runtime structure into a queryable call tree. A plugin-based implementation achieves zero intrusion, the five-layer model unifies semantics, and batched direct export balances performance and reliability. Together, these three support day-to-day operations around slow, expensive, and wrong.
