Skip to content

fix(python-sdk): keep reasoning_content for Gradient chat completions - #2008

Open
basil-k-aji-dev wants to merge 2 commits into
openlit:mainfrom
basil-k-aji-dev:fix/gradient-reasoning-stream
Open

basil-k-aji-dev wants to merge 2 commits into
openlit:mainfrom
basil-k-aji-dev:fix/gradient-reasoning-stream

Conversation

@basil-k-aji-dev

@basil-k-aji-dev basil-k-aji-dev commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Important

  1. We strictly follow a issue-first approach, please first open an issue relating to this Pull Request.
  2. PR title follows Conventional Commit format, for example feat: ... or
    fix(client): ....

Issue number: #2006

Change description:

Streamed Gradient chat completions dropped delta.reasoning_content. process_chunk had no branch for it, so scope._reasoning_text stayed empty for chat streams on reasoning models, although build_output_messages already renders _reasoning_text as a reasoning part (it was only filled from the Responses API reasoning_text.delta events). The sibling pydo instrumentation already handles the chat-completions delta.

process_chunk now appends a non-empty delta.get("reasoning_content") to scope._reasoning_text, in the same shape as pydo and without touching the content and tool_calls handling. The sync and async stream wrappers share process_chunk, so both are covered.

One line beyond the issue text: process_chat_response (the non-streaming chat path) did not read message.reasoning_content either, while pydo does (scope._reasoning_text = message.get("reasoning_content") or ""). I added the same line there, with a test, since it is the same gap in the same file.

Tested with sdk/python/tests/test_gradient_reasoning_stream.py (8 tests, no network): reasoning deltas accumulate alongside content, reasoning and content in one delta are both kept, None or a missing reasoning_content is ignored, tool-call assembly is unaffected, the output message has the reasoning part before the text part, and a streamed and a non-streamed span each carry the reasoning part end to end.

  • Without the change: 7 of the 8 fail, for example assert '' == 'step one'; the eighth is a guard for models without reasoning.
  • With the change: 8 passed. Dropping the branch, overwriting instead of appending, removing the None guard, using the wrong key, clobbering content, or dropping the non-streaming line were each caught.
  • pylint 10.00/10, ruff format --check clean. The cheap sdk/python tests that load give the same results with and without the change.

Things a reviewer should know:

Checklist

If your change doesn't seem to apply, please leave them unchecked.

  • PR title follows Conventional Commit format.
  • I have reviewed the contributing guidelines
  • Have you checked to ensure there aren't other open Pull Requests for the same update/change?
  • I have performed a self-review of this change
  • Changes have been tested
  • Changes are documented

Acknowledgment

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of the project license.

Summary by Sourcery

Preserve reasoning content across Gradient chat completion instrumentation paths.

Bug Fixes:

  • Preserve reasoning_content from streamed and non-streamed Gradient chat completions in generated telemetry output.

Enhancements:

  • Keep reasoning content alongside text and tool calls while ignoring invalid non-string values.

Tests:

  • Add regression coverage for streamed and non-streamed reasoning content, accumulation, output ordering, tool calls, missing values, and invalid types.

@basil-k-aji-dev
basil-k-aji-dev requested review from a team and ishanjainn as code owners November 24, 2026 21:03
@sourcery-ai

sourcery-ai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Capture reasoning content from streamed deltas and non-streamed messages so Gradient chat output includes reasoning alongside answer text.

  • sdk/python/src/openlit/instrumentation/gradient/utils.py L358-360, L756-757

Copy reasoning content onto the scope in the synchronous and asynchronous agent chat-completion wrappers.

  • sdk/python/src/openlit/instrumentation/gradient/async_gradient.py L284-286
  • sdk/python/src/openlit/instrumentation/gradient/gradient.py L320-322

Tests

Exercise streamed and non-streamed reasoning capture, output ordering, invalid values, and compatibility with content and tool calls.

  • sdk/python/tests/test_gradient_reasoning_stream.py L1-364

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

fix(python-sdk): preserve Gradient chat reasoning content

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Preserve reasoning content in streamed and non-streamed Gradient chat completions.
• Add regression tests for accumulation, tool calls, output ordering, and span attributes.
Merge Risk 🟡 Medium

Blast radius 🟡 Medium 💥 2 capabilities

  • 2 affected capabilities within one bounded functional scope: Gradient LLM instrumentation.
  • Regular synchronous and asynchronous chat-completion wrappers use the shared Gradient chunk and response processors and the same output-message construction path.
  • They therefore represent one bounded telemetry integration rather than separate capabilities per wrapper or streaming hop.
  • Agent chat completion is a distinct telemetry outcome from ordinary chat completion, but it remains within the same bounded Gradient instrumentation integration and uses the same output-message representation.
  • The sync and async implementations are delivery variants of this capability, not independent functional scopes.
Sources

sdk/python/src/openlit/instrumentation/gradient/utils.py[355-360]

        content = delta.get("content")
        if content:
            scope._llmresponse += content
        reasoning = delta.get("reasoning_content")
        if reasoning and isinstance(reasoning, str):
            scope._reasoning_text = getattr(scope, "_reasoning_text", "") + reasoning
Behavioral complexity 🟢 Low 🧩 Straightforward

  • Before the change, Gradient chat processing captured ordinary content but did not copy chat-completion reasoning_content into the existing reasoning scope field.
  • After the change, streamed chunks append string reasoning fragments and non-streamed messages assign a string reasoning value; the existing output builder then renders that field.
  • The new correctness condition is limited to accepting only string values, preserving fragment order, and keeping reasoning separate from ordinary content.
  • Existing scope management, output-message formatting, and telemetry emission are reused without introducing new states, concurrency, compatibility negotiation, coordinated writes, or algorithmic transformation.
Sources

sdk/python/src/openlit/instrumentation/gradient/utils.py[355-360]

        content = delta.get("content")
        if content:
            scope._llmresponse += content
        reasoning = delta.get("reasoning_content")
        if reasoning and isinstance(reasoning, str):
            scope._reasoning_text = getattr(scope, "_reasoning_text", "") + reasoning
Potential damage 🟡 Medium 🩹 Recoverable

  • If the changed extraction or accumulation regresses, affected Gradient telemetry may omit or misrepresent reasoning output while the underlying model response and agent behavior remain unchanged.
  • The existing output builder consumes the scope reasoning field, so the changed value can affect emitted span/event content.
  • This is a recoverable observability degradation: newly emitted telemetry is correct after code rollout, but already emitted telemetry cannot generally be retroactively repaired.
  • No evidence shows persistent application-state mutation, external compensation, or user-facing model-result corruption.
  • Reverting or correcting the instrumentation restores future telemetry.
  • Previously exported spans/events would require replacement or re-export from an independent source if repair is needed; the model response and application state do not require repair.
Sources

sdk/python/src/openlit/instrumentation/gradient/utils.py[355-360]

        content = delta.get("content")
        if content:
            scope._llmresponse += content
        reasoning = delta.get("reasoning_content")
        if reasoning and isinstance(reasoning, str):
            scope._reasoning_text = getattr(scope, "_reasoning_text", "") + reasoning
Assessed commit f9c0f6b
Diagram

graph TD
  SD["Streamed deltas"] --> PC["Chunk processor"] --> RS["Reasoning state"] --> OM["Output messages"] --> SP["Span attributes"]
  NR["Chat response"] --> CR["Response processor"] --> RS
Loading
High-Level Assessment

Use the existing scope accumulator and output-message builder. The sync and async wrappers already share the chunk processor, so changing that processor and the non-streaming response processor fixes both paths without introducing a new abstraction.

Files changed (2) +227 / -0

Bug fix (1) +4 / -0
utils.pyCapture Gradient chat reasoning content +4/-0

Capture Gradient chat reasoning content

• Appends non-empty reasoning_content deltas to the streaming scope and reads reasoning_content from non-streamed messages. Existing output-message construction can then include the reasoning part without changing content or tool-call processing.

sdk/python/src/openlit/instrumentation/gradient/utils.py

Tests (1) +223 / -0
test_gradient_reasoning_stream.pyCover streamed and non-streamed reasoning preservation +223/-0

Cover streamed and non-streamed reasoning preservation

• Adds eight network-free regression tests for reasoning accumulation, mixed and absent deltas, tool calls, output-part ordering, and reasoning on streamed and non-streamed spans.

sdk/python/tests/test_gradient_reasoning_stream.py

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review

Grey Divider

Tip of the day
💡 Did you know, you can show, collapse, or hide each part of a finding: code, evidence, and all

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@sourcery-ai sourcery-ai Bot 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.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="sdk/python/src/openlit/instrumentation/gradient/utils.py" line_range="360" />
<code_context>
             scope._llmresponse += content
+        reasoning = delta.get("reasoning_content")
+        if reasoning:
+            scope._reasoning_text = getattr(scope, "_reasoning_text", "") + reasoning
         finish = choice0.get("finish_reason")
         if finish:
</code_context>
<issue_to_address>
**Malformed reasoning chunks abort streams**

When the upstream stream supplies a truthy non-string `reasoning_content` value, `process_chunk` concatenates the value with a string and raises `TypeError`; `TracedSyncStream.__next__` and `TracedAsyncStream.__anext__` invoke it without handling per-chunk processing errors, so iteration aborts before delivering the completion.

Validate that the reasoning value is a string before appending it, and ignore or safely normalize values of other types.
</issue_to_address>

### Comment 2
<location path="sdk/python/src/openlit/instrumentation/gradient/utils.py" line_range="756" />
<code_context>
         message = choice0.get("message") or {}
         content = message.get("content") or ""
         scope._llmresponse = content if isinstance(content, str) else str(content)
+        scope._reasoning_text = message.get("reasoning_content") or ""
         scope._finish_reason = choice0.get("finish_reason") or ""
         if message.get("tool_calls"):
</code_context>
<issue_to_address>
**Agent reasoning is omitted from outputs**

When a non-streaming agent chat completion includes `message.reasoning_content`, the sync and async agent-wrapper branches copy `message.content` but not `message.reasoning_content` before calling `common_chat_logic`, so output messages, captured spans, and inference events omit the reasoning.

Copy `message.reasoning_content` into `scope._reasoning_text` in both agent-wrapper branches before calling `common_chat_logic`.
</issue_to_address>

### Comment 3
<location path="sdk/python/src/openlit/instrumentation/gradient/utils.py" line_range="360" />
<code_context>
             scope._llmresponse += content
+        reasoning = delta.get("reasoning_content")
+        if reasoning:
+            scope._reasoning_text = getattr(scope, "_reasoning_text", "") + reasoning
         finish = choice0.get("finish_reason")
         if finish:
</code_context>
<issue_to_address>
**Reasoning tokens and cost are undercounted**

When a reasoning completion has no nonzero provider completion-token usage, `common_chat_logic` estimates missing output usage from `scope._llmresponse` alone, excluding `scope._reasoning_text`, so recorded output-token usage and cost are too low.

Include `scope._reasoning_text` when estimating output tokens from the completion.

Also at `sdk/python/src/openlit/instrumentation/gradient/utils.py:756`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and the change copies reasoning_content from streamed and non-streamed responses into output-message span attributes, so telemetry can retain reasoning text that was not previously recorded. Reverting stops future capture, but it cannot remove spans already exported.

Blocking findings: sdk/python/src/openlit/instrumentation/gradient/utils.py:360, sdk/python/src/openlit/instrumentation/gradient/utils.py:756, sdk/python/src/openlit/instrumentation/gradient/utils.py:360


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

scope._llmresponse += content
reasoning = delta.get("reasoning_content")
if reasoning:
scope._reasoning_text = getattr(scope, "_reasoning_text", "") + reasoning

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.

🟡 Medium · Reasoning tokens and cost are undercounted

When a reasoning completion has no nonzero provider completion-token usage, common_chat_logic estimates missing output usage from scope._llmresponse alone, excluding scope._reasoning_text, so recorded output-token usage and cost are too low.

Include scope._reasoning_text when estimating output tokens from the completion.

Also at sdk/python/src/openlit/instrumentation/gradient/utils.py:756.

Prompt for AI agents
In `sdk/python/src/openlit/instrumentation/gradient/utils.py` at line 360:

**Reasoning tokens and cost are undercounted**

When a reasoning completion has no nonzero provider completion-token usage, `common_chat_logic` estimates missing output usage from `scope._llmresponse` alone, excluding `scope._reasoning_text`, so recorded output-token usage and cost are too low.

Include `scope._reasoning_text` when estimating output tokens from the completion.

Also at `sdk/python/src/openlit/instrumentation/gradient/utils.py:756`.

This branch was previously deployed

1 inactive (outdated) deployment
release-notes — d245d256 Deployed Nov 24, 2026 by basil-k-aji-dev via Normalize / Conventional title #899
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant