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

オープン 初心者向け
#4,583 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

@rupak-eng がすでに取り組んでいます。

2026年10月9日 から。

  • #4586 @rupak-eng による — オープン

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
85/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
python
領域
observability

調査の方向性

失敗している参照は 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

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

traceloop/openllmetry のほかの issue

traceloop/openllmetry の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。