Repository navigation
fix(anthropic): keep refusal stop_reason and stop_details on the logged response - #46104
Conversation
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
Merging this PR will not alter performance
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…on-dict upstream body
|
@litereview code-review |
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. No correctness findings. The earlier streamed JSON-mode finding is fixed. The four One description fix to make before merge: the Low caveat says a JSON-tool refusal ends with Checks and execution details
View review · Reviewed |
|
Real refusals need prompts built to trip Anthropic's safeguard, which we will not craft. The scripted upstream serves Anthropic's documented refusal wire shape, see Caveats |
|
@litereview code-review |
|
@litereview code-review |
…eceived_model_id on synthesized finish chunks
|
@litereview code-review |
… hits and skip non-object cached provider fields
|
@litereview code-review |
… wire, the cache and under chaos
|
@litereview code-review |
|
bugbot run |
|
@litereview code-review |
…sponse Also adds the round 3 audit cells for JSON-mode refusals, the proxy response serialization, and wrong-typed cached usage details on both stream replays
|
@litereview code-review |
|
bugbot run |
…usal_stop_details # Conflicts: # litellm/llms/anthropic/chat/handler.py
|
@litereview code-review |
… after main's stream change
|
@litereview code-review |
|
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 cde56b9. Configure here.
|
@litellm-stampbot |
litellm-stampbot: risk highNot approved at Rules (
Judge (gpt-6-luna): high, default behavior change, request hot path, complex diff
Pushes do not re-run this check. Comment |
…er a system message after the search turn The malformed kept result cells now expect the unanswered search call to be dropped, as main does since #45882. The stream cut cell checks streamed tool call names, since the kept search result names get_weather as a tool reference. The streamed response cache hit cell runs again because #46104 fixed it. The modify_params cap cell expects the four client marks, since the placeholder answer sends the search call as a plain tool_use with its mark, and a new cell covers a system message after the trailing search turn in both stream modes
…y modify_params sends it (#46591) * fix(anthropic): count a replayed server tool call's cache mark the way modify_params sends it With modify_params on, a trailing tool search turn whose call has a kept result got a placeholder answer from the factory and went out as a marked tool_use, but the cache control hook counted marks before that placeholder existed and skipped the mark, so a request at the cap reached Anthropic with 5 marks and failed with a 400. The hook now finds client answers on the sanitized messages, the same list the factory reads. Also make the replay checks cheaper (prefix check before validation, early return without provider_specific_fields, and look up client answers only when a tool call carries cache_control), drop the two audit cells that cover old gaps outside the tool search fix, and derive the pass-through test timeout from the graceful stop budget. * fix(anthropic): keep the duplicate tool result warning out of the cache control hook The hook finds client answers with only the step of the modify_params sanitize pass that pairs tool calls with their results, so a request with a duplicate tool result logs the warning once again instead of once per mark count. Also restore the Snowflake non-stream and cached-stream tool search cells as known bugs with pytest.skip instead of deleting them, and put the Anthropic pass-through test timeout back to 240 seconds. * fix(anthropic): count cache marks next to a message the pairing step cannot read With modify_params on and a marked tool call, the cache control hook paired tool calls with their results before counting. A message without a get method (a stray string or null in extra_body.messages, or an openai SDK ChatCompletionMessage) made that pairing raise AttributeError before any provider call, where main counted the marks and let the request through. The hook now pairs only when every message can be read the way the pairing step reads it, and otherwise counts on the messages as sent, like main did. * fix(anthropic): count cache marks after placing a later system message the way the request builder does * test(anthropic): cover a leading system prompt and a system message before the answer in the cache mark census * test(anthropic): align the tool search replay cells with main and cover a system message after the search turn The malformed kept result cells now expect the unanswered search call to be dropped, as main does since #45882. The stream cut cell checks streamed tool call names, since the kept search result names get_weather as a tool reference. The streamed response cache hit cell runs again because #46104 fixed it. The modify_params cap cell expects the four client marks, since the placeholder answer sends the search call as a plain tool_use with its mark, and a new cell covers a system message after the trailing search turn in both stream modes * fix(anthropic): count marks on the raw messages when they cannot be placed, and find client answers once per request * test(anthropic): cover marked tool calls next to a malformed tool id and a later system message * perf(anthropic): look up client tool answers only when a marked tool call is a server tool call Answered ids only decide whether a marked srvtoolu_ call is rebuilt as server_tool_use, so a request whose marked tool calls are all client calls no longer places system messages or runs the modify_params pairing step to count marks * test(anthropic): reach the client answer lookup with a marked search call in the malformed tool id cell * perf(anthropic): place mid-conversation system messages in linear time for models that keep them * fix(anthropic): count cache marks with the model's own system message placement and pair tool results in linear time * test(anthropic): cover modify_params dropping a tool answer that answers no call of the latest assistant turn * fix(anthropic): count marks with in-place system placement when the model lookup cannot confirm the flag * test(anthropic): cover a bare model with custom_llm_provider filling the cache mark budget through litellm.completion and Router * fix(anthropic): give unmapped models the request builder's converting placement and survive any model lookup failure * test(anthropic): cover an unmapped model name counting cache marks with the request builder's converting placement * fix(anthropic): count server tool call cache marks the request builder's way only on routes that build Anthropic Messages requests Databricks, OpenRouter and Bedrock Converse send every marked tool call as is, so the hook keeps the census main uses there. The seeding step carries custom_llm_provider on the injection points when a server tool call is marked, so a bare model name still resolves its route. * test(anthropic): cover two answered marked server tool calls before a system message on Databricks, OpenRouter and Bedrock Converse * fix(anthropic): keep main's cache mark count on GitHub Copilot and ChatGPT routes without resolving them, so a sync call with no stored login never starts the device flow * test(anthropic): cover a marked server tool call reaching the GitHub Copilot and ChatGPT login hosts like an unmarked one
TLDR
stop_detailswith a category, and LiteLLM dropped it, so callbacks only sawfinish_reason: "content_filter"stop_reasonandstop_detailsnow reach the caller and the logged response on/chat/completions,/v1/responsesand/v1/messages, streamed or not, on cache hits and in JSON modeDecisions made here, with the alternatives
stop_detailsis forwarded whole, not cut down totype,categoryandexplanation. Anthropic addsfallback_credit_token,fallback_has_prefill_claimandrecommended_modelto it only when the request sends thefallback-credit-2026-07-01beta header (fallback credit)./chat/completionsand/v1/responsesdrop that header today, so only/v1/messages, which forwards it, can log those fields. The logged/v1/messagescopy keeps the token on purpose. It is one-time, expires in five minutes, is bound to the org, and only reprices a retry's cache write, and that copy already holds the whole response. Redacting only the token was the alternative. An allowlist would need a code change for every new fieldstop_details, andstop_reason: "refusal"alone is added when the details are null. A normal stop adds nothing. Anthropic's refusal docs saystop_detailsis null for every stop reason other thanrefusal, so today only refusals add keys. Gating onrefusalwas the alternative, and it would drop the details if Anthropic ever sends them with another stop reasoncontainertakes and the one the ticket proposed. Putting them on the finish chunk instead needs a special case inCustomStreamWrapper, like the one MCP metadata has. Keeping them out of the client stream through the chunk's_hidden_params["provider_specific_fields"]would not reach the log, becausestream_chunk_buildermerges that only into the assembled response's hidden params, which the cost calculator and the Responses bridge read andstandard_logging_object["response"]never does/v1/responsesstream refusal'sresponse.incompleteevent now has a top-levelprovider_specific_fields, the same key the non-stream response already has/chat/completionsrefusal stream with no text is now stored in the response cache when caching is on. The cache skips a stream with no output, and the refusal fields count as output, so the second identical request is served from the cache the way a non-stream refusal already is on main. Keeping refusal streams out of the cache was the alternative. It would make the stream and non-stream paths differ, and a refusal that streamed some text first is cached on main anyway. One effect is that an identical retry inside the cache TTL gets the stored refusal back without reaching Anthropic, and the callback logs it as a cache hit with the samestop_details. Non-stream refusals already behave that way on mainprovider_specific_fieldsfor every provider, not only the refusal keys. The sync cache replay already did this, so the async replay now matches it, and a streamed cache hit sends what the first call sent. For example, an Anthropic web search call's search fields used to be dropped from a streamed cache hit and are now replayed. Replaying only the refusal keys was one alternative, and it would keep every other provider field different between a hit and a miss. Leaving the async replay alone was the other, and it would keep the sync and async replays apart and the refusal fields off streamed cache hitscompletion_tokens_detailsalong with the provider fields, in both the sync and async replays. Without it, a replayed first chunk that carries provider fields made the logged usage and the client's usage chunk losecompletion_tokens_detailson chat, and made a/v1/responsesstream dropoutput_tokens_details, which the OpenAI SDK types as required. With it, a streamed hit on/chat/completions,/v1/completionsor/v1/responsesreports the same reasoning and text token split as the first call, for every provider. Before this PR a streamed cache hit always reportedreasoning_tokens: 0, even when the first call used reasoning tokens. Filling inreasoning_tokens: 0again was the alternative, and it would keep that wrong number. Cache hits cost nothing, so spend does not change. A cachedprovider_specific_fieldsorcompletion_tokens_detailsthat is not an object, and cached details with a wrong-typed value such asreasoning_tokens: "abc", are skipped on replay, so the hit still replays its text the way base does_hidden_params["received_model_id"]when the stream wrapper adds its own finish chunk, which a refusal stream now makes it doUser Flow
Before: a callback that flags refusals only sees a generic content filter
"stream": truestop_detailswith acategoryfinish_reason: "content_filter"and nostop_detailsAfter: the callback reads the category
"stream": truestop_detailswith acategoryfinish_reason: "content_filter"plusstop_reasonandstop_detailsinmessage.provider_specific_fieldsRelevant issues
Fixes #43752
Linear ticket
Resolves LIT-9461
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
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 moreScreenshots / Proof of Fix
Last updated at cde56b9. /qa and /live-pr-risk ran at 2edd392, and cde56b9 changes only an integration test
Before and after
Headline, case 1, the reporter's streamed
/v1/messagesrefusalThe client sees
stop_detailson both legs. Before, the callback row hasmessage_provider_specific_fields: nulland nostop_detailsanywhere. After, the callback row{"call_type": "anthropic_messages", "stream": true, "finish_reason": "content_filter", "message_provider_specific_fields": {"stop_reason": "refusal", "stop_details": {"type": "refusal", "category": "cyber", "explanation": "This request was declined because it could enable cyber harm."}}, "stop_details_anywhere_in_response_or_hidden_params": true, "refusal_category_anywhere_in_response_or_hidden_params": true, "stop_details_in_standard_logging_response": true}Every case's command, client output and callback row on both legs
Before (f0fedda, merge base, upstream port 46346, proxy port 58380, 2 workers)
1. /v1/messages stream, scripted refusal (the reporter's request)
Steps: boot the proxy with the callback registered under
litellm_settings.callbacks, send the streamed/v1/messagesrequest below (the scripted upstream answers with the docs refusal), then read the client'smessage_deltaevent and the row the callback wroteClient output (the message_delta event):
Callback row:
{"call_type": "anthropic_messages", "stream": true, "finish_reason": "content_filter", "message_provider_specific_fields": null, "stop_details_anywhere_in_response_or_hidden_params": false, "refusal_category_anywhere_in_response_or_hidden_params": false, "stop_details_in_standard_logging_response": false}2. /chat/completions non-stream, scripted refusal
Command, client output and callback row
Client output (the full response):
Callback row:
{"call_type": "acompletion", "stream": false, "finish_reason": "content_filter", "message_provider_specific_fields": {"citations": null, "thinking_blocks": null}, "stop_details_anywhere_in_response_or_hidden_params": false, "refusal_category_anywhere_in_response_or_hidden_params": false, "stop_details_in_standard_logging_response": false}3. /chat/completions stream, scripted refusal
Command, client output and callback row
Client output (every chunk):
Callback row:
{"call_type": "acompletion", "stream": true, "finish_reason": "content_filter", "message_provider_specific_fields": null, "stop_details_anywhere_in_response_or_hidden_params": false, "refusal_category_anywhere_in_response_or_hidden_params": false, "stop_details_in_standard_logging_response": false}4. /v1/responses non-stream, scripted refusal
Command, client output and callback row
Client output (the response with id and usage shortened):
Callback row:
{"call_type": "aresponses", "stream": false, "finish_reason": "content_filter", "message_provider_specific_fields": {"citations": null, "thinking_blocks": null}, "stop_details_anywhere_in_response_or_hidden_params": false, "refusal_category_anywhere_in_response_or_hidden_params": false, "stop_details_in_standard_logging_response": false}5. /v1/messages stream, real Anthropic control, normal prompt
Command, client output and callback row
Client output (the message_delta event):
Callback row:
{"call_type": "anthropic_messages", "stream": true, "finish_reason": "stop", "message_provider_specific_fields": null, "stop_details_anywhere_in_response_or_hidden_params": false, "refusal_category_anywhere_in_response_or_hidden_params": false, "stop_details_in_standard_logging_response": false}6. /v1/responses stream, scripted refusal
Command, client output and callback row
Client output (the final event, with id and usage shortened):
Callback row:
{"call_type": "aresponses", "stream": true, "finish_reason": "content_filter", "message_provider_specific_fields": null, "stop_details_anywhere_in_response_or_hidden_params": false, "refusal_category_anywhere_in_response_or_hidden_params": false, "stop_details_in_standard_logging_response": false}7. /v1/messages non-stream, scripted refusal
Command, client output and callback row
Client output (the full response):
Callback row:
{"call_type": "anthropic_messages", "stream": false, "finish_reason": "content_filter", "message_provider_specific_fields": {"citations": null, "thinking_blocks": null}, "stop_details_anywhere_in_response_or_hidden_params": false, "refusal_category_anywhere_in_response_or_hidden_params": false, "stop_details_in_standard_logging_response": false}8. /chat/completions stream with
include_usage, scripted refusal, response cache on, the same request twiceCommands, cache headers and the full output
Instance A on port 40066 and instance B on port 37075, 2 workers each, with Redis on port 44337 and the upstream on port 44280
Call 1, sent to instance A
Response headers carry no
x-litellm-cache-key, so the response did not come from the cacheCall 2, sent to instance B
Response headers carry no
x-litellm-cache-key, so the response did not come from the cacheThe client output and callback row of both calls are in case8_before.md, whole, to keep the body under GitHub's size cap
The scripted upstream got 2 requests for the two calls, so call 2 was not served from the cache. Both rows log
stop_detailsnull9. /chat/completions non-stream with
response_formatjson_schema, scripted refusal through the JSON toolCommands, client output and callback row
Its own proxy on port 29637 (2 workers) and a scripted upstream on port 54816 that answers every non-stream call with the docs refusal, its content swapped for one
json_tool_calltool_use block.scripted-claude-json-toolmaps toanthropic/claude-scripted-9, which the cost map does not list, so the proxy sends thejson_tool_calltool with a forcedtool_choiceClient output of the first request (the full response):
Callback row of the first request:
{"call_type": "acompletion", "stream": false, "finish_reason": "stop", "message_provider_specific_fields": null, "stop_details_anywhere_in_response_or_hidden_params": false, "refusal_category_anywhere_in_response_or_hidden_params": false, "stop_details_in_standard_logging_response": false}The second request returned the same
messageand the same callback row, withmodelscripted-claudeAfter (2edd392, PR tip, upstream port 55589, proxy port 39974, 2 workers)
1. /v1/messages stream, scripted refusal (the reporter's request)
Client output (the message_delta event):
Callback row:
{"call_type": "anthropic_messages", "stream": true, "finish_reason": "content_filter", "message_provider_specific_fields": {"stop_reason": "refusal", "stop_details": {"type": "refusal", "category": "cyber", "explanation": "This request was declined because it could enable cyber harm."}}, "stop_details_anywhere_in_response_or_hidden_params": true, "refusal_category_anywhere_in_response_or_hidden_params": true, "stop_details_in_standard_logging_response": true}2. /chat/completions non-stream, scripted refusal
Command, client output and callback row
Client output (the full response):
Callback row:
{"call_type": "acompletion", "stream": false, "finish_reason": "content_filter", "message_provider_specific_fields": {"citations": null, "thinking_blocks": null, "stop_reason": "refusal", "stop_details": {"type": "refusal", "category": "cyber", "explanation": "This request was declined because it could enable cyber harm."}}, "stop_details_anywhere_in_response_or_hidden_params": true, "refusal_category_anywhere_in_response_or_hidden_params": true, "stop_details_in_standard_logging_response": true}3. /chat/completions stream, scripted refusal
Command, client output and callback row
Client output (every chunk):
Callback row:
{"call_type": "acompletion", "stream": true, "finish_reason": "content_filter", "message_provider_specific_fields": {"stop_reason": "refusal", "stop_details": {"type": "refusal", "category": "cyber", "explanation": "This request was declined because it could enable cyber harm."}}, "stop_details_anywhere_in_response_or_hidden_params": true, "refusal_category_anywhere_in_response_or_hidden_params": true, "stop_details_in_standard_logging_response": true}4. /v1/responses non-stream, scripted refusal
Command, client output and callback row
Client output (the response with id and usage shortened):
Callback row:
{"call_type": "aresponses", "stream": false, "finish_reason": "content_filter", "message_provider_specific_fields": {"citations": null, "thinking_blocks": null, "stop_reason": "refusal", "stop_details": {"type": "refusal", "category": "cyber", "explanation": "This request was declined because it could enable cyber harm."}}, "stop_details_anywhere_in_response_or_hidden_params": true, "refusal_category_anywhere_in_response_or_hidden_params": true, "stop_details_in_standard_logging_response": true}5. /v1/messages stream, real Anthropic control, normal prompt
Command, client output and callback row
Client output (the message_delta event):
Callback row:
{"call_type": "anthropic_messages", "stream": true, "finish_reason": "stop", "message_provider_specific_fields": null, "stop_details_anywhere_in_response_or_hidden_params": false, "refusal_category_anywhere_in_response_or_hidden_params": false, "stop_details_in_standard_logging_response": false}6. /v1/responses stream, scripted refusal
Command, client output and callback row
Client output (the final event, with id and usage shortened):
Callback row:
{"call_type": "aresponses", "stream": true, "finish_reason": "content_filter", "message_provider_specific_fields": {"stop_reason": "refusal", "stop_details": {"type": "refusal", "category": "cyber", "explanation": "This request was declined because it could enable cyber harm."}}, "stop_details_anywhere_in_response_or_hidden_params": true, "refusal_category_anywhere_in_response_or_hidden_params": true, "stop_details_in_standard_logging_response": true}7. /v1/messages non-stream, scripted refusal
Command, client output and callback row
Client output (the full response):
Callback row:
{"call_type": "anthropic_messages", "stream": false, "finish_reason": "content_filter", "message_provider_specific_fields": {"citations": null, "thinking_blocks": null, "stop_reason": "refusal", "stop_details": {"type": "refusal", "category": "cyber", "explanation": "This request was declined because it could enable cyber harm."}}, "stop_details_anywhere_in_response_or_hidden_params": true, "refusal_category_anywhere_in_response_or_hidden_params": true, "stop_details_in_standard_logging_response": true}8. /chat/completions stream with
include_usage, scripted refusal, response cache on, the same request twiceCommands, cache headers and the full output
Instance A on port 35720 and instance B on port 51515, 2 workers each, with Redis on port 28370 and the upstream on port 36570
Call 1, sent to instance A
Response headers carry no
x-litellm-cache-key, so the response did not come from the cacheCall 2, sent to instance B
Response header
x-litellm-cache-key(sent only when the response came from the cache):The client output and callback row of both calls are in case8_after.md, whole, to keep the body under GitHub's size cap
The scripted upstream got 1 request for the two calls, so call 2 was served from the Redis cache that instance A wrote. Both rows log the refusal
stop_detailsand the samecompletion_tokens_details9. /chat/completions non-stream with
response_formatjson_schema, scripted refusal through the JSON toolCommands, client output and callback row
Its own proxy on port 22660 (2 workers) and a scripted upstream on port 42961 that answers every non-stream call with the docs refusal, its content swapped for one
json_tool_calltool_use block.scripted-claude-json-toolmaps toanthropic/claude-scripted-9, which the cost map does not list, so the proxy sends thejson_tool_calltool with a forcedtool_choiceClient output of the first request (the full response):
Callback row of the first request:
{"call_type": "acompletion", "stream": false, "finish_reason": "stop", "message_provider_specific_fields": {"stop_reason": "refusal", "stop_details": {"type": "refusal", "category": "cyber", "explanation": "This request was declined because it could enable cyber harm."}}, "stop_details_anywhere_in_response_or_hidden_params": true, "refusal_category_anywhere_in_response_or_hidden_params": true, "stop_details_in_standard_logging_response": true}The second request returned the same
messageand the same callback row, withmodelscripted-claudeSide checks on the case 8 rig
Three more cache pairs on both legs
Each pair ran on the case 8 two-instance rig after a Redis flush, with call 1 to instance A and call 2 to instance B. With
streamleft out, both legs loggedcache_hitnull on call 1, then served call 2 from the cache with call 1'sid, and on the head both rows also log the refusalstop_details. On both legs the non-stream hit adds an empty choice-levelprovider_specific_fieldsthat the miss does not have, and since main moved past 2f3ccbe it no longer addssystem_fingerprint: null. With the real Anthropicanthropic-controldeployment, the case 5 prompt andinclude_usage, both legs served call 2 from the cache with call 1'sid. On both, the hit's usage chunk carriedcompletion_tokens_details{"reasoning_tokens":0,"text_tokens":4}andcost0.000076 like the miss, but unlike the miss it had noprompt_tokens_details,cache_creation_input_tokensorcache_read_input_tokens. With a second scripted upstream that streams a plainhellowithend_turn, one output token and the docs example'smodelclaude-fable-5, both legs served call 2 from the cache, and on both the miss's usage chunk showedcost0.00417 and the hit's 0.000834. So a miss prices the tokens at the upstream'sclaude-fable-5rate and a hit at the deployment'sclaude-sonnet-5-5rate on the base too, which is also why case 8's hit shows 0.000824 against the miss's 0.00412Observations from the run
/live-pr-risk A/B across the Anthropic family
Base f0fedda and head 2edd392 got the same 418 requests. Head logs
stop_detailson every Anthropic-family route and endpoint except Snowflake non-stream, and base logs none. Statuses and outbound requests match, and #46331's JSON schema and split answer rows keep the same content and finish reason on both legsProvider table, #46331 cells and every case
/live-pr-risk booted a base proxy (f0fedda) and a head proxy (2edd392, the same product code as cde56b9), each as two processes sharing one Postgres and one Redis, and sent the same 418 requests to both. Cache misses went to one process and hits to the other. Each Anthropic-family route pointed at a scripted upstream that serves the docs refusal in that provider's wire format, and real Anthropic, OpenAI, Gemini and Mistral sat behind forwarding recorders for the cache and usage cells. A cell reads "yes" when
standard_logging_object.responsehad nostop_detailson base and the docs categorycyberon head, for both stream and non-stream unless the cell says otherwise. Statuses and outbound requests matched between legs, apart from the 4 refusal streams head serves from the cacheThe "refusal after text" row streams some text first and then the refusal on
message_delta#46331 changed how Bedrock Mantle and Claude Platform stream a
response_formatanswer and how a split answer is joined. On those routes with a JSON schema, and with a split answer that ends in a refusalmessage_deltaon anthropic, bedrock invoke, mantle and platform, both legs give the same content and finish reason. Head adds the stop fields to the client output and the log, and base has them on none of these rowsStreamed cache hits
Streamed cache hits were checked on 20 hit and miss pairs across anthropic, gemini, openai, mistral, a thinking model and the refusal. On head every hit reports the same token split as its miss, in the client stream, the OpenAI SDK's typed usage, the callback and the spend row. For OpenAI and Mistral this means a hit no longer has the made-up
text_tokensJSON mode on anthropic and bedrock invoke
With
response_formatset, a refusal keeps the same finish reason on both legs, and head adds the stop fields on every surface below. Base has no stop fields in any of these cells. A declared schema and an envelope gave the same result{"answer": "hello"}Non-stream message keys and unexpected stop_details
A non-stream refusal on chat keeps the same message keys on both legs, and the OpenAI SDK reads the stop fields from
model_extraon headAn upstream
stop_detailsof an unexpected type or size is passed through as sent, on the JSON tool path too. Base passed it only on MessagesA tree with this PR merged into main at 6bd5580, which adds #46354's stream close, gave the same results as head on every scripted cell it ran
/audit at cde56b9
Every cell ran again at cde56b9 against the merge base f0fedda. Both head runs passed the same 103 cells, base failed 81 of them, and none of the 368 control cells failed because of this PR
Lanes, control reds, behavior changes and live cells
The cells are in wire, chaos and SDK cache. Both head runs used seed 46104. The 22 base passes are the cells expected to match on both legs, such as Snowflake non-stream, the
received_model_idcells, provider errors and wrong-typed cached usage detailsThe controls are the 368 existing Anthropic-family cells in providers and messages, plus the Vertex structured output and OpenAI chat wire files. The 25 reds ran again one worker at a time
The 14 boot timeouts came from a loaded rig box, where proxy boot took a median of 208s against 66s in the earlier round. The 10 Vertex cells fail the same way on main, because since #46331 the closing
}of a streamed JSON tool answer comes as its own frame. The SIGKILL cell restarts a 2-worker proxy, and on each leg it passed twice and ran over its 180s budget once, so it is load-sensitive on main tooreceived_model_idEight live cells called api.anthropic.com with claude-sonnet-5-5 and ordinary prompts at f0fedda and at cde56b9. Seven show no stop keys at the client or in the spend rows on either leg, which includes a JSON schema stream. On the
/v1/responsescall the model chose to think only on the head call (56 reasoning tokens against 0), so only that leg shows a thinking block. The eighth cell is a real streamed cache hit of a reasoning callType
🐛 Bug Fix
Caveats (if any)
Low
/v1/messagesstream hooks see nostop_details. Net negative to fix since no hook reads it/v1/responsescache hit drops the top-levelprovider_specific_fieldsfor every provider, as on main. Net negative to fix here since it is a cache layer fix on its own ticket.getwould do. Net negative to change since behavior is the samestopwhen not streamed andcontent_filterwhen streamed, as on main. Net negative to fix here since it changes every JSON-mode callerCaveat details
message_deltaas the streaming refusal docs describe. No live refusal is shown, because getting one means sending a prompt meant to trip Anthropic's safeguard, which this work does not do, and the non-Anthropic upstreams were scripted too. The real-Anthropic controls prove the normal path is unchanged. Net negative to fix: the only route to a live refusal is that prompt. The refusal test string older Anthropic docs listed no longer works. Sent straight to api.anthropic.com on 2026-10-13 as a stream to claude-sonnet-5-5 and claude-opus-5-5, it ended withstop_reason: "max_tokens"andstop_details: null, and the current streaming refusal docs no longer list it/v1/messageswith agentic hooks rebuilds the message for the hooks fromstop_reasonandstop_sequenceonly, so the hooks still see nostop_details. The logged copy is not affected. Net negative to fix here: no hook reads it, and the fix would re-run every live passstop_details/v1/responsescall served from the response cache returns no top-levelprovider_specific_fields, while the first call has them. The cached chat completion keeps no hidden params, and the Responses bridge reads the top-level fields from there. This is not new, and it drops every provider's top-level fields on a cache hit, not only the refusal ones. The logged response has the fields on both calls. Net negative to fix here: the fix belongs in the cache layer for every provider, so it is on a follow-up ticket.getwould be simpler. Net negative to change now: it has no behavior effect and would re-run every live passresponse_format, a non-stream refusal ends withfinish_reason: "stop"and a streamed one withcontent_filter. Main returns the same finish reasons since fix(anthropic): stream json_schema answers as content on Bedrock Mantle and Claude Platform, and join split answers #46331 changed the stream path, and this PR changes neither. The caller can now tell it was a refusal fromprovider_specific_fields.stop_reason. Net negative to fix here: changing a finish reason main already returns would change it for every JSON-mode caller, which is outside this ticketstopReason: content_filteredwithout stop details. This is an upstream limit with nothing in LiteLLM to changeFinal Attestation
Note
Medium Risk
Touches core streaming, cache replay, and Anthropic response transforms used across multiple provider routes; behavior changes visible to API clients (extra stream chunk on refusal) and logging callbacks.
Overview
Anthropic refusals no longer drop native
stop_reasonandstop_detailsafter mapping to OpenAI-stylecontent_filter. Those fields are merged intomessage.provider_specific_fields(and streamingdelta.provider_specific_fields) via a sharedrefusal_provider_specific_fieldshelper on non-stream transforms,message_deltastreaming, and JSON-mode tool paths.Cache replay and logging: Streamed cache hits now replay cached
provider_specific_fieldsandcompletion_tokens_detailswith pydantic validation (invalid shapes are skipped).CustomStreamWrapperkeepsreceived_model_idon synthesized finish chunks so logged assembled streams stay consistent.Large wire, chaos, and SDK integration coverage exercises proxy surfaces, caching, and malformed upstream payloads.
Reviewed by Cursor Bugbot for commit cde56b9. Bugbot is set up for automated code reviews on this repo. Configure here.