🐛 Bug Report: OpenAI instrumentation drops gen_ai.usage.cache_read.input_tokens when usage.prompt_tokens_details is None
メンテナーはふだん 1 日以内に返信
評価
- 難易度
- 2/5
- 見積もり時間
- 1〜3時間
- 初心者へのやさしさ
- 85/100
- issue の種類
- バグ
- 明瞭さ
- 明確に書かれている
- 活発さ
- 活発
- 技術スタック
- python
調査の方向性
失敗している参照は opentelemetry/instrumentation/openai/shared/init.py の285行目付近にある _set_response_attributes で、usage 辞書から prompt_tokens_details を読み取っている箇所です。chat_wrappers.py の339行目付近にある completion_tokens_details の処理と比較してください。そちらは None に対するガードがすでにあります。prompt_tokens_details が None に設定された usage オブジェクトでも gen_ai.usage.cache_read.input_tokens = 0 が得られれば完了です。これは再現手順の httpx MockTransport を使って、既存の span テストに対して確認できます。
索引モデルが issue の本文から書いたものです。
説明
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
- 主要言語
- Python
- スター
- 7.5k
- フォーク
- 1.2k
- 平均マージ
- 1日 23時間
- マージ済み PR(30日)
- 3
環境構築
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートあり
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
traceloop/openllmetry のほかの issue
-
🐛 Bug Report: OpenAI Responses: with_raw_response.create() raises when the body can't be parsed, though the uninstrumented call returns対応中かも このイシューにリンクされたプルリクエストがオープン中、またはマージ済みです。 オープンbug python
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
traceloop/openllmetry#4717 ·
メンテナーはふだん 1 日以内に返信
-
🐛 Bug Report: Incomplete cache token migration after #4243 breaks Bedrock and Groq instrumentation対応中かも @Quantum-Enigma-dot が 21 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
traceloop/openllmetry#4665 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
🐛 Bug Report: OpenAI instrumentation drops gen_ai.usage.reasoning_tokens on streamed chat completions対応中かも @jayfeng7 が 23 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 82/100
traceloop/openllmetry#4660 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
Bug Report: Failed dataset deletes still remove local rows and columns対応中かも @inchang-ing が 32 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 88/100
traceloop/openllmetry#4630 ·
メンテナーはふだん 1 日以内に返信
-
🐛 Bug Report: LiteLLM instrumentation does not record seed, stop, frequency_penalty, presence_penalty対応中かも @shantam77 が 38 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 85/100
traceloop/openllmetry#4598 · コメント 2 件 ·
メンテナーはふだん 1 日以内に返信
traceloop/openllmetry の issue をすべて見る
似ている issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 77/100
mozilla-ai/cq#601 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 68/100
メンテナーはふだん 1 日以内に返信
-
intcomma returns exponential notation for large floats対応中かも @Omarinho12345 が今日担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
python-humanize/humanize#521 ·
メンテナーはふだん 1 日以内に返信
-
LUCJ pass manager raises NoEdgeBetweenNodes when an edge is bad for two two-qubit gates対応中かも @hat-im が今日担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
メンテナーはふだん 1 日以内に返信
-
opensubtitlescom: provider rejects pt-PT even though its own converter maps it対応中かも @paulo-0308 が今日担当しました。 オープン
難易度 1/5 1時間未満 初心者へのやさしさ 88/100
Diaoul/subliminal#1405 ·