Repository navigation
fix(python-sdk): keep reasoning_content for Gradient chat completions - #2008
basil-k-aji-dev wants to merge 2 commits into
Conversation
Reviewer's GuideImplementationCapture reasoning content from streamed deltas and non-streamed messages so Gradient chat output includes reasoning alongside answer text.
Copy reasoning content onto the scope in the synchronous and asynchronous agent chat-completion wrappers.
TestsExercise streamed and non-streamed reasoning capture, output ordering, invalid values, and compatibility with content and tool calls.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
PR Summary by Qodofix(python-sdk): preserve Gradient chat reasoning content
AI Description
Merge Risk
|
Code Review by Qodo🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)
Great, no issues found!Qodo reviewed your code and found no material issues that require reviewTip of the day💡 Did you know, you can show, collapse, or hide each part of a finding: code, evidence, and all |
There was a problem hiding this comment.
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
| scope._llmresponse += content | ||
| reasoning = delta.get("reasoning_content") | ||
| if reasoning: | ||
| scope._reasoning_text = getattr(scope, "_reasoning_text", "") + reasoning |
There was a problem hiding this comment.
🟡 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`.
Important
feat: ...orfix(client): ....Issue number: #2006
Change description:
Streamed Gradient chat completions dropped
delta.reasoning_content.process_chunkhad no branch for it, soscope._reasoning_textstayed empty for chat streams on reasoning models, althoughbuild_output_messagesalready renders_reasoning_textas a reasoning part (it was only filled from the Responses APIreasoning_text.deltaevents). The siblingpydoinstrumentation already handles the chat-completions delta.process_chunknow appends a non-emptydelta.get("reasoning_content")toscope._reasoning_text, in the same shape aspydoand without touching thecontentandtool_callshandling. The sync and async stream wrappers shareprocess_chunk, so both are covered.One line beyond the issue text:
process_chat_response(the non-streaming chat path) did not readmessage.reasoning_contenteither, whilepydodoes (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,Noneor a missingreasoning_contentis 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.assert '' == 'step one'; the eighth is a guard for models without reasoning.Noneguard, using the wrong key, clobberingcontent, or dropping the non-streaming line were each caught.pylint10.00/10,ruff format --checkclean. The cheapsdk/pythontests that load give the same results with and without the change.Things a reviewer should know:
reasoning_contentwould raise inprocess_chunk, as a non-stringcontentalready does on the line above and inpydo.openaiandgroqalso accept areasoningkey through a shared helper; Gradient andpydoread onlyreasoning_content, and this keeps that parity.Checklist
If your change doesn't seem to apply, please leave them unchecked.
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:
reasoning_contentfrom streamed and non-streamed Gradient chat completions in generated telemetry output.Enhancements:
Tests: