Skip to content

fix: join streamed reasoning into one thought part per block - #6896

Open
benclarkeio wants to merge 1 commit into
google:mainfrom
benclarkeio:fix/aggregate-streaming-thought-parts
Open

fix: join streamed reasoning into one thought part per block#6896
benclarkeio wants to merge 1 commit into
google:mainfrom
benclarkeio:fix/aggregate-streaming-thought-parts

Conversation

@benclarkeio

Copy link
Copy Markdown
Contributor

Fixes #6895

Problem

Both stream finalizers join the text buffer but pass the reasoning buffer through as-is:

llm_response = _message_to_generate_content_response(
    ChatCompletionAssistantMessage(
        role="assistant",
        content="".join(text_parts),                          # joined
    ),
    model_version=model_version,
    thought_parts=list(reasoning_parts) if reasoning_parts else None,   # not joined
)

So the aggregated response — and the session event written from it — holds one types.Part(thought=True) per streamed delta. With xAI, whose deltas are per-token, one thought becomes ~40 parts. The same call with stream=False produces a single part, so the stored shape depends on the transport rather than on what the model said.

Fix

Call _aggregate_streaming_thought_parts in both finalizers. It already exists for this, and its docstring already claims session history as a target — only the outbound Anthropic path in _content_to_message_param was wired to it.

Signature boundaries are preserved: Anthropic closes each thinking block with a signature-only delta, and a signature only matches the text of its own block, so the helper splits there rather than merging everything adjacent. Providers that send no signature collapse to one part, which is what they mean.

Partial responses are untouched — they keep yielding one part per delta, which is what makes live streaming work.

Testing

Two tests added:

  • test_streaming_reasoning_assembled_from_many_fragments — 50 reasoning_content deltas arrive as 50 partials and aggregate to one thought part carrying the joined text.
  • test_streaming_reasoning_keeps_thinking_block_boundaries — two Anthropic thinking blocks, each closed by a signature-only delta, aggregate to two parts with their own signatures.

Both fail before the change. tests/unittests/models/test_litellm.py passes in full (405 passed). Formatted with pyink per the repo config.

Both stream finalizers passed the reasoning buffer through unjoined, so the
aggregated response held one thought part per delta while text was joined into
one. `_aggregate_streaming_thought_parts` already does the joining and splits on
`thought_signature`, so Anthropic block boundaries survive.
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.

LiteLlm streaming stores one thought part per reasoning delta

2 participants