Skip to content

fix(integrations): split reasoning from candidate token usage for OpenAI models - #8413

Open
lebeg wants to merge 1 commit into
google:mainfrom
lebeg:fix-openai-reasoning-usage
Open

lebeg wants to merge 1 commit into
google:mainfrom
lebeg:fix-openai-reasoning-usage

Conversation

@lebeg

@lebeg lebeg commented Nov 27, 2026

Copy link
Copy Markdown

Please ensure you have read the contribution guide before creating a pull request.

Link to Issue or Description of Change

1. Link to an existing issue (if applicable):

Problem:

OpenAI counts reasoning tokens inside completion_tokens (Chat Completions)
and output_tokens (Responses). OpenAILlm and OpenAIResponsesLlm reported
that count as candidates_token_count and the reasoning as
thoughts_token_count. telemetry/_token_usage.py sums the two into output
tokens, so reasoning was counted twice: 50 output tokens of which 38 are
reasoning became 88 in gen_ai.usage.output_tokens.

Solution:

Split at the provider, as AnthropicLlm does here and adk-go's openaimodel
does since google/adk-go#2511.

  • New _openai_common.split_reasoning_tokens(output, reasoning). It subtracts
    reasoning from the output count and caps it there, so candidates never go
    negative. Negative counts are read as zero. When either count is missing,
    both are returned as they are, so a response without reasoning details maps
    as before.
  • OpenAIResponsesLlm always splits. Responses counts reasoning inside
    output_tokens.
  • OpenAILlm splits too, except for endpoints that count reasoning outside
    completion_tokens. Gemini on Vertex AI and xAI do, and their
    total_tokens is prompt + completion + reasoning, which OpenAI's total never
    is when reasoning is reported. Those counts are already disjoint and are
    kept, which is what OpenAILlm reports for them today. adk-go uses the same
    rule.
  • The comment that left the fix to telemetry/_token_usage.py is gone.
Endpoint Provider usage Before: candidates / thoughts → output After
OpenAI Chat Completions (fixture) completion 50, reasoning 38 50 / 38 → 88 12 / 38 → 50
OpenAI Responses (fixture) output 50, reasoning 38 50 / 38 → 88 12 / 38 → 50
Gemini on Vertex AI, google/gemini-3.8-flash (live) prompt 39, completion 4, reasoning 96, total 139 4 / 96 → 100 4 / 96 → 100
Ollama 0.40.16, qwen3:8b (live) no reasoning details unchanged unchanged

Behavior change: for OpenAI reasoning turns, candidates_token_count no longer
includes reasoning. Callers that read it directly as the output count get the
non-reasoning part, and can add thoughts_token_count to recover the full
count. In this repo that is LoggingPlugin (logs it as output),
DebugLoggingPlugin, and BigQueryAgentAnalyticsPlugin, which writes it as
completion, so stored values for OpenAI reasoning turns drop at upgrade. This
matches what they already get from Gemini and AnthropicLlm.

Testing Plan

Unit Tests:

  • I have added or updated unit tests for my change.

  • All unit tests pass locally.

  • test_openai_llm.py::test_usage_metadata_splits_reasoning_from_candidates
    (replaces test_usage_metadata_maps_reasoning_tokens, which pinned the
    double count): 12 cases. Reasoning inside completion, zero, missing, all
    reasoning, reasoning above completion, negative reasoning and completion, and
    the outside-completion shape (Vertex numbers, reasoning below completion,
    zero total, negative prompt, negative completion).

  • test_openai_llm.py::test_usage_metadata_reports_output_tokens_once:
    TokenUsage.output_tokens is 50 for the OpenAI shape and 107 for the Vertex
    shape.

  • test_openai_responses_llm.py::test_usage_metadata_splits_reasoning_from_candidates
    (7 cases) and ::test_usage_metadata_reports_output_tokens_once (typed
    ResponseUsage).

  • test_response_parsing_maps_text_reasoning_tool_calls_and_usage: the
    candidate count is now 3 (output 7 minus reasoning 4), not 7.

With the source change reverted and the tests kept, 16 of the 26 usage tests
fail. Each of seven single-guard mutants (no outside-completion check, no
prompt or completion >= 0 guard, no cap, negative reasoning or output
allowed, Responses not split) fails at least one test. No new mypy errors
against main in the changed files, by the CI job's comparison.

$ pytest tests/unittests/integrations/openai -k usage
26 passed, 285 deselected
$ pytest tests/unittests            # Python 3.11.18
26638 passed, 99 skipped, 63 xfailed, 2 xpassed, 44 subtests passed in 398.96s
$ tox -e py312,py313,py314         # extras = test
py312: 26565 passed, 103 skipped, 63 xfailed, 2 xpassed
py313: 26565 passed, 103 skipped, 63 xfailed, 2 xpassed
py314: 26567 passed, 101 skipped, 63 xfailed, 2 xpassed

Manual End-to-End (E2E) Tests:

The same prompt through OpenAILlm against live endpoints, blocking and
streaming, on main and on this branch:

# main (03725e8)
vertex  blocking   {"completion_tokens":4,"completion_tokens_details":{"reasoning_tokens":113},"prompt_tokens":39,"total_tokens":156}
                   candidates=4 thoughts=113 -> output_tokens=117
vertex  streaming  {"completion_tokens":4,"completion_tokens_details":{"reasoning_tokens":89},"prompt_tokens":39,"total_tokens":132}
                   candidates=4 thoughts=89 -> output_tokens=93

# this branch
vertex  blocking   {"completion_tokens":4,"completion_tokens_details":{"reasoning_tokens":96},"prompt_tokens":39,"total_tokens":139}
                   candidates=4 thoughts=96 -> output_tokens=100
vertex  streaming  {"completion_tokens":4,"completion_tokens_details":{"reasoning_tokens":96},"prompt_tokens":39,"total_tokens":139}
                   candidates=4 thoughts=96 -> output_tokens=100
ollama  chat       {"prompt_tokens":49,"completion_tokens":834,"total_tokens":883}
                   candidates=834 thoughts=None -> output_tokens=834
ollama  responses  {"input_tokens":49,"output_tokens":1064,"total_tokens":1113,"output_tokens_details":{"reasoning_tokens":0}}
                   candidates=1064 thoughts=0 -> output_tokens=1064

I made no live OpenAI call. The OpenAI rows use fixtures shaped like OpenAI's
documented usage.

Checklist

  • I have read the CONTRIBUTING.md document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • I have manually tested my changes end-to-end.
  • Any dependent changes have been merged and published in downstream modules.

Additional context

  • Gemini API's own OpenAI layer (generativelanguage.googleapis.com/v1beta/openai/)
    sends no reasoning count, while its total_tokens includes thinking.
    gemini-3.8-flash returned {"completion_tokens":4,"prompt_tokens":40,"total_tokens":142},
    so 98 thinking tokens are missing from candidates and thoughts both before
    and after this change. That needs a separate fix, here and in adk-go.
  • ApigeeLlm and the OCI integration map completion_tokens and
    reasoning_tokens the same way. I can't test their backends, so they are
    left out of this change.

🤖 Generated with Claude Code

…nAI models

OpenAI counts reasoning tokens inside completion_tokens and output_tokens.
OpenAILlm and OpenAIResponsesLlm reported that count as candidates and the
reasoning as thoughts, and telemetry sums the two, so reasoning was counted
twice in gen_ai.usage.output_tokens.

Subtract reasoning from the candidate count, capped at the output count, as
AnthropicLlm and adk-go's openaimodel do. Chat Completions endpoints that
count reasoning outside completion_tokens, such as Gemini on Vertex AI and
xAI, report a total of prompt plus completion plus reasoning; their counts
are already disjoint and are kept.

Fixes google#8412
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.

OpenAILlm and OpenAIResponsesLlm count reasoning tokens twice in output usage

1 participant