On this page
- Key takeaways
- Why traditional monitoring isn’t enough
- Anatomy of an agent trace
- The OpenTelemetry GenAI semantic conventions
- Instrumenting an agent loop in Python
- What to capture, and what to protect
- Metrics that matter for agents
- A debugging workflow for production agents
- Choosing an observability stack
- FAQ
- Working with TechnoKeen
Observability for AI agents means you can reconstruct any production run after the fact: every model call, every tool call, the context the model saw, the tokens it spent, and why it stopped. The practical way to get there is distributed tracing, with one trace per agent run and one span per step, following the OpenTelemetry GenAI semantic conventions so your data isn’t locked to a single vendor. Logs and metrics still matter, but traces are what let you debug an agent.
Key takeaways
- Model each agent run as a trace, with child spans for every LLM call, tool execution, retrieval, and sub-agent handoff.
- Use the OpenTelemetry GenAI semantic conventions for span names and attributes so traces work across backends and frameworks.
- Capture prompts and completions deliberately: they are essential for debugging and also the most sensitive data in the system, so redact and control access.
- Track agent-specific signals such as steps per run, tool error rate, stop reasons, and cost per successful task, not just latency and HTTP errors.
- Connect traces to evals: production failures you find in traces should become regression test cases.
Why traditional monitoring isn’t enough
A conventional service is mostly deterministic. If a request fails, the stack trace and logs usually point to the cause. An agent fails differently.
Consider a support agent that gives a customer the wrong refund amount. Every HTTP call returned 200. No exception was thrown. Latency was normal. The failure lives in the content: the model read an outdated policy document from retrieval, or a tool returned the order total in cents and the model treated it as dollars, or a long conversation pushed the key instruction out of the context window.
None of that shows up in a request-level dashboard. To debug it, you need to see:
- What the model was given at each step (system prompt, history, retrieved documents, tool results).
- What it decided to do (tool calls and arguments).
- What came back from each tool.
- How many steps it took and why the loop ended.
That is a trace with rich span attributes. It is the agent equivalent of a stack trace.
Anatomy of an agent trace
A useful trace mirrors the agent’s control flow. Here is a typical structure for a single run of a support agent:
invoke_agent support-agent [trace root, 8.4s]
├── chat <model> [1.2s] reasoning: decide next step
├── execute_tool lookup_order [0.3s] order_id=88123
├── chat <model> [0.9s]
├── execute_tool search_policy_docs [0.6s] query="damaged item refund"
│ └── retrieval vector_store [0.2s] top_k=5
├── chat <model> [1.4s]
├── execute_tool create_ticket [0.4s] queue=refund-approvals
└── chat <model> [1.1s] finish_reason=stop
Each chat span records the model, token usage, and finish reason. Each execute_tool span records the tool name, arguments, result size, and any error. The root span carries run-level data: user or tenant ID, conversation ID, agent version, total cost, and the outcome.
In multi-agent systems, a handoff to another agent becomes a nested invoke_agent span, so you can see which agent made which decision. If agents run in separate services, standard trace context propagation (the W3C traceparent header) stitches the pieces together. Our guide to multi-agent systems covers where those boundaries tend to sit.
The OpenTelemetry GenAI semantic conventions
The OpenTelemetry GenAI semantic conventions define standard span names and attributes for generative AI operations, including model calls, tool execution, and agent invocation. Following them gives you three advantages: traces from different frameworks and providers look the same, you can switch observability backends without re-instrumenting, and auto-instrumentation libraries will produce compatible data.
Commonly used attributes include:
| Attribute | What it records | Example |
|---|---|---|
gen_ai.operation.name |
The kind of operation | chat, execute_tool, invoke_agent |
gen_ai.request.model |
Model requested | your provider’s model ID |
gen_ai.response.finish_reasons |
Why generation stopped | ["stop"], ["tool_calls"] |
gen_ai.usage.input_tokens |
Prompt tokens consumed | 5120 |
gen_ai.usage.output_tokens |
Completion tokens generated | 284 |
gen_ai.tool.name |
Tool being executed | lookup_order |
gen_ai.tool.call.id |
ID linking tool call to result | call_7f3a |
gen_ai.agent.name |
Agent being invoked | support-agent |
gen_ai.conversation.id |
Session or thread identifier | conv_91b2 |
One caution: at the time of writing, much of the GenAI convention set is still marked as in development, and some attribute names have changed between releases. Pin the semantic convention version you instrument against, and check the spec when upgrading instrumentation libraries.
Instrumenting an agent loop in Python
Many frameworks and provider SDKs now ship OpenTelemetry instrumentation, and you should use it where it exists. But you’ll usually still want manual spans around your own agent loop, because that’s where the business context lives. The example below uses the standard OpenTelemetry Python API.
import json
from opentelemetry import trace
from opentelemetry.trace import SpanKind, Status, StatusCode
tracer = trace.get_tracer("support-agent", "1.4.0")
MAX_STEPS = 12
MAX_ATTR_CHARS = 4000 # keep span attributes bounded
def truncate(value: str, limit: int = MAX_ATTR_CHARS) -> str:
return value if len(value) <= limit else value[:limit] + "...[truncated]"
def run_agent(user_message: str, conversation_id: str, tenant_id: str, llm, tools) -> str:
with tracer.start_as_current_span("invoke_agent support-agent", kind=SpanKind.INTERNAL) as root:
root.set_attribute("gen_ai.operation.name", "invoke_agent")
root.set_attribute("gen_ai.agent.name", "support-agent")
root.set_attribute("gen_ai.conversation.id", conversation_id)
root.set_attribute("app.tenant_id", tenant_id)
root.set_attribute("app.agent_version", "2026-06-10.1")
messages = [{"role": "user", "content": user_message}]
total_in, total_out = 0, 0
for step in range(MAX_STEPS):
with tracer.start_as_current_span(f"chat {llm.model}", kind=SpanKind.CLIENT) as span:
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.request.model", llm.model)
span.set_attribute("app.agent_step", step)
response = llm.complete(messages=messages, tools=tools.schemas())
span.set_attribute("gen_ai.usage.input_tokens", response.input_tokens)
span.set_attribute("gen_ai.usage.output_tokens", response.output_tokens)
span.set_attribute("gen_ai.response.finish_reasons", [response.finish_reason])
total_in += response.input_tokens
total_out += response.output_tokens
messages.append(response.as_message())
if not response.tool_calls:
root.set_attribute("app.steps", step + 1)
root.set_attribute("app.stop_reason", "completed")
root.set_attribute("app.total_input_tokens", total_in)
root.set_attribute("app.total_output_tokens", total_out)
return response.text
for call in response.tool_calls:
messages.append(execute_tool(call, tools))
root.set_attribute("app.steps", MAX_STEPS)
root.set_attribute("app.stop_reason", "max_steps_exceeded")
root.set_status(Status(StatusCode.ERROR, "agent hit step limit"))
return "I wasn't able to finish this request. I've passed it to a member of the team."
def execute_tool(call, tools) -> dict:
with tracer.start_as_current_span(f"execute_tool {call.name}", kind=SpanKind.INTERNAL) as span:
span.set_attribute("gen_ai.operation.name", "execute_tool")
span.set_attribute("gen_ai.tool.name", call.name)
span.set_attribute("gen_ai.tool.call.id", call.id)
span.set_attribute("app.tool.args", truncate(json.dumps(call.arguments)))
try:
result = tools.invoke(call.name, call.arguments)
payload = json.dumps(result)
span.set_attribute("app.tool.result_chars", len(payload))
return {"role": "tool", "tool_call_id": call.id, "content": payload}
except Exception as exc:
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
# Return the error to the model so it can recover, rather than crashing the run.
return {"role": "tool", "tool_call_id": call.id, "content": f"Error: {exc}"}
A few details are deliberate:
- Tool errors are recorded on the span and returned to the model. That lets the agent recover, and it lets you measure how often it does.
- Stop reason is an explicit attribute. “Completed”, “max steps exceeded”, “escalated”, and “refused” are very different outcomes that should be queryable.
- Custom attributes use an
app.prefix so they don’t collide with standard conventions. - Arguments are truncated. Unbounded span attributes can break exporters and inflate storage costs.
What to capture, and what to protect
Prompts and completions are the most useful debugging data you have. They are also where personal data, credentials pasted by users, and confidential documents end up. Handle them as a separate decision from basic span metadata.
A practical tiering:
- Always capture: operation type, model, token counts, latency, finish reason, tool names, error types, step counts, agent version, and tenant ID.
- Capture with redaction: tool arguments and results, with known sensitive fields (emails, account numbers, tokens) masked before export.
- Capture under access control: full prompt and completion content, stored in a restricted backend or as span events with a short retention period, and readable only by people who need it.
- Sample deliberately: keep full content for all errored runs and a sample of successful ones, rather than everything.
The OpenTelemetry GenAI instrumentations generally treat message content capture as opt-in for exactly this reason. Make that opt-in an explicit, reviewed choice. The OWASP Top 10 for LLM Applications lists sensitive information disclosure as a core risk, and your telemetry pipeline is part of that attack surface.
Metrics that matter for agents
Traces are for debugging individual runs. Metrics, usually derived from trace attributes, tell you when to start debugging. Beyond standard latency and error rate, track:
- Steps per run (distribution). A rising p95 often means the agent is looping or struggling with a changed tool.
- Stop reason breakdown. Watch the share of runs ending in step limits, escalations, or refusals.
- Tool error rate by tool. A spike usually means an upstream API changed or a tool description no longer matches behavior.
- Tokens and cost per run, and per successful run. Our post on controlling AI agent costs covers how to turn these into budgets.
- Context size per model call. Growing input tokens across steps is a leading indicator of context bloat. See context engineering for remedies.
- Feedback signals. Thumbs-down, escalations requested by users, and human overrides, joined to the trace ID.
Set alerts on changes rather than fixed thresholds where you can. Agent behavior shifts when models, prompts, or upstream data change, and a sudden change is the signal you want.
A debugging workflow for production agents
When a user reports a bad answer, a repeatable workflow saves hours.
- Find the trace. Every user-facing response should carry a trace or run ID that support staff can look up.
- Read the run top-down. Check the stop reason, step count, and which tools were called. Most problems are visible at this level.
- Locate the first wrong step. Find the earliest span where the agent’s input or decision went off track. Later errors are usually consequences.
- Classify the root cause. Common categories: bad retrieval, misleading tool output, ambiguous tool description, missing instruction, context overflow, or a genuine model reasoning error.
- Reproduce offline. Replay the recorded inputs against the same agent version. If you can’t reproduce it, run it several times, since the failure may be intermittent.
- Fix and add a regression case. Turn the trace into an eval case so the fix stays fixed. Our guide to evaluating AI agents shows how to structure those cases.
Step 4 matters more than it looks. Teams often respond to every failure by editing the system prompt. In many cases the real fix is in a tool: a clearer error message, a better description, or a result format the model can’t misread. Our post on tool design for AI agents goes deeper on this.
Choosing an observability stack
You have three broad options, and they aren’t mutually exclusive.
| Option | Strengths | Trade-offs |
|---|---|---|
| General APM with OpenTelemetry support | One place for agent and service traces; existing alerting and on-call | Weaker views for long prompts, token analysis, and eval workflows |
| LLM-specific observability platforms | Purpose-built trace views, prompt diffing, eval integration, cost dashboards | Another vendor; check OpenTelemetry compatibility and data residency |
| Self-hosted open-source tooling | Full control of sensitive prompt data | You operate it; feature depth varies |
Whatever you choose, instrument with OpenTelemetry at the source. That keeps the backend a deployment decision rather than a rewrite.
FAQ
What is the difference between logging and tracing for AI agents?
Logs are individual events, while a trace links every step of a run into one tree with timing and parent-child relationships. For agents, the order and causality of steps is what you need to debug, so traces are the primary tool. Logs remain useful for events outside the run, such as deployment changes.
Should I store full prompts and responses in my traces?
Store them for debugging, but treat them as sensitive data. Redact known sensitive fields, restrict who can read raw content, set short retention, and consider keeping full content only for errored runs and a sample of successful ones.
Do I need a specialized LLM observability tool?
Not necessarily. If you instrument with OpenTelemetry GenAI conventions, a general APM backend can store and query agent traces. Specialized tools add better prompt views, cost analysis, and eval integration, which many teams find worth it once agents carry real traffic.
How do I trace agents that call other agents?
Wrap each agent invocation in its own invoke_agent span and propagate trace context across service boundaries using standard W3C trace headers. Remote agents then appear as nested spans in the same trace. The A2A protocol runs over HTTP, so standard propagation applies.
Working with TechnoKeen
TechnoKeen instruments every agent we build with OpenTelemetry tracing, cost tracking, and alerting from day one, and we run production agents for clients under that model. If you’re struggling to debug an agent in production, talk to our team or see how we approach agent operations.
- #observability
- #OpenTelemetry
- #tracing
- #AI agents in production
TechnoKeen Engineering
TechnoKeen is an enterprise agentic AI company. Our engineers design, deploy, and govern AI agents for organizations in regulated and complex industries, and share what we learn in the field.
About TechnoKeen →