Scaling AI Agents in Production: Latency, Cost, and Failure Troubleshooting in Practice
Once AI agents move beyond a single local session, the questions change: where does latency actually go, which sessions and models drive token spend, and how do you reproduce a failure from days ago? This article uses a typical open-source command-line coding agent framework as a sample to explain a general approach: a four-layer data model (task, turn/step, model and tool calls, session correlation), plugin-based zero-intrusion collection, and aggregation plus drill-down workflows for latency attribution, cost analysis, and four categories of interruptions. It also outlines a practical stack for collection, transport, storage, and dashboards, and closes with the feedback loop that turns observability data into better prompts, tools, and sandbox policies.
1. Introduction: What Changes at Scale
AI agents are now part of everyday development workflows for many teams. Once usage scales up, the questions consumers ask are no longer limited to whether a single result is correct. Three additional concerns come to the fore: whether latency is spent on model inference or tool execution; which sessions and which models token consumption concentrates in; and at which step failures and interruptions occur, and whether the process can be traced back.
All three share one prerequisite: structured, correlatable process data that can be retained over the long term. The observability built into most open-source agent frameworks is scoped to a single machine, a single session, and real time. As soon as you need an overall view of a batch of tasks, a cost distribution over a period, or a reproduction of a failure from a few days ago, you have to fill in a cross-session, cross-machine trace data layer. This article uses a typical class of command-line coding agent framework (referred to below as DSH, meaning “a certain open-source coding agent framework”) as a sample and discusses a general solution to this problem. Baidu AI Cloud likewise emphasizes a combination of “native plugin collection + structured call chains + aggregated analysis” in the agent observability space, which can serve as a practical reference.
2. How This Class of Framework Runs: Why Process Data Is Inherently Fragmented
DSH is an open-source coding agent framework launched from the command line. It lets a large model autonomously complete a full task in a controlled environment: reading and writing files, executing commands, calling external services, and deciding the next action based on the result of each step.
In terms of organization, it uses a microkernel with full plugin architecture: the kernel is only responsible for assembling plugins by profile and managing their lifecycle, while model adapters, tool sets, sandbox policies, session persistence, and the rest are all pluggable plugins. The command line, terminal UI, and headless forms share the same kernel. Observability is mounted at this layer as well — this is the key point, because it means collection does not have to intrude on business code.
The execution model is a ReAct loop: one user task is called a turn, and each round of inference, tool call, and observation of the result within a turn is called a step. The number of loop rounds and which tools are called are decided by the model at runtime, so the execution structure cannot be determined before the run. This directly shapes the design of every troubleshooting method that follows: you cannot infer the call topology from static configuration and can only reconstruct it from the runtime event stream.
2.1 What the Framework Provides Out of the Box
Based on the event stream and on-disk data, this class of framework typically offers three ready-to-use capabilities:
- Session trajectory: an execution record table organized by turn inside the browser, where you can view token usage and latency for an individual record.
- Session event stream persisted to disk: the complete event stream is written to the local session directory as compressed JSONL, with no data loss.
- Tool call lookup: tool call arguments and return results are recorded in the event stream, with full-text search across sessions supported.
2.2 Why Call Relationships Still Need to Be Added on Top of This Data
The built-in data is a time-ordered sequence of session events stored on the local machine. It answers “what happened in this one session,” but it cannot answer three questions that arise at scale:
- No call relationships or latency attribution. The event stream is a flat timeline; parent-child hierarchy has to be inferred manually, so conclusions like “model inference accounts for 62% and tool execution 31%” cannot be derived automatically.
- No cross-machine aggregation. As the number of machines grows, the same batch of tasks is scattered across local directories on multiple machines, so you cannot roll up by task dimension or produce a cost distribution over a time period.
- No long-term retention or alerting. Local files are lost when instances are recycled, the scene of a failure from a few days ago cannot be reproduced, and threshold alerting is out of the question.
3. Target Data Model: A Four-Layer Structure
To solve the problems above, first abstract “one task” into four correlatable layers. This is the foundation for all retrieval and aggregation:
- Task layer: one user request, with a unique identifier running through the whole chain, carrying total latency, total tokens, and final status.
- Turn/step layer: each round of inference within a task, the smallest statistical unit for latency and token attribution.
- Call layer (model call / tool call): model requests and tool executions, recording model name, input and output size, argument digest, return code, and start and end times.
- Session correlation layer: links the task to the local session directory and event stream offsets, so you can drill down from an aggregated view to the original scene in one click.
Illustrative collection mapping logic (pseudocode, expressing the idea only):
def on_event(ev, ctx):if ev.type == "turn_start":ctx.turn = span.start(name="turn", attrs={"task_id": ctx.task_id})elif ev.type == "model_call":span = ctx.turn.child("model_call")span.set_attr("model", ev.model)span.set_attr("in_tokens", ev.usage.prompt_tokens)span.set_attr("out_tokens", ev.usage.completion_tokens)elif ev.type == "tool_call":span = ctx.turn.child("tool_call", attrs={"tool": ev.name})span.set_attr("args_digest", digest(ev.args)) # digest instead of full text, to control volumeelif ev.type == "turn_end":ctx.turn.end()
There are three key points: mount collection as a plugin rather than modifying the kernel; digest or truncate arguments and return values to keep trace data volume under control; and retain the offset pointing to the original event stream, so the data is both aggregatable and traceable.
4. Troubleshooting Methodology for the Three Classes of Problems
4.1 Latency: Do Time Attribution First, Then Optimize
Do not look at total latency first; look at its composition. Use the start and end times from the call layer to merge intervals and split a turn’s total duration into three parts: model inference, tool execution, and framework scheduling. In practice, external commands and network requests inside tool execution are the source of the long tail, while model inference latency grows roughly linearly with input context length. The corresponding actions differ once you have located the cause: for the former, consider parallelization, caching, and timeout settings; for the latter, consider context trimming, history compression, and prompt streamlining.
4.2 Cost: Drill Down by Session, Model, and Turn
Token attribution requires recording both input and output, and accumulating separately per model. The aggregated view should support three slices: by task to spot abnormal consumption (an abnormally high number of turns often means the loop has not converged), by model to see unit price and usage distribution, and by time period to see trends and spikes. The baseline for judging whether the cost is reasonable is the average number of turns per task and the average input size; tasks deviating more than twofold from the baseline should be reviewed first.
4.3 Failures: Distinguish Four Categories of Interruption and Preserve the Scene
- Model side: errors returned, truncation, or non-compliant formatting.
- Tool side: non-zero exit codes, timeouts, missing permissions or dependencies.
- Framework side: turn limit reached, context limit exceeded, plugin exceptions.
- Environment side: insufficient sandbox resources, unreachable network.
The recommended troubleshooting order is bottom-up: first pull the complete call chain by task identifier and locate the first abnormal span, then use session correlation to drill down into the original event stream and inspect the full arguments and output. For alerting, take “task failure rate,” “average number of turns,” and “per-task token percentiles” as core metrics, and combine them with logging and monitoring/alerting capabilities for threshold and spike detection.
5. Implementation Recommendations
Use native plugins for the collection layer, with zero intrusion; use a message queue in the transport layer to smooth peaks and avoid blocking the main flow under high concurrency; use object storage for long-term retention in the storage layer and logging/trace services for retrieval; and use dashboards in the presentation layer to carry aggregation and alerting. One final point to emphasize: the value of observability data lies in closing the loop — first define baselines and thresholds, then use traces to locate issues, and finally feed the conclusions back into prompts, tools, and sandbox policies, forming an iterative process of continuous convergence.
