AI Agent Observability Architecture in Practice: Plugin-Based Collection and Call Tree Reconstruction
This article explains how to build an observability system for AI Agent frameworks using non-intrusive plugins, event-stream collection, and post hoc call tree reconstruction. It covers lifecycle hooks, event schemas, session-level aggregation, latency and token metrics, batching, idempotent writes, and the engineering trade-offs required to answer where Agent tasks are slow, expensive, or failing.
AI Agent Observability Architecture in Practice: Plugin-Based Collection and Call Tree Reconstruction
1. Why Agents Need Observability at Scale
When debugging a single Agent task, manually reviewing logs is often sufficient. But once Agents become part of everyday development workflows and task volume grows rapidly, operating them becomes much like operating a microservice system. Teams repeatedly need answers to three questions:
Where is the time going? A task took two minutes to complete—but was the time spent on model inference or tool execution? Did time to first token (TTFT) increase the perceived latency? Which iteration in the ReAct loop caused the delay? Without segmented timing data, these questions can only be answered through guesswork.
Where is the money going? As token costs increase, which sessions and models account for most of the usage? Is the cache hit rate quietly declining? Is the ratio between input and output tokens healthy? These questions require quantitative metrics aggregated by session and by execution step.
Where did it fail? When a task fails, is the problem in the model or in a tool? How many retries occurred? At which step was execution interrupted? Can a failure from several days ago still be reconstructed in full?
Reviewing conversation records is not enough to answer these questions. What is needed is a way to reconstruct every task as a call tree with parent-child relationships and time intervals, while allowing the data to be aggregated across sessions and machines and retained over time. This is the goal of the architecture discussed in this article.
2. Understand the Observed System: Architecture Determines Data Shape
Many coding Agent frameworks are designed to let a large language model autonomously complete end-to-end tasks in a controlled environment. The Agent may read and write files, execute commands, and call external services, choosing each next action based on the result of the previous one. These frameworks typically have three architectural characteristics that directly affect observability design.
Characteristic 1: A microkernel with a fully plugin-based architecture. The kernel contains no business capabilities. It loads plugins according to configuration and manages their lifecycle. Model adapters, tool collections, sandbox policies, and session persistence are all replaceable. Web, terminal, and headless interaction modes can share the same kernel.
This means that observability can also be implemented as a plugin at the same layer, without modifying the framework core. This is the architectural foundation for non-intrusive collection.
Characteristic 2: A ReAct execution model with an unknown runtime structure. A user task can be treated as a turn, while each “reason → call a tool → observe the result” cycle within that turn is a step. The execution path cannot be predicted in advance. A task may finish in one iteration or continue for more than ten. A single step may trigger a subtask or invoke multiple tools in parallel.
Therefore, the observability system cannot rely on a fixed template. It must record an event stream and reconstruct the structure afterward.
Characteristic 3: Session persistence and context rolling. Long-running tasks may truncate historical context, meaning that the logs reviewed afterward may not match what the model actually saw at the time. To explain the model’s decision-making context, the observability system must retain both the original events and context snapshots.
3. Overall Design: Separation of Responsibilities Across Three Layers
The observability solution can be divided into three layers:
- Collection layer: Injected into the framework as a plugin, this layer listens for kernel lifecycle events, serializes them, and sends them in batches.
- Reconstruction layer: This layer receives the event stream, aggregates events by session, reconstructs a five-level call tree, and calculates metrics such as duration and token usage.
- Storage and query layer: This layer provides long-term retention, cross-session search, metric aggregation, and failure investigation.
The three layers are decoupled through a well-defined schema. The collection layer is responsible only for faithfully recording events, while the reconstruction layer is responsible only for rebuilding structure. Neither needs to block the other.
4. Non-Intrusive Collection: Designing the Event Plugin
4.1 Selecting Hook Points
The plugin does not modify business code. Instead, it subscribes to lifecycle events exposed by the framework kernel. Typical hook points include:
- Turn start and end
- The beginning of each step’s reasoning phase
- Tool invocation start and completion
- Observation result delivery
- Model request dispatch and response arrival, including time to first token
- Tool execution errors and retries
- Session persistence and context truncation
Each event carries a unified envelope:
{"trace_id": "session-uuid","turn_id": "turn-3","seq": 42,"ts": 1730000000123,"type": "tool.call.start","payload": { "tool": "file_edit", "args_digest": "..." }}
seq is a monotonically increasing sequence number within a session. It is used to reorder events when they arrive out of order. args_digest stores a parameter summary rather than the full arguments, balancing readability with sensitive-data protection.
4.2 Key Trade-Offs for Non-Intrusive Collection
- Read-only behavior: The plugin must never modify event content or the execution path, ensuring that observability does not change runtime behavior.
- Asynchronous side path: After an event is written to an in-memory queue, the plugin returns immediately. The impact on the main workflow should remain at the microsecond level.
- Graceful degradation: If the queue is full or transmission fails, events are dropped and the loss is counted. It is preferable to lose telemetry than to slow down or break the task itself.
5. From Event Streams to a Five-Level Call Tree
The reconstruction layer groups events by trace_id and rebuilds the following hierarchy:
Session(会话)└─ Turn(用户任务)└─ Step(一轮 ReAct)├─ LLM Call(模型调用,含 TTFT、Token 用量)└─ Tool Call(工具执行,含耗时、重试、错误码)
The core of reconstruction is interval pairing. start and end events are paired by type and sequence number to produce nodes with defined time intervals. Out-of-order events are sorted by seq first.
Once pairing is complete, the system can derive key metrics:
- Total turn duration: Durations are decomposed from the upper levels down through the tree, directly showing where time is being spent.
- Token usage and cache status: Token consumption and cache-hit markers at each level can be aggregated to show where costs are coming from.
- Failures and retry chains: Exception nodes and their associated retries are propagated upward, preserving the complete failure context and showing where execution broke down.
6. Engineering Trade-Offs in Batch Delivery
Event volume grows linearly with task scale. Sending events one at a time wastes connections and increases latency. In practice, observability systems commonly use direct batch delivery:
- Flush conditions: Flush when the queue reaches
Nevents or whenTmilliseconds have elapsed, balancing throughput and freshness. - Compression and encoding: Compress the batch JSON before transmission. In typical cases, compression can reduce its size by more than 70%.
- Idempotent writes: Use
trace_id + seqas the idempotency key so retries do not create duplicate records. - Backpressure control: When downstream storage is unavailable, apply rate limiting at the collection layer to prevent cascading failures.
The trade-off is clear: second-level freshness is sacrificed in exchange for throughput and stability. For troubleshooting, visibility within minutes is generally sufficient, while link reliability should take priority.
7. Conclusion
The essence of Agent observability is to transform an unpredictable, dynamic execution process into a structured call tree that can be searched, aggregated, and reconstructed later.
The design can be summarized in three principles:
- Use the plugin architecture to enable non-intrusive collection.
- Record execution as an event stream and reconstruct the call tree afterward, because the runtime structure cannot be known in advance.
- Use batch delivery and idempotent writes to balance throughput, freshness, and stability.
Once this system is in place, the three questions—“Where is it slow?”, “Where is it expensive?”, and “Where did it fail?”—can be answered with data instead of intuition. This is an essential step in moving Agents from experimentation into production operations.
