An agent run can finish in twelve seconds, spend more tokens than expected, and still return the wrong answer. A single dashboard number cannot tell you which of those problems occurred. The request may have waited on a retrieval service, retried an inference call, or invoked a tool that succeeded technically but returned stale business data. Meanwhile, the invoice may count cached tokens differently from your monitoring chart. The most useful observability design starts by refusing to collapse these questions into one.
This guide builds a concrete three-layer model: traces explain execution, a usage ledger explains charges, and evaluations explain whether the task succeeded. It then implements an offline Python trace, verifies its parent-child structure, calculates an intentionally hypothetical token charge, and shows how to move the design into production without copying private prompts into telemetry. The accompanying Python example was run locally with OpenTelemetry Python 1.42.1; its model and token usage are fixtures, not a commercial API benchmark. No hosted inference service was contacted.
There is an important 2026 compatibility caveat. The OpenTelemetry GenAI client conventions and agent conventions are labeled Development. Their dedicated repository is the current specification home. This is useful shared vocabulary, not a promise that every framework or backend exports identical stable fields. Pin your SDK and instrumentation releases, record the convention snapshot used for dashboards, and test your own emitted attributes before treating them as contractual.
One request, three different sources of truth
Imagine a customer-support agent that receives a question about an order. It retrieves a policy, asks a model to interpret the situation, and returns a proposed next action. The agent framework reports a successful run. What does that actually mean? It might mean only that the orchestration code did not throw an exception. It does not establish that the correct policy version was retrieved, that the recommendation was permitted, or that every token used by a retry appeared in the same trace.
| Evidence | Question answered | Authoritative record | Common mistake |
|---|---|---|---|
| Trace | Where did time go, and which operation failed? | Span tree plus correlated logs | Assuming a green span means a correct answer |
| Usage ledger | What did the provider report and what price applied? | Provider usage response, price version and billing reconciliation | Summing sampled spans as a complete invoice |
| Evaluation | Did the result satisfy task and safety requirements? | Versioned test cases, acceptance outcomes and human review where needed | Using latency or fluent prose as a quality score |
The three records can share a correlation identifier, but they should not be forced into the same storage policy. A trace backend may sample requests and retain metadata for days. A financial ledger may need an auditable, access-controlled history of every billable request. An evaluation store may preserve only approved test fixtures and judgments. Their retention, privacy, and failure-recovery requirements are different.
The architecture also gives you a debugging order. First ask whether a user request has a trace and whether the span tree contains the expected model and tool operations. Then inspect the provider's usage object for each attempted call, including retries and cache fields. Finally compare the agent's output with the acceptance condition. If one layer is missing, mark it missing rather than substituting a guess from another.
What belongs in an agent span tree?
OpenTelemetry represents an operation as a span with a name, timing, attributes, status, trace identifier and parent context. The agent conventions describe operations such as invoke_agent, invoke_workflow and execute_tool. The client-inference conventions cover model calls such as chat. The span kind matters: an outbound model request is generally CLIENT, while local orchestration and tool logic can be INTERNAL. A remote tool's HTTP client span is separate from the logical tool operation.
A useful parent-child tree for the support example is invoke_workflow support_triage containing execute_tool lookup_policy and chat mock-rule-model. A production agent might instead call the model before the tool, call several tools concurrently, or nest delegated agents. The tree should reflect what actually happened; it should not be rearranged to resemble a tidy marketing diagram. Consult the GenAI span guidance for operation boundaries and retry semantics.
Build an offline trace before touching a provider API
Starting with a real model call makes the first observability experiment needlessly expensive and difficult to reproduce. Instead, the companion Python example creates a deterministic workflow, one local tool span and one mocked inference span. The provider name is explicitly example.mock; the model name mock-rule-model is not a claim about an available commercial model. Usage counts are fixtures. This separation lets you validate the telemetry contract before integrating an SDK that can change its response schema.
Use Python 3.12 or a compatible supported Python release and install the two pinned packages. The tested local environment was Python 3.13 with opentelemetry-api==1.42.1 and opentelemetry-sdk==1.42.1; the repository's CI job uses Python 3.12 and must independently confirm that combination. A virtual environment avoids collisions with application instrumentation.
python3 -m venv .venv
. .venv/bin/activate
python -m pip install opentelemetry-api==1.42.1 opentelemetry-sdk==1.42.1
python examples/otel_agent_trace.py
python -m unittest discover -s examples -p test_otel_agent_trace.py -v
In the fixture, TracerProvider owns the SDK state, SimpleSpanProcessor exports spans synchronously, and InMemorySpanExporter holds them for assertions. This exporter is a test tool, not a production storage system. The tracer is obtained directly from the provider, so the example does not mutate a process-global tracer provider. That matters in notebook sessions, test suites and web services where another library may already have configured OpenTelemetry.
exporter = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer("llmscorebook.otel_agent_trace")
with tracer.start_as_current_span(
"invoke_workflow support_triage",
kind=SpanKind.INTERNAL,
attributes={"gen_ai.operation.name": "invoke_workflow"}
):
with tracer.start_as_current_span(
"execute_tool lookup_policy",
kind=SpanKind.INTERNAL,
attributes={"gen_ai.operation.name": "execute_tool"}
):
pass
# In the full example, a sibling CLIENT span represents a mocked model call.
The official Python instrumentation guide documents start_as_current_span, context management, attributes, events, and status recording. In ordinary synchronous code, the context manager creates the parent-child relationship. In asynchronous code, Python context propagation generally follows task context, but a queue or remote worker is a separate boundary: propagate trace context explicitly and decide whether the resumed job should be a child or a linked operation. Do not invent a single continuous span across an hours-long background job; use durable job IDs, separate processing spans and links where appropriate.
The fixture's verified console output contains three completed spans: execute_tool lookup_policy, chat mock-rule-model and invoke_workflow support_triage. The two child spans have parent contexts; the root does not. It prints a hypothetical charge of 0.00042 USD. The ordering reflects completion, not necessarily start order. This output is from the local offline example, not a screenshot of a production trace backend.
Keep the attributes useful and bounded
Attach the operation name, model identifier, provider discriminator, tool name, non-sensitive call ID, response status and token usage when available. Use stable, low-cardinality values for dimensions that will appear in metrics: model version, route family, tool class and deployment region. Avoid embedding arbitrary user prompts, raw URLs with secrets, email addresses, full file paths or tool arguments in metric labels. A unique request ID is useful in a trace but disastrous as a high-cardinality metric dimension.
There are two separate identifiers worth maintaining. The trace ID connects operations observed by the tracing system. An application-generated job ID connects durable records across restarts, worker leases and retries. The job ID can be stored in a restricted database and referenced in sanitized logs; its exposure in shared telemetry should follow your tenancy and privacy rules. A trace ID is not a substitute for durable checkpoint state or idempotency keys.
For remote calls, use W3C Trace Context through supported HTTP instrumentation rather than manually concatenating identifiers into prompts. The Python documentation describes default propagation behavior. At a trust boundary, accept only the propagation information your security policy allows, and avoid forwarding sensitive baggage across third-party services. If a provider SDK already creates inference spans, do not blindly add a second manual inference span around the same request: duplicated logical operations can make latency and usage appear doubled. Inspect the emitted tree first, then add spans for application logic that the SDK does not see.
Finally, record failures carefully. error.type can distinguish a timeout from an authorization rejection without storing an exception message containing private input. OpenTelemetry supports recording exceptions, but exception messages and stack frames can contain secrets. Redaction and retention decisions must precede exporter configuration, not be added after a telemetry incident.
A trace is not an invoice: build a usage ledger
Token fields are attractive because they seem to turn traces into billing reports. That is a dangerous shortcut. Sampling may omit successful requests; client failures may occur before a usage response arrives; streaming responses may provide final usage only after the last chunk; retries can produce multiple provider charges for one user-facing request. The tracing system tells you what its instrumentation observed. It does not certify that all billable operations were captured.
For each provider attempt, keep a separate restricted usage record with a stable attempt ID, application job ID, provider request ID when returned, requested and actual model names, response timestamp, total input and output usage, cache-read and cache-write components where exposed, request outcome, price-sheet version and currency. Store the raw provider usage object only where privacy and contract requirements permit. Do not put private prompts or unredacted response payloads into this ledger by default. Reconcile aggregate usage and spend with the provider's invoice or billing export rather than trusting local arithmetic as the final charge.
The current client-inference span specification includes gen_ai.usage.input_tokens, gen_ai.usage.output_tokens and cache-read attributes. It treats detailed cached-token counts as subsets of input, not as an extra independent total. The token metrics specification separately describes monotonic usage counters and per-operation histograms; those serve different analytical purposes. It is easy to double-count tokens by adding a cached subset to the total input or by summing histogram observations as though they were invoice line items.
Worked calculation: a cached prefix changes the mix, not the total
Consider a fictional request with 120 input tokens, of which 40 were cache reads, and 30 output tokens. Assume made-up prices of $2 per million fresh input tokens, $0.50 per million cache-read tokens and $8 per million output tokens. These are not actual provider prices; they are round numbers chosen to make the arithmetic inspectable. Assume no cache-write surcharge, batch discount, context surcharge, minimum charge, tax or image/audio billing.
The fresh input count is 120 − 40 = 80. Its charge is 80 × 2 / 1,000,000 = $0.000160. Cached input costs 40 × 0.50 / 1,000,000 = $0.000020. Output costs 30 × 8 / 1,000,000 = $0.000240. The illustrative total is $0.000420. Adding the 40 cached tokens to the original 120 before calculating would incorrectly bill 160 input tokens. Ignoring the 40 cache reads would miss the discount.
The downloadable example implements the calculation with decimal.Decimal rather than floating-point money arithmetic and rejects negative token counts or cached counts larger than total input. The offline tests check the arithmetic, invalid inputs, span structure and absence of prompt-message attributes. The example does not attempt to normalize every provider's usage response: that translation is a separate adapter, because some APIs report cached tokens, reasoning tokens or billable units differently.
There are two levels of cost analysis. An estimate applies a known rate table to observed usage, including the exact effective date, account tier, region, currency and discounts. A reconciled cost compares those estimates with authoritative billing records and explains residual differences. Both are useful, but only the second can support financial controls. If an inference response has no usage object, store usage_unknown rather than silently assigning zero. A zero charge and an unknown charge are materially different operational states.
Metrics, spans and logs have different arithmetic
Use a trace waterfall to find which step waited on a tool or model. Use counters to track aggregate input and output consumption when reliable billable counts are available. Use duration histograms to monitor distributions and outliers. Use structured logs for sanitized operational events that do not need a full trace. If a dashboard reports p95 latency, state whether it measures whole user requests, individual model calls or individual tool operations. Those percentiles cannot be added together to estimate end-to-end p95.
Likewise, a sampled trace set is useful for debugging but may be biased toward errors or slow requests. Multiplying its average token count by the total request count can produce a rough estimate only under documented sampling assumptions; it is not an invoice reconciliation strategy. Keep the durable usage ledger independent of sampling decisions. This separation is especially important when a team deliberately retains every failed trace while sampling successful traffic at a low rate.
Prompt privacy is an architecture decision, not an exporter flag
GenAI observability can accidentally become a second, less protected copy of a company's most sensitive information. A prompt may contain customer records, unreleased code, health details, access tokens, proprietary documents or an internal policy. A tool response can carry the same data even if the user prompt is innocuous. Logging full request and response bodies into a tracing vendor creates a new data-processing and retention surface that may have different access controls from the application database.
The OpenTelemetry GenAI content guidance recommends that instrumentation not capture instructions, inputs or outputs by default, while allowing explicit opt-in. In the offline example, we set operation, model, provider and usage attributes; we deliberately do not set gen_ai.input.messages, gen_ai.output.messages or tool argument bodies. The test suite asserts that these attributes are absent. This is a narrow, verifiable claim about our fixture, not a guarantee that every auto-instrumented library behaves the same way.
Adopt a data classification policy before enabling automatic instrumentation. Decide whether prompt content is forbidden, redacted, sampled for an approved debugging environment, or captured only under a short-lived incident procedure. Review SDK defaults and collector processors; some libraries record HTTP URLs, exception messages, headers or payload fragments through channels unrelated to the GenAI attributes. Scrubbing one named field does not make an entire trace safe. For regulated or multi-tenant workloads, include security and privacy review of exporters, dashboards, backups and third-party subprocessors.
| Data field | Default policy | Reason |
|---|---|---|
| Operation, model, tool class | Allow after validation | Explains execution with low privacy risk |
| Token counts and duration | Allow when source is trustworthy | Supports latency and consumption analysis |
| Raw prompts, completions and tool arguments | Do not collect | High chance of personal or proprietary data |
| Request IDs and tenant references | Scope or pseudonymize | Cross-system correlation can expose identities |
| Exception messages, headers and URLs | Filter and test | Can contain secrets and private parameters |
Be careful with “hash the prompt” as a universal fix. A deterministic hash of a low-entropy string can be vulnerable to guessing, and a stable cross-tenant fingerprint may reveal that two customers used the same sensitive template. If a fingerprint is necessary, define its threat model, salt or keyed hashing strategy, rotation policy and retention window. Often the safest observability design is to store no content-derived identifier at all.
Sampling and cardinality are part of correctness
High-cardinality labels can overwhelm metrics storage. A histogram split by model family and operation can be useful; a histogram split by every request ID is not. Keep request-specific identifiers in traces or restricted logs, not metric dimensions. Budget the number of models, tool types, deployment environments and error classes your dashboards will aggregate. Add a test that detects unexpected attribute growth after framework upgrades.
Head sampling decides near the beginning of a trace and is cheap, but it may miss slow or failed requests. Tail sampling can retain traces based on completed outcomes, at the cost of collector memory, buffering and more complex operations. Neither sampling mode should govern whether provider usage is written to the billing ledger. For critical financial or audit operations, sampling telemetry is not a substitute for durable application event records.
Retries deserve explicit treatment. If a logical inference operation automatically retries, the GenAI span guidance says the logical span should encompass the duration including retries. A developer may also add individual attempt spans for diagnosis, but those should not be mistaken for separate successful user requests. For billing, each provider attempt must be considered according to actual provider charging behavior, including failed or cancelled attempts. Never assume a timeout implies no charge.
Background jobs and streaming complicate the timeline
In an HTTP API that starts a long-running agent job, the request may finish in milliseconds while the job continues for minutes. A trace rooted in the original HTTP request cannot safely be treated as the whole lifecycle if execution resumes in a different process after a restart. Persist a job ID and parent trace context only where appropriate, then create worker execution spans with explicit links or propagated context. Keep job status, retries and idempotency in durable storage. Your trace backend is a diagnostic view, not a job scheduler.
For streaming inference, distinguish total duration from time to first chunk and time between output chunks. A response may stream useful text early and then stall; a single total-duration number hides that experience. The client-inference specification defines streaming metrics, but an application should verify which ones its SDK actually emits. A stream interrupted before final usage arrives must not silently report a fabricated token total. Preserve an explicit incomplete-usage status and reconcile later if the provider offers authoritative usage exports.
From a local exporter to a production OTLP pipeline
The in-memory exporter is intentionally disposable. A production service should usually export telemetry to an OpenTelemetry Collector or another explicitly supported OTLP endpoint, with authentication, network isolation, bounded queues and retention controls. The official Python exporter documentation describes HTTP and gRPC OTLP exporters and provides a local collector configuration. For a Python process, replace the test processor with a batch processor and an exporter that matches the receiver protocol; do not accidentally send OTLP/HTTP to a gRPC port.
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(
endpoint="http://localhost:4318/v1/traces"
))
)
tracer = provider.get_tracer("support-agent")
This is a configuration illustration, not a tested live exporter. Install the matching opentelemetry-exporter-otlp-proto-http==1.42.1 package before using it. The localhost endpoint assumes an OTLP/HTTP receiver exists and is reachable; the code does not start a collector. Production deployments should use appropriate TLS, credentials, secret handling, resource limits and egress policies. When an application shuts down, flush and close the provider according to the SDK lifecycle so buffered spans are not needlessly discarded.
For a small service, start with a single collector pipeline and verify end-to-end traces using a synthetic request that contains no private data. Only then enable it for a subset of real traffic. Inspect a trace in the destination backend: does the model call appear once, does its parent represent the correct workflow, are tool spans distinguishable from HTTP spans, and are sensitive attributes absent? If a collector processor drops data, verify that it is dropping the intended fields rather than silently deleting the model identity or error class needed for debugging.
Four dashboards worth building first
The first dashboard is user-request latency, broken down by route and agent version. Show median and tail latencies, error rate, and the distribution of tool versus inference time. This reveals whether an optimization should target retrieval, inference, orchestration or downstream dependencies. A faster model cannot fix a blocked database connection.
The second is model-call health: requests, retries, provider errors, time to first chunk where available, and usage completeness. This should distinguish model request failures from tool execution failures. A retry can improve user-visible success while increasing cost and tail latency. Display both, or the operational story becomes misleading.
The third is usage reconciliation: ledger totals by provider, model, billing unit, price version and day, alongside the actual provider billing export. Show the share of calls with unknown usage and a reconciliation difference. This dashboard should use the durable ledger rather than sampled trace counts. For a fuller discussion of provider tariff normalization, see LLM Scorebook's workload cost comparison and prompt caching economics guide.
The fourth is accepted task outcomes: pass rate on versioned test cases, human escalation rate, policy-violation rate, and cost per accepted task. A model upgrade that reduces tokens but increases correction work may not be an improvement. Define the denominator carefully: a partially completed task, a refusal, and a task cancelled by the user are different outcomes. Use acceptance tests that reflect the actual business workflow, not only whether the response sounds helpful.
A practical rollout and verification sequence
First, freeze a small representative set of agent tasks, including success, tool failure, retry, cancellation and a long-running worker resume. Record the expected span topology for each. Second, pin the OpenTelemetry SDK and instrumentation package versions and capture the GenAI convention snapshot date. Third, deploy sanitized trace collection with a clear opt-in policy for content. Fourth, add provider usage adapters with unit tests for cached tokens, reasoning tokens, partial responses and missing usage. Fifth, connect the ledger to a versioned price table and reconcile it against real invoices. Sixth, build outcome evaluations that can catch a technically successful but incorrect answer.
Test failure modes deliberately. Kill a worker mid-task; verify that durable job state survives even if a trace is incomplete. Trigger a provider timeout; verify the span records an error class without leaking a secret. Retry a request; verify that trace topology and billing attempts do not double-count a single accepted task. Simulate an empty usage response; verify the ledger marks it unknown. Run a synthetic prompt containing a fake secret; verify that no collector or backend attribute captures it. These tests turn observability from a dashboard project into a reliability control.
When something looks wrong, use this diagnosis order: inspect the user-facing task outcome, inspect the trace topology, inspect the individual provider attempt records, then inspect price normalization and billing reconciliation. A missing span points to instrumentation or sampling. A correct trace with wrong costs points to accounting. A correct trace and correct invoice with a bad answer points to evaluation, retrieval quality or application logic. The separation makes the next engineering action much clearer.
What the example proves—and what it does not
The companion fixture validates local parent-child spans and a precise hypothetical cost calculation using the installed OpenTelemetry Python SDK. It does not prove that a particular hosted model emits these fields, that a production collector is secure, that a provider's bill will match the example, or that an agent's output is correct. Those require integration tests, provider documentation and real acceptance criteria. Treat the GenAI conventions as a useful evolving vocabulary rather than a substitute for engineering verification.
The durable design is simple: trace the work, reconcile the usage, evaluate the result. When each layer has an explicit owner, a developer can answer the question that matters instead of optimizing the wrong graph. For adjacent architecture concerns, read our remote MCP security guide and agent context and cache guide.
Primary technical references and reproducibility
Sources reviewed October 12, 2026: OpenTelemetry GenAI agent spans; client inference conventions; token metrics; content and retry guidance; Python instrumentation; and Python OTLP exporters. Specification pages are under active development; check them again when upgrading an instrumentation library.