Skip to content

fix(anthropic): keep refusal stop_reason and stop_details on the logged response - #46104

Merged
mateo-berri merged 11 commits into
mainfrom
litellm_anthropic_refusal_stop_details
Oct 14, 2026
Merged

mateo-berri merged 11 commits into
mainfrom
litellm_anthropic_refusal_stop_details

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

  • Anthropic refusals send a stop_details with a category, and LiteLLM dropped it, so callbacks only saw finish_reason: "content_filter"
  • stop_reason and stop_details now reach the caller and the logged response on /chat/completions, /v1/responses and /v1/messages, streamed or not, on cache hits and in JSON mode
Decisions made here, with the alternatives
  • stop_details is forwarded whole, not cut down to type, category and explanation. Anthropic adds fallback_credit_token, fallback_has_prefill_claim and recommended_model to it only when the request sends the fallback-credit-2026-07-01 beta header (fallback credit). /chat/completions and /v1/responses drop that header today, so only /v1/messages, which forwards it, can log those fields. The logged /v1/messages copy 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 field
  • The keys are added when Anthropic sends a non-null stop_details, and stop_reason: "refusal" alone is added when the details are null. A normal stop adds nothing. Anthropic's refusal docs say stop_details is null for every stop reason other than refusal, so today only refusals add keys. Gating on refusal was the alternative, and it would drop the details if Anthropic ever sends them with another stop reason
  • The chat stream carries the fields on the chunk the stream wrapper already emits for a delta's provider fields, the same path container takes and the one the ticket proposed. Putting them on the finish chunk instead needs a special case in CustomStreamWrapper, 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, because stream_chunk_builder merges that only into the assembled response's hidden params, which the cost calculator and the Responses bridge read and standard_logging_object["response"] never does
  • A /v1/responses stream refusal's response.incomplete event now has a top-level provider_specific_fields, the same key the non-stream response already has
  • A /chat/completions refusal 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 same stop_details. Non-stream refusals already behave that way on main
  • A streamed cache hit now replays the cached message's whole provider_specific_fields for 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 hits
  • A streamed cache hit now replays the cached completion_tokens_details along 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 lose completion_tokens_details on chat, and made a /v1/responses stream drop output_tokens_details, which the OpenAI SDK types as required. With it, a streamed hit on /chat/completions, /v1/completions or /v1/responses reports the same reasoning and text token split as the first call, for every provider. Before this PR a streamed cache hit always reported reasoning_tokens: 0, even when the first call used reasoning tokens. Filling in reasoning_tokens: 0 again was the alternative, and it would keep that wrong number. Cache hits cost nothing, so spend does not change. A cached provider_specific_fields or completion_tokens_details that is not an object, and cached details with a wrong-typed value such as reasoning_tokens: "abc", are skipped on replay, so the hit still replays its text the way base does
  • The logged response of a stream keeps _hidden_params["received_model_id"] when the stream wrapper adds its own finish chunk, which a refusal stream now makes it do

User Flow

Before: a callback that flags refusals only sees a generic content filter

  1. They register a custom callback and send POST https://litellm-domain/v1/messages with "stream": true
  2. Anthropic refuses. The client sees a stop_details with a category
  3. The callback gets finish_reason: "content_filter" and no stop_details

After: the callback reads the category

  1. They register a custom callback and send POST https://litellm-domain/v1/messages with "stream": true
  2. Anthropic refuses. The client sees a stop_details with a category
  3. The callback gets finish_reason: "content_filter" plus stop_reason and stop_details in message.provider_specific_fields

Relevant issues

Fixes #43752

Linear ticket

Resolves LIT-9461

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

Screenshots / 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

Case Request Before f0fedda After 2edd392
1 /v1/messages stream row has no stop_details row logs stop_details, cyber
2 /chat/completions no stop_details message and row carry them
3 /chat/completions stream finish chunk only chunk before finish carries them
4 /v1/responses no stop_details top-level stop_details
5 /v1/messages stream, real Anthropic end_turn, nothing logged same, unchanged
6 /v1/responses stream no stop_details response.incomplete carries them
7 /v1/messages row has no stop_details row logs stop_details
8 chat stream, cache, 2 instances 2 upstream calls, no hit 1 upstream call, hit logs them
9 chat json_schema, JSON tool no stop_details message and row carry them

Headline, case 1, the reporter's streamed /v1/messages refusal

curl -sN $PROXY/v1/messages -H "x-api-key: $KEY" -H "anthropic-version: 2023-06-01" -H "content-type: application/json" -d '{"model":"scripted-claude","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"scripted refusal leg"}]}'

The client sees stop_details on both legs. Before, the callback row has message_provider_specific_fields: null and no stop_details anywhere. 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/messages request below (the scripted upstream answers with the docs refusal), then read the client's message_delta event and the row the callback wrote

curl -sN $PROXY/v1/messages -H "x-api-key: $KEY" -H "anthropic-version: 2023-06-01" -H "content-type: application/json" -d '{"model":"scripted-claude","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"scripted refusal leg"}]}'

Client output (the message_delta event):

event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "refusal", "stop_sequence": null, "stop_details": {"type": "refusal", "category": "cyber", "explanation": "This request was declined because it could enable cyber harm."}}, "usage": {"output_tokens": 0}}

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
curl -sN $PROXY/chat/completions -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude","max_tokens":64,"messages":[{"role":"user","content":"scripted refusal leg"}]}'

Client output (the full response):

{"id":"chatcmpl-2590f712-8133-43ad-83e4-50ac5e7bde0e","created":1792005101,"model":"scripted-claude","object":"chat.completion","choices":[{"finish_reason":"content_filter","index":0,"message":{"role":"assistant","provider_specific_fields":{"citations":null,"thinking_blocks":null},"content":null}}],"usage":{"completion_tokens":0,"prompt_tokens":412,"total_tokens":412,"completion_tokens_details":{"reasoning_tokens":0,"text_tokens":0},"prompt_tokens_details":{"cached_tokens":0,"text_tokens":412,"cache_write_tokens":0,"cache_creation_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}

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
curl -sN $PROXY/chat/completions -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"scripted refusal leg"}]}'

Client output (every chunk):

data: {"id":"chatcmpl-5240cbd9-5391-4ca2-82ed-916b74f95a46","object":"chat.completion.chunk","created":1792005103,"model":"scripted-claude","choices":[{"index":0,"delta":{},"finish_reason":"content_filter"}]}
data: [DONE]

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
curl -sN $PROXY/v1/responses -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude","max_output_tokens":64,"input":"scripted refusal leg"}'

Client output (the response with id and usage shortened):

{"id": "resp_...", "created_at": 1792005105, "error": null, "incomplete_details": {"reason": "content_filter"}, "instructions": null, "metadata": {}, "model": "scripted-claude", "object": "response", "output": [], "parallel_tool_calls": false, "temperature": null, "tool_choice": "auto", "tools": [], "top_p": null, "max_output_tokens": 64, "previous_response_id": null, "reasoning": null, "status": "incomplete", "text": {}, "truncation": null, "usage": "...", "user": null, "store": null, "provider_specific_fields": {"citations": null, "thinking_blocks": null}}

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
curl -sN $PROXY/v1/messages -H "x-api-key: $KEY" -H "anthropic-version: 2023-06-01" -H "content-type: application/json" -d '{"model":"anthropic-control","max_tokens":32,"stream":true,"messages":[{"role":"user","content":"Reply with the single word: hello"}]}'

Client output (the message_delta event):

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null,"stop_details":null,"container":null},"usage":{"input_tokens":18,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":4,"output_tokens_details":{"thinking_tokens":0}}    }

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
curl -sN $PROXY/v1/responses -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude","max_output_tokens":64,"stream":true,"input":"scripted refusal leg"}'

Client output (the final event, with id and usage shortened):

data: {"type": "response.incomplete", "response": {"id": "resp_...", "created_at": 1792005110, "incomplete_details": {"reason": "content_filter"}, "metadata": {}, "model": "claude-sonnet-5-5", "object": "response", "output": [{"type": "message", "id": "msg_9b908d5b-5fe4-425b-8335-08a2fe65c7cf", "status": "incomplete", "role": "assistant", "content": [{"type": "output_text", "text": "", "annotations": []}]}], "parallel_tool_calls": false, "tool_choice": "auto", "tools": [], "max_output_tokens": 64, "status": "incomplete", "text": {}, "usage": "..."}, "model": "scripted-claude"}

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
curl -sN $PROXY/v1/messages -H "x-api-key: $KEY" -H "anthropic-version: 2023-06-01" -H "content-type: application/json" -d '{"model":"scripted-claude","max_tokens":64,"messages":[{"role":"user","content":"scripted refusal leg"}]}'

Client output (the full response):

{"id":"msg_01XFUDYJgAACzvnptvVoYEL","type":"message","role":"assistant","model":"scripted-claude","content":[],"stop_reason":"refusal","stop_details":{"type":"refusal","category":"cyber","explanation":"This request was declined because it could enable cyber harm."},"usage":{"input_tokens":412,"output_tokens":0}}

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 twice

Commands, 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

curl -sN -D call1.headers $PROXY_A/chat/completions -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude","max_tokens":64,"stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"scripted refusal leg"}]}'

Response headers carry no x-litellm-cache-key, so the response did not come from the cache

Call 2, sent to instance B

curl -sN -D call2.headers $PROXY_B/chat/completions -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude","max_tokens":64,"stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"scripted refusal leg"}]}'

Response headers carry no x-litellm-cache-key, so the response did not come from the cache

The 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_details null

9. /chat/completions non-stream with response_format json_schema, scripted refusal through the JSON tool

Commands, 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_call tool_use block. scripted-claude-json-tool maps to anthropic/claude-scripted-9, which the cost map does not list, so the proxy sends the json_tool_call tool with a forced tool_choice

curl -sN $PROXY/chat/completions -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude-json-tool","max_tokens":64,"response_format":{"type":"json_schema","json_schema":{"name":"answer","schema":{"type":"object","properties":{"answer":{"type":"string"}},"required":["answer"],"additionalProperties":false},"strict":true}},"messages":[{"role":"user","content":"scripted refusal leg"}]}'
curl -sN $PROXY/chat/completions -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude","max_tokens":64,"response_format":{"type":"json_schema","json_schema":{"name":"answer","schema":{"type":"object","properties":{"answer":{"type":"string"}},"required":["answer"],"additionalProperties":false},"strict":true}},"messages":[{"role":"user","content":"scripted refusal leg"}]}'

Client output of the first request (the full response):

{"id":"chatcmpl-cb15a146-136b-4bd8-a68e-eec58ea4e286","created":1792005375,"model":"scripted-claude-json-tool","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"{\"answer\": \"Hello..\"}","role":"assistant"}}],"usage":{"completion_tokens":0,"prompt_tokens":412,"total_tokens":412,"completion_tokens_details":{"reasoning_tokens":0,"text_tokens":0},"prompt_tokens_details":{"cached_tokens":0,"text_tokens":412,"cache_write_tokens":0,"cache_creation_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}

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 message and the same callback row, with model scripted-claude

After (2edd392, PR tip, upstream port 55589, proxy port 39974, 2 workers)

1. /v1/messages stream, scripted refusal (the reporter's request)

curl -sN $PROXY/v1/messages -H "x-api-key: $KEY" -H "anthropic-version: 2023-06-01" -H "content-type: application/json" -d '{"model":"scripted-claude","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"scripted refusal leg"}]}'

Client output (the message_delta event):

event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "refusal", "stop_sequence": null, "stop_details": {"type": "refusal", "category": "cyber", "explanation": "This request was declined because it could enable cyber harm."}}, "usage": {"output_tokens": 0}}

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
curl -sN $PROXY/chat/completions -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude","max_tokens":64,"messages":[{"role":"user","content":"scripted refusal leg"}]}'

Client output (the full response):

{"id":"chatcmpl-b9a8e700-fa1d-4167-adaa-0ccb88dfb2c4","created":1792005117,"model":"scripted-claude","object":"chat.completion","choices":[{"finish_reason":"content_filter","index":0,"message":{"role":"assistant","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."}},"content":null}}],"usage":{"completion_tokens":0,"prompt_tokens":412,"total_tokens":412,"completion_tokens_details":{"reasoning_tokens":0,"text_tokens":0},"prompt_tokens_details":{"cached_tokens":0,"text_tokens":412,"cache_write_tokens":0,"cache_creation_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}

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
curl -sN $PROXY/chat/completions -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"scripted refusal leg"}]}'

Client output (every chunk):

data: {"id":"chatcmpl-7296bb3f-704f-4c9c-8a3b-992bdc42bdcb","created":1792005119,"model":"scripted-claude","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"provider_specific_fields":{"stop_reason":"refusal","stop_details":{"type":"refusal","category":"cyber","explanation":"This request was declined because it could enable cyber harm."}},"content":"","role":"assistant"}}]}
data: {"id":"chatcmpl-7296bb3f-704f-4c9c-8a3b-992bdc42bdcb","object":"chat.completion.chunk","created":1792005119,"model":"scripted-claude","choices":[{"index":0,"delta":{},"finish_reason":"content_filter"}]}
data: [DONE]

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
curl -sN $PROXY/v1/responses -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude","max_output_tokens":64,"input":"scripted refusal leg"}'

Client output (the response with id and usage shortened):

{"id": "resp_...", "created_at": 1792005121, "error": null, "incomplete_details": {"reason": "content_filter"}, "instructions": null, "metadata": {}, "model": "scripted-claude", "object": "response", "output": [], "parallel_tool_calls": false, "temperature": null, "tool_choice": "auto", "tools": [], "top_p": null, "max_output_tokens": 64, "previous_response_id": null, "reasoning": null, "status": "incomplete", "text": {}, "truncation": null, "usage": "...", "user": null, "store": null, "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."}}}

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
curl -sN $PROXY/v1/messages -H "x-api-key: $KEY" -H "anthropic-version: 2023-06-01" -H "content-type: application/json" -d '{"model":"anthropic-control","max_tokens":32,"stream":true,"messages":[{"role":"user","content":"Reply with the single word: hello"}]}'

Client output (the message_delta event):

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null,"stop_details":null,"container":null},"usage":{"input_tokens":18,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":4,"output_tokens_details":{"thinking_tokens":0}}     }

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
curl -sN $PROXY/v1/responses -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude","max_output_tokens":64,"stream":true,"input":"scripted refusal leg"}'

Client output (the final event, with id and usage shortened):

data: {"type": "response.incomplete", "response": {"id": "resp_...", "created_at": 1792005126, "incomplete_details": {"reason": "content_filter"}, "metadata": {}, "model": "claude-sonnet-5-5", "object": "response", "output": [{"type": "message", "id": "msg_cba988e1-48dc-4437-9415-d531af401482", "status": "incomplete", "role": "assistant", "content": [{"type": "output_text", "text": "", "annotations": []}]}], "parallel_tool_calls": false, "tool_choice": "auto", "tools": [], "max_output_tokens": 64, "status": "incomplete", "text": {}, "usage": "...", "provider_specific_fields": {"stop_reason": "refusal", "stop_details": {"type": "refusal", "category": "cyber", "explanation": "This request was declined because it could enable cyber harm."}}}, "model": "scripted-claude"}

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
curl -sN $PROXY/v1/messages -H "x-api-key: $KEY" -H "anthropic-version: 2023-06-01" -H "content-type: application/json" -d '{"model":"scripted-claude","max_tokens":64,"messages":[{"role":"user","content":"scripted refusal leg"}]}'

Client output (the full response):

{"id":"msg_01XFUDYJgAACzvnptvVoYEL","type":"message","role":"assistant","model":"scripted-claude","content":[],"stop_reason":"refusal","stop_details":{"type":"refusal","category":"cyber","explanation":"This request was declined because it could enable cyber harm."},"usage":{"input_tokens":412,"output_tokens":0}}

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 twice

Commands, 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

curl -sN -D call1.headers $PROXY_A/chat/completions -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude","max_tokens":64,"stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"scripted refusal leg"}]}'

Response headers carry no x-litellm-cache-key, so the response did not come from the cache

Call 2, sent to instance B

curl -sN -D call2.headers $PROXY_B/chat/completions -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude","max_tokens":64,"stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"scripted refusal leg"}]}'

Response header x-litellm-cache-key (sent only when the response came from the cache):

x-litellm-cache-key: b0eb8b31a083e3d57b144209846d1d3cb8dea4580b09aaa84488bf732a9b6b04

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_details and the same completion_tokens_details

9. /chat/completions non-stream with response_format json_schema, scripted refusal through the JSON tool

Commands, 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_call tool_use block. scripted-claude-json-tool maps to anthropic/claude-scripted-9, which the cost map does not list, so the proxy sends the json_tool_call tool with a forced tool_choice

curl -sN $PROXY/chat/completions -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude-json-tool","max_tokens":64,"response_format":{"type":"json_schema","json_schema":{"name":"answer","schema":{"type":"object","properties":{"answer":{"type":"string"}},"required":["answer"],"additionalProperties":false},"strict":true}},"messages":[{"role":"user","content":"scripted refusal leg"}]}'
curl -sN $PROXY/chat/completions -H "Authorization: Bearer $KEY" -H "content-type: application/json" -d '{"model":"scripted-claude","max_tokens":64,"response_format":{"type":"json_schema","json_schema":{"name":"answer","schema":{"type":"object","properties":{"answer":{"type":"string"}},"required":["answer"],"additionalProperties":false},"strict":true}},"messages":[{"role":"user","content":"scripted refusal leg"}]}'

Client output of the first request (the full response):

{"id":"chatcmpl-e9f363d9-5934-4b27-b96a-2e5528bd02a3","created":1792005377,"model":"scripted-claude-json-tool","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"{\"answer\": \"Hello..\"}","role":"assistant","provider_specific_fields":{"stop_reason":"refusal","stop_details":{"type":"refusal","category":"cyber","explanation":"This request was declined because it could enable cyber harm."}}}}],"usage":{"completion_tokens":0,"prompt_tokens":412,"total_tokens":412,"completion_tokens_details":{"reasoning_tokens":0,"text_tokens":0},"prompt_tokens_details":{"cached_tokens":0,"text_tokens":412,"cache_write_tokens":0,"cache_creation_tokens":0},"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}

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 message and the same callback row, with model scripted-claude

Side 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 stream left out, both legs logged cache_hit null on call 1, then served call 2 from the cache with call 1's id, and on the head both rows also log the refusal stop_details. On both legs the non-stream hit adds an empty choice-level provider_specific_fields that the miss does not have, and since main moved past 2f3ccbe it no longer adds system_fingerprint: null. With the real Anthropic anthropic-control deployment, the case 5 prompt and include_usage, both legs served call 2 from the cache with call 1's id. On both, the hit's usage chunk carried completion_tokens_details {"reasoning_tokens":0,"text_tokens":4} and cost 0.000076 like the miss, but unlike the miss it had no prompt_tokens_details, cache_creation_input_tokens or cache_read_input_tokens. With a second scripted upstream that streams a plain hello with end_turn, one output token and the docs example's model claude-fable-5, both legs served call 2 from the cache, and on both the miss's usage chunk showed cost 0.00417 and the hit's 0.000834. So a miss prices the tokens at the upstream's claude-fable-5 rate and a hit at the deployment's claude-sonnet-5-5 rate on the base too, which is also why case 8's hit shows 0.000824 against the miss's 0.00412

Observations from the run

  • /v1/responses carries stop_details top-level, streamed or not (this PR)
  • /v1/messages non-stream logging copy carries stop_details too (this PR)
  • Chat stream gains an empty chunk before finish (this PR)
  • Refusal stream now cached, so repeats skip upstream (this PR)
  • JSON-mode non-stream chat refusal keeps stop_details now (this PR)
  • Stream cache hit reuses call 1's chunk id (pre-existing)
  • Stream cache hit drops prompt_tokens_details from usage (pre-existing)
  • Hit cost uses deployment price, miss upstream model's (pre-existing)
  • Cache miss logs cache_hit null non-stream, false streamed (pre-existing)
  • Non-stream cache hit adds empty choice-level provider_specific_fields (pre-existing)
  • Non-stream cache hit dropped system_fingerprint on both legs (main)
  • Streaming rows log provider_specific_fields null, non-stream a dict (pre-existing)
  • Callback model is the underlying model, not the alias (pre-existing)
  • /v1/responses logs a ModelResponse to callbacks (pre-existing)
  • JSON-mode refusal says finish_reason stop, not content_filter (pre-existing)
  • Real Anthropic sends stop_details null on message_start and message_delta (upstream)

/live-pr-risk A/B across the Anthropic family

Base f0fedda and head 2edd392 got the same 418 requests. Head logs stop_details on 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 legs

Provider 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.response had no stop_details on base and the docs category cyber on 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 cache

Provider Chat Messages Responses
anthropic yes yes yes
azure_ai yes yes yes
bedrock invoke yes yes yes
bedrock mantle yes yes yes
claude platform yes yes yes
vertex yes yes yes
snowflake stream only stream only stream only
refusal after text yes stream yes stream yes
/anthropic pass-through n/a yes n/a

The "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_format answer and how a split answer is joined. On those routes with a JSON schema, and with a split answer that ends in a refusal message_delta on 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 rows

#46331 cell Finish Stop fields on head
Mantle JSON, stream content_filter yes
Mantle JSON, non-stream stop yes
Platform JSON, stream content_filter yes
Platform JSON, non-stream stop yes
Split refusal, stream content_filter yes
Split refusal, non-stream stop yes
Stream cache hit content_filter yes
Responses stream incomplete yes
Normal JSON or split reply stop none
Streamed 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_tokens

Hit check base head
Hit split equals miss 4 of 17 20 of 20
Spend split equals miss 4 of 17 20 of 20
SDK reads hit details 2 of 7 7 of 7
Non-object psf hit 200 200
Wrong-typed details hit 200 200
Refusal stream cached no yes
JSON mode on anthropic and bedrock invoke

With response_format set, 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

JSON-mode refusal Finish Stop fields on head
Native schema, stream content_filter yes
Native schema, non-stream content_filter yes
JSON tool, stream content_filter yes
JSON tool, non-stream stop yes
JSON tool, cache hit stop yes
JSON tool, OpenAI SDK stop yes
JSON tool, Responses stream incomplete yes
JSON tool, Responses completed yes
Normal JSON-mode reply base head
Content {"answer": "hello"} same
Finish stop stop
Message fields none none
Logged stop fields none none
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_extra on head

Non-stream refusal Message keys Stop fields on head
anthropic same as base yes
bedrock invoke same as base yes
vertex same as base yes
openai same as base n/a

An upstream stop_details of an unexpected type or size is passed through as sent, on the JSON tool path too. Base passed it only on Messages

Upstream stop_details base head
int, list or empty Messages only every surface
5 KB string Messages only every surface
object on a normal reply Messages only every surface
Status 200 200

A 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
Lane Commit Passed Failed Skipped
base f0fedda 22 81 0
head run 1 cde56b9 103 0 0
head run 2 cde56b9 103 0 0
controls cde56b9 341 25 2

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_id cells, provider errors and wrong-typed cached usage details

The 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

Control reds Count Head, 1 worker Base f0fedda
Proxy boot over 240s 14 13 pass, 1 skip not run
Vertex JSON schema stream 10 fail fail
Worker SIGKILL burst 1 2 of 3 pass 2 of 3 pass

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 too

Behavior change at the head Declared in
Empty refusal chat stream is cached Decisions
Stream hit replays cached provider fields Decisions
Added finish chunk keeps received_model_id TLDR
Stream hits keep the usage split Decisions
Wrong-typed cached details are skipped Decisions
JSON tool refusal keeps the fields TLDR

Eight 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/responses call 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 call

Leg Miss reasoning Hit reasoning
base 62 0
head 62 62

Type

🐛 Bug Fix

Caveats (if any)

Low

  • Refusal legs replay Anthropic's documented refusal from a scripted upstream. Net negative to fix since a live refusal needs a prompt built to trip the safeguard
  • Agentic /v1/messages stream hooks see no stop_details. Net negative to fix since no hook reads it
  • Snowflake non-stream responses get no fields. Net negative to fix since nothing shows Snowflake sending them
  • A non-stream /v1/responses cache hit drops the top-level provider_specific_fields for every provider, as on main. Net negative to fix here since it is a cache layer fix on its own ticket
  • A TypedDict and a pydantic adapter read two keys where .get would do. Net negative to change since behavior is the same
  • A JSON tool refusal finishes with stop when not streamed and content_filter when streamed, as on main. Net negative to fix here since it changes every JSON-mode caller
  • Bedrock Converse sends no stop details, an upstream limit
Caveat details
  • Every refusal leg in this PR (QA cases 1 to 4 and 6 to 9, the /live-pr-risk table, and the unit fixtures) is served the refusal example in Anthropic's docs, copied verbatim on 2026-10-12, and streamed on message_delta as 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 with stop_reason: "max_tokens" and stop_details: null, and the current streaming refusal docs no longer list it
  • Streaming /v1/messages with agentic hooks rebuilds the message for the hooks from stop_reason and stop_sequence only, so the hooks still see no stop_details. The logged copy is not affected. Net negative to fix here: no hook reads it, and the fix would re-run every live pass
  • Snowflake streams pick up the fields through the shared Anthropic stream parser, but Snowflake non-stream responses go through Snowflake's own mapping and do not. Net negative to fix here: nothing shows Snowflake sending stop_details
  • A non-streamed /v1/responses call served from the response cache returns no top-level provider_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
  • The refusal-field read uses a TypedDict and a small pydantic adapter for two keys, and only the non-stream path uses the adapter. A plain .get would be simpler. Net negative to change now: it has no behavior effect and would re-run every live pass
  • On the JSON tool path, which Anthropic models without native structured output and Bedrock invoke use for response_format, a non-stream refusal ends with finish_reason: "stop" and a streamed one with content_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 from provider_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 ticket
  • The default Bedrock Converse route still gives no refusal category, because Converse returns stopReason: content_filtered without stop details. This is an upstream limit with nothing in LiteLLM to change

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
  • 2edd392 passes /live-pr-risk

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_reason and stop_details after mapping to OpenAI-style content_filter. Those fields are merged into message.provider_specific_fields (and streaming delta.provider_specific_fields) via a shared refusal_provider_specific_fields helper on non-stream transforms, message_delta streaming, and JSON-mode tool paths.

Cache replay and logging: Streamed cache hits now replay cached provider_specific_fields and completion_tokens_details with pydantic validation (invalid shapes are skipped). CustomStreamWrapper keeps received_model_id on 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.

@devin-ai-integration

devin-ai-integration Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@codspeed

codspeed Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 31 untouched benchmarks


Comparing litellm_anthropic_refusal_stop_details (cde56b9) with main (039dea2)

Open in CodSpeed

@codecov

codecov Bot commented Oct 12, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@litereview

litereview Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings. The earlier streamed JSON-mode finding is fixed. The four -sse JSON-tool cases now expect content_filter, and the full refusal wire and chaos suites pass on this head.

One description fix to make before merge: the Low caveat says a JSON-tool refusal ends with finish_reason: "stop" "streamed or not". That doesn't match the code or the updated test. Streamed JSON-tool refusals finish with content_filter, just as they did on main. Only the non-stream path forces stop.

Checks and execution details
  • Passed · Real testing evidence (required): The PR changes translation behavior in scope: litellm/llms/anthropic/chat/transformation.py, handler.py and common_utils.py now carry refusal stop_reason/stop_details on responses and stream chunks. Qualifying integration tests drive the real proxy through /chat/completions (stream and non-stream), /v1/responses, /v1/messages, Bedrock invoke, Vertex, cache hits, JSON mode and spend logs against a scripted upstream, and assert both the client output and the logged payload. Fixture provenance is documented: tests/integration/_support/anthropic_refusal.py and tests/unit/llms/anthropic/anthropic_docs_refusal.py cite Anthropic's refusal docs URL and say the payload was copied verbatim on 2026-10-12. Executed locally on cde56b9: the providers refusal wire and chaos files gave 99 passed, and tests/integration/sdk/test_response_cache_sync_sdk.py gave 7 passed.
  • Passed · Unit tests for changed modules (optional): Ran pytest on the Anthropic chat handler/transformation, streaming handler, convert-to-streaming-response, passthrough logging handler, Bedrock invoke Claude and Vertex Anthropic transformation tests: 1042 passed.

View review · Reviewed cde56b942526

@mateo-berri

Copy link
Copy Markdown
Contributor

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

@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@litereview

litereview Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@litereview

litereview Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

…eceived_model_id on synthesized finish chunks
@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@litereview

litereview Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

… hits and skip non-object cached provider fields
@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

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

@mateo-berri

Copy link
Copy Markdown
Contributor

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

Copy link
Copy Markdown
Contributor

@litereview code-review

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

…usal_stop_details

# Conflicts:
#	litellm/llms/anthropic/chat/handler.py
@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@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!

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

Reviewed by Cursor Bugbot for commit cde56b9. 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

@mateo-berri
mateo-berri merged commit 47e4ed8 into main Oct 14, 2026
90 checks passed
@mateo-berri
mateo-berri deleted the litellm_anthropic_refusal_stop_details branch October 14, 2026 21:42
@mateo-berri

Copy link
Copy Markdown
Contributor

@litellm-stampbot

@litellm-stampbot

Copy link
Copy Markdown

litellm-stampbot: risk high

Not approved at cde56b9. approval blocked: pull request is closed.

Rules (stampbot/risk_rules.yml):

  • approval blocked: pull request is closed

Judge (gpt-6-luna): high, default behavior change, request hot path, complex diff

  • tier: high (confidence 1.00)
  • change_kind: default_behavior_change (confidence 0.95)
  • blast_radius: request_hot_path (confidence 0.69)
  • complexity: complex (confidence 1.00)

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@litellm-stampbot litellm-stampbot Bot added the risk:high Sensitive, broad, or high-risk change label Oct 14, 2026
mateo-berri added a commit that referenced this pull request Oct 15, 2026
…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
mateo-berri added a commit that referenced this pull request Oct 15, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Sensitive, broad, or high-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Preserve Anthropic-native refusal metadata (stop_reason, stop_details) through streaming aggregation

1 participant