Repository navigation
fix(anthropic): replay OpenAI encrypted reasoning byte for byte through the /v1/messages bridge - #40451
Conversation
…d /v1/messages Reasoning items the Responses API returned for a /v1/messages turn were rebuilt from their summary text on every replay, so the prompt the model saw changed between turns and the prompt cache never matched. The bridge now asks for reasoning.encrypted_content, carries it in the thinking signature (or as a redacted_thinking block when there is no summary), and replays it verbatim as the reasoning item's encrypted_content. Anthropic replay paths drop those tagged blocks so a cross-model resume never forwards OpenAI bytes to Anthropic
…rm, not the empty-block pass
🤖 Devin AI EngineerI'll be helping with this pull request! Here's what you should know: ✅ I will automatically:
Note: I can only respond to comments from users who have write access to this repository. ⚙️ Control Options:
|
Greptile SummaryThis PR carries OpenAI encrypted reasoning through the Anthropic Messages bridge, replays it across turns, and adds deployment affinity and cross-provider sanitization
Confidence Score: 4/5The PR is not yet safe to merge because cross-group OpenAI routing can discard readable reasoning context, and a repository typing requirement remains unmet The cross-group affinity path unconditionally removes complete bridge-tagged blocks, even when the destination is another OpenAI Responses deployment that can retain their readable text as summary-only reasoning. The new Anthropic sanitization helpers also violate the repository’s strong-typing requirement. The prior affinity finding is no longer outstanding because its thread was resolved and the current code reads the callback’s messages argument Files Needing Attention: litellm/litellm_core_utils/prompt_templates/common_utils.py, litellm/llms/anthropic/common_utils.py
|
| Filename | Overview |
|---|---|
| litellm/litellm_core_utils/prompt_templates/common_utils.py | Adds encrypted-reasoning encoding and replay helpers, but cross-group stripping now unnecessarily discards readable summaries |
| litellm/router_utils/pre_call_checks/encrypted_content_affinity_check.py | Extends affinity detection to Messages history and strips unusable reasoning when the origin is outside the routed group |
| litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py | Translates encrypted Responses reasoning into replayable Anthropic block shapes and restores each item on subsequent requests |
| litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py | Emits summary separators, encrypted signature deltas, and redacted-thinking blocks for streamed reasoning |
| litellm/llms/anthropic/common_utils.py | Adds foreign-reasoning sanitization for Anthropic requests, but introduces coarse dictionary parameter types forbidden by repository guidance |
Reviews (6): Last reviewed commit: "fix(router): drop bridge-tagged reasonin..." | Re-trigger Greptile
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Devin e2e QATested at: f49ebc9 Setup shared by both legs: the same config as the PR description ( Three prompts typed into Claude Code, one turn each: the five-houses zebra puzzle ("Do not use any tools. Solve this in your head and answer briefly. Five houses in a row ... Who drinks water, and who owns the zebra?"), then "No tools. Which house colour does the zebra owner live in, and who is their left-hand neighbour? One line.", then "No tools. And who smokes Kools? One line." In the upstream logs below, request #1 is a smoke curl with Before (075655c)Claude Code, three turns on gpt-5.1
No request asks for
Turn two's response reached Claude Code with no thinking block at all because its reasoning item had no summary
Cross-model replay to claude-sonnet-4-6The assistant turn carries the
The proxy log shows Anthropic first answered
After (f49ebc9)Claude Code, three turns on gpt-5.1
Every request carries
Cross-model replay to claude-sonnet-4-6Same two payloads as the Before leg
One request to Anthropic, no
Observations from the run The bridge replays every reasoning item with |
…provider returns it The bridge now asks for reasoning.encrypted_content whenever the provider's Responses config lists include, independent of the client's thinking block, and leaves it out for providers such as Perplexity that reject the param. Bridge-tagged blocks are stripped on the chat adapter path too, so a mid session model switch to Gemini or Bedrock no longer forwards them as real signatures, a bare prefix counts as bridge-tagged, and non-mapping messages pass through the strip untouched.
…t that minted it The encrypted_content_affinity check only read the pin from the Responses input, which /v1/messages builds after the router has picked a deployment, so a model group spread across OpenAI orgs sent follow-up turns to the wrong org and got invalid_encrypted_content back. The check now also decodes the pin from bridge-tagged thinking and redacted_thinking blocks in the Anthropic messages. The bridge also keeps a deployment's own include list next to reasoning.encrypted_content instead of replacing it.
…itellm_responses_bridge_replay_encrypted_reasoning # Conflicts: # litellm/router_utils/pre_call_checks/encrypted_content_affinity_check.py # tests/test_litellm/router_utils/pre_call_checks/test_encrypted_content_affinity_check.py
…ip bridge reasoning on a cross-group route The encrypted_content_affinity check only read the Anthropic history from request_kwargs["messages"], so a caller that passes it through the callback's messages argument alone skipped the pin. Read the argument first and fall back to the kwargs. When the minting deployment is not a candidate of the routed group, the base already strips the Responses input's encrypted reasoning; do the same for the bridge-tagged thinking blocks in Anthropic messages so the routed deployment gets the readable thinking text instead of ciphertext it cannot decrypt.
|
bugbot run |
…ng deployment is not in the routed group The cross-group branch of EncryptedContentAffinityCheck removed only the signature from Anthropic-shaped thinking blocks, which left unsigned thinking blocks that Anthropic and Bedrock reject (thinking.signature: Field required). Drop the whole block, the way #40280 drops undecryptable Responses input items, so the routed request carries the conversation text with no reasoning item for those turns
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 5a1be56. Configure here.
8ec2f00
into
litellm_internal_staging
TLDR
Problem this solves:
How it solves it:
include: ["reasoning.encrypted_content"]on every bridged Responses call to a provider whose Responses API returns it (OpenAI), with or without a clientthinkingblockencrypted_content_affinitycheck reads the pin from the replayed thinking block too, so a model group spread across OpenAI orgs keeps follow-ups on the org that minted the reasoninggpt-5.1-tier), the check drops the bridge-tagged blocks whole instead of forwarding reasoning the routed org cannot decrypt, the same way fix(router): strip encrypted reasoning on an auto-router tier change instead of a 503 #40280 drops undecryptable reasoning items from ResponsesinputUser Flow
Claude Code pointed at a LiteLLM proxy with
ANTHROPIC_MODEL=gpt-5.1(an OpenAI reasoning model behind the Anthropic Messages bridge), in a session with follow-up questionsBefore
The reasoning gpt-5.1 produced in turn one never comes back on turn two, so the prompt prefix is rebuilt from a lossy summary and the model gets thinking blocks with no signature
POST http://localhost:4000/v1/messageswithmodel: gpt-5.1,thinking: {type: adaptive},stream: true, and the first questionthinkingblock whosesignature_deltais empty; the reply text followsPOST http://localhost:4000/v1/messagesagain with the whole conversation, the earlierthinkingblock replayed withsignature: ""POST http://localhost:4000/v1/messagestoclaude-sonnet-4-6with that same conversation gets400 Invalid signature in thinking blockfrom Anthropic, and only an internal strip-everything retry turns it into a200with no thinking at allgpt-5.1load balanced across two OpenAI orgs andencrypted_content_affinityenabled, turn two lands on either org: there is no encrypted reasoning to pin on, and the check cannot read a pin off this route anywayPOST http://localhost:4000/v1/messagesreplaying that conversation withmodel: gpt-5.1-tier(a group on a third OpenAI org) goes through on the same lossy summary rebuild; nothing ties the conversation to the org that produced the reasoningAfter
The encrypted reasoning gpt-5.1 produced comes back on every later turn unchanged, and Claude Code shows it as a signed thinking block
POST http://localhost:4000/v1/messageswithmodel: gpt-5.1,thinking: {type: adaptive},stream: true, and the first questionthinkingblock whosesignature_deltaholds the encrypted reasoning (litellm_encrypted_reasoning:...), or aredacted_thinkingblock whosedataholds it when the model returned no summary; the reply text followsPOST http://localhost:4000/v1/messagesagain with the whole conversation, the earlier block replayed as Claude Code received itPOST http://localhost:4000/v1/messagestoclaude-sonnet-4-6(orgemini-3.8-flash) with that same conversation returns200on the first attempt, the bridge-tagged block dropped up front, and Anthropic answers with its own thinking blockgpt-5.1load balanced across two OpenAI orgs andencrypted_content_affinityenabled, turn two is pinned to the org that produced the reasoning (x-litellm-model-idmatches turn one every time), so OpenAI never sees encrypted reasoning minted by another orgPOST http://localhost:4000/v1/messagesreplaying that conversation withmodel: gpt-5.1-tier(a group on a third OpenAI org) returns200fromopenai-org-con the first attempt: the minting org is not a candidate in that group, so the check drops the bridge-tagged blocks the new org cannot decrypt and the routed request carries the conversation's text with no reasoning item for those turnsRelevant issues
Fixes #40288
Linear ticket
Resolves LIT-7339
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/test_litellm/<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@greptileaito re-request a review after pushing changes)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
Setup shared by both legs: the same proxy config, two uvicorn workers, a recording reverse proxy in front of
api.openai.comset as the OpenAIapi_baseso the bytes the proxy sends upstream can be diffed turn over turn, and Claude Code v2.1.266 driven interactively in tmux against the proxyPer leg: Before boots the proxy from a checkout of the merge base 075655c on port 28813, with the client recorder on 34517 and the OpenAI recorder on 41423; After boots it from the PR tip 5a1be56 on port 24754, with the client recorder on 30016 and the OpenAI recorder on 41554. The Before screenshot file is named after the PR head at the time it was uploaded (751431d), not the merge base the leg ran at; the After one is named after the tip it ran at. Claude Code auto-updated from 2.1.266 to 2.1.267 between the two legs
Three prompts typed into Claude Code, one turn each: the five-houses zebra puzzle ("Do not use any tools. Solve this in your head ..."), then "No tools. Which house colour does the zebra owner live in, and who is their left-hand neighbour? One line.", then "No tools. And who smokes Kools? One line."
Before (075655c)
Proxy on port 28813, booted from a checkout of the merge base
Claude Code, three turns on gpt-5.1
POST https://api.openai.com/v1/responseson each turn (one line per input item, reasoning items hashed)The proxy never asks for
reasoning.encrypted_content, so every response item's 2.8 to 5.6 KB of encrypted reasoning is dropped on the floor. What gets replayed is a fresh item rebuilt from the summary text (encrypted_content=None), and items that came back without a summary are not replayed at allPOST http://127.0.0.1:34517/v1/messagesCross-model replay to claude-sonnet-4-6
Take the conversation Claude Code built through the bridge (an assistant turn whose
thinkingblock carries the bridge signature) and send it to an Anthropic-backed model on the same proxyAnthropic first answered
400 messages.1.content.0: Invalid signature in thinking block(visible in the proxy log), then the existing invalid-signature retry stripped every thinking block and resent, which is why the200carries no thinking block at all despitethinking.type: enabledMulti-deployment replay pins to the minting deployment
Two
openai/gpt-5.1deployments in one model group, each on its own OpenAI org in production (here the same key twice, told apart bymodel_info.id), with the router'sencrypted_content_affinitycheck enabledTurn one, then the same follow-up replayed six times with turn one's thinking block as the client received it
Turn one's thinking block has no signature (nothing encrypted came back), so there is nothing to pin and the follow-ups spread across both deployments. With real encrypted reasoning in the replay (the After leg) and two different orgs, every replay that lands on the other org is a
400 invalid_encrypted_contentfrom OpenAI, and the affinity check that LiteLLM's own error text points at could not see the pin on this route because it only read the Responsesinput, which/v1/messagesbuilds after the router has already picked a deploymentAfter (5a1be56)
Every case below ran at the tip 5a1be56 against one proxy booted from that commit with two uvicorn workers on port 24754, with a client recorder on 30016 in front of it for the Claude Code leg and an OpenAI recorder on 41554 as the
api_baseof thegpt-5.1andgpt-5.1-tierdeployments. The Claude Code leg ran first and the curl cases after it, so the recorder numbers below continue from the Claude Code leg's. The config listsgpt-5.1(openai/gpt-5.1,drop_params: true),claude-sonnet-4-6,gemini-3.8-flash(gemini/gemini-3.8-flash),bedrock-sonnet-5(bedrock/us.anthropic.claude-sonnet-5),perplexity-sonar(perplexity/perplexity/sonar, nodrop_params), the two-deploymentgpt-5.1-hagroup (model_info.idopenai-org-aandopenai-org-b),gpt-5.1-tier(openai/gpt-5.1,model_info.id: openai-org-c),router_settings.optional_pre_call_checks: ["encrypted_content_affinity"], andlitellm_settings.reasoning_auto_summary: trueClaude Code, three turns on gpt-5.1
Re-run at 5a1be56: Claude Code v2.1.267 in tmux,
ANTHROPIC_BASE_URLpointing at a recorder on 30016 in front of the proxy on 24754 (two uvicorn workers),ANTHROPIC_MODEL=gpt-5.1, the same three prompts typed into the TUI as in the Before legPOST https://api.openai.com/v1/responseson each turnEvery request asks for the encrypted reasoning and every replayed item carries the exact bytes the model produced (the sha of each response item's
encrypted_content, taken from itsresponse.output_item.doneevent, reappears unchanged as the input item on every later turn), and OpenAI's cache covers the whole growing prefix:cached_tokens29568 of 30133 on turn two, 30080 of 30585 on turn three, 30464 of 30901 on the last request. The request the proxy sends is the same with or without a clientthinkingblock, since Claude Code sends one on every turn here; request #1 is the boot-time title request. Two of the four turns came back with no summary this run, so they travel asredacted_thinkingblocks belowPOST http://127.0.0.1:30016/v1/messagesEach turn's block carries the encrypted reasoning (the
litellm_encrypted_reasoning:payload plus the deployment wrapper, hence the length over the raw ciphertext) in thethinkingblock'ssignaturewhen OpenAI returned a summary and in aredacted_thinkingblock'sdatawhen it did not, and Claude Code replays every one of them untouched, both shapes side by side. The 4716b46 run of this leg had three signedthinkingblocks and a summary-less last turn; the e27a018 run had the summary-less turn firstMulti-deployment replay pins to the minting deployment
Two
openai/gpt-5.1deployments in one model group, each on its own OpenAI org in production (here the same key twice, told apart bymodel_info.id), with the router'sencrypted_content_affinitycheck enabledTurn one, then the same follow-up replayed six times with turn one's thinking block as the client received it
Turn one came back as a
thinkingblock whosesignaturecarries the encrypted reasoning wrapped with the minting deployment id, and all six replays are pinned toopenai-org-a. The proxy log shows the check doing it:EncryptedContentAffinityCheck: decoded model_id=openai-org-a from the request's encrypted content markersthenpinning -> deployment=openai-org-a, once per replay (six lines). The same case at e27a018 landed turn one onopenai-org-bas aredacted_thinkingblock (no summary that turn) and pinned all six replays there, so both block shapes carry the pinTool-use continuation on gpt-5.1
A tool call turn, then the
tool_resultcontinuation with the assistant's reasoning andtool_useblocks replayed as the client received them (the shape every agentic turn in Claude Code takes)On the OpenAI recorder, the continuation replays the reasoning item ahead of the tool call and its output, byte for byte the item turn one returned
(The 4716b46 run of this case returned turn one as a signed
thinkingblock with a 1784-char item and replayed it the same way)Auto-router tier change strips the other org's reasoning
The customer's auto-router can send a follow-up to a different model group than the turn that produced the reasoning. Here
gpt-5.1-tieris a third OpenAI org that never minted anything in the conversation, so the pin from turn one names a deployment that is not a candidateTurn one on
gpt-5.1-ha, then the follow-up replayed withmodel: gpt-5.1-tierand turn one's blocks as the client received themThe proxy log names the decision:
EncryptedContentAffinityCheck: model_id=openai-org-a is not a candidate for the routed group gpt-5.1-tier; forwarding without its encrypted reasoning. On the recorder, the request that reached org-c carries the three messages and no reasoning itemThe same replay built from a signed
thinkingblock with readable text (turn one of an earlier multi-deployment run: a 6569-char signature fromopenai-org-aover the text "Recalling clues for a puzzle ..."), withmax_tokens: 4096The signed text block is dropped whole too: nothing from turn one's reasoning reaches org-c, its text included, and the new org answers from the conversation text alone. At 4716b46 this replay kept the text as an unsigned
thinkingblock, which the OpenAI bridge turned into a summary-only reasoning item but Anthropic and Bedrock reject outright, the model-switch case nextMid-session model switch with the affinity check on
The same signed text turn from
openai-org-areplayed to an Anthropic, a Gemini, and a Bedrock deployment withencrypted_content_affinityenabled (the/modelswitch in Claude Code after a few OpenAI turns, on a proxy that also runs the multi-org group). This is the Bugbot finding on 4716b46: the check stripped the signature and left the text behind as an unsignedthinkingblockAt 4716b46 (the previous tip, proxy on 26604)
Anthropic's 200 there is the second attempt: the proxy log shows the 400 on the unsigned block and then
Anthropic /v1/messages: invalid thinking signature; stripping thinking blocks and retrying (attempt 2/2). Bedrock has no such retry and returns the 400 to the clientAt 5a1be56 (proxy on 24754)
All three answer on the first attempt with their own reasoning, and the proxy log has the three
not a candidate for the routed grouplines and no strip-and-retry lineCross-model replay to claude-sonnet-4-6, gemini-3.8-flash, and bedrock-sonnet-5
Same two commands as the Before leg, against the proxy booted from this branch
One request to Anthropic, no 400, no strip-and-retry in the proxy log, and Claude's own thinking block comes back
The same bridge-signed history sent to a Gemini deployment (the mid-session
/modelswitch in Claude Code from gpt-5.1 to Gemini)At the merge base the same history carries
signature: ""and Gemini answers 200 as well; the interim tip of this branch (751431d) forwarded the bridge-tagged signature as athoughtSignatureand Gemini answered400 Base64 decoding failed, which is what the chat-adapter strip fixesThe same history sent to a Bedrock deployment (
bedrock/us.anthropic.claude-sonnet-5)Bedrock answers 200 with the bridge-tagged block dropped up front, and this run came back with Bedrock's own signed thinking block in front of the text (the 4716b46 run answered without thinking)
/v1/chat/completionswith a bridge-taggedthinking_blocks[].signaturestill gets the provider's 400 on Gemini and Bedrock, exactly as it does at the merge base for any signature the provider did not mint: the chat bridge never emits bridge-tagged signatures, so that history only exists when a client copies one across routes by handA Responses provider that rejects
includeperplexity/perplexity/sonaris routed to the same bridge (moderesponses) but its Responses API rejectsinclude, so the bridge leaves it out thereWithout the provider check this call fails with
UnsupportedParamsError: LlmProviders.PERPLEXITY does not support parameters: {'include': ['reasoning.encrypted_content']}unless the deployment setsdrop_paramsObservations from the run
cached_tokens=0on turn two and hits on the next two with byte-identical input prefixes; this run hit on every turn after the first. What the PR controls is the input bytesresponse.output_item.doneandresponse.completedcarry differentencrypted_contentbytes of the same length). The bridge replays theoutput_item.donebytes, and OpenAI accepts and caches them, as the per-turn cache hits above showType
🐛 Bug Fix
Caveats (if any)
Medium
/v1/chat/completionsclients keep lossy reasoning replay_RESPONSES_API_PROVIDERSisfrozenset({"openai"}), so Azure Responses-mode deployments reach OpenAI through the chat->Responses bridge from/v1/messages, and that bridge never asks forinclude. Follow-up: LIT-7419signature(orredacted_thinking.data), the client replays all of them, and the bridge forwards all of them. Issue [Bug]: reasoning items rebuilt from lossy summary text on every turn, breaking prompt-cache byte-stability for OpenAI reasoning models behind /v1/messages #40288 flagged the per-turn growth and asked for this to be chosen explicitly, naming a last-N-turns cap as one option. Alternatives not taken: replaying only the last N turns' payloads, or dropping payloads past a byte budget. Both change the input bytes for every turn after the first drop, which is the lossy prefix this PR removes, and OpenAI only reads reasoning it can decrypt, so a dropped item is a lost item. The client owns history length (Claude Code compacts), and the same growth already exists for Anthropic's own signaturesredacted_thinkingblockreasoning_auto_summaryorthinking.summary, OpenAI returns no summary text, so the block is{"type": "redacted_thinking", "data": "litellm_encrypted_reasoning:..."}where the merge base returned text only. That is the Messages API's shape for opaque reasoning; an emptythinkingblock would misrepresent it as visible textLow
thinking.signature: Field required, the Bugbot finding on 4716b46, shown in the model-switch case above), and the merge base lost the same text through its strip-and-retry, so dropping it up front is the same outcome without the failed requestinput. Alternatives not taken: keeping the readable text as an unsigned thinking block (what 4716b46 did; the OpenAI bridge turned it into a summary-only reasoning item, but Anthropic and Bedrock 400 on it, so the router would have to know the routed provider to pick per target), a 400 naming the pin (every tier change in the customer's auto-router would then fail), or routing back to the minting deployment (it is not a candidate in the routed group, which is the point of the tier change)output_item.donewith noidlands on whichever block is current_close_reasoning_itemfalls back to the current block index when the item has no id. OpenAI always sends reasoning item ids and only OpenAI-routed deployments reach this iterator, so it needs a non-OpenAI upstream behind theopenai/prefix to triggerFinal Attestation