Repository navigation
fix(anthropic): count a replayed server tool call's cache mark the way modify_params sends it - #46591
Conversation
…y 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.
|
Automatic reviews are disabled for this repository. |
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
@litereview code-review |
Merging this PR will not alter performance
|
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. Completed · Some checks not run. No correctness findings. I traced the hook's new route gating, the I also compared the rewritten I didn't run the provider wire suites ( Checks and execution details
The scoped files are
Supporting evidence: the PR also lists live Anthropic request ids at
Result: 567 passed. This was after The factory and mid-conversation unit files passed in the combined run: 971 passed, and the only 2 failures were those
Result: 37 passed. These tests drive
Result: 0 output differences over 30,000 random conversations covering Inputs that start with a system message differ only in exception type (
View review · Reviewed |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…he 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.
|
bugbot run |
|
@litereview code-review |
…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.
…ver_tool_replay_follow_up # Conflicts: # litellm/llms/anthropic/common_utils.py
|
bugbot run |
|
@litereview code-review |
…e the way the request builder does
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 1 · PR risk: 0/10 |
…efore the answer in the cache mark census
…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
…laced, and find client answers once per request
…and a later system message
…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
…call in the malformed tool id cell
|
bugbot run |
|
@litereview code-review |
…e for models that keep them
…th the request builder's converting placement
|
bugbot run |
|
@litereview code-review |
…r'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.
|
bugbot run |
|
@litereview code-review |
… system message on Databricks, OpenRouter and Bedrock Converse
|
bugbot run |
|
@litereview code-review |
…atGPT routes without resolving them, so a sync call with no stored login never starts the device flow
|
bugbot run |
|
@litereview code-review |
…Copilot and ChatGPT login hosts like an unmarked one
|
bugbot run |
|
@litereview code-review |
…ver_tool_replay_follow_up # Conflicts: # litellm/llms/anthropic/common_utils.py # tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py
|
bugbot run |
|
@litereview code-review |
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 f4ab3ac. Configure here.
|
@litellm-stampbot |
litellm-stampbot: risk lowApproved at Rules (
Judge (gpt-6-luna): low, probability of high 0.03 (high at or above 0.90)
Pushes do not re-run this check. Comment |
kerry-berri
left a comment
There was a problem hiding this comment.
Low risk by rule and by judgement at f4ab3ac
TLDR
Problem this solves:
modify_paramson, a lone trailing search call still sends a placeholder answerHow it solves it:
modify_paramspairing stepDecisions on the placeholder, system message placement, routes, pairing, the mark budget, and the audit cells
The lone trailing search call keeps its
modify_paramsplaceholder answer instead of being rebuilt from its kept result. A rebuilt result would end the request on an assistant turn, andclaude-opus-5-5answers 400 "This model does not support assistant message prefill." The other options were appending a user turn the caller never sent, or counting marks from a full request build, which costs far more per countThe hook places later system messages with the model's own
supports_mid_conversation_systemflag, the flag the request builder reads, so the count matches what Anthropic receives on every model. The sync SDK and the Router leavecustom_llm_providerout of the hook's params, so when that lookup cannot resolve the model, the hook reads the flag from the cost map entry the model name matches on its own. A model that neither lookup knows gets the converting placement, as the request builder gives it. A caller with no model at hand counts with the flagged placement, which counts at least every mark Anthropic receives, so it never sends a fifth. Those callers are the logging delta, which does not depend on placement, the/v1/messagesroute, which carries no OpenAI tool calls, and the client cache control check. Messages the hook cannot place or pair are counted as sent, like main. The other option was the flagged placement for every model, which dropped the injected system mark main sends on models without the flag, such asclaude-sonnet-4-6The hook counts this way only when the route's chat config builds Anthropic Messages requests, which covers the Anthropic, Bedrock invoke, Bedrock Mantle, Vertex AI and Azure AI Claude routes. Databricks extends the Anthropic config but sends an OpenAI-shaped request, and OpenRouter and Bedrock Converse have their own builders, so those routes keep main's count, the tool answers in the messages minus the server tool calls rebuilt from kept results. Without this, the hook skipped a mark those routes still send, and all three answered 400 "Found 5" where main answered 200. The sync SDK and the Router leave
custom_llm_providerout of the hook's params, so the step that seeds injection points stamps it on them, only when a marked server tool call is present, and every other request keeps its configured points as they are. GitHub Copilot and ChatGPT keep main's count without resolving the route, since resolving them starts their device login when no login is stored, which blocked a sync call. A route the hook cannot resolve keeps the Anthropic count, as this PR did before the route check. The other option was a list of provider names, which a new route that reuses the Anthropic config would missThe
modify_paramspairing step now finds an orphaned tool result with a set lookup on the latest assistant's tool call ids, computed once per message list, instead of scanning back through every kept message for each tool result. It drops the same results as main on generated conversations, and its cost now grows linearly with the number of answered tool callsWhen the caller's own marks and the injection points add up to more than 4, the caller's marks go out and injection stops at the cap, which is what the hook already does on main
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. The streamed response cache hit cell runs again, since #46104 keeps the kept result on a cached stream. The cap cell expects the caller's four marks. The non-streamed case of
test_snowflake_claude_keeps_the_tool_search_result_on_the_responseskips as a known bug main has too. New cells cover a system message after the trailing search turn in both stream modes, a marked search call next to a malformed tool id and a later system message, which answers 400 as on main, and a client answer to one of two marked search calls on a model with the flag and onclaude-sonnet-4-6User Flow
Before: an agent with
modify_paramson and four cache marks gets a 400 when it sends a tool search call back on its own as the last assistant turnlitellm.modify_params = Trueand callslitellm.completiononanthropic/claude-opus-5-5with tool search and a deferredget_weathersrvtoolu_...search call, the search result, and aget_weathercallget_weather, asks a follow-up, and sends the search call back last, unanswered, withcache_controlon both calls, two user blocks, andcache_control_injection_pointslitellm.completionraises 400 "A maximum of 4 blocks with cache_control may be provided. Found 5", streaming or not, and so does the proxy's POST /v1/chat/completionsAfter: the same turn comes back 200 with the model's answer
litellm.modify_params = Trueand callslitellm.completiononanthropic/claude-opus-5-5with tool search and a deferredget_weathersrvtoolu_...search call, the search result, and aget_weathercallget_weather, asks a follow-up, and sends the search call back last, unanswered, withcache_controlon both calls, two user blocks, andcache_control_injection_pointslitellm.completionreturns 200 with the model's answer, streaming or not, and so does the proxy's POST /v1/chat/completionsRelevant issues
Follow-up to #46440
Linear ticket
Resolves LIT-9576
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 moreDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
/audit at f4ab3ac against b4a63d3
Audit round 3 of 3
PASS. The head is f4ab3ac, which merges main b4a63d3 into the branch. The base leg is the merge base b4a63d3 with the branch's 7 changed test paths overlaid. Every inventory row is VERIFIED at f4ab3ac, and no row is unverified. Round 1 ran at 4c60d8f and round 2 at 9ee8798. The merge has a product change in
tool_call_is_rebuilt_as_server_tool_use, so every cell, the chaos cells and the live rows ran again on both legsAll lanes ran on rig
lit46591au(CI's Python 3.12 per-group environment, seed 4106601, order seed 0) in oneremote_rig.py round. A run id islit46591au/<lane>plus its finish time (UTC, 2026-10-15)The 4 base reds are the expected ones. The trailing marked search turn, two marked searches on
claude-opus-5-5, and the bareinvoke/us.anthropic.claude-opus-5-5call throughlitellm.completionandRouter.completioneach get a 400 "A maximum of 4 blocks with cache_control may be provided. Found 5" from the scripted upstream on base, and pass on the head. Both head runs collected the same 158 cells and passed the same 157, and each of the 158 cells has the same outcome as in round 2. The one skip on both legs is the existing Snowflake non-stream BUG skip, since a non-streamed Snowflake Claude response drops thetool_search_tool_resultblock on main tooNode ids
Selected cells, all under
tests/integration/:Among them, these cells are new on this branch:
providers/test_anthropic_tool_search_result_modify_params_wire.py::test_two_answered_marked_search_calls_before_a_system_message_stay_within_the_cache_mark_cap_off_anthropic, 12 cells over Databricks, OpenRouter and Bedrock Conversesdk/test_device_code_login_guard_sdk.py::test_a_marked_server_tool_call_reaches_the_auth_host_like_an_unmarked_one_when_the_login_is_denied[chatgpt]and[copilot]sdk/test_cache_control_census_pydantic_messages_sdk.py::test_bare_model_with_custom_llm_provider_fills_the_cache_mark_budget_like_the_request_builder, 6 cellsproviders/test_anthropic_tool_search_result_modify_params_wire.py::test_modify_params_client_answer_to_one_of_two_marked_search_calls_fills_the_cache_mark_budget[keeps-mid-conversation-system]and[converts-mid-conversation-system]The controls ran once on the head: 512 cells in 24 files that share the hook, the census helpers in
factory.py,tool_call_is_rebuilt_as_server_tool_useor the Responses bridge. Round 2's controls ran again, and main's own tool search cells joined them because they cross the merged function (test_openai_responses_tool_search_wire.py48,test_chat_completions_tool_search_wire.py39,test_responses_bridge_tool_search_replay.py30,test_chat_completions_tool_search_history_wire.py15,test_chat_completions_tool_search_chaos.py4). The one skip is main's own BUG skip intest_openai_responses_tool_search_wire.py, on a path this PR does not touchFixed on this branch
Two regressions against base were found during review and fixed before round 3, and each cell above passes on both head runs:
Inherited red (Low)
providers/test_responses_bridge_tool_search_chaos.py::test_a_previous_response_id_turn_replays_the_function_call_without_the_search_callfails the same way on the merge base (lit46591au/probe9-base) and on the head, and this PR does not touch its path. #46440 keeps the Claude search result withsrvtoolu_ids in replayed history, while this cell from #45882 asserts that nosrvtoolu_id leaves the bridgeLive rows (real Anthropic API)
Each leg's two-worker proxy took POST /v1/chat/completions with
anthropic/claude-opus-5-5. Every first turn kept thetool_search_tool_resultfor itssrvtoolu_call, and every replay answered 200The client is the litellm Python SDK with a real Anthropic key, and turn 2 also runs with a later system message and through
litellm.RouterThe SDK script, sdk_m3.py (turn 1, then turn 2 built from turn 1)
The proxy commands (turn 1, then turn 2 built from turn 1 with jq)
The proxy case boots
litellm --config config.yaml --port $PORT --num_workers 2from the same tree, setsU=http://127.0.0.1:$PORT, and sends real calls with curl and the OpenAI SDKThe OpenAI SDK script through the proxy, proxy_m3.py
Before (b4a63d3, main)
The proxy run, curl plus jq
get_weathercallThe same turns through the proxy with the OpenAI SDK
After (f4ab3ac)
The proxy run, curl plus jq
get_weathercallThe same turns through the proxy with the OpenAI SDK
On `claude-sonnet-4-6`, a model without mid-conversation system messages, main raises the same 400 and this PR answers 200
Every #46440 tool search regression case at f4ab3ac
answer_allanswer_allmodify_paramsmodify_paramssearch_onlysearch_onlyweb_searchweb_searchweb_search_modifyweb_search_modifycache_markcache_marktool_loopmodify_params_unansweredget_weather) and tried it for Paris, but themodify_params_unansweredget_weather) and asked it for the weather incache_mark_modify_trailingcache_mark_modify_trailingThe #46440 case through the proxy, booted from f4ab3ac with 2 workers, with curl non-streaming and the OpenAI SDK streaming
Databricks, OpenRouter and Bedrock Converse answer 400 "Found 5" at the earlier tip 4c60d8f and 200 at f4ab3ac, like main
Each route gets four marks, from the caller and the injection points, with
modify_paramson. Databricks and OpenRouter get a plainget_weathertool, since both reject the tool search tool on main too. On Databricks and OpenRouter theweather_answered_after_systemcase answers 400 on main too, and this PR leaves it aloneA stray string in `extra_body.messages` next to a marked tool call
Type
🐛 Bug Fix
✅ Test
Caveats (if any)
High
Medium
tool_search_tool_result, as on mainLow
modify_paramsplaceholder, not its kept resultFinal Attestation