🐛 Bug Report: OpenAI instrumentation drops gen_ai.usage.cache_read.input_tokens when usage.prompt_tokens_details is None

Aperta Adatta ai principianti
#4,583 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

@rupak-eng ci sta già lavorando.

Dal 9/10/2026.

  • #4586 di @rupak-eng — aperta

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
85/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python
Ambito
observability

Direzione di ricerca

La ricerca che fallisce si trova in _set_response_attributes in opentelemetry/instrumentation/openai/shared/init.py, vicino alla riga 285, dove prompt_tokens_details viene letto dal dizionario usage. Confrontalo con la gestione di completion_tokens_details in chat_wrappers.py (intorno alla riga 339), che è già protetta da None. Il lavoro è completo quando un oggetto usage con prompt_tokens_details impostato a None produce comunque gen_ai.usage.cache_read.input_tokens = 0, cosa che puoi verificare con l'httpx MockTransport della riproduzione rispetto ai test di span esistenti.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Which component is this bug for?

OpenAI Instrumentation

📜 Description

_set_response_attributes in opentelemetry/instrumentation/openai/shared/__init__.py (line 285 at df4921a / 0.62.4) does:

prompt_tokens_details = dict(usage.get("prompt_tokens_details", {}))

prompt_tokens_details is optional in the Chat Completions usage object. When a response doesn't include it, the openai SDK still has the key, set to None (CompletionUsage.prompt_tokens_details = None). So usage.get("prompt_tokens_details", {}) returns None, and dict(None) raises TypeError: 'NoneType' object is not iterable.

@dont_throw catches the error and logs it only at DEBUG ("OpenLLMetry failed to trace in _set_response_attributes"), so nothing is visible by default. Because this is the last statement in the function, the span keeps model, id, finish reasons and token counts, but gen_ai.usage.cache_read.input_tokens is never set. It happens for every chat completion without prompt_tokens_details: non-streaming and streaming, sync and async.

The completion_tokens_details lookup in chat_wrappers.py (around line 339) already handles None correctly (if tokens_details:); the prompt side doesn't.

👟 Reproduction steps

pip install openai opentelemetry-sdk opentelemetry-instrumentation-openai

import json, httpx, openai
from opentelemetry.instrumentation.openai import OpenAIInstrumentor
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

def respond(request):
    # usage without prompt_tokens_details (the field is optional)
    return httpx.Response(200, json={
        "id": "chatcmpl-1", "object": "chat.completion", "created": 0, "model": "gpt-4o-mini",
        "choices": [{"index": 0, "message": {"role": "assistant", "content": "hi"}, "finish_reason": "stop"}],
        "usage": {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10}})

exporter = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
OpenAIInstrumentor().instrument(tracer_provider=provider)

client = openai.OpenAI(api_key="x", http_client=httpx.Client(transport=httpx.MockTransport(respond)))
r = client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "hello"}])
print("usage.prompt_tokens_details:", r.usage.prompt_tokens_details)

attrs = exporter.get_finished_spans()[0].attributes
print("gen_ai.usage.input_tokens:", attrs.get("gen_ai.usage.input_tokens"))
print("gen_ai.usage.cache_read.input_tokens:", attrs.get("gen_ai.usage.cache_read.input_tokens", "MISSING"))

Enable DEBUG logging for opentelemetry.instrumentation.openai to see the swallowed TypeError. The same happens with stream=True, stream_options={"include_usage": True}.

👍 Expected behavior

A missing or None prompt_tokens_details is treated like an empty one, and the span gets gen_ai.usage.cache_read.input_tokens = 0, as it does when the field is present. For example:

prompt_tokens_details = dict(usage.get("prompt_tokens_details") or {})
👎 Actual Behavior with Screenshots

usage.prompt_tokens_details: None
gen_ai.usage.input_tokens: 7
gen_ai.usage.cache_read.input_tokens: MISSING

DEBUG log: OpenLLMetry failed to trace in _set_response_attributes, error: ... TypeError: 'NoneType' object is not iterable

When the response includes "prompt_tokens_details": {"cached_tokens": 4}, the attribute is recorded correctly (4).

🤖 Python Version

3.12

📃 Provide any additional context for the Bug.

opentelemetry-instrumentation-openai 0.62.4 (also main at df4921a), openai 2.54.0, opentelemetry-sdk 1.x.
Affects any OpenAI-compatible endpoint that omits prompt_tokens_details from usage.

👀 Have you spent some time to check if this bug has been raised before?
  • I checked and didn't find similar issue
Are you willing to submit PR?

None

Lingua principale
Python
Stelle
7.5k
Fork
1.2k
Merge medio
2g 6h
PR unite (30g)
2

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di traceloop/openllmetry

Tutte le issue di traceloop/openllmetry

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.