VynarisEarly beta
Get my API key

OpenTelemetry LLM Tracing: Spans, Tokens and Cost in Python

OpenTelemetry LLM tracing in Python: instrument OpenAI-style calls with GenAI semantic conventions, record tokens and cost per request. Tested 2026-11-22.

TL;DR: Install opentelemetry-instrumentation-openai-v2, call OpenAIInstrumentor().instrument(), and every chat call becomes a chat <model> span with gen_ai.usage.input_tokens and gen_ai.usage.output_tokens. Token counts are not dollars, so add a cost attribute yourself: computed from a price table, or read from the x-vynaris-cost-usd header if you call models through Vynaris. We ran every snippet below on 2026-11-22; one dependency pin is needed today, and it is in step 1.

Try it: point the same instrumented OpenAI client at https://api.vynaris.com/v1 and each span can carry the exact cost of the request that produced it. Get a Vynaris API key.

OpenTelemetry LLM tracing means recording each model call as a span that follows the OpenTelemetry GenAI semantic conventions: span name {gen_ai.operation.name} {gen_ai.request.model}, span kind CLIENT, required attributes gen_ai.operation.name and gen_ai.provider.name, and token usage in gen_ai.usage.*. Any OTLP backend (Jaeger, Grafana Tempo, Honeycomb, Datadog) can then show latency, tokens and cost per call next to the rest of your traces. Two things changed in 2026 that most guides miss: the GenAI conventions moved to their own repository, open-telemetry/semantic-conventions-genai, in May 2026, and the newest opentelemetry-util-genai releases break the current OpenAI instrumentation, so you need a pin.

What are the OpenTelemetry GenAI semantic conventions?

The OpenTelemetry GenAI semantic conventions are the agreed attribute names for spans, metrics and events that describe calls to generative AI models. Every attribute is still marked Development, so names can change between releases. The old pages in the main semantic-conventions repository now say they are "no longer maintained in this repository".

These are the attributes an inference span carries, from client-inference.md:

AttributeRequirementExample
gen_ai.operation.nameRequiredchat, generate_content
gen_ai.provider.nameRequiredopenai, gcp.vertex_ai
gen_ai.request.modelConditionally requiredgpt-6.2-sol
gen_ai.response.modelRecommendedmodel that actually answered
gen_ai.usage.input_tokensRecommended3000 (includes cached tokens)
gen_ai.usage.output_tokensRecommended500
gen_ai.usage.cache_read.input_tokensRecommended when non-zero2500
gen_ai.usage.reasoning.output_tokensRecommended when non-zero120
gen_ai.input.messagesOpt-Inthe prompt, as structured parts

There is no cost attribute in the conventions. That gap is what step 5 fills.

An LLM call becomes a CLIENT span with GenAI attributes, nested under your own request span
Output of the script in this guide, run 2026-11-22.

What you need

How do I trace LLM calls with OpenTelemetry in Python?

Five steps, each verified with a run on 2026-11-22.

Step 1: Install the packages with the working pin

pip install "openai<3" httpx opentelemetry-sdk opentelemetry-exporter-otlp-proto-http \
  opentelemetry-instrumentation-openai-v2 "opentelemetry-util-genai==0.4b0"

Without the last pin, pip installs opentelemetry-util-genai 1.3b0 (2026-10-23), and the import fails with ModuleNotFoundError: No module named 'opentelemetry.util.genai.instruments'. We hit the same error with 1.2b0. Version 0.4b0, released the same day as the instrumentation, works.

Step 2: Set up a tracer provider and the instrumentor

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor

provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)

OpenAIInstrumentor().instrument()

Call instrument() before you create the client. It patches the OpenAI SDK, so any client, including one pointed at another OpenAI-compatible base URL, is traced.

Step 3: Turn on the current conventions

export OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental

Without it, the span carries the older gen_ai.system: openai. With it, we got gen_ai.provider.name: openai, the attribute the current conventions require. If you already use this variable for other opt-ins, append ,gen_ai_latest_experimental.

Step 4: Make a call inside your own span

from openai import OpenAI

client = OpenAI(base_url="https://api.vynaris.com/v1", api_key="VYNARIS_KEY")
tracer = trace.get_tracer("support-bot")

with tracer.start_as_current_span("support.reply") as span:
    raw = client.chat.completions.with_raw_response.create(
        model="gpt-6.2-sol",
        messages=[{"role": "user", "content": "Summarise this ticket: ..."}],
    )
    resp = raw.parse()

The instrumentor creates a child span named chat gpt-6.2-sol with kind CLIENT, and in our run it set gen_ai.request.model, gen_ai.response.model, gen_ai.response.id, gen_ai.response.finish_reasons, gen_ai.usage.input_tokens: 3000 and gen_ai.usage.output_tokens: 500. with_raw_response keeps the HTTP headers, which step 5 uses.

Step 5: Record the cost on the span

How do I record token usage and cost on each span? Tokens are already there from step 4. For cost you have two options.

Option A, compute it from a price table you maintain:

# USD per 1M tokens, Standard tier, verified 2026-11-22
PRICES = {"gpt-6.2-sol": (2.00, 10.00), "claude-sonnet-5.5": (2.00, 10.00), "gemini-3.8-flash": (0.75, 3.75)}

inp, out = PRICES[resp.model]
cost = (resp.usage.prompt_tokens * inp + resp.usage.completion_tokens * out) / 1_000_000
span.set_attribute("app.llm.cost_usd", cost)

For 3,000 input and 500 output tokens on gpt-6.2-sol that is (3,000 x $2 + 500 x $10) / 1,000,000 = $0.011. The catch: cached tokens, batch discounts and price changes all make this number drift from your invoice. Google's Gemini 3.8 Flash price, for example, doubles on 2027-01-01.

Option B, read the billed cost from the response. Vynaris returns it on every response as headers, documented in the Vynaris docs: x-vynaris-request-id, x-vynaris-served-model, x-vynaris-cost-usd, x-vynaris-baseline-usd and x-vynaris-saved.

span.set_attribute("vynaris.cost_usd", float(raw.headers["x-vynaris-cost-usd"]))
span.set_attribute("vynaris.served_model", raw.headers["x-vynaris-served-model"])
span.set_attribute("vynaris.request_id", raw.headers["x-vynaris-request-id"])

This is the charge for that request, so your traces add up to your ledger without a price table to maintain. Use your own namespace (app. or vynaris.) for these: the gen_ai. prefix is reserved for the conventions.

Each step adds data to the trace, and the last one adds dollars
Tokens come from the instrumentor; cost comes from you or the response header.

Export to a backend

Swap the console exporter for OTLP and set the endpoint:

from opentelemetry.sdk.resources import Resource
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

provider = TracerProvider(resource=Resource.create({"service.name": "support-bot"}))
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318

Datadog LLM Observability, for one, says it accepts spans that follow GenAI conventions from OpenTelemetry 1.37 onward (Datadog docs). Group by gen_ai.request.model and sum your cost attribute to get spend per model.

How to verify it worked

  1. Run the script with the console exporter. You should see two spans: support.reply (INTERNAL) and chat gpt-6.2-sol (CLIENT).
  2. Check the child span has gen_ai.usage.input_tokens and gen_ai.usage.output_tokens that match resp.usage.
  3. Check the parent span has your cost attribute and it is not 0.
  4. With the opt-in set, check for gen_ai.provider.name instead of gen_ai.system.

Should prompts and completions be captured in traces?

Not by default, and the instrumentation agrees: message content is off unless you set OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT. With the latest conventions on, the values are span_only, event_only or span_and_event; true is the legacy value. Prompts often hold customer data, so turning this on copies that data into your tracing backend with its own retention and access rules.

A middle path from the same package: OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK=upload with OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH set to a bucket (needs pip install "opentelemetry-util-genai[upload]"). Content goes to storage you control, and the span keeps a reference (gen_ai.input.messages_ref).

Common errors and fixes

ErrorCauseFix
No module named 'opentelemetry.util.genai.instruments'util-genai 1.x installedpin opentelemetry-util-genai==0.4b0
No module named 'httpx' on importopenai 3.x installed, which no longer ships httpxuse openai<3 and install httpx
Span shows gen_ai.system, not gen_ai.provider.nameold conventions are the defaultset OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental
No spans at allinstrument() ran after the client was built, or no tracer provider setinstrument first, set the provider before any call

FAQ

Does OpenTelemetry record LLM cost?

No. The GenAI conventions record tokens, not money. Add a cost attribute in your own namespace, computed from prices or taken from a gateway response header.

Does this work with Claude or Gemini?

The OpenAI instrumentation traces any call made through the OpenAI SDK. Through Vynaris, Claude and Gemini models answer on the same OpenAI-compatible endpoint, so the same spans appear. Note that gen_ai.provider.name then reads openai, because it names the client, not the model maker.

Are the GenAI semantic conventions stable?

No. Every attribute is marked Development as of 2026-11-22, which is why the opt-in variable exists.

What is the difference between spans and the GenAI metrics?

Spans describe one call. Metrics such as gen_ai.client.operation.duration (a histogram in seconds) and the token-usage metrics aggregate across calls, which is cheaper for dashboards. See the GenAI metrics spec.

For the money side, see how to track LLM API costs, the Claude Code gateway guide and our OpenAI-compatible API providers list.

Put the real cost on every span

Token counts tell you how much a call used; the cost header tells you what it billed. Point your instrumented client at Vynaris and both land on the same trace. Get your Vynaris API key.