Skip to content

fix(anthropic): count a replayed server tool call's cache mark the way modify_params sends it - #46591

Merged
mateo-berri merged 23 commits into
mainfrom
litellm_anthropic_server_tool_replay_follow_up
Oct 15, 2026
Merged

mateo-berri merged 23 commits into
mainfrom
litellm_anthropic_server_tool_replay_follow_up

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

How it solves it:

  • The hook counts marks on the messages the request builder sends that model, so it places later system messages the same way and runs the modify_params pairing step
  • It does that once per request, only for a marked server tool call on a route that builds Anthropic Messages requests
  • Databricks, OpenRouter, Bedrock Converse, GitHub Copilot and ChatGPT build other request shapes, so they keep main's count
  • Both steps now take linear time
Decisions on the placeholder, system message placement, routes, pairing, the mark budget, and the audit cells

The lone trailing search call keeps its modify_params placeholder answer instead of being rebuilt from its kept result. A rebuilt result would end the request on an assistant turn, and claude-opus-5-5 answers 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 count

The hook places later system messages with the model's own supports_mid_conversation_system flag, the flag the request builder reads, so the count matches what Anthropic receives on every model. The sync SDK and the Router leave custom_llm_provider out 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/messages route, 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 as claude-sonnet-4-6

The 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_provider out 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 miss

The modify_params pairing 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 calls

When 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_response skips 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 on claude-sonnet-4-6

User Flow

Before: an agent with modify_params on and four cache marks gets a 400 when it sends a tool search call back on its own as the last assistant turn

  1. The app sets litellm.modify_params = True and calls litellm.completion on anthropic/claude-opus-5-5 with tool search and a deferred get_weather
  2. It gets back a srvtoolu_... search call, the search result, and a get_weather call
  3. It answers get_weather, asks a follow-up, and sends the search call back last, unanswered, with cache_control on both calls, two user blocks, and cache_control_injection_points
  4. litellm.completion raises 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/completions

After: the same turn comes back 200 with the model's answer

  1. The app sets litellm.modify_params = True and calls litellm.completion on anthropic/claude-opus-5-5 with tool search and a deferred get_weather
  2. It gets back a srvtoolu_... search call, the search result, and a get_weather call
  3. It answers get_weather, asks a follow-up, and sends the search call back last, unanswered, with cache_control on both calls, two user blocks, and cache_control_injection_points
  4. litellm.completion returns 200 with the model's answer, streaming or not, and so does the proxy's POST /v1/chat/completions

Relevant 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

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

Delays in PR merge?

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

Screenshots / Proof of Fix

  • f4ab3ac passes /live-pr-risk, rerun on the main merge
  • f4ab3ac passes /audit
/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 legs

All lanes ran on rig lit46591au (CI's Python 3.12 per-group environment, seed 4106601, order seed 0) in one remote_rig.py round. A run id is lit46591au/<lane> plus its finish time (UTC, 2026-10-15)

Run id Commit Cells Result Finished
lit46591au/base-providers b4a63d3 124 121 pass, 2 red, 1 skip 20:43:11
lit46591au/base-sdk b4a63d3 34 32 pass, 2 red 20:45:18
lit46591au/head-run1-providers f4ab3ac 124 123 pass, 1 skip 20:51:32
lit46591au/head-run1-sdk f4ab3ac 34 34 pass 20:53:57
lit46591au/head-run2-providers f4ab3ac 124 123 pass, 1 skip 20:59:56
lit46591au/head-run2-sdk f4ab3ac 34 34 pass 21:02:17
lit46591au/ctl-providers f4ab3ac 505 503 pass, 1 red, 1 skip 21:38:26
lit46591au/ctl-sdk f4ab3ac 7 7 pass 21:39:02
lit46591au/probe9-base b4a63d3 3 2 pass, 1 red 21:40:59

The 4 base reds are the expected ones. The trailing marked search turn, two marked searches on claude-opus-5-5, and the bare invoke/us.anthropic.claude-opus-5-5 call through litellm.completion and Router.completion each 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 the tool_search_tool_result block on main too

Node ids

Selected cells, all under tests/integration/:

File Cells
providers/test_anthropic_tool_search_result_matrix_wire.py 62
providers/test_anthropic_tool_search_result_modify_params_wire.py 37
providers/test_vertex_passthrough_wire.py 18
providers/test_anthropic_tool_search_result_passthrough_wire.py 4
providers/test_anthropic_tool_search_result_chaos.py 3
sdk/test_device_code_login_guard_sdk.py 24
sdk/test_cache_control_census_pydantic_messages_sdk.py 6
sdk/test_tool_loop_server_tool_replay_sdk.py 4

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 Converse
  • sdk/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 cells
  • providers/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_use or 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.py 48, test_chat_completions_tool_search_wire.py 39, test_responses_bridge_tool_search_replay.py 30, test_chat_completions_tool_search_history_wire.py 15, test_chat_completions_tool_search_chaos.py 4). The one skip is main's own BUG skip in test_openai_responses_tool_search_wire.py, on a path this PR does not touch

Fixed 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:

Shape Broke at Fixed by
Databricks, OpenRouter, Converse sent 5 marks (400) 2f21e51 190fb72
Copilot or ChatGPT started an extra device login 190fb72 9ee8798

Inherited red (Low)

providers/test_responses_bridge_tool_search_chaos.py::test_a_previous_response_id_turn_replays_the_function_call_without_the_search_call fails 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 with srvtoolu_ ids in replayed history, while this cell from #45882 asserts that no srvtoolu_ id leaves the bridge

Live 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 the tool_search_tool_result for its srvtoolu_ call, and every replay answered 200

Row Base replay Head replay
Non-stream round trip req_011Cg4gC8rjjBGHnpM1kNkRr req_011Cg4hVkiLuEW7DEQpWQpGT
Stream round trip req_011Cg4gCWhtEvkN9FY83fc8V req_011Cg4hVzmvpB8ydnRT9DrR8
Both calls answered req_011Cg4gD1DP88JFWTCPYiq3K req_011Cg4hWWqwNJobmt8zTX4cb
Search answered only req_011Cg4gDGWssKvhS4P3TZxwj req_011Cg4hWkzjDG5YEP3tMWi7S

The client is the litellm Python SDK with a real Anthropic key, and turn 2 also runs with a later system message and through litellm.Router

The SDK script, sdk_m3.py (turn 1, then turn 2 built from turn 1)
import os
import re

import litellm

litellm.modify_params = True
litellm.suppress_debug_info = True
MODEL = os.environ.get("QA_MODEL", "anthropic/claude-opus-5-5")
TOOLS = [
    {"type": "tool_search_tool_bm25_20251119", "name": "tool_search_tool_bm25"},
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a city",
            "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
        },
        "defer_loading": True,
    },
]
SYSTEM = {"role": "system", "content": "You are a helpful assistant."}
ASK = "Find a weather tool and use it to get the weather in Paris."
MARK = {"type": "ephemeral"}

first = litellm.completion(model=MODEL, max_tokens=1024, tools=TOOLS, messages=[SYSTEM, {"role": "user", "content": ASK}])
turn = first.choices[0].message.model_dump(exclude_none=True)
print("turn 1:", [(c["function"]["name"], c["id"]) for c in turn["tool_calls"]],
      [r["type"] for r in turn["provider_specific_fields"]["tool_results"]])
calls = [call | {"cache_control": MARK} for call in turn["tool_calls"]]
client_calls = [c for c in calls if not c["id"].startswith("srvtoolu_")]
search_calls = [c for c in calls if c["id"].startswith("srvtoolu_")]
messages = [
    SYSTEM,
    {"role": "user", "content": [
        {"type": "text", "text": "Context: the user is planning a trip.", "cache_control": MARK},
        {"type": "text", "text": ASK, "cache_control": MARK},
    ]},
    turn | {"tool_calls": client_calls},
    *({"role": "tool", "tool_call_id": c["id"], "content": "18C and cloudy"} for c in client_calls),
    {"role": "user", "content": "Search for any other weather tool too."},
    turn | {"content": "", "tool_calls": search_calls},
]
points = [{"location": "message", "role": "system"}, {"location": "message", "index": -1}]
router = litellm.Router(model_list=[{"model_name": "claude", "litellm_params": {"model": MODEL}}])
cases = (
    ("turn 2", litellm.completion, MODEL, messages),
    ("turn 2 + later system message", litellm.completion, MODEL, [*messages, {"role": "system", "content": "Answer in one sentence."}]),
    ("router turn 2", router.completion, "claude", messages),
)
for label, call, model, case_messages in cases:
    for stream in (False, True):
        try:
            response = call(model=model, max_tokens=1024, tools=TOOLS, messages=case_messages,
                            cache_control_injection_points=points, stream=stream)
            if stream:
                response = litellm.stream_chunk_builder(list(response), messages=case_messages)
            print(f"{label} stream={stream}: 200 |", (response.choices[0].message.content or "")[:60].replace("\n", " "))
        except litellm.BadRequestError as error:
            found = re.search(r"A maximum of 4 blocks with cache_control may be provided\. Found \d+", str(error))
            print(f"{label} stream={stream}: {error.status_code} |", found.group(0) if found else str(error)[:200])
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 2 from the same tree, sets U=http://127.0.0.1:$PORT, and sends real calls with curl and the OpenAI SDK

model_list:
  - model_name: claude-opus-5-5
    litellm_params:
      model: anthropic/claude-opus-5-5
      api_key: os.environ/ANTHROPIC_API_KEY
litellm_settings:
  modify_params: true
#!/bin/zsh
set -u
U=$1
AUTH="Authorization: Bearer $LITELLM_MASTER_KEY"
TOOLS='[{"type":"tool_search_tool_bm25_20251119","name":"tool_search_tool_bm25"},{"type":"function","function":{"name":"get_weather","description":"Get the current weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}},"defer_loading":true}]'
ASK="Find a weather tool and use it to get the weather in Paris."
echo '$ curl -s $U/v1/chat/completions -d "{model: claude-opus-5-5, tools: [tool_search_tool_bm25, get_weather (defer_loading)], messages: [system, user ask]}" > turn1.json'
curl -s $U/v1/chat/completions -H "$AUTH" -H 'Content-Type: application/json' \
  -d "$(jq -n --argjson tools $TOOLS --arg ask $ASK '{model: "claude-opus-5-5", max_tokens: 1024, tools: $tools, messages: [{role: "system", content: "You are a helpful assistant."}, {role: "user", content: $ask}]}')" > turn1.json
echo '$ jq -c ".choices[0].message | {tool_calls: [.tool_calls[] | [.function.name, .id]], tool_results: [.provider_specific_fields.tool_results[]?.type]}" turn1.json'
jq -c '.choices[0].message | {tool_calls: [.tool_calls[] | [.function.name, .id]], tool_results: [.provider_specific_fields.tool_results[]?.type]}' turn1.json
for stream in false true; do
  jq --argjson tools $TOOLS --arg ask $ASK --argjson stream $stream '
    .choices[0].message as $m
    | ($m.tool_calls | map(. + {cache_control: {type: "ephemeral"}})) as $calls
    | ([$calls[] | select(.id | startswith("srvtoolu_") | not)]) as $client
    | {model: "claude-opus-5-5", max_tokens: 1024, tools: $tools, stream: $stream,
       cache_control_injection_points: [{location: "message", role: "system"}, {location: "message", index: -1}],
       messages: [
         {role: "system", content: "You are a helpful assistant."},
         {role: "user", content: [
           {type: "text", text: "Context: the user is planning a trip.", cache_control: {type: "ephemeral"}},
           {type: "text", text: $ask, cache_control: {type: "ephemeral"}}]},
         ($m + {tool_calls: $client}),
         ($client[] | {role: "tool", tool_call_id: .id, content: "18C and cloudy"}),
         {role: "user", content: "Search for any other weather tool too."},
         ($m + {content: "", tool_calls: [$calls[] | select(.id | startswith("srvtoolu_"))]})]}' turn1.json > turn2_$stream.json
  echo "\$ curl -s -w 'HTTP %{http_code}' \$U/v1/chat/completions -d @turn2_$stream.json   # stream=$stream, modify_params on, both calls and two user blocks marked, the search call last and unanswered"
  curl -s -w '\nHTTP %{http_code}\n' $U/v1/chat/completions -H "$AUTH" -H 'Content-Type: application/json' -d @turn2_$stream.json > turn2_$stream.out
  if [[ $stream == true ]]; then
    grep -o '"content":"[^"]*"' turn2_$stream.out | head -40 | sed 's/"content":"//; s/"$//' | tr -d '\n' | cut -c1-160; echo
    grep -o 'A maximum of 4 blocks with cache_control may be provided. Found [0-9]*' turn2_$stream.out | head -1
    tail -1 turn2_$stream.out
  else
    head -n -1 turn2_$stream.out | jq -c '{status: (if .error then .error.code else "ok" end), answer: (.choices[0].message.content // null | if . then .[0:160] else null end), error: (.error.message // null | if . then (capture("(?<m>A maximum of 4 blocks[^\"]*Found [0-9]+)").m // .[0:200]) else null end)}'
    tail -1 turn2_$stream.out
  fi
done
The OpenAI SDK script through the proxy, proxy_m3.py
import json
import os
import sys

import openai
from openai import OpenAI

client = OpenAI(base_url=sys.argv[1], api_key=os.environ["LITELLM_MASTER_KEY"])
TOOLS = [
    {"type": "tool_search_tool_bm25_20251119", "name": "tool_search_tool_bm25"},
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a city",
            "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
        },
        "defer_loading": True,
    },
]
PROMPT = "Find a weather tool and use it to get the weather in Paris."
SYSTEM = {"role": "system", "content": "You are a helpful assistant. " * 300}
EPHEMERAL = {"type": "ephemeral"}
POINTS = [{"location": "message", "role": "system"}, {"location": "message", "index": -1}]

first = client.chat.completions.create(
    model="claude-opus-5-5", messages=[SYSTEM, {"role": "user", "content": PROMPT}], tools=TOOLS, max_tokens=1024
)
turn = first.choices[0].message.model_dump(exclude_none=True)
print("turn 1:", first.id, [(c["function"]["name"], c["id"][:16]) for c in turn.get("tool_calls", [])])
print("turn 1 tool_results:", [r.get("type") for r in turn.get("provider_specific_fields", {}).get("tool_results", [])])
calls = [call | {"cache_control": EPHEMERAL} for call in turn.get("tool_calls", [])]
client_calls = [c for c in calls if not c["id"].startswith("srvtoolu_")]
search_calls = [c for c in calls if c["id"].startswith("srvtoolu_")]
history = [
    SYSTEM,
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "Context: the user is planning a trip.", "cache_control": EPHEMERAL},
            {"type": "text", "text": PROMPT, "cache_control": EPHEMERAL},
        ],
    },
    turn | {"tool_calls": client_calls},
    *({"role": "tool", "tool_call_id": c["id"], "content": "18C and cloudy"} for c in client_calls),
    {"role": "user", "content": "Search for any other weather tool too."},
    turn | {"content": "", "tool_calls": search_calls},
]
print("turn 2 request: cache_control on 2 user blocks,", len(calls), "tool calls; injection points", json.dumps(POINTS))
for stream in (False, True):
    try:
        response = client.chat.completions.create(
            model="claude-opus-5-5",
            messages=history,
            tools=TOOLS,
            max_tokens=1024,
            stream=stream,
            extra_body={"cache_control_injection_points": POINTS},
        )
        text = "".join((c.choices[0].delta.content or "") for c in response if c.choices) if stream else response.choices[0].message.content
        print(f"turn 2 stream={stream}: 200 |", (text or "")[:160].replace("\n", " "))
    except openai.APIStatusError as e:
        print(f"turn 2 stream={stream}: {e.status_code} |", str(e.message)[:300])

Before (b4a63d3, main)

  1. Turn 2 raises a 400 in both modes, directly and through the Router, but not with a later system message
$ ANTHROPIC_API_KEY=... .venv/bin/python sdk_m3.py
turn 1: [('tool_search_tool_bm25', 'srvtoolu_019V71jTJzTC7WL6PWaQdpch'), ('get_weather', 'toolu_019J6hPdofN3YLs8q1MNHukE')] ['tool_search_tool_result']
turn 2 stream=False: 400 | A maximum of 4 blocks with cache_control may be provided. Found 5
turn 2 stream=True: 400 | A maximum of 4 blocks with cache_control may be provided. Found 5
turn 2 + later system message stream=False: 200 | The search turned up only one weather tool, get_weather (the
turn 2 + later system message stream=True: 200 | The search found only one weather tool, `get_weather`, which
router turn 2 stream=False: 400 | A maximum of 4 blocks with cache_control may be provided. Found 5
router turn 2 stream=True: 400 | A maximum of 4 blocks with cache_control may be provided. Found 5
The proxy run, curl plus jq
  1. Turn 1 returns the search call, its kept result, and a get_weather call
$ curl -s $U/v1/chat/completions -d "{model: claude-opus-5-5, tools: [tool_search_tool_bm25, get_weather (defer_loading)], messages: [system, user ask]}" > turn1.json
$ jq -c ".choices[0].message | {tool_calls: [.tool_calls[] | [.function.name, .id]], tool_results: [.provider_specific_fields.tool_results[]?.type]}" turn1.json
{"tool_calls":[["tool_search_tool_bm25","srvtoolu_01Au39yj8uHmCdpvhXj7GGjU"],["get_weather","toolu_014mq3SLnWtNR35c83RiwrG6"]],"tool_results":["tool_search_tool_result"]}
  1. Turn 2, non-streaming, fails at Anthropic with 5 marks
$ curl -s -w 'HTTP %{http_code}' $U/v1/chat/completions -d @turn2_false.json   # stream=false, modify_params on, both calls and two user blocks marked, the search call last and unanswered
{"status":"400","answer":null,"error":"A maximum of 4 blocks with cache_control may be provided. Found 5"}
HTTP 400
  1. Turn 2, streaming, fails at Anthropic with 5 marks
$ curl -s -w 'HTTP %{http_code}' $U/v1/chat/completions -d @turn2_true.json   # stream=true, modify_params on, both calls and two user blocks marked, the search call last and unanswered
A maximum of 4 blocks with cache_control may be provided. Found 5
HTTP 400
The same turns through the proxy with the OpenAI SDK
$ python proxy_m3.py $U/v1
turn 1: chatcmpl-8213dafc-5eca-44d4-a9a1-ac80d125d73e [('tool_search_tool_bm25', 'srvtoolu_01DFsV1'), ('get_weather', 'toolu_01ET6pJKMK')]
turn 1 tool_results: ['tool_search_tool_result']
turn 2 request: cache_control on 2 user blocks, 2 tool calls; injection points [{"location": "message", "role": "system"}, {"location": "message", "index": -1}]
turn 2 stream=False: 400 | Error code: 400 - {'error': {'message': 'litellm.BadRequestError: AnthropicException - {"type":"error","error":{"type":"invalid_request_error","message":"A maximum of 4 blocks with cache_control may be p
turn 2 stream=True: 400 | Error code: 400 - {'error': {'message': 'litellm.BadRequestError: AnthropicException - b\'{"type":"error","error":{"type":"invalid_request_error","message":"A maximum of 4 blocks with cache_control may be

After (f4ab3ac)

  1. Turn 2 answers 200 in every case and both modes
$ ANTHROPIC_API_KEY=... .venv/bin/python sdk_m3.py
turn 1: [('tool_search_tool_bm25', 'srvtoolu_01So91HwGWHTacpdr9yHjwns'), ('get_weather', 'toolu_01CXe84fZrNdAqSNo8Pg5JSi')] ['tool_search_tool_result']
turn 2 stream=False: 200 | I couldn't search for other weather tools. The search was in
turn 2 stream=True: 200 | I couldn't find any other weather tools because the search w
turn 2 + later system message stream=False: 200 | The search only found the same `get_weather` tool I already 
turn 2 + later system message stream=True: 200 | The search turned up only `get_weather`, the same tool I alr
router turn 2 stream=False: 200 | I couldn't find another weather tool. The search was interru
router turn 2 stream=True: 200 | I couldn't search for other weather tools because the search
The proxy run, curl plus jq
  1. Turn 1 returns the search call, its kept result, and a get_weather call
$ curl -s $U/v1/chat/completions -d "{model: claude-opus-5-5, tools: [tool_search_tool_bm25, get_weather (defer_loading)], messages: [system, user ask]}" > turn1.json
$ jq -c ".choices[0].message | {tool_calls: [.tool_calls[] | [.function.name, .id]], tool_results: [.provider_specific_fields.tool_results[]?.type]}" turn1.json
{"tool_calls":[["tool_search_tool_bm25","srvtoolu_013JPULwLH6MTRX5QJNzJ9kC"],["get_weather","toolu_0166CTnKu2p8W6wxwKGq21tF"]],"tool_results":["tool_search_tool_result"]}
  1. Turn 2, non-streaming, answers 200
$ curl -s -w 'HTTP %{http_code}' $U/v1/chat/completions -d @turn2_false.json   # stream=false, modify_params on, both calls and two user blocks marked, the search call last and unanswered
{"status":"ok","answer":"I couldn't find another weather tool because the search was stopped before it returned anything. I haven't run it again in case you stopped it on purpose. Just ","error":null}
HTTP 200
  1. Turn 2, streaming, answers 200
$ curl -s -w 'HTTP %{http_code}' $U/v1/chat/completions -d @turn2_true.json   # stream=true, modify_params on, both calls and two user blocks marked, the search call last and unanswered
I didn't get any results for \other weather tools.\ was interrupted before it returned anything, so I can't say yet whether there are other weather tools to com
HTTP 200
The same turns through the proxy with the OpenAI SDK
$ python proxy_m3.py $U/v1
turn 1: chatcmpl-fad065d4-a983-4d4e-ade5-d4415a75a879 [('tool_search_tool_bm25', 'srvtoolu_01P7Ddb'), ('get_weather', 'toolu_01JeprRcsC')]
turn 1 tool_results: ['tool_search_tool_result']
turn 2 request: cache_control on 2 user blocks, 2 tool calls; injection points [{"location": "message", "role": "system"}, {"location": "message", "index": -1}]
turn 2 stream=False: 200 | I couldn't find another weather tool because the search was interrupted before it returned anything. Let me know if you'd like me to try again.  I also need to 
turn 2 stream=True: 200 | I couldn't run the search for other weather tools because it was interrupted before it returned anything, so I can't say yet whether there are any.  One correct
On `claude-sonnet-4-6`, a model without mid-conversation system messages, main raises the same 400 and this PR answers 200
$ QA_MODEL=anthropic/claude-sonnet-4-6 ANTHROPIC_API_KEY=... .venv/bin/python sdk_m3.py   # b4a63d3b6a, main
turn 1: [('tool_search_tool_bm25', 'srvtoolu_01XtzF1d1Ecvi3VqVDwk7WDf'), ('get_weather', 'toolu_01UtoFUtEtWEbzDisr9EhKUi')] ['tool_search_tool_result']
turn 2 stream=False: 400 | A maximum of 4 blocks with cache_control may be provided. Found 5
turn 2 stream=True: 400 | A maximum of 4 blocks with cache_control may be provided. Found 5
turn 2 + later system message stream=False: 200 | It appears that **`get_weather`** is the only weather tool a
turn 2 + later system message stream=True: 200 | Based on the search results, **`get_weather` is the only wea
router turn 2 stream=False: 400 | A maximum of 4 blocks with cache_control may be provided. Found 5
router turn 2 stream=True: 400 | A maximum of 4 blocks with cache_control may be provided. Found 5
$ QA_MODEL=anthropic/claude-sonnet-4-6 ANTHROPIC_API_KEY=... .venv/bin/python sdk_m3.py   # f4ab3ac754
turn 1: [('tool_search_tool_bm25', 'srvtoolu_01K31HRQ5f7gGiaoNiR43Ffv'), ('get_weather', 'toolu_0182YBXJkQC4sQAP4TLT9fF6')] ['tool_search_tool_result']
turn 2 stream=False: 200 | It seems the search was interrupted and no results were retu
turn 2 stream=True: 200 | It seems the search was interrupted and no results were retu
turn 2 + later system message stream=False: 200 | Based on the search results, **`get_weather` is the only wea
turn 2 + later system message stream=True: 200 | It appears that **`get_weather`** is the only weather tool a
router turn 2 stream=False: 200 | It seems the search was interrupted and no results were retu
router turn 2 stream=True: 200 | It seems the search was interrupted and no results were retu
Every #46440 tool search regression case at f4ab3ac
import json
import os
import sys

import litellm

MODEL = "anthropic/claude-opus-5-5"
TOOLS = [
    {"type": "tool_search_tool_bm25_20251119", "name": "tool_search_tool_bm25"},
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a city",
            "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
        },
        "defer_loading": True,
    },
    {
        "type": "function",
        "function": {
            "name": "get_stock_price",
            "description": "Get the latest stock price for a ticker symbol",
            "parameters": {"type": "object", "properties": {"ticker": {"type": "string"}}, "required": ["ticker"]},
        },
        "defer_loading": True,
    },
]
PROMPT = "Search your tools for a weather tool and use it to get the weather in Paris"
SEARCH_ONLY_PROMPT = "Search your tools once for a tool that books flights. If there is none, say so and stop"
WEB_SEARCH_TOOLS = [{"type": "web_search_20250305", "name": "web_search", "max_uses": 1}, TOOLS[1] | {"defer_loading": False}]
WEB_SEARCH_PROMPT = "Search the web once for the capital of France, then get the weather there with get_weather"


def ask(messages, stream, extra, tools=TOOLS):
    response = litellm.completion(
        model=MODEL, messages=messages, tools=tools, max_tokens=4096, stream=stream, **extra
    )
    if stream:
        response = litellm.stream_chunk_builder(list(response), messages=messages)
    return response.choices[0].message


CACHE_POINTS = [
    {"location": "message", "role": "system"},
    {"location": "message", "role": "user"},
    {"location": "message", "role": "tool"},
]


def run_tool_loop_case():
    litellm.modify_params = False
    print(f"=== variant=tool_loop litellm.__file__={litellm.__file__}")
    executed = []

    def execute(tool_call):
        executed.append(tool_call.function.name)
        return {"role": "tool", "tool_call_id": tool_call.id, "content": "18C and cloudy"}

    try:
        answer = litellm.run_tool_loop(
            model=MODEL, messages=[{"role": "user", "content": PROMPT}], tools=TOOLS, execute_tool=execute, max_tokens=4096
        )
        print("executor called for:", executed)
        print("final answer:", (answer or "")[:200])
    except Exception as e:
        print("executor called for:", executed)
        print("loop error:", type(e).__name__, str(e)[:600])


TRAILING_POINTS = [{"location": "message", "role": "system"}, {"location": "message", "index": -1}]


def run_cache_mark_modify_trailing(stream):
    litellm.modify_params = True
    print(f"=== variant=cache_mark_modify_trailing stream={stream} litellm.__file__={litellm.__file__}")
    system = {"role": "system", "content": "You are a helpful assistant. " * 300}
    first = ask([system, {"role": "user", "content": PROMPT}], stream, {})
    calls = first.tool_calls or []
    print("turn 1 tool calls:", [(c.function.name, c.id[:20]) for c in calls])
    print("turn 1 tool_results types:", [r.get("type") for r in ((first.provider_specific_fields or {}).get("tool_results") or [])])
    turn = first.model_dump()
    for call in turn["tool_calls"]:
        call["cache_control"] = {"type": "ephemeral"}
    marked_ask = {
        "role": "user",
        "content": [
            {"type": "text", "text": "Context: the user is planning a trip.", "cache_control": {"type": "ephemeral"}},
            {"type": "text", "text": PROMPT, "cache_control": {"type": "ephemeral"}},
        ],
    }
    print("client cache_control on:", [c["function"]["name"] for c in turn["tool_calls"]], "+ two user ask blocks")
    client_turn = turn | {"tool_calls": [c for c in turn["tool_calls"] if not c["id"].startswith("srvtoolu_")]}
    search_turn = turn | {"content": "", "tool_calls": [c for c in turn["tool_calls"] if c["id"].startswith("srvtoolu_")]}
    history = [
        system,
        marked_ask,
        client_turn,
        *({"role": "tool", "tool_call_id": c["id"], "content": "18C and cloudy"} for c in client_turn["tool_calls"]),
        {"role": "user", "content": "Search for any other weather tool too."},
        search_turn,
    ]
    try:
        second = ask(history, stream, {"cache_control_injection_points": TRAILING_POINTS})
        print("turn 2 answer:", (second.content or "")[:200], "| tool_calls:", [c.function.name for c in (second.tool_calls or [])])
    except Exception as e:
        print("turn 2 error:", type(e).__name__, str(e)[:600])


def run(variant, stream):
    if variant == "tool_loop":
        return run_tool_loop_case()
    if variant == "cache_mark_modify_trailing":
        return run_cache_mark_modify_trailing(stream)
    extra = {}
    answer_server_calls = False
    litellm.modify_params = False
    if variant in ("modify_params", "web_search_modify", "modify_params_unanswered"):
        litellm.modify_params = True
    elif variant in ("answer_all", "search_only", "web_search", "cache_mark"):
        answer_server_calls = True
    elif variant == "thinking":
        extra = json.loads(os.environ.get("THINK_EXTRA", "{\"reasoning_effort\": \"high\"}"))
    print(f"=== variant={variant} stream={stream} litellm.__file__={litellm.__file__}")
    prompt = {"search_only": SEARCH_ONLY_PROMPT, "web_search": WEB_SEARCH_PROMPT, "web_search_modify": WEB_SEARCH_PROMPT}.get(variant, PROMPT)
    tools = WEB_SEARCH_TOOLS if variant.startswith("web_search") else TOOLS
    system = [{"role": "system", "content": "You are a helpful assistant. " * 300}] if variant == "cache_mark" else []
    messages = [*system, {"role": "user", "content": prompt}]
    first = ask(messages, stream, extra, tools)
    calls = first.tool_calls or []
    print("turn 1 tool calls:", [(c.function.name, c.id[:20]) for c in calls], "| text:", (first.content or "")[:120])
    psf = first.provider_specific_fields or {}
    print("turn 1 psf keys:", sorted(psf.keys()))
    print("turn 1 tool_results types:", [r.get("type") for r in (psf.get("tool_results") or [])])
    print("turn 1 code_interpreter_results:", psf.get("code_interpreter_results", "<absent>"))
    print("turn 1 thinking blocks:", len(getattr(first, "thinking_blocks", None) or []))
    if variant == "cache_mark":
        first = first.model_dump()
        for call in first["tool_calls"]:
            if call["id"].startswith("srvtoolu_"):
                call["cache_control"] = {"type": "ephemeral"}
        extra = {"cache_control_injection_points": CACHE_POINTS}
        print("client cache_control on:", [c["function"]["name"] for c in first["tool_calls"] if "cache_control" in c])
    messages.append(first)
    messages += [
        {"role": "tool", "tool_call_id": c.id, "content": "18C and cloudy"}
        for c in calls
        if variant != "modify_params_unanswered" and (answer_server_calls or not c.id.startswith("srvtoolu_"))
    ]
    try:
        second = ask(messages, stream, extra, tools)
        print("turn 2 answer:", (second.content or "")[:200], "| tool_calls:", [c.function.name for c in (second.tool_calls or [])])
    except Exception as e:
        print("turn 2 error:", type(e).__name__, str(e)[:600])


if __name__ == "__main__":
    for spec in sys.argv[1:]:
        variant, mode = spec.split(":")
        run(variant, mode == "stream")
$ ANTHROPIC_API_KEY=... .venv/bin/python regression_loops.py answer_all:nonstream answer_all:stream modify_params:nonstream modify_params:stream search_only:nonstream search_only:stream web_search:nonstream web_search:stream web_search_modify:nonstream web_search_modify:stream cache_mark:nonstream cache_mark:stream tool_loop:nonstream modify_params_unanswered:nonstream modify_params_unanswered:stream cache_mark_modify_trailing:nonstream cache_mark_modify_trailing:stream
Case Stream Turn 2
answer_all False 200, I found a weather tool and checked Paris: it's currently 18°C (about 6
answer_all True 200, It's currently 18°C (about 64°F) and cloudy in Paris. I got this from
modify_params False 200, I found a weather tool and used it. It's currently 18°C (about 64°F) a
modify_params True 200, It's currently 18°C and cloudy in Paris. I found this with a weather t
search_only False 200, I didn't find a tool that books flights. My one search returned only "
search_only True 200, I couldn't find a tool that books flights. The search for "book flight
web_search False 200, The capital of France is Paris. Paris is the capital and most populous
web_search True 200, The capital of France is Paris. It sits in the north-central part of t
web_search_modify False 200, The capital of France is Paris. It sits in the north-central part of t
web_search_modify True 200, Paris is the capital of France. It's in the north-central part of the
cache_mark False 200, In Paris it's 18°C (about 64°F) and cloudy right now. / tool_calls: []
cache_mark True 200, It's currently 18°C (about 64°F) and cloudy in Paris. I got this from
tool_loop False 200, I found a weather tool and used it to check Paris. It's currently 18°C
modify_params_unanswered False 200, I found a weather tool (get_weather) and tried it for Paris, but the
modify_params_unanswered True 200, I found a weather tool (get_weather) and asked it for the weather in
cache_mark_modify_trailing False 200, I didn't find any other weather tools, because the search was interrup
cache_mark_modify_trailing True 200, I couldn't search for other weather tools because the search was inter

The #46440 case through the proxy, booted from f4ab3ac with 2 workers, with curl non-streaming and the OpenAI SDK streaming

$ curl -s $URL/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -d {"model":"claude-opus-5-5","max_tokens":1024,"tools":[...],"messages":[user]}
{"tool_calls":[{"name":"tool_search_tool_bm25","id":"srvtoolu_011GxTS4NJNshNgWku8njom4"},{"name":"get_weather","id":"toolu_014d39X5hx1GmAZ3etLjSmdg"}],"tool_results_types":["tool_search_tool_result"]}
$ curl -s $URL/v1/chat/completions ... -d {"messages":[user, <assistant message from turn 1 as returned>, tool get_weather "18C and cloudy"]}
HTTP 200
{"answer":"I found a weather tool and used it. Paris is currently 18°C (about 64°F) and cloudy.","error":""}
$ python proxy_stream.py $U/v1
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01Lv5SrQjaR'), ('get_weather', 'toolu_019fJKvhitg4e2')]
turn 1 provider_specific_fields.tool_results types: ['tool_search_tool_result']
turn 2 answer: I found a weather tool and checked Paris: it's currently 18°C (about 64°F) and cloudy.
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_params on. Databricks and OpenRouter get a plain get_weather tool, since both reject the tool search tool on main too. On Databricks and OpenRouter the weather_answered_after_system case answers 400 on main too, and this PR leaves it alone

import os

import litellm

litellm.modify_params = True
litellm.num_retries = 0
EPH = {"type": "ephemeral"}
POINTS = [{"location": "message", "role": "system"}, {"location": "message", "index": -1}]
WEATHER = {
    "name": "get_weather",
    "description": "Get the weather for a city",
    "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
}
SEARCH_TOOLS = [
    {"type": "tool_search_tool_bm25_20251119", "name": "tool_search_tool_bm25"},
    {"type": "function", "function": WEATHER, "defer_loading": True},
]
PLAIN_TOOLS = [{"type": "function", "function": WEATHER}]


def search_call(call_id):
    return {"id": call_id, "type": "function", "cache_control": EPH,
            "function": {"name": "tool_search_tool_bm25", "arguments": '{"query": "weather"}'}}


def kept_result(call_id):
    return {"type": "tool_search_tool_result", "tool_use_id": call_id,
            "content": {"type": "tool_search_tool_search_result",
                        "tool_references": [{"type": "tool_reference", "tool_name": "get_weather"}]}}


def opening(*tool_calls):
    search_ids = [call["id"] for call in tool_calls if call["id"].startswith("srvtoolu_")]
    return [
        {"role": "system", "content": "Use the provided tool results to answer the user."},
        {"role": "user", "content": [{"type": "text", "text": "Weather in London and Paris?", "cache_control": EPH}]},
        {"role": "assistant", "content": "", "tool_calls": list(tool_calls),
         "provider_specific_fields": {"tool_results": [kept_result(call_id) for call_id in search_ids]}},
    ]


weather_call = {"id": "toolu_01Weather", "type": "function", "cache_control": EPH,
                "function": {"name": "get_weather", "arguments": '{"city": "Paris"}'}}
SHAPES = {
    "both_searches_answered": [
        *opening(search_call("srvtoolu_01Search"), search_call("srvtoolu_02Search")),
        {"role": "tool", "tool_call_id": "srvtoolu_01Search", "content": "found get_weather"},
        {"role": "tool", "tool_call_id": "srvtoolu_02Search", "content": "found get_weather"},
        {"role": "system", "content": "Answer in one sentence."},
    ],
    "weather_answered_after_system": [
        *opening(search_call("srvtoolu_01Search"), weather_call),
        {"role": "system", "content": "Answer in one sentence."},
        {"role": "tool", "tool_call_id": "toolu_01Weather", "content": "18C and cloudy"},
    ],
}
ROUTES = {
    "databricks/databricks-claude-sonnet-4-6": {"api_key": os.environ["DATABRICKS_API_KEY"],
                                                "api_base": os.environ["DATABRICKS_API_BASE"], "tools": PLAIN_TOOLS},
    "openrouter/anthropic/claude-sonnet-4.6": {"api_key": os.environ["OPENROUTER_API_KEY"], "tools": PLAIN_TOOLS},
    "bedrock/converse/us.anthropic.claude-sonnet-4-6": {"aws_region_name": "us-west-2", "tools": SEARCH_TOOLS},
    "anthropic/claude-sonnet-4-6": {"tools": SEARCH_TOOLS},
}
for model, params in ROUTES.items():
    for shape, messages in SHAPES.items():
        try:
            response = litellm.completion(model=model, messages=messages, max_tokens=64,
                                          cache_control_injection_points=POINTS, **params)
            print(f"{model} {shape}: 200 {(response.choices[0].message.content or '')[:60]!r}")
        except Exception as error:
            print(f"{model} {shape}: {getattr(error, 'status_code', None)} {' '.join(str(error).split())[:260]}")
$ ANTHROPIC_API_KEY=... DATABRICKS_API_KEY=... OPENROUTER_API_KEY=... python route_check.py   # b4a63d3b6a, main
databricks/databricks-claude-sonnet-4-6 both_searches_answered: 200 ''
databricks/databricks-claude-sonnet-4-6 weather_answered_after_system: 400 litellm.BadRequestError: DatabricksException - {"error_code":"BAD_REQUEST","message":"{\"message\":\"messages.2: `tool_use` ids were found without `tool_result` blocks immediately after: srvtoolu_01Search. Each `tool_use` blo
openrouter/anthropic/claude-sonnet-4.6 both_searches_answered: 200 ''
openrouter/anthropic/claude-sonnet-4.6 weather_answered_after_system: 400 litellm.BadRequestError: OpenrouterException - {"error":{"message":"Provider returned error","code":400,"metadata":{"raw":"{\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"A maximum of 4 blocks w
bedrock/converse/us.anthropic.claude-sonnet-4-6 both_searches_answered: 200 "I'll fetch the weather for both cities at the same time!"
bedrock/converse/us.anthropic.claude-sonnet-4-6 weather_answered_after_system: 200 "I'll get the weather for both cities at the same time!"
anthropic/claude-sonnet-4-6 both_searches_answered: 200 'Let me fetch the weather for both cities simultaneously!'
anthropic/claude-sonnet-4-6 weather_answered_after_system: 200 ''
$ python route_check.py   # 4c60d8f8dd, the tip before the route check
databricks/databricks-claude-sonnet-4-6 both_searches_answered: 400 litellm.BadRequestError: DatabricksException - {"error_code":"BAD_REQUEST","message":"{\"message\":\"A maximum of 4 blocks with cache_control may be provided. Found 5.\"}"}
databricks/databricks-claude-sonnet-4-6 weather_answered_after_system: 400 litellm.BadRequestError: DatabricksException - {"error_code":"BAD_REQUEST","message":"{\"message\":\"messages.2: `tool_use` ids were found without `tool_result` blocks immediately after: srvtoolu_01Search. Each `tool_use` blo
openrouter/anthropic/claude-sonnet-4.6 both_searches_answered: 400 litellm.BadRequestError: OpenrouterException - {"error":{"message":"Provider returned error","code":400,"metadata":{"raw":"{\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"A maximum of 4 blocks with cac
openrouter/anthropic/claude-sonnet-4.6 weather_answered_after_system: 400 litellm.BadRequestError: OpenrouterException - {"error":{"message":"Provider returned error","code":400,"metadata":{"raw":"{\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"A maximum of 4 blocks w
bedrock/converse/us.anthropic.claude-sonnet-4-6 both_searches_answered: 400 litellm.BadRequestError: BedrockException - {"message":"The model returned the following errors: A maximum of 4 blocks with cache_control may be provided. Found 5."}
bedrock/converse/us.anthropic.claude-sonnet-4-6 weather_answered_after_system: 400 litellm.BadRequestError: BedrockException - {"message":"Expected toolResult blocks at messages.2.content for the following Ids: srvtoolu_01Search"}
anthropic/claude-sonnet-4-6 both_searches_answered: 200 'Let me fetch the weather for both cities simultaneously!'
anthropic/claude-sonnet-4-6 weather_answered_after_system: 200 'Let me fetch the weather for both cities at the same time!'
$ python route_check.py   # f4ab3ac754
databricks/databricks-claude-sonnet-4-6 both_searches_answered: 200 ''
databricks/databricks-claude-sonnet-4-6 weather_answered_after_system: 400 litellm.BadRequestError: DatabricksException - {"error_code":"BAD_REQUEST","message":"{\"message\":\"messages.2: `tool_use` ids were found without `tool_result` blocks immediately after: srvtoolu_01Search. Each `tool_use` blo
openrouter/anthropic/claude-sonnet-4.6 both_searches_answered: 200 ''
openrouter/anthropic/claude-sonnet-4.6 weather_answered_after_system: 400 litellm.BadRequestError: OpenrouterException - {"error":{"message":"Provider returned error","code":400,"metadata":{"raw":"{\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"A maximum of 4 blocks w
bedrock/converse/us.anthropic.claude-sonnet-4-6 both_searches_answered: 200 "I'll fetch the weather for both cities simultaneously!"
bedrock/converse/us.anthropic.claude-sonnet-4-6 weather_answered_after_system: 200 "I'll get the weather for both cities at the same time!"
anthropic/claude-sonnet-4-6 both_searches_answered: 200 'Let me fetch the weather for both cities simultaneously!'
anthropic/claude-sonnet-4-6 weather_answered_after_system: 200 'Let me get the weather for both cities at the same time!'
A stray string in `extra_body.messages` next to a marked tool call
import litellm

litellm.modify_params = True
litellm.suppress_debug_info = True
marked_call = {"id": "toolu_1", "type": "function", "function": {"name": "f", "arguments": "{}"},
               "cache_control": {"type": "ephemeral"}}
try:
    litellm.completion(model="anthropic/claude-opus-5-5", max_tokens=16, messages=[{"role": "user", "content": "Say hi"}],
                       extra_body={"messages": ["junk", {"role": "assistant", "content": "", "tool_calls": [marked_call]}]},
                       cache_control_injection_points=[{"location": "message", "role": "user"}])
    print("stray message in extra_body: 200")
except Exception as error:
    print("stray message in extra_body:", type(error).__name__, getattr(error, "status_code", None), "|", str(error)[:160])
$ ANTHROPIC_API_KEY=... .venv/bin/python stray_message_check.py   # b4a63d3b6a, main
stray message in extra_body: BadRequestError 400 | litellm.BadRequestError: AnthropicException - {"type":"error","error":{"type":"invalid_request_error","message":"extra_body: Extra inputs are not per
$ ANTHROPIC_API_KEY=... .venv/bin/python stray_message_check.py   # f4ab3ac754
stray message in extra_body: BadRequestError 400 | litellm.BadRequestError: AnthropicException - {"type":"error","error":{"type":"invalid_request_error","message":"extra_body: Extra inputs are not per

Type

🐛 Bug Fix
✅ Test

Caveats (if any)

High

  • The caveats loop hit its 4-round cap, so the fixes at 1f5f809, 190fb72 and 9ee8798 had no fresh caveats round

Medium

  • One cell skips because a non-streamed Snowflake Claude response drops the kept tool_search_tool_result, as on main

Low

  • A lone trailing search call still sends the modify_params placeholder, not its kept result
  • The pairing debug line logs twice per request when a server tool call is marked
  • Bedrock Converse still undercounts a marked server tool call on replay, so a follow-up user turn after it answers 400 "Found 5", as on main
  • OpenRouter answers 400 "Found 5" for an unanswered search call next to a later system message, as on main
  • One Responses bridge chaos cell fails on main too, because of fix(anthropic): keep tool_search_tool_result so the search call replays with its result #46440

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

…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.
@greptile-apps

greptile-apps Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Automatic reviews are disabled for this repository.

@devin-ai-integration

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

Copy link
Copy Markdown
Contributor

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

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@codspeed

codspeed Bot commented Oct 15, 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_server_tool_replay_follow_up (f4ab3ac) with main (ad83e3d)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (4a4a0e8) during the generation of this report, so ad83e3d was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@litereview

litereview Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

Completed · Some checks not run.

No correctness findings.

I traced the hook's new route gating, the custom_llm_provider stamp on seeded points, and the mid-conversation flag lookup through to the counts used for injection. The early return when no server tool call is marked gives the same count as main: tool_call_is_rebuilt_as_server_tool_use only reads answered_tool_ids for a marked srvtoolu_ call.

I also compared the rewritten _pair_tool_calls_with_results and flagged-placement helpers against the base revision's code on 30,000 random conversations. Both returned the same output as base on every input the request builder can send.

I didn't run the provider wire suites (tests/integration/providers/...). They need the gateway, PostgreSQL and Redis rig, which this sandbox doesn't have. The PR's audit table cites d42ad63268, while the reviewed head is f4ab3ac7.

Checks and execution details
  • Passed · real-testing-evidence (required): Not applicable: no LLM translation changes in the scoped paths.

The scoped files are litellm/llms/anthropic/common_utils.py, litellm/litellm_core_utils/prompt_templates/factory.py and mid_conversation_system.py. None of them changes the wire translation:

  • tool_call_is_rebuilt_as_server_tool_use: the change only short-circuits on non-srvtoolu_ ids or None fields. find_anthropic_server_tool_result already returned None for those, so behavior is unchanged.
  • Refactors in factory.py and mid_conversation_system.py: _pair_tool_calls_with_results (the set lookup), _anchorable_blocks and _runs_by_anchor are linear-time rewrites. A differential fuzz against the base b4a63d3b copies of both modules ran 30,000 random conversations after split_leading_system_run, with both flag values. It found 0 output differences and 0 errors for place_mid_conversation_system and sanitize_messages_for_tool_calling.
  • New helpers: tool_call_ids_answered_by_client(..., supports_mid_conversation_system), tool_call_ids_answered_in and _as_the_request_builder_sends_them have only one caller, the cache control hook (litellm/integrations/...), which uses them to count cache marks.

Supporting evidence: the PR also lists live Anthropic request ids at 9ee87987ac.

  • Passed · Unit tests for hook, factory and mid-conversation placement (optional): Command: uv run --no-sync pytest tests/unit/integrations/test_anthropic_cache_control_hook.py

Result: 567 passed. This was after uv sync --inexact --frozen --extra proxy --group proxy-dev --group e2e-dev. The first run, without the proxy extras, had 2 failures caused by a missing mcp module.

The factory and mid-conversation unit files passed in the combined run: 971 passed, and the only 2 failures were those mcp import errors in the hook file.

  • Passed · SDK integration tests touched by the PR (optional): Command: PYTHONPATH=tests uv run --no-sync pytest tests/integration/sdk/test_cache_control_census_pydantic_messages_sdk.py tests/integration/sdk/test_device_code_login_guard_sdk.py

Result: 37 passed. These tests drive litellm.completion and Router.completion against a local scripted Anthropic peer, including the new bare-model budget cells and the device-login guard cells.

  • Passed · Differential fuzz vs base for placement and pairing (optional): Script: /tmp/fuzz.py. It loads the base revision's mid_conversation_system.py and factory.py from raw.githubusercontent at b4a63d3b and compares them with the head versions.

Result: 0 output differences over 30,000 random conversations covering srvtoolu_ and client calls, kept results, orphaned or empty tool ids, and system messages.

Inputs that start with a system message differ only in exception type (KeyError vs RuntimeError). Real callers strip the leading system run first, so those inputs never reach this code.

  • Not run · Provider wire integration suites (optional): Not run: tests/integration/providers/test_anthropic_tool_search_result_*_wire.py needs the gateway, PostgreSQL and Redis rig from tests/integration/run.py, and this sandbox has no postgres, redis or docker. The PR's audit table reports these suites passing at d42ad63268.

View review · Reviewed f4ab3ac75475

@codecov

codecov Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

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

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

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

Copy link
Copy Markdown
Contributor Author

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 Author

@litereview code-review

@veria-ai

veria-ai Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

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

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

…th the request builder's converting placement
@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

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

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

… system message on Databricks, OpenRouter and Bedrock Converse
@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

…atGPT routes without resolving them, so a sync call with no stored login never starts the device flow
@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

…Copilot and ChatGPT login hosts like an unmarked one
@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

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

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@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 f4ab3ac. Configure here.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@litellm-stampbot

Copy link
Copy Markdown

litellm-stampbot: risk low

Approved at f4ab3ac.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Judge (gpt-6-luna): low, probability of high 0.03 (high at or above 0.90)

  • risk: low (probability of high 0.03)

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:low Small, isolated, low-risk change label Oct 15, 2026

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

Low risk by rule and by judgement at f4ab3ac

@mateo-berri
mateo-berri merged commit 62af39a into main Oct 15, 2026
95 of 96 checks passed
@mateo-berri
mateo-berri deleted the litellm_anthropic_server_tool_replay_follow_up branch October 15, 2026 21:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:low Small, isolated, low-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants