Skip to main content
Back to Blog

Find the Tool Call That Dominates an Agent Run's OpenTelemetry Trace

A recorded CI-triage agent run, exported as OTLP/JSON and read against the OpenTelemetry GenAI conventions: three execute_tool attempts under one call ID took 5.38 of 8.55 seconds, a job log was billed on every later model call, and invoke_agent repeated the token total. Each fix, and the trace after it.

Shashank Rawlani

Engineering Leader | Builder | Problem Solver | AI Engineer

Published Nov 13, 202611 min read
View AI-ready Markdown
A dim bar spans the top. Below, a short green bar, two long orange bars with dashed cut-off ends, then short and wide green bars. Two orange flows carry one large orange block into two green panels; a small panel on the left holds little.
Quick answer: Export the run as OTLP/JSON and paste it into the Agent Trace Viewer. Read the repeated-tool-calls panel first: execute_tool spans that share a gen_ai.tool.call.id are one model request attempted several times, and their combined duration is usually the latency answer. Then read input tokens per chat span, not per trace, because a large tool result is paid for again on every later model call. Do not add up gen_ai.usage.input_tokens across all spans: agent spans often repeat the total of the calls under them.

A CI-triage agent is asked one question, "Why did checkout.spec.ts fail on run 4812?", and answers in two sentences. The run takes 8.55 seconds. A query that sums gen_ai.usage.input_tokens over every span in the trace reports 108,650 input tokens for those two sentences. Both numbers are real, and only one of them is what the run cost. Neither says why.

The trace does say why, but not in a form a list of spans makes obvious. This walk-through runs that trace through a viewer that reads the OpenTelemetry GenAI conventions, finds one tool call that took 63% of the time and one tool result that made up most of every later prompt, fixes each, and shows the traces after each fix.

The run that produced the trace

The agent is a small loop instrumented by hand with the OpenTelemetry JS SDK 2.11.0, following the GenAI semantic conventions. Its spans were serialized by JsonTraceSerializer from @opentelemetry/otlp-transformer 0.222.0, the serializer the OTLP/HTTP JSON exporter uses. Two parts are controlled so the run can be repeated: the model is a local stub that reports input tokens as characters divided by four, and the CI API is a local server. The timeouts are not simulated. The log endpoint does not answer the first two requests, and AbortSignal.timeout(2500) really aborts them. The third request returns a 107,058-character job log. This export is the viewer's built-in sample, so Load sample reproduces everything below.

One of the eight spans, abridged, shows the encoding rules a hand-written exporter tends to get wrong:

{
  "traceId": "fa3a906b2b2fba3594c67ac7f6da9d0c",
  "spanId": "edcfdf6b91bb2454",
  "parentSpanId": "0565295db1ae8cc3",
  "name": "execute_tool fetch_ci_log",
  "kind": 1,
  "startTimeUnixNano": "1790961790828000000",
  "endTimeUnixNano": "1790961793335665125",
  "attributes": [
    { "key": "gen_ai.operation.name", "value": { "stringValue": "execute_tool" } },
    { "key": "gen_ai.tool.name", "value": { "stringValue": "fetch_ci_log" } },
    { "key": "gen_ai.tool.call.id", "value": { "stringValue": "call_fetch_log_1" } },
    { "key": "error.type", "value": { "stringValue": "timeout" } }
  ],
  "status": { "code": 2, "message": "fetch aborted after 2500 ms (attempt 1)" }
}

The OTLP specification requires trace and span IDs as hex strings, not the base64 the generic protobuf JSON mapping would produce, and enums as integers: kind 1 is INTERNAL and status code 2 is ERROR. Timestamps are 64-bit integers, so they are written as decimal strings; a JSON number cannot hold 1,790,961,793,335,665,125 exactly. The same rule allows readers to accept numbers, and the JS serializer uses that: it writes intValue as a plain JSON number ("intValue": 49). It also falls back to numeric timestamps when BigInt is unavailable. A reader that only accepts the strict form rejects the JS SDK's own output.

Eight spans and one call ID

The viewer's Copy summary output for the sample, timeline section:

invoke_agent ci-triage  +0 ms  8.55 s 54,325 in / 106 out (not added)
  chat stub-chat-1  +0 ms  623 ms 49 in / 29 out
  execute_tool fetch_ci_log  +623 ms  2.51 s  ERROR timeout
  execute_tool fetch_ci_log  +3.13 s  2.50 s  ERROR timeout
  execute_tool fetch_ci_log  +5.63 s  372 ms
  chat stub-chat-1  +6.00 s  1.48 s 27,099 in / 32 out
  execute_tool search_known_flakes  +7.49 s  117 ms
  chat stub-chat-1  +7.60 s  943 ms 27,177 in / 45 out

Repeated tool calls
- fetch_ci_log (gen_ai.tool.call.id call_fetch_log_1): 3 attempts, 2 failed, 5.38 s in total

The totals panel reports 3 model calls covering 3.05 seconds and 4 tool calls covering 5.50 seconds. That count of four is spans, not decisions: the model asked for two tools. Three execute_tool spans carry the same gen_ai.tool.call.id, which the conventions define as the identifier of the tool call the model issued, so they are three attempts at one request. Together they took 5.38 of the 8.55 seconds, and 5.01 of those seconds were the two aborts. The model calls, which a cost review usually looks at first, took 36% of the wall-clock time.

The viewer measures those shares as the union of span intervals, so two tools running in parallel for the same second count as one second. Adding durations would claim more tool time than the trace lasted.

The tokens went into the two calls after the log

The three chat spans report 49, 27,099 and 27,177 input tokens. The first call saw only the system prompt and the question. The second saw the whole job log, because the loop appended the tool result to the history verbatim. The third saw it again, because history only grows. A tool result is paid for once per later model call, so 107 KB fetched once was billed twice, and a longer run bills it again on every further call.

The fix is in the loop, not the model. Playwright prints the failure at the end of the log, so the tail is what the model needs:

// Before: the whole log becomes context for every later call
history.push({ role: "tool", parts: [{ type: "tool_call_response", id: call.id, response: log }] });

// After: the last 20 lines, where the assertion error and its locator are
const tail = log.split("\n").slice(-20).join("\n");
history.push({ role: "tool", parts: [{ type: "tool_call_response", id: call.id, response: tail }] });

Rerun with that change, the same viewer reports 696 and 774 input tokens for the two later calls and 1,519 for the trace, down from 54,325. Latency did not move at all: 8.55 seconds, the same three attempts. Tokens and time had separate causes, which is the reason to read them as separate columns rather than as one "expensive step".

The stub's characters-divided-by-four is not a real tokenizer, so the absolute counts are approximate. The ratio is the finding: a provider's tokenizer changes the numbers, not the fact that the log was most of every later prompt.

Why the naive sum reports 108,650

The invoke_agent span also carries gen_ai.usage.input_tokens: 54,325, the sum of its three model calls. That is allowed. The conventions list gen_ai.usage.input_tokens as Recommended on the invoke-agent span as well as on inference spans, and the reference implementations for openai-agents, LangChain, CrewAI and others in the conventions repository populate it there. What the conventions do not say is whether the agent's value is a sum of the calls beneath it or something else, so a dashboard that sums every span counts the run twice:

jq '[.. | objects | select(.key? == "gen_ai.usage.input_tokens") | .value.intValue] | add' trace.json
# 108650

The viewer counts a span's tokens only when no descendant reports tokens, and compares what it skipped. Here the note reads that the agent span reports "the same as the spans under it. It is not added again." When the agent reports more than its children, as happens when one model call is uninstrumented, the note turns into a warning and the totals keep the children's figure, because a number that cannot be attributed to a call cannot be fixed.

Cached tokens need the same care. gen_ai.usage.cache_read.input_tokens "SHOULD be included in" gen_ai.usage.input_tokens, so the viewer shows it as a subset of input, never added to it.

Making the retry cost less than the timeout

The retry loop that produced the 5.38 seconds:

for (let attempt = 1; ; attempt++) {
  const span = tracer.startSpan(`execute_tool ${call.name}`, { attributes: {
    "gen_ai.operation.name": "execute_tool",
    "gen_ai.tool.name": call.name,
    "gen_ai.tool.call.id": call.id,     // same id on every attempt: this is what groups them
  } }, agentContext);
  try {
    const response = await fetch(url, { signal: AbortSignal.timeout(2500) });
    // ...record the result, end the span, return
  } catch (error) {
    span.setAttribute("error.type", "timeout");
    span.setStatus({ code: SpanStatusCode.ERROR, message: `fetch aborted after 2500 ms (attempt ${attempt})` });
    span.end();
    if (attempt === 3) throw error;
  }
}

Each attempt waits the full 2.5 seconds for an endpoint whose successful answer, in the third span, took 372 ms. Dropping the per-attempt timeout to 800 ms, about twice the observed success, changes the second trace's fetch spans to 807 ms, 803 ms and 371 ms, and the run to 5.15 seconds. Keep the same call ID across attempts so the grouping survives, and put the attempt number in an application attribute such as app.tool.attempt rather than inventing a gen_ai.* name.

The cost is real. One successful response is a sample, not a latency distribution, and a timeout below the endpoint's slow tail turns slow successes into failures and spends a retry on each. Set it from the endpoint's p99 over a week of these spans, and give the loop a total deadline so three attempts can never exceed what the caller will wait for. This tool is a read, so retrying it is harmless. A tool that writes is different: a client-side abort does not stop the server, which is the ambiguous first attempt testing API idempotency, retries and timeouts reproduces. For the schedule itself, testing retry backoff without sleeping covers asserting the delays without waiting for them.

Old and new attribute names in one export

Every gen_ai.* attribute and operation name is still at Development stability, and the conventions moved out of the main semantic-conventions repository into their own in version 1.42.0, in June 2026. Exports from mixed instrumentation versions are normal. The most common leftover is the pair gen_ai.usage.prompt_tokens and completion_tokens, deprecated and "Replaced by gen_ai.usage.input_tokens". A span written by an older library looks like this:

{ "key": "gen_ai.system", "value": { "stringValue": "openai" } },
{ "key": "gen_ai.usage.prompt_tokens", "value": { "intValue": "70" } },
{ "key": "gen_ai.usage.completion_tokens", "value": { "intValue": "7" } }

The viewer does not fold those into input and output. It totals them on their own labelled line, which in the copied summary reads Deprecated prompt_tokens / completion_tokens | 70 / 7 on 1 span, not included above, and reads the provider from gen_ai.system with a note. A span carrying both names uses the current ones and says the deprecated values were ignored. Merging them silently would double-count every call an exporter reports under both names during a migration.

The conventions' own examples need one more allowance. In the published tool-call example, the second chat gpt-4 client span has no gen_ai.operation.name, which is Required. The viewer takes the operation from the first word of the span name only when the span carries other gen_ai.* attributes and the word is a defined operation, and marks it with a question mark.

What the viewer will not infer

A span whose parent is not in the paste becomes a flagged root. That is usually a parent in another service's export, and the viewer cannot tell which. A parent chain that loops is broken at its earliest span. A child that starts before its parent is flagged as clock skew with the gap in milliseconds rather than drawn as if it were nested, because durations across two hosts' clocks are not comparable.

Content is hidden by default. gen_ai.input.messages, gen_ai.output.messages, tool arguments and results, and deprecated gen_ai.prompt values are all Opt-In in the conventions, which say instrumentations "SHOULD NOT capture them by default". When a trace has them, the viewer shows their size until Show prompt and completion content is ticked, and the copied summary and JSON export never include them. The page makes no network request with the trace.

It reads spans only. The gen_ai.client.inference.operation.details event is a log record, exported on the logs signal, so content captured that way is not in a trace export at all. It does not price tokens, and it groups retries only by call ID or by identical tool name and arguments; a model that reissues a failed call with new arguments looks like two separate calls.

Questions about reading agent traces

Which export does the viewer accept? An OTLP/JSON export with resourceSpans, the Collector file exporter's one-request-per-line output, a JSON array of OTLP spans, or the objects Python's ConsoleSpanExporter prints, which use 0x-prefixed IDs and ISO timestamps. Up to 10 MB and 20,000 spans.

The agent span says one number and the viewer says another. Which is right? The viewer's total is the sum of the deepest spans that report tokens. If the agent span reports more, some model call under it is not instrumented, and finding it matters more than choosing a number.

Can it tell a retry from two calls to the same tool? Only through gen_ai.tool.call.id, which is Recommended rather than Required on execute_tool spans. If your instrumentation omits it, add it; nothing else in the span links an attempt to the model request that caused it.

Where does a wrongly-called tool go next? If the trace shows the model calling a tool with arguments the tool rejects, the definition is a likelier cause than the model. The MCP Tool Schema Checker finds the schema mistakes that make agents mis-call tools.

Apply this now

Export one slow or expensive agent run as OTLP/JSON and open it in the viewer. Write down three numbers from it: the time in the largest repeated-tool-call group, the input tokens of the largest chat span, and the trace total with agent spans excluded. If the first is above a third of the trace, set that tool's timeout from its observed successes and add a total deadline. If the second is several times the first call's input, find the tool result that entered the history and cut it to what the model needs. If your instrumentation does not set gen_ai.tool.call.id, add it before the next run, because without it the retries above are invisible.

OpenTelemetry references