Instrumenting AI Agents for Real: Tokens, Cost, Tool Calls and Decisions That Get Judged Later
What the Claude, OpenAI and Gemini SDKs actually report, what OpenTelemetry standardises and what it doesn't, and the exact code and queries we use for every AI agent metric: Claude calls and retries, cache-aware tokens, cost from a price table, runs and stop reasons, tool hand-offs and loops, and decision quality from random audits that arrive late.
Key takeaways
- The three big APIs disagree on what 'input tokens' means. Anthropic's response.usage.input_tokens excludes cache reads and writes; OpenAI's input_tokens and Gemini's promptTokenCount include cached tokens. Normalise to four counts per call (full-price input, cache read, cache write, output) before you price anything.
- Record tokens, not dollars. Price them at query time from a price table, because prices have tiers (cache writes at 1.25x, cache reads at a tenth or less, long prompts priced higher, batch at half), and a price change should not need a deploy.
- The Claude SDK retries 429 and 5xx twice by default, honouring retry-after. Count failures after retries from the call, and the 429s behind them from HTTP client spans, or you will either miss rate limiting or page on noise.
- Derive run and tool-call counts from spans in the OpenTelemetry Collector before you sample traces. Sampling first makes every rate wrong.
- Whether an automatic decision was right is only known when a person checks it. Record decisions when they happen and verdicts when they arrive, and estimate the wrong rate from a random audit sample, with the sample size next to it. Watch the share decided alone as the early signal.
An earlier version of this benchmark cheated. Each metric came from the same line of code that decided what happened: cost was tokens times a number typed into the script, and a decision was right or wrong the moment it was made. Real agents get none of that. So we rebuilt the benchmark to send exactly what a real service can know at the moment it records something, and nothing more.
The setup
Four agents, each its own service, each calling Claude with tools and then asking a small decision model to choose an action:
| Agent | Work | Model | Tools |
|---|---|---|---|
| booking-agent | Chat bookings | claude-haiku-5-5 | messaging, ERP |
| triage-agent | Support case triage | claude-haiku-5-5 | CRM |
| invoice-agent | Invoice matching | claude-sonnet-5-5 | OCR, ERP |
| secops-agent | Security alert triage | claude-sonnet-5-5 | SIEM, EDR |
If the decision model's top option is at least 5/6 likely, the agent acts alone; otherwise a person decides. One run produces this trace:
POST /webhooks/booking SERVER (HTTP server instrumentation)
└─ invoke_agent booking-agent INTERNAL (ours)
├─ anthropic.messages.create CLIENT (Claude SDK)
│ └─ POST CLIENT (httpx instrumentation, one per attempt)
├─ execute_tool erp.create_order INTERNAL (ours)
│ └─ POST CLIENT (httpx, the vendor API)
├─ anthropic.messages.create …
└─ predict decision-model INTERNAL (ours)Everything goes over OTLP to an OpenTelemetry Collector, then to Prometheus-compatible metrics, a trace store, a log store, and a copy of every span as a row in ClickHouse.
What is standard, and what is ours
Before any code, the vocabulary. OpenTelemetry's GenAI semantic conventions cover model calls and the basic agent and tool spans. They are still marked as in development, so names can change; pin the versions you use.
| Name | Kind | Standard? |
|---|---|---|
gen_ai.client.operation.duration | histogram, seconds | yes |
gen_ai.client.token.usage (gen_ai.token.type = input/output) | histogram, tokens | yes |
gen_ai.operation.name = chat / execute_tool / invoke_agent | attribute | yes |
gen_ai.provider.name, gen_ai.request.model, gen_ai.response.model, gen_ai.response.finish_reasons, gen_ai.tool.name, gen_ai.tool.call.id, gen_ai.agent.name, error.type | attributes | yes |
gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.usage.cache_read.input_tokens, gen_ai.usage.cache_write.input_tokens | span attributes | yes |
http.client.request.duration, http.request.resend_count | HTTP metric and attribute | yes, stable |
anthropic.messages.create span and anthropic.request.id | span name, attribute | the Claude SDK's own |
llm.usage.cache_read.input_tokens, llm.usage.cache_write.input_tokens | counters | ours: there is no standard cache metric |
llm.price.usd_per_million_tokens | gauge | ours |
agent.decisions, agent.decision.confidence, agent.decision.verdicts, agent.review_queue.* | metrics | ours: nothing standard covers decisions |
Our rule: use the standard name wherever one exists, and keep our own names few, prefixed, and documented next to the code that records them.
1. Claude calls: what the SDK gives you
The official SDKs emit OpenTelemetry spans themselves (in beta at the time of writing). Register a tracer provider before the first call and every client.messages.create() produces an anthropic.messages.create span:
from anthropic import Anthropic
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)
client = Anthropic() # max_retries=2 by defaultThe span carries gen_ai.provider.name="anthropic", the model, gen_ai.usage.* token counts, anthropic.request.id (the request-id header, which is what Anthropic support will ask you for), and error.type on failure. Prompts and responses are left out unless you turn content mode on.
The SDK gives you spans, not metrics. For rates, percentiles and alerting you need metrics too. We record the two standard GenAI metrics ourselves, in one wrapper around the call:
import time
import anthropic
from opentelemetry import metrics
meter = metrics.get_meter("agents")
DURATION = meter.create_histogram("gen_ai.client.operation.duration", unit="s")
TOKENS = meter.create_histogram("gen_ai.client.token.usage", unit="{token}")
CACHE_READ = meter.create_counter("llm.usage.cache_read.input_tokens", unit="{token}")
CACHE_WRITE = meter.create_counter("llm.usage.cache_write.input_tokens", unit="{token}")
def create(**kwargs):
attrs = {"gen_ai.operation.name": "chat", "gen_ai.provider.name": "anthropic",
"gen_ai.request.model": kwargs["model"], "server.address": "api.anthropic.com"}
start = time.monotonic()
try:
msg = client.messages.create(**kwargs)
except anthropic.APIStatusError as e: # after the SDK's own retries
DURATION.record(time.monotonic() - start, {**attrs, "error.type": e.type})
raise
except anthropic.APIConnectionError:
DURATION.record(time.monotonic() - start, {**attrs, "error.type": "connection_error"})
raise
u = msg.usage
read = u.cache_read_input_tokens or 0
write = u.cache_creation_input_tokens or 0
attrs["gen_ai.response.model"] = msg.model
DURATION.record(time.monotonic() - start, attrs)
# usage.input_tokens excludes the cache; the convention (and the SDK's span) include it.
TOKENS.record(u.input_tokens + read + write, {**attrs, "gen_ai.token.type": "input"})
TOKENS.record(u.output_tokens, {**attrs, "gen_ai.token.type": "output"})
CACHE_READ.add(read, {"gen_ai.request.model": kwargs["model"]})
CACHE_WRITE.add(write, {"gen_ai.request.model": kwargs["model"]})
return msge.type is the API's error type string: rate_limit_error (429), overloaded_error (529), api_error (500), invalid_request_error (400). Using it as error.type keeps the label small and stable.
Retries: two numbers, not one
The SDK retries 408, 409, 429 and 5xx responses and connection errors twice, waiting retry-after when the API sends it. So the duration above includes the retries, and an error is recorded only when all three attempts failed. That is the number to alert on, but it hides rate limiting that the retries absorbed. To see every attempt, add the httpx instrumentation, which records the stable HTTP client metric with the status code and marks retries with http.request.resend_count:
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
HTTPXClientInstrumentor().instrument()# Claude calls failing after retries
sum by (service_name, error_type) (rate(gen_ai_client_operation_duration_seconds_count{error_type!=""}[5m]))
/ ignoring(error_type) group_left sum by (service_name) (rate(gen_ai_client_operation_duration_seconds_count[5m]))
# Every attempt to the API, by status: 429s here with no failures above were absorbed by retries
sum by (http_response_status_code) (rate(http_client_request_duration_seconds_count{server_address="api.anthropic.com"}[5m]))In our rate-limit test, 40% of first attempts got 429. Because each retry waited its retry-after of 2 to 20 seconds, p95 call latency more than doubled long before many calls actually failed. The attempts chart showed it first.
Streaming
With client.messages.stream(...), input token counts arrive in the message_start event and the cumulative output count in the final message_delta. stream.get_final_message() returns the message with the complete usage, so the wrapper works unchanged. If you care about time to first token, record it yourself at the first content event.
OpenAI and Gemini
The same wrapper works with the field mapping changed. The trap is that "input" means different things:
| Anthropic Messages | OpenAI Responses | Gemini generateContent | |
|---|---|---|---|
| Input tokens field | usage.input_tokens | usage.input_tokens | usageMetadata.promptTokenCount |
| Includes cached tokens? | No | Yes | Yes |
| Cache read | cache_read_input_tokens | input_tokens_details.cached_tokens | cachedContentTokenCount |
| Cache write | cache_creation_input_tokens | not reported (no write charge) | not per call |
| Output | output_tokens (thinking included) | output_tokens (reasoning included) | candidatesTokenCount, plus thoughtsTokenCount reported separately |
| Ran out of output | stop_reason="max_tokens" | status="incomplete", incomplete_details.reason="max_output_tokens" | finishReason="MAX_TOKENS" |
(OpenAI's older Chat Completions API calls them prompt_tokens, completion_tokens, prompt_tokens_details.cached_tokens and completion_tokens_details.reasoning_tokens, and reports finish_reason="length".) Get this wrong and either cached tokens are counted twice, or Gemini's thinking tokens, which are billed as output, disappear from your cost.
2. Tokens and the prompt cache
The standard histogram splits tokens into input and output only. That is not enough to price a call, because cached input is priced very differently from fresh input. That is why we keep the two cache counters next to it, and every call can be broken into four classes:
full-price input = input − cache_read − cache_writeThe ratio that matters operationally is the cache hit ratio:
sum by (service_name) (rate(llm_usage_cache_read_input_tokens_total[10m]))
/ sum by (service_name) (rate(gen_ai_client_token_usage_sum{gen_ai_token_type="input"}[10m]))Our agents use automatic prompt caching: the system prompt and tool definitions (2,000 to 4,000 tokens) are read from the cache on almost every call, and each turn's new content is written to it. A healthy agent reads 70 to 90% of its input tokens from the cache. In one failure we injected, a prompt change rendered the current time into the system prompt. Every call then wrote the whole prefix to the cache at 1.25 times the input price and read nothing back. There were no errors, and cost per run went up several times. The hit ratio panel showed it immediately.
3. Cost
Record tokens, never dollars. Dollars computed in the application are frozen at the price you shipped with, cannot be recomputed when you find a mistake, and differ from the bill in ways you cannot trace. Keep prices as data.
Claude's list prices for the two models we use, per million tokens (check the current pricing page before copying):
| Model | Input | Output | Cache read | Cache write (5 min) |
|---|---|---|---|---|
claude-haiku-5-5 | $0.10 | $0.50 | $0.01 | $0.125 |
claude-sonnet-5-5 | $2.00 | $10.00 | $0.10 | $2.50 |
A one-hour cache write costs twice the input price instead of 1.25 times. Haiku 5.5's price is for prompts up to 100K tokens and higher beyond. The Batch API is half price. Fast mode on Opus 5.5 costs double, and usage.speed tells you which one you got. A price table keyed only by model is an approximation; how much it matters depends on which of these you use.
We publish the table as a gauge from a small job that reads a reviewed config file:
llm_price_usd_per_million_tokens{gen_ai_request_model="claude-sonnet-5-5", llm_token_class="cache_read"} 0.10and join it at query time. Spend per hour, by agent:
sum by (service_name) (
( sum by (service_name, gen_ai_request_model) (rate(gen_ai_client_token_usage_sum{gen_ai_token_type="input"}[5m]))
- sum by (service_name, gen_ai_request_model) (rate(llm_usage_cache_read_input_tokens_total[5m]))
- sum by (service_name, gen_ai_request_model) (rate(llm_usage_cache_write_input_tokens_total[5m]))
) * on (gen_ai_request_model) group_left max by (gen_ai_request_model) (llm_price_usd_per_million_tokens{llm_token_class="input"})
+ sum by (service_name, gen_ai_request_model) (rate(llm_usage_cache_write_input_tokens_total[5m]))
* on (gen_ai_request_model) group_left max by (gen_ai_request_model) (llm_price_usd_per_million_tokens{llm_token_class="cache_write"})
+ sum by (service_name, gen_ai_request_model) (rate(llm_usage_cache_read_input_tokens_total[5m]))
* on (gen_ai_request_model) group_left max by (gen_ai_request_model) (llm_price_usd_per_million_tokens{llm_token_class="cache_read"})
+ sum by (service_name, gen_ai_request_model) (rate(gen_ai_client_token_usage_sum{gen_ai_token_type="output"}[5m]))
* on (gen_ai_request_model) group_left max by (gen_ai_request_model) (llm_price_usd_per_million_tokens{llm_token_class="output"})
) / 1e6 * 3600It is long, but it is the whole cost model in one place. If a model has no price, the join drops it. That is better than pricing it at zero, but it should also raise an alert.
Per-run cost comes from spans, not metrics. Metrics cannot tell you which run was expensive. The SDK puts usage on every anthropic.messages.create span, so the most expensive runs of the last hour are a query over the span table, joined to the same prices kept as a small table:
SELECT TraceId AS trace, any(ServiceName) AS agent, count() AS claude_calls,
round(sum(
(toFloat64OrZero(SpanAttributes['gen_ai.usage.input_tokens'])
- toFloat64OrZero(SpanAttributes['gen_ai.usage.cache_read.input_tokens'])
- toFloat64OrZero(SpanAttributes['gen_ai.usage.cache_write.input_tokens'])) * p.input
+ toFloat64OrZero(SpanAttributes['gen_ai.usage.cache_read.input_tokens']) * p.cache_read
+ toFloat64OrZero(SpanAttributes['gen_ai.usage.cache_write.input_tokens']) * p.cache_write
+ toFloat64OrZero(SpanAttributes['gen_ai.usage.output_tokens']) * p.output) / 1e6, 4) AS usd
FROM otel_traces AS s
JOIN llm_prices AS p ON p.model = s.SpanAttributes['gen_ai.request.model']
WHERE SpanName = 'anthropic.messages.create' AND Timestamp > now() - INTERVAL 1 HOUR
GROUP BY TraceId ORDER BY usd DESC LIMIT 20Note that the span's gen_ai.usage.input_tokens already includes the cache, unlike the API response, so the same subtraction applies.
Reconcile daily. Spans are best effort, and the SDK's exported spans are explicitly not a complete record of usage. Once a day, compare your total with the provider's own usage and cost report (Anthropic's Usage and Cost Analytics API, or the equivalent billing export) and alert when they drift apart by more than a few percent. Usually the difference is a model missing from the table, or a client that is not instrumented.
4. Runs and how they end
A run is the invoke_agent span. It ends with status error and an error.type when it did not finish:
error.type | Meaning |
|---|---|
max_tokens | the final reply hit max_tokens (stop_reason="max_tokens"): cut off mid-answer |
max_turns | our loop guard stopped it |
invalid_arguments | the model kept sending a tool arguments it could not use |
rate_limit_error, overloaded_error, ... | a Claude call failed after retries |
a vendor code, e.g. INVALID_SESSION | a tool's API failed |
Watch stop_reason on every response, not only on errors. max_tokens is an HTTP 200 with a truncated answer. refusal (on newer Claude models) is also a 200 and should be handled before you read content. pause_turn means a server tool paused a long turn and you should continue it. None of these raise an exception.
Count runs and tool calls from spans, in the Collector, before sampling. We keep 20% of traces. If you count runs from the traces you kept, every rate is a fifth of the truth, and a sampler that keeps all errors makes error rates far worse than they are. The Collector's spanmetrics connector turns every span into RED metrics first; only then is the trace sampled:
connectors:
forward/agents: {}
spanmetrics:
histogram: { unit: s }
dimensions:
- name: gen_ai.operation.name
- name: gen_ai.agent.name
- name: gen_ai.tool.name
- name: error.type
processors:
filter/runs_and_tools:
traces:
span:
- 'attributes["gen_ai.operation.name"] != "invoke_agent" and attributes["gen_ai.operation.name"] != "execute_tool"'
probabilistic_sampler/agents: { sampling_percentage: 20 } # by trace ID: kept traces stay whole
service:
pipelines:
traces/agents: { receivers: [otlp], exporters: [forward/agents] }
traces/agents_red: { receivers: [forward/agents], processors: [filter/runs_and_tools], exporters: [spanmetrics] }
traces/agents_kept: { receivers: [forward/agents], processors: [probabilistic_sampler/agents], exporters: [otlp/tempo, clickhouse] }
metrics: { receivers: [otlp, spanmetrics], exporters: [prometheusremotewrite] }# Runs not finishing, by reason
sum by (service_name, error_type) (rate(traces_span_metrics_calls_total{gen_ai_operation_name="invoke_agent", status_code="STATUS_CODE_ERROR"}[5m]))5. Tool calls, bad hand-offs and loops
Each tool the model asks for becomes an execute_tool <name> span with gen_ai.tool.name and gen_ai.tool.call.id (the id of the tool_use block, e.g. toolu_...), so a span can be matched to the exact request in the conversation.
A failing tool and a bad hand-off are different problems. In one case the tool is broken. In the other, the model sent arguments the tool cannot use. Schema validation catches wrong types, and Anthropic's strict: true tool use guarantees the input matches the schema. But schemas check shape, not meaning: "trandate": "next Tuesday" is a valid string. So we check arguments ourselves before calling the tool:
def run_tool(block):
with tracer.start_as_current_span(f"execute_tool {block.name}", attributes={
"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": block.name,
"gen_ai.tool.call.id": block.id}) as span:
problem = check_arguments(block.name, block.input) # schema + meaning: dates, IDs, ranges
if problem:
span.set_attribute("error.type", "invalid_arguments")
span.set_status(Status(StatusCode.ERROR, problem))
return {"type": "tool_result", "tool_use_id": block.id, "is_error": True, "content": problem}
try:
result = TOOLS[block.name](**block.input)
except VendorError as e:
span.set_attribute("error.type", e.code) # e.g. INVALID_SESSION, 131047
span.set_status(Status(StatusCode.ERROR, str(e)))
return {"type": "tool_result", "tool_use_id": block.id, "is_error": True, "content": str(e)}
return {"type": "tool_result", "tool_use_id": block.id, "content": json.dumps(result)}Returning is_error: true lets the model correct itself. We give it two more tries and then end the run with error.type=invalid_arguments. Gemini reports a related failure directly as finishReason="MALFORMED_FUNCTION_CALL".
A bad hand-off has to be judged per tool. In our test, 55% of calls to the order tool were rejected, but that tool is one of three the agent calls, so the agent-wide error rate barely moved.
Loops produce no errors at all. They show up as tool calls per run:
sum by (service_name) (rate(traces_span_metrics_calls_total{gen_ai_operation_name="execute_tool"}[10m]))
/ sum by (service_name) (rate(traces_span_metrics_calls_total{gen_ai_operation_name="invoke_agent"}[10m]))Our invoice agent normally makes about 2.7 tool calls per run. After a bad prompt change it repeated the same purchase-order lookup until the 16-turn guard stopped it. If you want to prove the calls were identical, put a hash of the tool name and arguments on the span as an attribute. Never make it a metric label.
6. Decision confidence
The decision model returns a probability for each option, and we record the top one:
CONFIDENCE = meter.create_histogram("agent.decision.confidence", unit="{probability}")
CONFIDENCE.record(p_top, {"agent.decision.model.version": version})As a heatmap with 0.833 marked, it shows where decisions fall relative to the threshold. A less confident model shifts the mass below the line, and almost everything goes to a person. An overconfident one piles up near 1.0. Confidence alone cannot tell you whether the model is right to be confident. That needs verdicts.
7. Decisions and verdicts
This is where honest instrumentation differs most from a simulator. When a decision is made, you know its route and nothing about its correctness:
DECISIONS = meter.create_counter("agent.decisions", unit="{decision}")
route = "auto" if p_top >= 5 / 6 else "human_review"
DECISIONS.add(1, {"agent.decision.route": route, "agent.decision.model.version": version})
span.set_attributes({"agent.decision.id": decision_id, "agent.decision.confidence": p_top,
"agent.decision.route": route})Decided alone, or handed to a person?
Nothing in OpenTelemetry's conventions says which way a decision went, so it has to be recorded where the routing happens. We record it in three places, each for a different question:
| Signal | Where | Answers |
|---|---|---|
agent.decisions{agent.decision.route="auto" | "human_review"} | counter | What share is handed to people, per agent and model version, now and over time |
agent.decision.route, agent.decision.confidence, agent.decision.id | span attributes on the decision step | Which way this run went, and how sure the model was |
agent.review_queue.depth, agent.review_queue.oldest_age | gauges, from the review tool | Whether people are keeping up with the hand-offs |
# Share handed to a person, per agent
sum by (service_name) (rate(agent_decisions_total{agent_decision_route="human_review"}[5m]))
/ sum by (service_name) (rate(agent_decisions_total[5m]))If an agent framework hands off through a step rather than a threshold, the same question is answered from traces: a tool or step whose job is escalation (escalate_to_human, create_ticket, request_approval) or a run that pauses waiting for approval. Count those spans per agent and you have the hand-off rate without any new metric. What you cannot do is infer it from errors or latency: a hand-off is a successful run.
Correctness arrives later, from people, as a separate event against the same decision ID:
VERDICTS = meter.create_counter("agent.decision.verdicts", unit="{verdict}")
VERDICTS.add(1, {"agent.verdict.source": source, # review | audit | complaint
"agent.verdict.result": result, # upheld | overturned
"agent.decision.route": route,
"agent.decision.model.version": version}) # of the decision, not of todayThe three sources tell you very different things:
- review: a person works a case the agent handed over, and the verdict says whether the model's top option was the one they chose. This is useful for calibration, but it only covers decisions the model was unsure about.
- complaint: a customer reports a wrong automatic decision hours later. It is real, but a biased and incomplete sample: most wrong decisions are never reported.
- audit: a random 3% of automatic decisions go to a reviewer on purpose and are checked 5 to 40 minutes later. This is the only unbiased estimate of how often the agent is wrong when it decides alone.
# Wrong when deciding alone, from audits, over the last hour
sum by (service_name) (increase(agent_decision_verdicts_total{agent_verdict_source="audit", agent_verdict_result="overturned"}[1h]))
/ sum by (service_name) (increase(agent_decision_verdicts_total{agent_verdict_source="audit"}[1h]))Always show the number of audits next to it. At our peak, about 1.8 automatic decisions per second at 3% gives around 190 audits an hour. At an 8% wrong rate, a 95% interval on 190 audits is roughly ±4 points; at night, with 60 audits, it is about ±7. Below 20 audits we do not alert at all.
What the delay means in practice. When the decision model lost its calibration in our test, the first thing that moved was the share decided alone, which jumped by more than 25 points within minutes. Audits could not confirm the damage until 20 to 40 minutes later. So we alert on both: the share decided alone as the early warning, and the audited wrong rate as the confirmation.
8. Work saved per 100 decisions
The score from the first post (+1 for a right decision made alone, −5 for a wrong one, 0 for one handed to a person) can no longer be counted directly, because right and wrong are only known from audits. It becomes an estimate:
work saved per 100 ≈ 100 × (share decided alone) × (1 − 6 × audited wrong rate)It goes below zero when more than 1/6 of automatic decisions are wrong, which is exactly the break-even that set the 0.833 threshold. Agree on the payoffs for each workflow with whoever owns the outcome. If they change, the threshold changes too: break-even is cost_wrong / (cost_wrong + gain_right).
9. The review queue
Read the queue from the review tool itself, every minute, as two gauges: agent.review_queue.depth and agent.review_queue.oldest_age. Alert on the age of the oldest case, not on depth. A queue of 600 that is cleared within six minutes is healthy. A queue of 30 whose oldest case is two days old is not.
How each failure showed up
| Injected failure | Errors? | First signal | When |
|---|---|---|---|
| API rate limiting | some, after retries | 429 attempts, then call p95 | at once |
| Less confident decision model | none | share handed to a person, review queue age | minutes |
| Overconfident decision model | none | share decided alone | minutes |
| ... confirmed by | audited wrong rate, work saved < 0 | 20 to 40 min | |
Replies hitting max_tokens | none (HTTP 200) | runs not finishing, error.type=max_tokens | minutes |
| Agent looping, prompt cache defeated | none | tool calls per run, cache hit ratio, cost per run | minutes |
| Bad tool hand-off | tool-level only | invalid_arguments share for one tool | minutes |
| Expired ERP session | yes | tool errors INVALID_SESSION, runs failing | at once |
Four of the eight raise no error at all, and the most damaging one is only confirmed by people, half an hour later.
Rules that apply to all of it
Standard names first, our names few. Everything about the model call uses the GenAI conventions and the SDK's own spans. We invented names only for cache counters, prices and decisions, and documented each one next to the code that records it.
IDs on spans, never on metric labels. Decision IDs, request IDs, tool call IDs and case IDs go on spans and logs. Metric labels stay small and bounded: agent, model, tool, version, route, error type.
Version everything the agent depends on. Put the decision model version, the prompt version (we use service.version) and the model ID on every span and decision. Most of our failures started at a version change.
Derive metrics before sampling, and sample traces by trace ID. Every count comes from all spans. Traces are for reading one bad run end to end.
Tokens are data, dollars are a query. Prices live in a table, and the total is reconciled with the provider's report every day.
Frequently asked questions
Does Anthropic's usage.input_tokens include cached tokens?
No. In the Messages API response, usage.input_tokens counts only the tokens after the last cache breakpoint; cache_read_input_tokens and cache_creation_input_tokens are reported separately. The Claude SDK's OpenTelemetry spans are different: gen_ai.usage.input_tokens on the anthropic.messages.create span includes cache reads and writes. OpenAI's input_tokens and Gemini's promptTokenCount also include cached tokens.
How do you calculate the cost of an LLM agent run?
For every model call in the run, retries and sub-agents included, take full-price input, cache-read, cache-write and output tokens, multiply each by the model's price for that token class, and add them up. Keep the prices in a table you join at query time, compute per-run cost by summing the usage attributes on the run's spans, and reconcile the daily total with the provider's own usage and cost report.
How do you know if an AI agent's automatic decision was wrong?
Only when someone checks. Send a small random share of automatic decisions (we use 3%) to a reviewer, record each verdict against the decision's ID when it arrives, and compute the wrong rate from those audits alone. Complaints and overturned hand-offs are biased samples. Show how many audits the number rests on, and expect it to lag the decision by however long an audit takes.
How do you detect a bad tool hand-off?
Validate the model's tool arguments before running the tool. A schema check (or Anthropic's strict tool use) guarantees the right types, but not meaning: 'next Tuesday' is a valid string and an invalid date. Reject it with your own check, return an is_error tool_result to the model, and set error.type=invalid_arguments on the execute_tool span so it is counted apart from real tool failures.
How do you detect an AI agent stuck in a loop?
Count tool calls per run (execute_tool spans divided by invoke_agent spans) and compare with the agent's usual level; enforce a max-turns guard and record when it stops a run as error.type=max_turns. A loop shows up as more tokens and cost per run with no errors. If the loop also rewrites the prompt prefix, the prompt cache hit ratio falls at the same time.

Founder & CEO, Rocketgraph
Kaushik founded Rocketgraph to make observability affordable at any scale. He writes about telemetry economics, object-storage architectures, and using AI agents to triage production incidents.