Production-grade guide to agent observability covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Agent observability is the practice of instrumenting, monitoring, and diagnosing the behavior of AI agents across their lifecycle—from deployment to execution, from context management to decision-making. It matters when agents fail silently: when a customer-facing assistant returns a plausible but incorrect response, or when a batch agent processes thousands of records yet fails to update a key metric. Observability enables engineers to answer *why* an agent did what it did, *when* it deviated from expected behavior, and *how* to debug a failure that spans multiple services and execution phases.
To understand agent behavior, engineers must track a single agent invocation from start to finish. This requires distributed tracing, where a unique trace_id propagates across services, capturing each step of an agent’s journey.
Each agent call begins with an HTTP request to a /invoke endpoint. The request includes a trace_id header and a parent_span_id header if the agent is nested within a larger workflow. The agent responds with a trace_id in the HTTP X-Trace-ID header and includes it in its final result JSON.
POST /invoke HTTP/1.1
Host: agents.example.com
Content-Type: application/json
X-Trace-ID: 7a1b2c3d-4e5f-6a7b-8c9d-0e1f2a3b4c5d
X-Parent-Span-ID: 9f8e7d6c-5b4a-3c2d-1e0f-9a8b7c6d5e4f
{
"agent": "customer-support-bot",
"input": {
"user_id": 12345,
"query": "How do I reset my password?"
}
}
The agent logs each major phase using structured logging with timestamp, level, component, trace_id, span_id, and event. Each log entry includes a duration_ms and context object with the agent’s state.
{
"timestamp": "2025-04-05T12:34:56.789Z",
"level": "info",
"component": "agent",
"trace_id": "7a1b2c3d-4e5f-6a7b-8c9d-0e1f2a3b4c5d",
"span_id": "9f8e7d6c-5b4a-3c2d-1e0f-9a8b7c6d5e4f",
"event": "agent.start",
"duration_ms": 12,
"context": {
"agent": "customer-support-bot",
"input": {
"user_id": 12345,
"query": "How do I reset my password?"
}
}
}
When an agent calls a sub-agent or external API, it creates a new span_id and includes the trace_id in the request. This enables cross-service tracing. A service receiving the call extracts trace_id and span_id from headers and logs them. The full trace appears in a trace viewer as a timeline of spans.
trace_id propagation.A common error is omitting X-Trace-ID from the response, causing downstream services to lose the trace context. Another is using trace_id as a query parameter but forgetting to set it in the X-Trace-ID header. When both are present, the agent must reconcile them: use the header as the canonical trace_id, and log a warning if the query parameter differs.
Observability begins with metrics. Agents expose a /metrics endpoint in Prometheus format. Engineers scrape this endpoint regularly and build dashboards in Grafana or similar.
The core metrics include:
agent_execution_count_total{agent="name"}: total invocationsagent_execution_duration_seconds{agent="name"}: distribution of execution timesagent_error_count_total{agent="name"}: failures by error typeagent_context_size_bytes{agent="name"}: average size of input contextA typical metrics response:
# TYPE agent_execution_count_total counter
agent_execution_count_total{agent="customer-support-bot"} 14273
agent_execution_count_total{agent="order-fulfillment-agent"} 8942
# HELP agent_execution_duration_seconds Latency of agent execution
# TYPE agent_execution_duration_seconds histogram
agent_execution_duration_seconds_bucket{agent="customer-support-bot",le="0.1"} 1024
agent_execution_duration_seconds_bucket{agent="customer-support-bot",le="0.5"} 3201
agent_execution_duration_seconds_bucket{agent="customer-support-bot",le="1.0"} 5892
agent_execution_duration_seconds_bucket{agent="customer-support-bot",le="2.0"} 10345
agent_execution_duration_seconds_bucket{agent="customer-support-bot",le="+Inf"} 14273
agent_execution_duration_seconds_sum{agent="customer-support-bot"} 1823.4
agent_execution_duration_seconds_count{agent="customer-support-bot"} 14273
# HELP agent_error_count_total Count of agent errors
# TYPE agent_error_count_total counter
agent_error_count_total{agent="customer-support-bot",error="context-too-large"} 156
agent_error_count_total{agent="customer-support-bot",error="llm-call-failed"} 87
Sub-agents often log their own metrics but forget to expose them at the /metrics endpoint. This leads to a gap: the top agent appears fast, but the sub-agents are the real bottleneck. Engineers must ensure that every agent registers its own metrics, and that a central metrics collector aggregates them.
A second failure: using gauge for execution_count instead of counter. A gauge reports the current value, but a counter tracks the total number of events. When the agent restarts, a gauge resets, while a counter continues. Using gauge leads to undercounting during restarts and rollouts.
When an agent fails, logs are the primary diagnostic tool. Each agent writes structured logs in JSON format, with a consistent schema across all agents.
Each log line includes:
timestamp: ISO 8601 with millisecondslevel: trace, debug, info, warn, error, fatalcomponent: agent, llm, context, planner, executortrace_id, span_id: for linking logs to tracesevent: a string describing the action, e.g., llm.call.start, planner.decision.madeduration_ms: time taken for the eventcontext: key-value pairs describing the state at the timeerror: optional object with message, code, detailsExample of a failed LLM call:
{
"timestamp": "2025-04-05T12:34:56.789Z",
"level": "error",
"component": "llm",
"trace_id": "7a1b2c3d-4e5f-6a7b-8c9d-0e1f2a3b4c5d",
"span_id": "1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d",
"event": "llm.call.failed",
"duration_ms": 2134,
"context": {
"model": "gpt-4-turbo",
"prompt_tokens": 142,
"temperature": 0.7,
"max_tokens": 512
},
"error": {
"message": "OpenAI API returned 429 Too Many Requests",
"code": "rate_limit_exceeded",
"details": {
"retry_after_seconds": 45,
"limit": 1000,
"remaining": 37,
"reset_at": "2025-04-05T12:35:41Z"
}
}
}
error object in logs.A common pattern is to log error as a string but not as a structured object. When the error is only a message, it is hard to extract retry logic or error codes. Engineers must ensure that every error path uses a structured error object, and that the error.code is used to classify failures.
Another subtle issue: context is often duplicated across logs. The agent logs the input context at agent.start, but then the planner logs its own context at planner.start. When an error occurs, the logs show two context objects, and engineers must correlate them. To reduce noise, agents should merge context values into a single object when creating a new span.
Anomalies in agent behavior—such as a sudden spike in execution time, or a surge in context-too-large errors—require alerting and anomaly detection.
Alerts are configured via a declarative alerts.yaml file in the agent’s configuration directory.
alerts:
- name: "agent-execution-latency-spike"
description: "Agent execution time exceeds 90th percentile by 50%"
query: |
rate(agent_execution_duration_seconds{agent="customer-support-bot"}[1h]) > 1.5 * histogram_quantile(0.9, rate(agent_execution_duration_seconds{agent="customer-support-bot"}[1h]))
threshold: 1.5
severity: "warning"
notification:
channel: "slack"
webhook: "https://hooks.slack.com/services/ABC/DEF/GHI"
message: "Agent {{agent}} execution latency spiked above threshold: {{value}}s"
cooldown: 15m
silence: 30m
- name: "context-too-large-errors"
description: "More than 100 errors per hour of context-too-large"
query: |
count_over_time(
agent_error_count_total{agent="customer-support-bot",error="context-too-large"}[1h]
) > 100
threshold: 100
severity: "critical"
notification:
channel: "email"
recipients:
- "[email protected]"
- "[email protected]"
template: "context-too-large-alert.html"
cooldown: 1h
The alerting system evaluates the query every 5 minutes and triggers an alert when the condition is met for three consecutive intervals.
An alert for execution_duration_seconds > 2.0 will trigger when the agent is slow but may miss a gradual degradation. A better approach is to use a percentage-based threshold: duration > 1.2 * median(duration[1d]). This adapts to seasonal changes and avoids false positives during high load.
Another common issue: stale alert definitions. Engineers write an alert, but the alerts.yaml file is not versioned or deployed. When a new agent is rolled out, the alert for context-too-large is missing. Engineers must ensure that the alerts.yaml is part of the agent’s deployment package and is updated with every release.
The agent’s context—the data it uses to make decisions—is central to its behavior. Observability must include tools to inspect and validate context.
Each agent maintains a context.json file in a shared storage (e.g., S3, or a mounted volume). The file is updated during execution and includes:
input: the initial input to the agentsteps: an array of all executed stepsstate: the current state of the agentmetadata: timestamps, execution IDs, and configurationExample context.json:
{
"input": {
"user_id": 12345,
"query": "How do I reset my password?"
},
"steps": [
{
"step_id": "1",
"type": "llm_call",
"model": "gpt-4-turbo",
"prompt": "Explain password reset process for a user...",
"output": "To reset your password, go to login page...",
"duration_ms": 1234,
"context": {
"prompt_tokens": 142,
"completion_tokens": 203
}
},
{
"step_id": "2",
"type": "database_query",
"sql": "SELECT * FROM user_profiles WHERE user_id = ?",
"result_count": 1,
"duration_ms": 342,
"context": {
"fetched": "2025-04-05T12:34:56Z"
}
}
],
"state": {
"current_step": "2",
"status": "completed",
"last_updated": "2025-04-05T12:34:56.789Z"
},
"metadata": {
"execution_id": "e7a1b2c3-d4e5-f6a7-b8c9-d0e1f2a3b4c5",
"agent_version": "v1.3.2"
}
}
Engineers can query the context.json file directly via curl or psql to validate the agent’s reasoning:
curl -H "X-Trace-ID: 7a1b2c3d-4e5f-6a7b-8c9d-0e1f2a3b4c5d" \
https://agents.example.com/context/e7a1b2c3-d4e5-f6a7-b8c9-d0e1f2a3b4c5 \
| jq .
An agent fails mid-execution, but the context.json is written only at the end. This makes debugging difficult. Engineers must ensure that the agent writes context.json after each step, and that it is updated even when an error occurs. A failure during a step should include the updated context at that point.
Another issue: context.json grows unbounded. After many invocations, the file becomes large and slow to load. Engineers must implement a rotation strategy: keep the last N versions of context.json, and archive older versions to long-term storage.
trace_id and span_id headers for all inter-service calls.event, context, and error objects./metrics with counter for total counts.alerts.yaml, using relative thresholds.context.json.context key.Observability is not a feature—it is the foundation of agent reliability. When an agent fails, the answer is not in the code, but in the logs, traces, and metrics. Engineers who invest in observability can answer *what* the agent did, *why* it did it, and *how* to fix it—without ever seeing the agent’s code.
This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy