Skip to content

fix(caching): keep reasoning, citations, and audio on streamed cache hits - #32096

Merged
mateo-berri merged 8 commits into
BerriAI:mainfrom
jesco-absolut:litellm_fix_streaming_cache_reasoning
Oct 29, 2026
Merged

mateo-berri merged 8 commits into
BerriAI:mainfrom
jesco-absolut:litellm_fix_streaming_cache_reasoning

Conversation

@jesco-absolut

@jesco-absolut jesco-absolut commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

A streamed cache hit drops reasoning, citations, and audio, and sends tool calls before the text. This replays the cached message in a live stream's order

Details

TLDR

Problem this solves:

  • Streamed cache hits drop reasoning, citations, and audio, and reorder tool calls

How it solves it:

  • Replays the whole cached message
  • Sends reasoning, then text, then tool calls
  • Ends on its own finish chunk, keeping audio-only answers

User Flow

Before: a cached stream loses fields and order the first stream had

  1. The proxy admin turns on Redis response caching
  2. The developer streams POST https://litellm-domain/v1/chat/completions to Claude with reasoning_effort and gets reasoning and signed delta.thinking_blocks
  3. The repeat is a cache hit with the same id, but only the answer text
  4. Web search and audio repeats lose delta.annotations and delta.audio
  5. A tool call's repeat comes before the text, or loses the reasoning

After: the cached stream keeps everything the first stream had, reasoning first

  1. The proxy admin turns on Redis response caching
  2. The developer streams POST https://litellm-domain/v1/chat/completions to Claude with reasoning_effort and gets reasoning and signed delta.thinking_blocks
  3. The repeat is a cache hit with the same id, with the reasoning and signed thinking blocks before the text
  4. Web search and audio repeats keep delta.annotations, on the last text chunk, and delta.audio
  5. A tool call's repeat sends the reasoning, any text, then the call

Relevant issues

Fixes #32068, closed though main still has the bug

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Live curl runs, the client from #32068, against real Anthropic and OpenAI, one --num_workers 2 proxy per leg (base on 25917, tip on 26917) on one Redis. Each repeat is the cache hit. This gist has every stream, and shape lists a stream's chunks

shape() { grep '^data: {' "$1" | cut -c7- | jq -c '[(.choices[0].delta | keys), .choices[0].finish_reason]' | uniq -c; }
Config
model_list:
  - model_name: claude-sonnet-5-5
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: gpt-5-search-api
    litellm_params:
      model: openai/gpt-5-search-api
      api_key: os.environ/OPENAI_API_KEY
  - model_name: gpt-audio-1.5
    litellm_params:
      model: openai/gpt-audio-1.5
      api_key: os.environ/OPENAI_API_KEY

litellm_settings:
  cache: true
  cache_params:
    type: redis
    host: 127.0.0.1
    port: 24917
    ttl: 3600
Case Before, cache hit After, cache hit
Chat, Claude reasoning no reasoning reasoning and signed block
Chat, web search no annotations annotation kept
Chat, audio answer no audio audio and transcript kept
Responses, Claude reasoning no reasoning summary reasoning summary kept
Chat, text and tool call before text reasoning, text, call
Responses, tool call no reasoning item reasoning, message, call
Chat, tool only no reasoning reasoning, then call
SDK sync, tool turns call first or merged reasoning, text, call
Chat, blank text and tool no reasoning reasoning, blank, call

Before (77064d6)

Chat, Claude reasoning

  1. First call, saved to a file
$ curl -sN http://localhost:25917/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-5-5","stream":true,"reasoning_effort":"high","messages":[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"How many primes are there between 2000 and 2100? Work it out, then give only the count. (qa round 9)"}]}' > chat-reasoning-1.sse
$ grep -o '"id":"chatcmpl-[^"]*"' chat-reasoning-1.sse | sort -u
"id":"chatcmpl-acd202e8-c1c5-4373-b7ea-1cab99105894"
$ grep -c '"reasoning_content"\|"annotations"' chat-reasoning-1.sse
25
  1. The same curl again into chat-reasoning-2.sse is a cache hit with the same id and no reasoning
$ grep -o '"id":"chatcmpl-[^"]*"' chat-reasoning-2.sse | sort -u
"id":"chatcmpl-acd202e8-c1c5-4373-b7ea-1cab99105894"
$ shape chat-reasoning-2.sse
      1 [["content","provider_specific_fields","role"],null]
      1 [[],"stop"]

Chat, web search

Steps
  1. First call, saved to a file
$ curl -sN http://localhost:25917/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"gpt-5-search-api","stream":true,"web_search_options":{},"messages":[{"role":"user","content":"What is the latest LiteLLM release on GitHub? Answer in one sentence and cite the page. (qa round 9)"}]}' > chat-annotations-1.sse
$ grep -o '"id":"chatcmpl-[^"]*"' chat-annotations-1.sse | sort -u
"id":"chatcmpl-49ef9df2-4aa8-49f7-82b3-368d05a1067f"
"id":"chatcmpl-56f3c9e7-5458-4e99-8a79-bdc5e8e9fe7f"
"id":"chatcmpl-bc4eaba8-89e6-4921-bb4e-ce44644d078b"
$ grep -c '"reasoning_content"\|"annotations"' chat-annotations-1.sse
1
  1. The same curl again, saved to chat-annotations-2.sse. It answers from the cache with one of the first call's ids, and the url_citation is gone
$ grep -o '"id":"chatcmpl-[^"]*"' chat-annotations-2.sse | sort -u
"id":"chatcmpl-56f3c9e7-5458-4e99-8a79-bdc5e8e9fe7f"
$ grep -c '"reasoning_content"\|"annotations"' chat-annotations-2.sse
0
$ shape chat-annotations-2.sse
      1 [["content","role"],null]
      8 [["content"],null]
      1 [[],"stop"]

Chat, audio answer

Steps
  1. First call, saved to a file
$ curl -sN http://localhost:25917/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"gpt-audio-1.5","stream":true,"modalities":["text","audio"],"audio":{"voice":"alloy","format":"pcm16"},"messages":[{"role":"user","content":"Say hello in three words. (qa round 9)"}]}' > chat-audio-1.sse
$ grep -o '"id":"chatcmpl-[^"]*"' chat-audio-1.sse | sort -u
"id":"chatcmpl-EeMYeJmZtbmo6K0B6LT2qmW69mUNI"
$ grep -c '"audio":{' chat-audio-1.sse
11
  1. The same curl again into chat-audio-2.sse comes back from the cache with the same id and no audio at all
$ grep -o '"id":"chatcmpl-[^"]*"' chat-audio-2.sse | sort -u
"id":"chatcmpl-EeMYeJmZtbmo6K0B6LT2qmW69mUNI"
$ grep -c '"audio":{' chat-audio-2.sse
0
$ shape chat-audio-2.sse
      1 [["content","role"],null]
      1 [[],"stop"]

Responses, Claude reasoning

Steps
  1. First call, saved to a file
$ curl -sN http://localhost:25917/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-5-5","stream":true,"reasoning":{"effort":"high","summary":"auto"},"input":"How many primes are there between 2000 and 2100? Work it out, then give only the count. (qa round 9)"}' > responses-reasoning-1.sse
$ grep -c 'response.reasoning_summary_text.delta' responses-reasoning-1.sse
18
  1. The same curl again twice, the third time with -D responses-reasoning-3.headers. Both repeats cost nothing and come back in milliseconds, so they came from the cache, and neither carries a reasoning summary
$ grep -c 'response.reasoning_summary_text.delta' responses-reasoning-2.sse
0
$ grep -c 'response.reasoning_summary_text.delta' responses-reasoning-3.sse
0
$ tr -d '\r' < responses-reasoning-3.headers | grep -iE '^x-litellm-(response-cost-original|response-duration-ms):'
x-litellm-response-cost-original: 0.0
x-litellm-response-duration-ms: 29.16407585144043

Chat, reasoning and tool call

Steps
  1. First call, saved to a file, streams the reasoning, then the text, then the tool call
$ curl -sN http://localhost:25917/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-5-5","stream":true,"reasoning_effort":"high","tools":[{"type":"function","function":{"name":"get_weather","description":"Get the current weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}],"messages":[{"role":"user","content":"Work out how many primes there are between 2000 and 2100, give the count in one sentence, then check the weather in Paris. (qa round 9)"}]}' > chat-tool-1.sse
$ grep -o '"id":"chatcmpl-[^"]*"' chat-tool-1.sse | sort -u
"id":"chatcmpl-a80c4994-41ce-49b9-b58c-196970c60000"
$ shape chat-tool-1.sse
      1 [["content","provider_specific_fields","reasoning_content","role","thinking_blocks"],null]
     16 [["content","provider_specific_fields","reasoning_content","thinking_blocks"],null]
     13 [["content"],null]
      5 [["content","tool_calls"],null]
      1 [[],"tool_calls"]
  1. The same curl again into chat-tool-2.sse is a cache hit with the same id, no reasoning, and the tool call on the first text chunk
$ grep -o '"id":"chatcmpl-[^"]*"' chat-tool-2.sse | sort -u
"id":"chatcmpl-a80c4994-41ce-49b9-b58c-196970c60000"
$ shape chat-tool-2.sse
      1 [["content","provider_specific_fields","role","tool_calls"],null]
     29 [["content"],null]
      1 [[],"tool_calls"]

Responses, reasoning and tool call

Steps
  1. First call, saved to a file with its headers
$ curl -sN http://localhost:25917/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-5-5","stream":true,"reasoning":{"effort":"high","summary":"auto"},"tools":[{"type":"function","name":"get_weather","description":"Get the current weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}],"input":"Work out how many primes there are between 2000 and 2100, give the count in one sentence, then check the weather in Paris. (qa round 9)"}' -D responses-tool-1.headers > responses-tool-1.sse
$ grep '^data: {' responses-tool-1.sse | cut -c7- | jq -r 'select(.type=="response.output_item.added") | .item.type' | paste -sd' '
reasoning message function_call
$ tr -d '\r' < responses-tool-1.headers | grep -iE '^x-litellm-response-duration-ms:'
x-litellm-response-duration-ms: 672.6150512695312
  1. The same curl again twice into responses-tool-2.sse and responses-tool-3.sse. Both come back in milliseconds from the cache, without the reasoning item
$ grep '^data: {' responses-tool-2.sse | cut -c7- | jq -r 'select(.type=="response.output_item.added") | .item.type' | paste -sd' '
message function_call
$ grep '^data: {' responses-tool-3.sse | cut -c7- | jq -r 'select(.type=="response.output_item.added") | .item.type' | paste -sd' '
message function_call
$ tr -d '\r' < responses-tool-3.headers | grep -iE '^x-litellm-response-duration-ms:'
x-litellm-response-duration-ms: 49.870967864990234

Chat, tool only

Steps
  1. First call, saved to a file with its headers, streams the reasoning, then the tool call
$ curl -sN http://localhost:25917/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -D chat-toolonly-1.headers -d '{"model":"claude-sonnet-5-5","stream":true,"reasoning_effort":"high","tools":[{"type":"function","function":{"name":"get_weather","description":"Get the current weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}],"messages":[{"role":"user","content":"Work out which of Paris, Lyon, Marseille and Toulouse has the most letters, then check the weather there. Reply only with the tool call and write no text. (qa round 9)"}]}' > chat-toolonly-1.sse
$ shape chat-toolonly-1.sse
      1 [["content","provider_specific_fields","reasoning_content","role","thinking_blocks"],null]
      8 [["content","provider_specific_fields","reasoning_content","thinking_blocks"],null]
      5 [["content","tool_calls"],null]
      1 [[],"tool_calls"]
  1. The same curl again into chat-toolonly-2.sse is a cache hit with the same id, with no reasoning at all
$ grep -ho '"id":"chatcmpl-[^"]*"' chat-toolonly-1.sse chat-toolonly-2.sse | sort -u
"id":"chatcmpl-1476268b-fc21-43f4-a185-8b142eeedced"
$ shape chat-toolonly-2.sse
      1 [["content","provider_specific_fields","role","tool_calls"],null]
      1 [[],"tool_calls"]
$ tr -d '\r' < chat-toolonly-2.headers | grep -iE '^x-litellm-response-duration-ms:'
x-litellm-response-duration-ms: 12.588977813720703

SDK sync stream

Steps

litellm.completion(stream=True) with an in-memory cache serves hits through the sync path. sdk.py streams one prompt twice, and the second call is the hit. With text, the hit sends the tool call on its first chunk. Without text, it sends the reasoning and the tool call together

import hashlib
import sys

import litellm
from litellm.caching.caching import Cache

litellm.cache = Cache()
TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a city",
            "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
        },
    }
]
ASK = sys.argv[1]

for call in (1, 2):
    stream = litellm.completion(
        model="anthropic/claude-sonnet-5-5",
        messages=[{"role": "user", "content": ASK}],
        tools=TOOLS,
        reasoning_effort="high",
        stream=True,
    )
    shapes, reasoning, text, args = [], "", "", ""
    for chunk in stream:
        choice = chunk.choices[0]
        keys = sorted(k for k, v in choice.delta.model_dump(exclude_none=True).items() if v not in ("", [], {}))
        shape = f"{keys} finish={choice.finish_reason}" if choice.finish_reason else str(keys)
        if shapes and shapes[-1][1] == shape:
            shapes[-1][0] += 1
        else:
            shapes.append([1, shape])
        reasoning += getattr(choice.delta, "reasoning_content", None) or ""
        text += choice.delta.content or ""
        args += "".join(tc.function.arguments or "" for tc in getattr(choice.delta, "tool_calls", None) or [])
    print(f"== call {call} cache_hit={stream._hidden_params.get('cache_hit')}")
    for count, shape in shapes:
        print(f"  {count} x {shape}")
    print(f"  reasoning sha256={hashlib.sha256(reasoning.encode()).hexdigest()[:16]} ({len(reasoning)} chars)")
    print(f"  text={text!r}")
    print(f"  tool args={args!r}")
$ python sdk.py 'Work out how many primes there are between 2000 and 2100, give the count in one sentence, then check the weather in Paris. (qa round 9 sdk)'
== call 1 cache_hit=None
  1 x ['provider_specific_fields', 'reasoning_content', 'role', 'thinking_blocks']
  11 x ['provider_specific_fields', 'reasoning_content', 'thinking_blocks']
  1 x ['provider_specific_fields', 'thinking_blocks']
  14 x ['content']
  5 x ['tool_calls']
  1 x [] finish=tool_calls
  reasoning sha256=1552c1128f2ecb4c (136 chars)
  text="There are 14 primes between 2000 and 2100: 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089 and 2099.\n\nNext, I'll check the weather in Paris."
  tool args='{"city": "Paris"}'
== call 2 cache_hit=True
  1 x ['content', 'provider_specific_fields', 'reasoning_content', 'role', 'thinking_blocks', 'tool_calls']
  29 x ['content']
  1 x [] finish=tool_calls
  reasoning sha256=1552c1128f2ecb4c (136 chars)
  text="There are 14 primes between 2000 and 2100: 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089 and 2099.\n\nNext, I'll check the weather in Paris."
  tool args='{"city": "Paris"}'
$ python sdk.py 'Work out which of Paris, Lyon, Marseille and Toulouse has the most letters, then check the weather there. Reply only with the tool call and write no text. (qa round 9 sdk)'
== call 1 cache_hit=None
  1 x ['provider_specific_fields', 'reasoning_content', 'role', 'thinking_blocks']
  7 x ['provider_specific_fields', 'reasoning_content', 'thinking_blocks']
  1 x ['provider_specific_fields', 'thinking_blocks']
  5 x ['tool_calls']
  1 x [] finish=tool_calls
  reasoning sha256=1dab1ce3252dc601 (96 chars)
  text=''
  tool args='{"city": "Marseille"}'
== call 2 cache_hit=True
  1 x ['provider_specific_fields', 'reasoning_content', 'role', 'thinking_blocks', 'tool_calls']
  1 x [] finish=tool_calls
  reasoning sha256=1dab1ce3252dc601 (96 chars)
  text=''
  tool args='{"city": "Marseille"}'

Chat, blank text and tool

Steps
  1. First call streams the reasoning, a blank text chunk, then the tool call
$ curl -sN http://localhost:25917/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -D chat-blank-1.headers -d '{"model":"claude-sonnet-5-5","stream":true,"reasoning_effort":"high","tools":[{"type":"function","function":{"name":"get_weather","description":"Get the current weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}],"messages":[{"role":"user","content":"Work out which of Paris, Lyon, Marseille and Toulouse has the most letters, then check the weather there. Your visible text before the tool call must be exactly two newline characters and nothing else. (qa round 9)"}]}' > chat-blank-1.sse
$ shape chat-blank-1.sse
      1 [["content","provider_specific_fields","reasoning_content","role","thinking_blocks"],null]
     11 [["content","provider_specific_fields","reasoning_content","thinking_blocks"],null]
      1 [["content"],null]
      5 [["content","tool_calls"],null]
      1 [[],"tool_calls"]
$ grep '^data: {' chat-blank-1.sse | cut -c7- | jq -s -c '{text: ([.[].choices[0].delta.content // empty] | join("")), reasoning: ([.[].choices[0].delta.reasoning_content // empty] | join("") | length)}'
{"text":" ","reasoning":124}
  1. The same curl again into chat-blank-2.sse is a cache hit with the same id, with the blank text but no reasoning
$ grep -ho '"id":"chatcmpl-[^"]*"' chat-blank-1.sse chat-blank-2.sse | sort -u
"id":"chatcmpl-7557a50a-a78d-43e4-a5f0-d8a2312d1224"
$ shape chat-blank-2.sse
      1 [["content","provider_specific_fields","role","tool_calls"],null]
      1 [[],"tool_calls"]
$ grep '^data: {' chat-blank-2.sse | cut -c7- | jq -s -c '{text: ([.[].choices[0].delta.content // empty] | join("")), reasoning: ([.[].choices[0].delta.reasoning_content // empty] | join("") | length)}'
{"text":" ","reasoning":0}

After (d6fdf73)

Chat, Claude reasoning

  1. First call, saved to a file
$ curl -sN http://localhost:26917/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-5-5","stream":true,"reasoning_effort":"high","messages":[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"How many primes are there between 2000 and 2100? Work it out, then give only the count. (qa round 9)"}]}' > chat-reasoning-1.sse
$ grep -o '"id":"chatcmpl-[^"]*"' chat-reasoning-1.sse | sort -u
"id":"chatcmpl-1528d30b-ea50-4d4f-ae70-fa6e28519851"
  1. The same curl again into chat-reasoning-2.sse is a cache hit with the same id, with the reasoning and signed blocks first
$ grep -o '"id":"chatcmpl-[^"]*"' chat-reasoning-2.sse | sort -u
"id":"chatcmpl-1528d30b-ea50-4d4f-ae70-fa6e28519851"
$ shape chat-reasoning-2.sse
      1 [["provider_specific_fields","reasoning_content","role","thinking_blocks"],null]
      1 [["content"],null]
      1 [[],"stop"]
$ grep -o '"signature":"[^"]\{16\}' chat-reasoning-1.sse chat-reasoning-2.sse
chat-reasoning-1.sse:"signature":"CAQSjgYKEAgTGAI4
chat-reasoning-1.sse:"signature":"CAQSjgYKEAgTGAI4
chat-reasoning-2.sse:"signature":"CAQSjgYKEAgTGAI4
chat-reasoning-2.sse:"signature":"CAQSjgYKEAgTGAI4

Chat, web search

Steps
  1. First call, saved to a file
$ curl -sN http://localhost:26917/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"gpt-5-search-api","stream":true,"web_search_options":{},"messages":[{"role":"user","content":"What is the latest LiteLLM release on GitHub? Answer in one sentence and cite the page. (qa round 9)"}]}' > chat-annotations-1.sse
$ grep -o '"id":"chatcmpl-[^"]*"' chat-annotations-1.sse | sort -u
"id":"chatcmpl-1561d96e-2106-451a-ac27-e075fbbc4b80"
"id":"chatcmpl-448395d6-ae1a-4830-aba8-d5429b5b5b97"
"id":"chatcmpl-83a126b4-d494-4276-9f1b-56d997c81f04"
$ grep -c '"reasoning_content"\|"annotations"' chat-annotations-1.sse
1
  1. The same curl again, saved to chat-annotations-2.sse. It answers from the cache, and its last text chunk carries the url_citation
$ grep -o '"id":"chatcmpl-[^"]*"' chat-annotations-2.sse | sort -u
"id":"chatcmpl-1561d96e-2106-451a-ac27-e075fbbc4b80"
$ grep -c '"reasoning_content"\|"annotations"' chat-annotations-2.sse
1
$ shape chat-annotations-2.sse
      1 [["content","role"],null]
     15 [["content"],null]
      1 [["annotations","content"],null]
      1 [[],"stop"]

Chat, audio answer

Steps
  1. First call, saved to a file
$ curl -sN http://localhost:26917/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"gpt-audio-1.5","stream":true,"modalities":["text","audio"],"audio":{"voice":"alloy","format":"pcm16"},"messages":[{"role":"user","content":"Say hello in three words. (qa round 9)"}]}' > chat-audio-1.sse
$ grep -o '"id":"chatcmpl-[^"]*"' chat-audio-1.sse | sort -u
"id":"chatcmpl-EeN2KNEUIpAYbnl8RAqNyD9iVWrpH"
$ grep -c '"audio":{' chat-audio-1.sse
10
$ grep '^data: {' chat-audio-1.sse | cut -c7- | jq -r '.choices[0].delta.audio.data // empty' | tr -d '\n' | wc -c
92800
  1. The same curl again into chat-audio-2.sse comes back from the cache with the same id, and one chunk carries all of the first call's audio with its transcript
$ grep -o '"id":"chatcmpl-[^"]*"' chat-audio-2.sse | sort -u
"id":"chatcmpl-EeN2KNEUIpAYbnl8RAqNyD9iVWrpH"
$ shape chat-audio-2.sse
      1 [["audio","role"],null]
      1 [[],"stop"]
$ grep '^data: {' chat-audio-2.sse | cut -c7- | jq -r 'select(.choices[0].delta.audio) | .choices[0].delta.audio | [.id, (.data|length), .transcript] | @tsv'
audio_6ae3708c7ccc8191926b9dbfe4e7d0c4	92800	Hi there, friend!

Responses, Claude reasoning

Steps
  1. First call, saved to a file
$ curl -sN http://localhost:26917/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-5-5","stream":true,"reasoning":{"effort":"high","summary":"auto"},"input":"How many primes are there between 2000 and 2100? Work it out, then give only the count. (qa round 9)"}' > responses-reasoning-1.sse
$ grep -c 'response.reasoning_summary_text.delta' responses-reasoning-1.sse
21
  1. The same curl again twice, the third time with -D responses-reasoning-3.headers. Both repeats cost nothing and come back in milliseconds, so they came from the cache, and each carries the whole reasoning summary in one delta
$ grep -c 'response.reasoning_summary_text.delta' responses-reasoning-2.sse
1
$ grep -c 'response.reasoning_summary_text.delta' responses-reasoning-3.sse
1
$ tr -d '\r' < responses-reasoning-3.headers | grep -iE '^x-litellm-(response-cost-original|response-duration-ms):'
x-litellm-response-cost-original: 0.0
x-litellm-response-duration-ms: 174.22890663146973

Chat, reasoning and tool call

Steps
  1. First call, saved to a file, streams the reasoning, then the text, then the tool call
$ curl -sN http://localhost:26917/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-5-5","stream":true,"reasoning_effort":"high","tools":[{"type":"function","function":{"name":"get_weather","description":"Get the current weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}],"messages":[{"role":"user","content":"Work out how many primes there are between 2000 and 2100, give the count in one sentence, then check the weather in Paris. (qa round 9)"}]}' > chat-tool-1.sse
$ grep -o '"id":"chatcmpl-[^"]*"' chat-tool-1.sse | sort -u
"id":"chatcmpl-9538c52a-33ae-434c-b7b2-3602d52807f7"
$ shape chat-tool-1.sse
      1 [["content","provider_specific_fields","reasoning_content","role","thinking_blocks"],null]
     18 [["content","provider_specific_fields","reasoning_content","thinking_blocks"],null]
     12 [["content"],null]
      5 [["content","tool_calls"],null]
      1 [[],"tool_calls"]
  1. The same curl again into chat-tool-2.sse is a cache hit with the same id, sending the reasoning, then the text, then the tool call
$ grep -o '"id":"chatcmpl-[^"]*"' chat-tool-2.sse | sort -u
"id":"chatcmpl-9538c52a-33ae-434c-b7b2-3602d52807f7"
$ shape chat-tool-2.sse
      1 [["provider_specific_fields","reasoning_content","role","thinking_blocks"],null]
     30 [["content"],null]
      1 [["tool_calls"],null]
      1 [[],"tool_calls"]

Responses, reasoning and tool call

Steps
  1. First call, saved to a file with its headers
$ curl -sN http://localhost:26917/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"claude-sonnet-5-5","stream":true,"reasoning":{"effort":"high","summary":"auto"},"tools":[{"type":"function","name":"get_weather","description":"Get the current weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}],"input":"Work out how many primes there are between 2000 and 2100, give the count in one sentence, then check the weather in Paris. (qa round 9)"}' -D responses-tool-1.headers > responses-tool-1.sse
$ grep '^data: {' responses-tool-1.sse | cut -c7- | jq -r 'select(.type=="response.output_item.added") | .item.type' | paste -sd' '
reasoning message function_call
$ tr -d '\r' < responses-tool-1.headers | grep -iE '^x-litellm-response-duration-ms:'
x-litellm-response-duration-ms: 867.487907409668
  1. The same curl again twice into responses-tool-2.sse and responses-tool-3.sse. Both come back in milliseconds from the cache, with the reasoning item first like the live answer
$ grep '^data: {' responses-tool-2.sse | cut -c7- | jq -r 'select(.type=="response.output_item.added") | .item.type' | paste -sd' '
reasoning message function_call
$ grep '^data: {' responses-tool-3.sse | cut -c7- | jq -r 'select(.type=="response.output_item.added") | .item.type' | paste -sd' '
reasoning message function_call
$ tr -d '\r' < responses-tool-3.headers | grep -iE '^x-litellm-response-duration-ms:'
x-litellm-response-duration-ms: 73.2109546661377

Chat, tool only

Steps
  1. First call, saved to a file with its headers, streams the reasoning, then the tool call
$ curl -sN http://localhost:26917/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -D chat-toolonly-1.headers -d '{"model":"claude-sonnet-5-5","stream":true,"reasoning_effort":"high","tools":[{"type":"function","function":{"name":"get_weather","description":"Get the current weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}],"messages":[{"role":"user","content":"Work out which of Paris, Lyon, Marseille and Toulouse has the most letters, then check the weather there. Reply only with the tool call and write no text. (qa round 9)"}]}' > chat-toolonly-1.sse
$ shape chat-toolonly-1.sse
      1 [["content","provider_specific_fields","reasoning_content","role","thinking_blocks"],null]
      8 [["content","provider_specific_fields","reasoning_content","thinking_blocks"],null]
      5 [["content","tool_calls"],null]
      1 [[],"tool_calls"]
  1. The same curl again into chat-toolonly-2.sse is a cache hit with the same id, sending the reasoning, then the tool call
$ grep -ho '"id":"chatcmpl-[^"]*"' chat-toolonly-1.sse chat-toolonly-2.sse | sort -u
"id":"chatcmpl-3fbced4f-c946-4651-baf5-1f225e33baad"
$ shape chat-toolonly-2.sse
      1 [["provider_specific_fields","reasoning_content","role","thinking_blocks"],null]
      1 [["tool_calls"],null]
      1 [[],"tool_calls"]
$ tr -d '\r' < chat-toolonly-2.headers | grep -iE '^x-litellm-response-duration-ms:'
x-litellm-response-duration-ms: 35.55893898010254

SDK sync stream

Steps

The same sdk.py. Both hits send the reasoning first and the tool call last, like the first call

$ python sdk.py 'Work out how many primes there are between 2000 and 2100, give the count in one sentence, then check the weather in Paris. (qa round 9 sdk)'
== call 1 cache_hit=None
  1 x ['provider_specific_fields', 'reasoning_content', 'role', 'thinking_blocks']
  6 x ['provider_specific_fields', 'reasoning_content', 'thinking_blocks']
  1 x ['provider_specific_fields', 'thinking_blocks']
  14 x ['content']
  5 x ['tool_calls']
  1 x [] finish=tool_calls
  reasoning sha256=bd81d77936adec1c (102 chars)
  text="There are 14 primes between 2000 and 2100: 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089 and 2099.\n\nNext, I'll check the weather in Paris."
  tool args='{"city": "Paris"}'
== call 2 cache_hit=True
  1 x ['provider_specific_fields', 'reasoning_content', 'role', 'thinking_blocks']
  30 x ['content']
  1 x ['tool_calls']
  1 x [] finish=tool_calls
  reasoning sha256=bd81d77936adec1c (102 chars)
  text="There are 14 primes between 2000 and 2100: 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089 and 2099.\n\nNext, I'll check the weather in Paris."
  tool args='{"city": "Paris"}'
$ python sdk.py 'Work out which of Paris, Lyon, Marseille and Toulouse has the most letters, then check the weather there. Reply only with the tool call and write no text. (qa round 9 sdk)'
== call 1 cache_hit=None
  1 x ['provider_specific_fields', 'reasoning_content', 'role', 'thinking_blocks']
  6 x ['provider_specific_fields', 'reasoning_content', 'thinking_blocks']
  1 x ['provider_specific_fields', 'thinking_blocks']
  5 x ['tool_calls']
  1 x [] finish=tool_calls
  reasoning sha256=c8dea27298f1fd7a (79 chars)
  text=''
  tool args='{"city": "Marseille"}'
== call 2 cache_hit=True
  1 x ['provider_specific_fields', 'reasoning_content', 'role', 'thinking_blocks']
  1 x ['tool_calls']
  1 x [] finish=tool_calls
  reasoning sha256=c8dea27298f1fd7a (79 chars)
  text=''
  tool args='{"city": "Marseille"}'

Chat, blank text and tool

Steps
  1. First call streams the reasoning, a blank text chunk, then the tool call
$ curl -sN http://localhost:26917/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -D chat-blank-1.headers -d '{"model":"claude-sonnet-5-5","stream":true,"reasoning_effort":"high","tools":[{"type":"function","function":{"name":"get_weather","description":"Get the current weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}],"messages":[{"role":"user","content":"Work out which of Paris, Lyon, Marseille and Toulouse has the most letters, then check the weather there. Your visible text before the tool call must be exactly two newline characters and nothing else. (qa round 9)"}]}' > chat-blank-1.sse
$ shape chat-blank-1.sse
      1 [["content","provider_specific_fields","reasoning_content","role","thinking_blocks"],null]
     10 [["content","provider_specific_fields","reasoning_content","thinking_blocks"],null]
      1 [["content"],null]
      5 [["content","tool_calls"],null]
      1 [[],"tool_calls"]
$ grep '^data: {' chat-blank-1.sse | cut -c7- | jq -s -c '{text: ([.[].choices[0].delta.content // empty] | join("")), reasoning: ([.[].choices[0].delta.reasoning_content // empty] | join("") | length)}'
{"text":" ","reasoning":102}
  1. The same curl again into chat-blank-2.sse is a cache hit with the same id, with the reasoning, the blank text, then the call
$ grep -ho '"id":"chatcmpl-[^"]*"' chat-blank-1.sse chat-blank-2.sse | sort -u
"id":"chatcmpl-46beead2-c6ad-407f-b32d-4e840bc4a5cd"
$ shape chat-blank-2.sse
      1 [["provider_specific_fields","reasoning_content","role","thinking_blocks"],null]
      1 [["content"],null]
      1 [["tool_calls"],null]
      1 [[],"tool_calls"]
$ grep '^data: {' chat-blank-2.sse | cut -c7- | jq -s -c '{text: ([.[].choices[0].delta.content // empty] | join("")), reasoning: ([.[].choices[0].delta.reasoning_content // empty] | join("") | length)}'
{"text":" ","reasoning":102}

Observations from the run

  • OpenAI's own stream mixes chunk ids, same on both legs

Type

Bug Fix

Test

Caveats (if any)

Low

  • Interleaved thinking replays before all text, since the cache keeps one block list

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR
Bugbot summary

[!NOTE]
Medium Risk
Changes how all streamed cache hits are chunked and ordered in a widely used conversion path, though behavior is heavily covered by new tests.

Overview
When stream=True hits the response cache, LiteLLM replays the cached completion as multiple SSE chunks. This PR replaces the old “slice content only” replay with shared _replay_deltas / _replay_frames logic used by both sync and async converters.

Replay order now mirrors a live stream: reasoning/thinking (and role) first, word-shaped content slices next, annotations on the last text chunk, tool_calls after text, then a separate empty-delta frame carrying finish_reason and usage. Fields like audio, images, and provider-specific data ride the appropriate frames instead of being stripped or duplicated on every slice.

Unit tests and a new integration suite assert ordering for reasoning, citations, audio, tool-only turns, and whitespace-only text. Test helpers get minor Redis[bytes] typing.

Reviewed by Cursor Bugbot for commit d6fdf73. Bugbot is set up for automated code reviews on this repo. Configure here.

@greptile-apps

greptile-apps Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] Refactors how cached streaming responses replay reasoning and metadata.

Core streaming behavior changes for all cache hits, but the new sequencing matches live stream order and is heavily tested with both unit and integration coverage

Summary

Fixes streamed response cache hits to preserve reasoning, citations, audio, and tool calls that were previously dropped or reordered. Refactors replay logic to emit deltas in live-stream order: reasoning first, then word-sliced content, then tool calls, with a final finish frame carrying usage.

Major changes:

  • Replaces single-chunk cache replay with _replay_deltas / _replay_frames that sequence reasoning → text → tools → finish across multiple frames
  • Moves annotations to last text chunk, tool calls after all text, usage to finish frame only
  • Preserves whitespace-only content between reasoning and tools, handles no-content responses (audio-only, tool-only)
  • Comprehensive test coverage: integration tests against Redis + mocked upstream, unit tests for edge cases and CustomStreamWrapper

Reviews (6) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile

@codecov

codecov Bot commented Jul 4, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@jesco-absolut
jesco-absolut force-pushed the litellm_fix_streaming_cache_reasoning branch from df9e379 to 33f60b6 Compare August 9, 2026 06:19
@codspeed

codspeed Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 2 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 38 untouched benchmarks


Comparing jesco-absolut:litellm_fix_streaming_cache_reasoning (d6fdf73) with main (c98641f)

Open in CodSpeed

@yuneng-berri
yuneng-berri deleted the branch BerriAI:main September 13, 2026 04:28
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 15:52
@devin-ai-integration
devin-ai-integration Bot requested a review from a team September 23, 2026 15:52
@jesco-absolut
jesco-absolut force-pushed the litellm_fix_streaming_cache_reasoning branch from 33f60b6 to 0811d06 Compare October 10, 2026 07:06
Resolve the conflict with main's _first_replay_delta by validating the whole
cached message into the first replayed Delta, keeping main's guard that drops a
cached provider_specific_fields that is not an object. The replay now carries
reasoning_content, thinking_blocks, and annotations like the sync replay does.

Extend the regression test to cover annotations on the first replayed chunk.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

… stream order

A cached answer replayed as a stream now ends with its own empty finish chunk, so a chunk that
carries only audio or images keeps its payload and role. Reasoning fields lead on a chunk with no
text, and annotations arrive once on the last text slice, matching a live stream's order.
@mateo-berri mateo-berri changed the title fix(proxy): preserve reasoning fields on streaming cache hits fix(caching): keep reasoning, citations, and audio on streamed cache hits Oct 29, 2026
…tream

Only the role, reasoning fields and provider fields lead a replayed answer. Tool calls now arrive on
their own chunk after the last text slice, and logprobs ride the first text chunk, so a cached
answer with reasoning and a tool call keeps a live stream's reasoning, text, tool call order.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

… no text

A cached answer that thinks and then only calls a tool now replays its reasoning on its own chunk before the
tool call, the order a live stream sends, instead of one chunk carrying both.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…h reasoning

A cached answer that thinks, sends only whitespace as text, and then calls a tool now replays that whitespace
between the reasoning and the tool call, instead of dropping it.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor 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.

Stale Bugbot comment from a previous run.

…_cache_reasoning

# Conflicts:
#	litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor 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.

Stale Bugbot comment from a previous run.

"provider_specific_fields": _cached_provider_specific_fields(
_CACHED_MESSAGE_PROVIDER_FIELDS.validate_python(message)
),
}

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.

Function calls dropped on cache replay

Medium Severity

_first_replay_delta and _replay_deltas now build frames with Delta.model_validate, which skips Delta.__init__. Legacy function_call therefore stays a raw dict. CustomStreamWrapper then reads .arguments on that value, catches the error, and replaces the delta with an empty one, so a streamed cache hit loses the call.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d6fdf73. Configure here.

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.

Checked at d6fdf73. Delta.model_validate coerces the dict into FunctionCall, and a cached function_call streams through CustomStreamWrapper intact with finish_reason function_call

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor 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.

✅ Bugbot reviewed your changes and found no new issues!

1 issue from previous review remains unresolved.

Fix All in Cursor

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit d6fdf73. Configure here.

@mateo-berri mateo-berri 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.

LGTM. Thanks for the contribution!

@mateo-berri
mateo-berri merged commit 3057c47 into BerriAI:main Oct 29, 2026
95 of 97 checks passed
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]: reasoning_content lost on streaming cache hit; FIX included

3 participants