Home / Insights / AI Agents and Automation
AI Agents and Automation
Observability for AI Agents: Tracing Tool Calls, Cost and Failures in Production
An AI agent that works in a demo can still fail quietly in production: looping on a tool, burning tokens or taking a wrong action that nobody notices for days. This guide explains what to instrument, how to choose tooling and how to turn traces into decisions.
Key takeaways
- Agent observability needs a trace per task, with a span for every model call, tool call, guardrail check and human approval, so one failed run can be replayed end to end.
- Cost is a reliability signal: track tokens and steps per completed task, not just monthly spend, and enforce hard per-task budgets in code.
- Most production failures are not model errors but tool errors, missing data, loops and silent wrong actions, so classify failures by cause and alert on each class.
- Prompts and tool outputs often contain personal data; decide what is captured, redacted and retained before you switch tracing on, not after.
- Traces only pay off when they feed back into evaluation sets, regression tests and a weekly review that changes prompts, tools or guardrails.
On this page
- Why agents need a different kind of observability
- What should you capture for every agent run?
- Framework tracing, OpenTelemetry or a dedicated LLM platform?
- How do you track and control cost per task?
- Which failures should you classify and alert on?
- How do you trace agents without creating a privacy problem?
- Rolling out observability and running a weekly review
- Agent observability launch checklist
- Frequently asked questions
- Sources and methodology
Teams that move an AI agent from pilot to production usually discover the same gap. Classic application monitoring tells you that an API returned 200 in 300 milliseconds. It does not tell you that the agent called the CRM lookup tool six times with slightly different arguments, gave up, and then wrote a confident but wrong summary to the customer record. The request succeeded; the task failed.
This article is for CTOs, engineering leads and operations owners who are responsible for agents that read data, call tools and take actions in live systems. It covers what agent observability actually means, which signals to capture, how to choose between framework tracing, OpenTelemetry and dedicated LLM platforms, how to roll it out without leaking sensitive data, and what a sensible alerting and review routine looks like. It assumes you already have basic logging and metrics for your services; if not, start with our guide to observability with OpenTelemetry.
Why agents need a different kind of observability
A conventional web request follows a path your engineers wrote. An agent chooses its own path at runtime. Anthropic’s engineering guidance on building effective agents draws exactly this line: workflows run LLMs and tools through predefined code paths, while agents let the model dynamically direct its own process and tool use. The same guidance warns that this autonomy brings higher costs and the potential for compounding errors, and recommends stopping conditions such as a maximum number of iterations.
That has three practical consequences for monitoring.
The unit of work is the task, not the request
One user request may produce ten model calls, four tool calls, a retrieval step and an approval. If you only log at the HTTP layer, you see a single slow request. You need a parent record for the whole task with every step nested beneath it, so that you can see what the agent decided and in which order.
Failure is often semantic, not technical
A tool can return valid JSON that is the wrong customer. A model can produce fluent text that ignores a policy. Neither raises an exception. Observability for agents therefore has to include quality signals: evaluation scores, guardrail outcomes, human corrections and escalation reasons.
Cost is variable per task
Because the agent decides how many steps to take, the cost of a task is not fixed. A prompt change that makes the agent slightly less certain can double the average number of tool calls. Without per-task cost tracking you discover this from the monthly invoice.
Action: write down, for each agent, what a successful task looks like in business terms (ticket correctly routed, refund drafted within policy, record updated) before you decide what to instrument.
What should you capture for every agent run?
The most useful structure is a trace per task containing spans for each step. The OpenAI Agents SDK documentation on tracing is a good reference model: a trace represents one end-to-end workflow, and spans record agent runs, LLM generations, function tool calls, guardrails and handoffs, each with timing and a parent link. Even if you use a different framework, that hierarchy is the one to aim for.
Minimum fields per span
| Span type | Capture | Why it matters |
|---|---|---|
| Task (root) | Task ID, agent name and version, prompt version, user or tenant ID (pseudonymised), channel, outcome, total steps, total tokens, total cost estimate | Lets you group, filter and compare runs across releases |
| Model call | Model name, parameters, input and output token counts, latency, finish reason, error | Cost, latency and truncation diagnosis |
| Tool call | Tool name, validated arguments, result status, result size, latency, retries | Most production failures surface here |
| Retrieval | Query, document IDs returned, scores, access filter applied | Explains wrong answers and checks permission scoping |
| Guardrail | Check name, pass or fail, reason | Shows which policies trigger and how often |
| Human step | Approver role, decision, edit distance or correction, wait time | Quality signal and bottleneck signal |
Content: capture deliberately, not by default
Full prompts and outputs are the most valuable debugging data and the most sensitive. The OpenTelemetry project’s introduction to generative AI observability describes the GenAI semantic conventions capturing model parameters, token usage and response metadata in traces, while prompt and response payloads are recorded only when content capture is explicitly enabled. The OpenAI Agents SDK takes the opposite default: its trace_include_sensitive_data setting captures inputs and outputs unless you turn it off. Know which default your stack uses.
Versioning
Record the version of the system prompt, tool definitions and model on every task. When quality drops, the first question is always what changed, and you cannot answer it without versions on the trace.
Action: agree a span schema like the table above with your team and add it to your definition of done for any new agent or tool.
Framework tracing, OpenTelemetry or a dedicated LLM platform?
There are three broad routes, and most teams end up combining two of them.
| Option | Strengths | Limitations | Fits when |
|---|---|---|---|
| Built-in framework tracing (for example the OpenAI Agents SDK, LangGraph with its companion tooling) | Near-zero setup; spans for agent concepts such as handoffs and guardrails out of the box | Tied to one framework; traces may go to the vendor by default; limited correlation with the rest of your system | Early production, a single framework, small team |
| OpenTelemetry with GenAI conventions, exported to your existing backend | Vendor-neutral; agent spans sit next to database, queue and API spans; your retention and access rules apply | Conventions were still in development as of early 2025; more engineering effort; you build quality views yourself | You already run OpenTelemetry and want one place to debug |
| Dedicated LLM observability platform (hosted or self-hosted) | Prompt and trace views, evaluation scoring, datasets, cost dashboards | Another data processor to assess; overlap with existing monitoring; pricing tied to volume | Several agents, a dedicated AI team, heavy evaluation work |
How to decide
- Where can the data legally go? If traces will contain customer data, the destination must pass the same review as any other processor. Self-hosting or exporting into your existing stack is often simpler for regulated clients.
- Who will look at the traces? Engineers debugging incidents want correlation with infrastructure. Product and operations staff reviewing quality want readable conversations and scores.
- How many frameworks will you run? If you expect more than one agent framework or model provider, a neutral format avoids rework.
The OpenAI Agents SDK illustrates the pattern of keeping options open: add_trace_processor() sends spans to an additional destination alongside the default exporter, while set_trace_processors() replaces the defaults entirely, so nothing goes to OpenAI unless you include it. Look for that kind of control in whatever framework you choose.
Action: pick one primary store for traces and one place where quality is reviewed. Avoid sending the same sensitive spans to three tools because each was easy to enable.
How do you track and control cost per task?
Token spend is the most visible agent cost, but the metric that matters is cost per successful task. An agent that is cheap per call but needs three attempts and a human rescue is expensive.
Metrics worth charting
- Input and output tokens per task, by agent version
- Model calls and tool calls per task (median and 95th percentile)
- Estimated cost per task, calculated from token counts and your current price table
- Cost per successful task, dividing by tasks that met the success definition
- Share of tasks that hit a step or budget limit
Budgets belong in code, not dashboards
OWASP’s 2025 Top 10 for LLM applications lists Unbounded Consumption as a distinct risk, including denial-of-wallet attacks that exploit pay-per-use pricing. Its mitigations include rate limiting and user quotas, timeouts and throttling, and monitoring with anomaly detection on resource usage. For agents, translate that into hard limits enforced by the orchestrator:
- Maximum steps per task, after which the agent stops and escalates.
- Maximum tokens or estimated spend per task.
- Per-user and per-tenant quotas per hour or day.
- Timeouts on every tool call, with a defined fallback.
- An alert when cost per task for any agent version exceeds a set multiple of its trailing average.
For example, a 30-person insurance broker running an email triage agent might set a ceiling of eight steps and a small fixed token budget per email, route anything over the limit to a human queue, and review the over-limit emails weekly. Those emails usually reveal a missing tool or an ambiguous instruction rather than a model problem.
Action: before launch, define step and spend limits for each agent and log every time a limit is hit as its own failure class.
Which failures should you classify and alert on?
Generic error rates hide what is going wrong. A simple failure taxonomy, attached to every failed or escalated task, makes traces actionable.
| Failure class | Typical signal in the trace | First response |
|---|---|---|
| Tool error | Non-success status, timeout, schema validation failure | Fix the integration or add retry and fallback |
| Bad tool use | Wrong tool chosen, malformed or repeated arguments | Improve tool names, descriptions and argument constraints |
| Loop or stall | Same tool called repeatedly, step limit reached | Tighten stopping conditions; add a clarification path |
| Missing context | Retrieval returned nothing relevant; agent asked for data it cannot reach | Fix data access or scope the task more narrowly |
| Policy or guardrail block | Guardrail span failed | Check whether the block was correct; tune or keep |
| Silent wrong outcome | Run completed, but a human corrected or reversed it | Add the case to the evaluation set; review prompt |
| Model or provider issue | Rate limit, provider error, truncated output | Backoff, fallback model, capacity planning |
Anthropic’s guidance on tool design is relevant to the second row: it recommends investing as much effort in the agent-computer interface as in a human interface, with clear descriptions, examples and boundaries between similar tools. Traces are how you find which tools need that investment.
Catching silent failures
Silent wrong outcomes are the most damaging and the hardest to see. Three techniques help:
- Human feedback capture: record approvals, edits and reversals as spans on the original trace.
- Sampled review: each week, a domain expert grades a random sample of completed tasks against a short rubric.
- Automated checks: post-run validators that compare the action taken with business rules, such as refund amount within policy or record updated matches the customer in the request.
Our article on evaluating an AI chatbot before users depend on it covers how to build the rubric and test set these reviews rely on.
Action: add a required failure class field to your escalation and incident forms so that every failure is counted in the same taxonomy.
How do you trace agents without creating a privacy problem?
Agent traces can easily become the most sensitive dataset in your organisation: they hold prompts, retrieved documents, tool results and outputs, often for every customer interaction. Treat the trace store as production data.
Controls to put in place before go-live
- Classify fields. Mark which span attributes may contain personal or confidential data.
- Redact at the source. Apply masking in the exporter or processor before data leaves the service. The OpenAI Agents SDK documentation suggests putting redaction inside a custom exporter and dropping any batch that fails redaction, rather than relying on clean-up later.
- Make content capture configurable. Allow full content in staging and for sampled production traces, with metadata-only capture as the default elsewhere.
- Set retention. Keep metadata and metrics longer; expire full content quickly unless it has been promoted into an evaluation set with appropriate approval.
- Restrict access. Role-based access to trace content, with access itself logged.
- Document processors. Any third-party trace platform belongs in your data processing records and client contracts.
NIST’s AI Risk Management Framework organises AI risk work into four functions: Govern, Map, Measure and Manage. Observability is where Measure and Manage become concrete: the traces, metrics and reviews are the evidence that risks identified at design time are being monitored in operation. Clients in healthcare and financial services increasingly ask to see that evidence.
Action: run a short data protection review of your trace pipeline, covering fields, destinations, retention and access, as part of the agent’s launch checklist.
Rolling out observability and running a weekly review
Observability is not finished when the dashboards exist. It pays off when it changes what the team does each week.
A practical rollout sequence
- Week 1: instrument the root task span and model calls with token counts and versions. Ship to staging.
- Week 2: add tool, retrieval and guardrail spans; implement step and budget limits; add redaction.
- Week 3: add human feedback spans, the failure taxonomy and the first dashboards: success rate, cost per successful task, escalation rate and latency.
- Week 4: define alerts and an on-call owner; start the weekly review.
The timeline is illustrative; a single agent with three or four tools can often follow it, while agents with many integrations take longer.
The weekly agent review
Thirty to sixty minutes, with the engineering owner, the product or operations owner and someone who knows the domain. Agenda:
- Trend of success rate, escalation rate and cost per successful task by agent version
- Top failure classes and their counts
- Five to ten traces from the sampled review, especially silent wrong outcomes
- Decisions: which cases join the evaluation set, which tools or prompts change, which limits move
Every prompt or tool change should then run against the evaluation set before release, a discipline we describe in more detail in MLOps and LLMOps and the readiness checklist for LLM features.
At PoliteTech this is how we run agents in production for clients through our AI agent development work: every agent step is written to an action log, quality dashboards and production alerts are in place from launch, regression tests run before and after changes, and cost limits cap model calls and steps per task.
Agent observability launch checklist
Use this before any agent takes actions in a live system.
- Success definition for the task is written in business terms.
- Every task has a root trace with agent, prompt, tool and model versions.
- Model, tool, retrieval, guardrail and human steps each produce spans with status and latency.
- Token counts and estimated cost are recorded per span and rolled up per task.
- Step limits, spend limits, per-user quotas and tool timeouts are enforced in code.
- A failure taxonomy is defined and attached to every failed or escalated task.
- Human approvals, edits and reversals are recorded on the original trace.
- Content capture defaults, redaction, retention and access controls have been reviewed.
- Alerts exist for success-rate drops, cost-per-task spikes, limit hits and tool error spikes, each with a named owner.
- A weekly review is scheduled and feeds an evaluation set used before every release.
If you can tick all ten, you will know within a day, not a month, when an agent starts to drift.
Frequently asked questions
Is our existing APM tool enough to monitor AI agents?
It covers latency, errors and infrastructure, which you still need. It usually does not capture agent decisions, token usage, tool arguments or quality signals. Most teams extend existing tracing with agent-specific spans rather than replacing it.
Should we log full prompts and responses in production?
Only deliberately. Full content is invaluable for debugging but often contains personal data. A common pattern is metadata-only by default, full content for a sampled and access-controlled subset, redaction before export and short retention.
How much overhead does tracing add?
Span export is normally asynchronous and small compared with model latency. The larger costs are storage for full content and the team time to review traces. Sampling and retention rules keep both under control.
What should trigger an alert versus a weekly review item?
Alert on sudden, actionable changes: tool error spikes, success-rate drops, cost-per-task jumps and budget-limit hits. Put gradual quality drift and individual wrong outcomes into the weekly review, where someone can decide what to change.
Can we switch observability vendors later?
Yes, if you plan for it. Emitting spans in a neutral format such as OpenTelemetry, or using framework hooks that let you replace exporters, keeps the instrumentation in your code and the destination a configuration choice.
Sources and methodology
Guidance reflects PoliteTech delivery experience. The external references below informed specific points in this article.
- Anthropic: Building effective agents (December 2024) — accessed 9 November 2026. Workflow versus agent distinction, compounding errors, stopping conditions and tool interface design.
- OpenAI Agents SDK documentation: Tracing — accessed 9 November 2026. Trace and span model, default span types, sensitive data setting, custom processors and redaction in exporters.
- OpenTelemetry blog: OpenTelemetry for Generative AI (December 2024) — accessed 9 November 2026. GenAI semantic conventions, token and metadata capture, opt-in content capture and development status.
- OWASP Top 10 for LLM Applications 2025: LLM10 Unbounded Consumption — accessed 9 November 2026. Denial-of-wallet risk and mitigations such as quotas, timeouts and usage monitoring.
- NIST: AI Risk Management Framework — accessed 9 November 2026. Govern, Map, Measure and Manage functions as a frame for operational monitoring evidence.
Related reading
Continue your research
Can you see what your AI agents are doing in production?
We can review your agent’s tracing, cost controls and failure handling, or build observability in from the first release.
