Skip to content

fix(openai): record cache_read tokens when prompt_tokens_details is None - #4586

Open
rupak-eng wants to merge 1 commit into
traceloop:mainfrom
rupak-eng:fix/openai-cache-read-tokens-none-guard
Open

rupak-eng wants to merge 1 commit into
traceloop:mainfrom
rupak-eng:fix/openai-cache-read-tokens-none-guard

Conversation

@rupak-eng

@rupak-eng rupak-eng commented Oct 9, 2026 •

Copy link
Copy Markdown

Fixes #4583

_set_response_attributes did dict(usage.get("prompt_tokens_details", {})). The openai SDK carries the key with a None value when the response omits the optional field, so dict(None) raised TypeError (swallowed by @dont_throw), and gen_ai.usage.cache_read.input_tokens was never set. A missing/None value is now treated as empty, so the attribute is recorded as 0 — mirroring the completion_tokens_details None guard in chat_wrappers.py.

Testing

  • Reproduced first with the issue's httpx.MockTransport harness: gen_ai.usage.cache_read.input_tokens was MISSING before, 0 after (no API key/network).
  • New tests/traces/test_usage_cache_read_tokens.py: 4 mock-based tests — sync, streaming (stream_options usage), async with prompt_tokens_details=None → attribute recorded as 0; plus a pin that a present cached_tokens value still records correctly. 3 of the 4 fail on unpatched code (the 4th pins pre-existing behavior).
  • Existing tests/traces/test_semconv_compliance.py: 34/34 pass with the change. ruff check clean on both files.

Summary by CodeRabbit

  • Bug Fixes
    • OpenAI tracing now handles missing prompt-token details without failing, while preserving cached-token counts when available.
    • Added coverage for synchronous, asynchronous, and streaming requests.

_set_response_attributes did dict(usage.get('prompt_tokens_details', {}));
the openai SDK carries the key with a None value when the response omits
the optional field, so dict(None) raised TypeError (swallowed by
@dont_throw), and gen_ai.usage.cache_read.input_tokens was never set.
Treat a missing/None value as empty so the attribute is recorded as 0.

Adds mock-transport regression tests covering sync, streaming (with
stream_options usage), and async paths, plus the cached-tokens-present
behavior pin.

Fixes traceloop#4583
@coderabbitai

coderabbitai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e289fb7f-df24-4184-918e-4d935cbfad37
📥 Commits

Reviewing files that changed from the base of the PR and between df4921a and 46b5ffa.

📒 Files selected for processing (2)
  • packages/opentelemetry-instrumentation-openai/opentelemetry/instrumentation/openai/shared/__init__.py
  • packages/opentelemetry-instrumentation-openai/tests/traces/test_usage_cache_read_tokens.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

The OpenAI instrumentation now handles missing or None prompt-token details when recording cache-read token attributes. Regression tests cover synchronous, asynchronous, and streaming responses.

Changes

OpenAI usage tracing

Layer / File(s) Summary
Handle optional prompt-token details
packages/opentelemetry-instrumentation-openai/opentelemetry/instrumentation/openai/shared/__init__.py, packages/opentelemetry-instrumentation-openai/tests/traces/test_usage_cache_read_tokens.py
The instrumentation uses an empty mapping when prompt_tokens_details is missing or None. Tests check input-token and cache-read-token attributes for synchronous, asynchronous, and streaming responses, including a response with cached tokens.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Low

Merge Risk: ⚪ Minimal · up to 46b5f

OpenAI responses without prompt-token details should now record zero cache-read tokens. No actionable merge risk remains beyond normal checks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: recording cache-read tokens when prompt_tokens_details is None.
Linked Issues check Passed Issue #4583 requires gen_ai.usage.cache_read.input_tokens to be recorded as 0 when prompt_tokens_details is missing or None, for synchronous, asynchronous, and streaming chat completions. The ch…
Out of Scope Changes check Passed The pull request changes only the OpenAI response-usage handling and adds regression tests for issue #4583. The tests directly verify the required zero and cached-token attributes. No unrelated produc…
  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@chrikrah chrikrah left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rupak-eng the or {} line in shared/__init__.py is right. The new test module breaks five existing tests in this package, so it needs one change before merge.

blocking: the local span_exporter fixture builds and tears down its own OpenAIInstrumentor(), and that leaves global state behind for test_vision.py, which runs later. The constructor overwrites Config.upload_base64_image, so test_vision_base64 fails on a KeyError. The other four fail on assert 10 == 2 over the log records. Restoring Config after the fixture fixes only the first one.

$ pytest tests -q -p no:sugar      # head 46b5ffa, Python 3.10, openai 1.99.7
FAILED tests/traces/test_vision.py::test_vision_base64 - KeyError: 'gen_ai.in...
5 failed, 290 passed, 1 skipped
$ pytest tests -q -p no:sugar      # base df4921a
291 passed, 1 skipped

Replace the local span_exporter fixture with the shared one, as test_responses.py:1014 does:

@pytest.fixture(autouse=True)
def _instrumented(instrument_legacy):
    yield
$ pytest tests -q -p no:sugar      # head, local fixture replaced
295 passed, 1 skipped
$ pytest tests/traces/test_usage_cache_read_tokens.py -q   # same, `or {}` reverted
3 failed, 1 passed

After that change, nothing uses the TracerProvider, SimpleSpanProcessor and InMemorySpanExporter imports.

non-blocking: when input_tokens_details is absent, responses_wrappers.py:490 omits gen_ai.usage.cache_read.input_tokens. This path records 0.

@doronkopit5 should a missing prompt_tokens_details record 0 here, or be omitted like the Responses path?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

2 participants