LLM Observability: Traces, Logs and Costs
When an AI feature is slow, wrong or expensive, a trace per request shows which model call or tool failed, which prompt version ran and what it cost.
5 min read / Updated / Last checked
- Format
- Guide · Intermediate
- Who it is for
- Founders and the builders they hire
- You leave with
- Instrument model and tool calls with OpenTelemetry spans, attach token cost and prompt version, and find a failed tool call in minutes.
The problem
In April 2026, Datadog reported from its customers' production data that around 5% of AI model requests fail, and that nearly 60% of those failures are caused by capacity limits [1]. Capacity errors are only the most visible failures. A model can also return a wrong answer with a 200 status code, a tool can time out halfway through an agent run, and a prompt change can quietly double the cost of every request.
The founder hears about these as symptoms: a customer says the assistant was wrong, the support lead says it got slow on Tuesday, the invoice from the model provider is higher than planned. Without instrumentation, the team answers with guesses. Ordinary request logs show one line per HTTP call to the app. They do not show that the request made four model calls and two tool calls, that the second tool call timed out, that the model then answered without the order data, or that the request cost eleven times the average because a retry loop resent a long prompt.
LLM observability means recording each of those steps with enough detail to answer three questions afterwards: what failed, why, and what it cost.
How it works
Three kinds of telemetry do different jobs.
- Traces record one request as a tree of spans, each span being one timed step with attributes. An agent run is the root span. Under it sit one span per model call and one per tool call. Traces answer "what happened in this request?"
- Metrics are counts and distributions over time: error rate per tool, latency percentiles, tokens per hour. They answer "is it getting worse?" and drive alerts.
- Logs are individual events with text, such as a validation failure or a retry decision, attached to the trace they belong to.
OpenTelemetry, the open standard for traces, metrics and logs, defines semantic conventions for generative AI, so spans mean the same thing in every backend. They are still marked as in development [2]. A model call span is named after the operation and model, such as chat gpt-6.1-terra, and carries attributes for the provider, requested model, input and output token counts, cached input tokens and finish reasons [2]. A tool call span is named execute_tool plus the tool name, carries the tool name and call ID, and records error.type when the call fails [3]. Tool arguments and results are opt-in [3]. The same goes for prompts and completions, which the conventions mark opt-in because they contain whatever users typed [2].
Two attributes are yours to add. Cost is token counts times the price from the provider's pricing page, stored on the span. Prompt version is the ID of the instructions and tool definitions that ran, so a regression can be tied to the change that caused it.
Defaults differ by tool, so check them. The OpenAI Agents SDK traces by default, sends traces to OpenAI, and includes sensitive data unless configured otherwise [4].
From one agent request to an alert
Fig. 01- Agent run spaninvoke_agent, user and ticket IDs
- Model call spanstokens, cost, prompt version
- Tool call spanstool name, error.type
- ExporterOTLP, content redacted
- Dashboards, alertserrors, latency, cost per task
By the numbers
- of AI model requests fail in production, in Datadog's April 2026 report [1]
- ~5%
- of those failures are caused by capacity limits [1]
- ~60%
- of organizations in LangChain's survey of late 2025 have some observability for their agents [5]
- 89%
- have tracing detailed enough to inspect individual agent steps and tool calls [5]
- 62%
| Question | Where the answer lives |
|---|---|
| Which tool failed, and how? | execute_tool span with gen_ai.tool.name and error.type |
| What did this request cost? | gen_ai.usage.input_tokens and output_tokens times price, summed over the trace |
| Is the prompt cache working? | gen_ai.usage.cache_read.input_tokens on model spans |
| Did the model stop early? | gen_ai.response.finish_reasons |
| Did last week's prompt change make it worse? | Your app.prompt_version attribute, grouped against error rate and eval score |
| Which model actually answered? | gen_ai.request.model against the response model |
The gap between the two LangChain figures is the useful part. Most teams have some observability, but 27 points fewer can inspect individual steps and tool calls [5], and that is the level at which agent failures are diagnosed. Datadog's numbers say what to look for first [1]: if most failures are capacity limits, the first dashboard is error rate by provider and error type, and the first fix is backoff and quota planning rather than prompt work.
The table shows that most answers need no custom code beyond two attributes. Token counts, finish reasons, tool names and error types are already in the conventions. Cost and prompt version are the two fields teams forget and later need most.
Implementation
These helpers wrap model calls and tool calls in spans named the way the conventions describe. They use the OpenTelemetry Python API and work with any backend that accepts OTLP, the OpenTelemetry protocol. The price comes from OpenAI's pricing page as read in November 2026 [6].
"""Spans for model calls and tool calls, named per the OpenTelemetry GenAI conventions."""
from contextlib import contextmanager
from opentelemetry import trace
tracer = trace.get_tracer("support-agent")
PRICE_PER_MTOK = {"gpt-6.1-terra": (1.00, 5.00)} # (input, output) USD, from the pricing page
@contextmanager
def model_span(model: str, prompt_version: str):
with tracer.start_as_current_span(f"chat {model}") as span:
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.provider.name", "openai")
span.set_attribute("gen_ai.request.model", model)
span.set_attribute("app.prompt_version", prompt_version) # your own attribute
yield span
def record_usage(span, model: str, input_tokens: int, output_tokens: int, finish: str):
span.set_attribute("gen_ai.usage.input_tokens", input_tokens)
span.set_attribute("gen_ai.usage.output_tokens", output_tokens)
span.set_attribute("gen_ai.response.finish_reasons", [finish])
price_in, price_out = PRICE_PER_MTOK[model]
cost = (input_tokens * price_in + output_tokens * price_out) / 1_000_000
span.set_attribute("app.cost_usd", round(cost, 6))
@contextmanager
def tool_span(tool_name: str, call_id: str):
with tracer.start_as_current_span(f"execute_tool {tool_name}") as span:
span.set_attribute("gen_ai.operation.name", "execute_tool")
span.set_attribute("gen_ai.tool.name", tool_name)
span.set_attribute("gen_ai.tool.call.id", call_id)
try:
yield span
except Exception as exc:
span.set_attribute("error.type", type(exc).__name__)
span.set_status(trace.StatusCode.ERROR)
raise # arguments and results stay out of the span unless you opt inTo use them, wrap each agent request in a root span named invoke_agent with the user ID and ticket ID as attributes. Inside it, wrap every model call with model_span and record usage from the provider's response, and wrap every tool function with tool_span. Configure the OpenTelemetry SDK once at startup with an OTLP exporter pointed at your tracing backend, and keep prompt and argument capture off until you have a redaction policy.
If you use a framework with built-in tracing, decide where its traces go before launch. For the OpenAI Agents SDK, either keep its default export and switch off sensitive-data capture, or disable it with OPENAI_AGENTS_DISABLE_TRACING=1 and use your own spans [4].
Then build three things on top of the spans:
- A dashboard with error rate per tool and per provider, p95 latency per step, and cost per successful task per day.
- Alerts for a tool error rate above its normal range, and for cost per user per day above a cap you set from your pricing.
- A replay path. Every trace a customer complains about gets copied, with personal data removed, into the eval cases, so the same failure is tested on every future change.
Test it
This test uses the SDK's in-memory exporter to prove a request produces the trace you will need during an incident: correct names, cost, prompt version, the failed tool, and no customer data.
import pytest
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
exporter = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
trace.set_tracer_provider(provider)
from telemetry import model_span, record_usage, tool_span, tracer # noqa: E402
def test_one_ticket_produces_a_trace_you_can_debug():
with tracer.start_as_current_span("invoke_agent support-agent") as run:
run.set_attribute("gen_ai.operation.name", "invoke_agent")
with model_span("gpt-6.1-terra", "triage-v7") as span:
record_usage(span, "gpt-6.1-terra", 1_800, 150, "tool_calls")
with pytest.raises(TimeoutError):
with tool_span("get_order", "call_1"):
raise TimeoutError("orders API timed out")
model, tool, agent = exporter.get_finished_spans()
assert model.name == "chat gpt-6.1-terra"
assert model.attributes["app.cost_usd"] == 0.00255 # 1,800 x $1 + 150 x $5, per million
assert model.attributes["app.prompt_version"] == "triage-v7"
assert tool.name == "execute_tool get_order"
assert tool.attributes["error.type"] == "TimeoutError"
assert model.parent.span_id == tool.parent.span_id == agent.context.span_id
assert "gen_ai.tool.call.arguments" not in tool.attributes # no customer data by defaultExpected: one passing test. Then run a drill in staging:
- Make one tool fail on purpose, for example by pointing the orders API at a closed port.
- Send five requests that need that tool.
- Ask someone who did not cause the failure to find it. Expected: from the dashboard they reach the failing
execute_toolspan, itserror.typeand the user affected in under five minutes. - Check the exported spans for customer messages, email addresses and tool arguments. Expected: none, unless your policy opted in and redacts them.
Decision
Instrument before launch, not after the first incident, because the trace you need is the one from the request that already failed.
- Use OpenTelemetry names and attributes so you can change tracing vendors without re-instrumenting [2][3].
- Add cost and prompt version to every model span on day one.
- Keep prompt, completion and tool-argument capture off until there is a redaction and retention policy.
- Budget about a day to instrument an MVP agent and a day for dashboards and alerts.
- Feed failing traces into How to Test an AI Agent Before Customers Use It, and turn cost per task into pricing with AI Unit Economics and Token Budgets.
Sources
- [1]AI Is Hitting Operational Limits as Companies Rush to Scale, Datadog Report Finds (opens in a new tab)Datadog, April 2026
- [2]Semantic conventions for generative client AI inference spans (opens in a new tab)OpenTelemetry, November 2026
- [3]Semantic conventions for execute tool spans (opens in a new tab)OpenTelemetry, November 2026
- [4]Tracing (opens in a new tab)OpenAI Agents SDK, November 2026
- [5]State of Agent Engineering (opens in a new tab)LangChain, June 2026
- [6]Pricing (opens in a new tab)OpenAI API Docs, November 2026
Technical guidance, not legal or security certification.
Related resources
Need a technical review of an AI-built MVP?
Discuss your build