Skip to content

fix(anthropic): keep tool_search_tool_result so the search call replays with its result - #46440

Merged
mateo-berri merged 8 commits into
mainfrom
litellm_anthropic_tool_search_result_roundtrip
Oct 15, 2026
Merged

mateo-berri merged 8 commits into
mainfrom
litellm_anthropic_tool_search_result_roundtrip

Conversation

@mateo-berri

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

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Claude tool search answers with a tool_search_tool_result block
  • LiteLLM threw that block away, stream and non-stream
  • Sending the turn back then gets a 400 from Anthropic

How it solves it:

  • Keep the block in provider_specific_fields["tool_results"], both modes, with no code_interpreter_results for it
  • On replay, it goes right after its server_tool_use
  • If the client also answers a server tool call whose result LiteLLM kept, and another tool answer or user message follows, the kept result goes back and the client's answer (or the modify_params placeholder) is dropped
  • run_tool_loop replays provider_specific_fields only for a turn with a server tool call, and runs only client tool calls
  • The cache control hook counts a mark on a server tool call only when it goes out as tool_use

Decision: when the client's answer to a server tool call is the only message after that turn, it wins and the call goes back as tool_use. Keeping the server result would end the request on an assistant turn, which Opus 5.5 rejects with a 400

User Flow

Before: a developer running a tool-search agent loop on Claude through the SDK gets a 400 on the second call

  1. They call litellm.completion() or Router.completion() on anthropic/claude-opus-5-5 with tool_search_tool_bm25_20251119 plus defer_loading: true function tools, stream or not
  2. Claude searches, finds get_weather and calls it. The returned message has the srvtoolu_ call but no search result
  3. They send that assistant message back with the get_weather tool result
  4. Anthropic answers 400 tool_use ids were found without tool_result blocks immediately after: srvtoolu_...

After: the same loop finishes

  1. Same first call, stream or not
  2. The returned message now carries the tool_search_tool_result block in provider_specific_fields.tool_results
  3. They send that assistant message back with the get_weather tool result
  4. Claude answers with the weather

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

The customer calls the SDK, so four cases use it and two go through a 2-worker proxy (no DB). Each is a two-turn loop on anthropic/claude-opus-5-5 against the real Anthropic API, with tool search and two defer_loading tools. Turn 2 sends back the assistant message as returned, plus a tool answer for get_weather. Eight more cases cover the other rows of the table

sdk_loop.py (the four SDK cases)
import os
import sys

import litellm
from litellm import Router

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"

router = Router(
    model_list=[
        {"model_name": "claude", "litellm_params": {"model": MODEL, "api_key": os.environ["ANTHROPIC_API_KEY"]}}
    ]
)


def ask(client, messages, stream):
    model = "claude" if client == "router" else MODEL
    call = router.completion if client == "router" else litellm.completion
    response = call(model=model, messages=messages, tools=TOOLS, max_tokens=1024, stream=stream)
    if stream:
        response = litellm.stream_chunk_builder(list(response), messages=messages)
    return response.choices[0].message


def run(client, stream):
    print(f"=== {client}.completion() stream={stream} on {MODEL}")
    messages = [{"role": "user", "content": PROMPT}]
    first = ask(client, messages, stream)
    calls = first.tool_calls or []
    print("turn 1 tool calls:", [(c.function.name, c.id[:20]) for c in calls])
    results = (first.provider_specific_fields or {}).get("tool_results") or []
    print("turn 1 provider_specific_fields.tool_results types:", [r.get("type") for r in results])
    messages.append(first)
    messages += [
        {"role": "tool", "tool_call_id": c.id, "content": "18C and cloudy"}
        for c in calls
        if not c.id.startswith("srvtoolu_")
    ]
    try:
        second = ask(client, messages, stream)
        print("turn 2 answer:", second.content)
    except Exception as e:
        print("turn 2 error:", type(e).__name__, str(e)[:400])


if __name__ == "__main__":
    for spec in sys.argv[1:]:
        client, mode = spec.split(":")
        run(client, mode == "stream")
proxy_nonstream.sh, proxy_stream.py, and the proxy config
#!/bin/zsh
set -u
URL=$1
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}]'
USER_MSG='{"role":"user","content":"Search your tools for a weather tool and use it to get the weather in Paris"}'
echo '$ curl -s $URL/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -d {"model":"claude-opus-5-5","max_tokens":1024,"tools":[...],"messages":[user]}'
FIRST=$(curl -s "$URL/v1/chat/completions" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' \
  -d "{\"model\":\"claude-opus-5-5\",\"max_tokens\":1024,\"tools\":$TOOLS,\"messages\":[$USER_MSG]}")
print -r -- "$FIRST" | jq -c '{tool_calls: [.choices[0].message.tool_calls[]? | {name: .function.name, id: .id}], tool_results_types: [.choices[0].message.provider_specific_fields.tool_results[]?.type]}'
ASSISTANT=$(print -r -- "$FIRST" | jq -c '.choices[0].message')
TOOL_MSGS=$(print -r -- "$FIRST" | jq -c '[.choices[0].message.tool_calls[]? | select(.id | startswith("srvtoolu_") | not) | {role:"tool", tool_call_id:.id, content:"18C and cloudy"}]')
BODY=$(jq -cn --argjson tools "$TOOLS" --argjson user "$USER_MSG" --argjson a "$ASSISTANT" --argjson t "$TOOL_MSGS" \
  '{model:"claude-opus-5-5",max_tokens:1024,tools:$tools,messages:([$user,$a]+$t)}')
echo '$ curl -s $URL/v1/chat/completions ... -d {"messages":[user, <assistant message from turn 1 as returned>, tool get_weather "18C and cloudy"]}'
SECOND=$(curl -s -o /dev/stdout -w '\n%{http_code}' "$URL/v1/chat/completions" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$BODY")
echo "HTTP ${SECOND##*$'\n'}"
print -r -- "${SECOND%$'\n'*}" | jq -c '{answer: .choices[0].message.content, error: ((.error.message // "") | .[0:400])}'
import os
import sys

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,
    },
    {
        "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,
    },
]


def stream_turn(messages):
    calls, text, fields = {}, "", {}
    for chunk in client.chat.completions.create(
        model="claude-opus-5-5", messages=messages, tools=TOOLS, max_tokens=1024, stream=True
    ):
        if not chunk.choices:
            continue
        delta = chunk.choices[0].delta
        text += delta.content or ""
        for call in delta.tool_calls or []:
            entry = calls.setdefault(call.index, {"id": "", "name": "", "arguments": ""})
            entry["id"] = call.id or entry["id"]
            entry["name"] += (call.function and call.function.name) or ""
            entry["arguments"] += (call.function and call.function.arguments) or ""
        fields.update((delta.model_extra or {}).get("provider_specific_fields") or {})
    return calls, text, fields


messages = [{"role": "user", "content": "Search your tools for a weather tool and use it to get the weather in Paris"}]
calls, text, fields = stream_turn(messages)
print("turn 1 tool calls:", [(c["name"], c["id"][:20]) for c in calls.values()])
print("turn 1 provider_specific_fields.tool_results types:", [r.get("type") for r in fields.get("tool_results") or []])
messages.append(
    {
        "role": "assistant",
        "content": text or None,
        "tool_calls": [
            {"id": c["id"], "type": "function", "function": {"name": c["name"], "arguments": c["arguments"]}}
            for c in calls.values()
        ],
        "provider_specific_fields": fields,
    }
)
messages += [
    {"role": "tool", "tool_call_id": c["id"], "content": "18C and cloudy"}
    for c in calls.values()
    if not c["id"].startswith("srvtoolu_")
]
try:
    _, answer, _ = stream_turn(messages)
    print("turn 2 answer:", answer)
except Exception as e:
    print("turn 2 error:", type(e).__name__, str(e)[:400])
model_list:
  - model_name: claude-opus-5-5
    litellm_params:
      model: anthropic/claude-opus-5-5
      api_key: os.environ/ANTHROPIC_API_KEY
regression_loops.py (the regression cases)
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])


def run(variant, stream):
    if variant == "tool_loop":
        return run_tool_loop_case()
    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")
Commands each leg ran, against its own proxy on a random port
python sdk_loop.py completion:stream completion:nonstream router:nonstream router:stream
./proxy_nonstream.sh $URL
python proxy_stream.py $URL/v1
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
Case Before After
completion() and Router.completion(), both modes 400 on turn 2 answers
Proxy, stream=False (curl) 400 on turn 2 answers
Proxy, stream=True (OpenAI SDK) 400 on turn 2 answers
Client also answers the search call answers answers
litellm.modify_params = True search read as interrupted answers with the search
modify_params, no tool answers sent search read as interrupted only get_weather read as interrupted
Search finds nothing, client answers it answers answers
Client answers a web_search call 400 on turn 2 answers with the results
modify_params with web_search 400 on turn 2 answers with the results
Client cache_control on the search call answers answers
litellm.run_tool_loop runs the search call runs only get_weather

Before (457b5d2)

The six main cases get the User Flow's 400 on turn 2, and turn 1's tool_results is []. All four web_search cases get unexpected tool_use_id found in tool_result blocks. With modify_params and no tool answers, Claude says both calls were interrupted

Raw before output, all fourteen cases
## SDK
=== completion.completion() stream=True on anthropic/claude-opus-5-5
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_012R8xcRpkH'), ('get_weather', 'toolu_017GJgcaWguyvx')]
turn 1 provider_specific_fields.tool_results types: []
turn 2 error: BadRequestError litellm.BadRequestError: AnthropicException - b'{"type":"error","error":{"type":"invalid_request_error","message":"messages.2: `tool_use` ids were found without `tool_result` blocks immediately after: srvtoolu_012R8xcRpkHTo6L663yoYo7z. Each `tool_use` block must have a corresponding `tool_result` block in the next message."},"request_id":"req_011Cg2fUonsAm6gGJ3HKZajU"}'
=== completion.completion() stream=False on anthropic/claude-opus-5-5
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01UH9V1LUJb'), ('get_weather', 'toolu_0181QEuqnjks1j')]
turn 1 provider_specific_fields.tool_results types: []
turn 2 error: BadRequestError litellm.BadRequestError: AnthropicException - {"type":"error","error":{"type":"invalid_request_error","message":"messages.2: `tool_use` ids were found without `tool_result` blocks immediately after: srvtoolu_01UH9V1LUJbVHKST9JtXyfn1. Each `tool_use` block must have a corresponding `tool_result` block in the next message."},"request_id":"req_011Cg2fUyv4ZkCmbzkdYZxQ6"}
=== router.completion() stream=False on anthropic/claude-opus-5-5
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01TuHjJTGfo'), ('get_weather', 'toolu_01MGzLpaTiNThn')]
turn 1 provider_specific_fields.tool_results types: []
turn 2 error: BadRequestError litellm.BadRequestError: AnthropicException - {"type":"error","error":{"type":"invalid_request_error","message":"messages.2: `tool_use` ids were found without `tool_result` blocks immediately after: srvtoolu_01TuHjJTGfo7GrkvZpRLYpN6. Each `tool_use` block must have a corresponding `tool_result` block in the next message."},"request_id":"req_011Cg2fVG8da7Dn66vkkqfn8"}

LiteLLM: model group 'claude'
=== router.completion() stream=True on anthropic/claude-opus-5-5
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01WmkDAqzqG'), ('get_weather', 'toolu_01XyKn78pL3LMa')]
turn 1 provider_specific_fields.tool_results types: []
turn 2 error: BadRequestError litellm.BadRequestError: AnthropicException - b'{"type":"error","error":{"type":"invalid_request_error","message":"messages.2: `tool_use` ids were found without `tool_result` blocks immediately after: srvtoolu_01WmkDAqzqGaPFME9Ku9kprJ. Each `tool_use` block must have a corresponding `tool_result` block in the next message."},"request_id":"req_011Cg2fVitxYZ8pKu516LmKd"}'

LiteLLM: model group 'clau
## proxy non-stream (curl)
$ 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_019PNaZxq9fgQq92ksMtoLZK"},{"name":"get_weather","id":"toolu_01UBMMopEq9Fmu6ytNyZKpQa"}],"tool_results_types":[]}
$ curl -s $URL/v1/chat/completions ... -d {"messages":[user, <assistant message from turn 1 as returned>, tool get_weather "18C and cloudy"]}
HTTP 400
{"answer":null,"error":"litellm.BadRequestError: AnthropicException - {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"messages.2: `tool_use` ids were found without `tool_result` blocks immediately after: srvtoolu_019PNaZxq9fgQq92ksMtoLZK. Each `tool_use` block must have a corresponding `tool_result` block in the next message.\"},\"request_id\":\"req_011Cg2fWVAz2yW1fRFKacUGa\"}\n\nLiteLLM: model group 'claude-"}
## proxy stream (openai SDK)
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_017c9h5K5QQ'), ('get_weather', 'toolu_015VaNPQVn9xkh')]
turn 1 provider_specific_fields.tool_results types: []
turn 2 error: BadRequestError Error code: 400 - {'error': {'message': 'litellm.BadRequestError: AnthropicException - b\'{"type":"error","error":{"type":"invalid_request_error","message":"messages.2: `tool_use` ids were found without `tool_result` blocks immediately after: srvtoolu_017c9h5K5QQSiQVfcnk8f2ei. Each `tool_use` block must have a corresponding `tool_result` block in the next message."},"request_id":"req_011Cg2fX7bjCr

## regression loops (SDK)
=== variant=answer_all stream=False litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_base/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_012XyTV4RWP'), ('get_weather', 'toolu_012oUnB1DRakGU')] | text: 
turn 1 psf keys: ['citations', 'thinking_blocks']
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: It's currently **18°C and cloudy** in Paris.

One caveat: the tool search didn't return a weather tool's definition the way it should have. It just returned the text "18C and cloudy." I called a `get_ | tool_calls: []
=== variant=answer_all stream=True litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_base/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01DYPbWnQSP'), ('get_weather', 'toolu_01Dbhh7nqsRypo')] | text: 
turn 1 psf keys: []
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: It's **18°C and cloudy** in Paris right now.

Something odd happened along the way. I called a tool named `get_weather` at the same time as the search, before the search had confirmed that tool existe | tool_calls: []
=== variant=modify_params stream=False litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_base/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01WMqjEjhj4'), ('get_weather', 'toolu_012HEhz8ntezn2')] | text: 
turn 1 psf keys: ['citations', 'thinking_blocks']
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: It's 18°C and cloudy in Paris right now.

The tool search didn't run because it was interrupted. I'd also called a `get_weather` tool in the same step without first confirming that it existed. That ca | tool_calls: []
=== variant=modify_params stream=True litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_base/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01SJrjzKmy9'), ('get_weather', 'toolu_01TwsLw6xzM53T')] | text: 
turn 1 psf keys: []
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: It's currently **18°C and cloudy** in Paris.

One thing you should know: your tool search was interrupted and returned nothing. I called the weather tool at the same time, before the search had confir | tool_calls: []
=== variant=search_only stream=False litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_base/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01J4dsYhXVE')] | text: I searched once and found no tool that books flights, so I'm stopping here as you asked.
turn 1 psf keys: ['citations', 'thinking_blocks']
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: I ran one search for "book flight", and it didn't turn up a flight-booking tool. The only thing it returned was "18C and cloudy", which looks like weather information rather than a tool. | tool_calls: []
=== variant=search_only stream=True litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_base/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01UWdYYtfmW')] | text: I searched once and found no tool that books flights, so I've stopped there.
turn 1 psf keys: []
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: I searched my tools once for something that books flights and didn't find one. The search returned only "18C and cloudy," which looks like weather information. So I can't book a flight, and I'm stoppi | tool_calls: []
=== variant=web_search stream=False litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_base/litellm/__init__.py
turn 1 tool calls: [('web_search', 'srvtoolu_01HBzmByrd5'), ('get_weather', 'toolu_014YkoAbMwETNE')] | text: 
turn 1 psf keys: ['citations', 'thinking_blocks', 'web_search_calls', 'web_search_results']
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0

Give Feedback / Get Help: https://github.com/BerriAI/litellm/issues/new
LiteLLM.Info: If you need to debug this error, use `litellm.turn_on_debug()'.

turn 2 error: BadRequestError litellm.BadRequestError: AnthropicException - {"type":"error","error":{"type":"invalid_request_error","message":"messages.2.content.0: unexpected `tool_use_id` found in `tool_result` blocks: srvtoolu_01HBzmByrd5qg9oAtRmoB3Zw. Each `tool_result` block must have a corresponding `tool_use` block in the previous message."},"request_id":"req_011Cg2fbLu3QvEi3pW7yokJK"}
=== variant=web_search stream=True litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_base/litellm/__init__.py
turn 1 tool calls: [('web_search', 'srvtoolu_013udnLZuKw'), ('get_weather', 'toolu_01Qp6Y27e4S3cq')] | text: 
turn 1 psf keys: ['web_search_calls', 'web_search_results']
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0

Give Feedback / Get Help: https://github.com/BerriAI/litellm/issues/new
LiteLLM.Info: If you need to debug this error, use `litellm.turn_on_debug()'.

turn 2 error: BadRequestError litellm.BadRequestError: AnthropicException - b'{"type":"error","error":{"type":"invalid_request_error","message":"messages.2.content.0: unexpected `tool_use_id` found in `tool_result` blocks: srvtoolu_013udnLZuKwqccPiZ7dXD3MY. Each `tool_result` block must have a corresponding `tool_use` block in the previous message."},"request_id":"req_011Cg2fbsSpkzXAwjmArDGLf"}'

## regression loops, newer cases (SDK)
20:18:51 - LiteLLM:WARNING: anthropic_cache_control_hook.py:542 - AnthropicCacheControlHook: Reached the provider limit of 4 cache breakpoints. Skipping further injection.
20:18:58 - LiteLLM:WARNING: anthropic_cache_control_hook.py:542 - AnthropicCacheControlHook: Reached the provider limit of 4 cache breakpoints. Skipping further injection.
=== variant=tool_loop litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_base/litellm/__init__.py
executor called for: ['tool_search_tool_bm25', 'get_weather']
final answer: It's 18°C (about 64°F) and cloudy in Paris right now.

I made a mistake in how I got this. I sent the tool search and a weather request (`get_weather` for Paris) at the same time, so I called the weat
=== variant=web_search_modify stream=False litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_base/litellm/__init__.py
turn 1 tool calls: [('web_search', 'srvtoolu_01NKpc2p3Sa'), ('get_weather', 'toolu_01B3uxcoqZyPfh')] | text: 
turn 1 psf keys: ['citations', 'thinking_blocks', 'web_search_calls', 'web_search_results']
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0

Give Feedback / Get Help: https://github.com/BerriAI/litellm/issues/new
LiteLLM.Info: If you need to debug this error, use `litellm.turn_on_debug()'.

turn 2 error: BadRequestError litellm.BadRequestError: AnthropicException - {"type":"error","error":{"type":"invalid_request_error","message":"messages.2.content.1: unexpected `tool_use_id` found in `tool_result` blocks: srvtoolu_01NKpc2p3SaVuKtfJjfxBP8H. Each `tool_result` block must have a corresponding `tool_use` block in the previous message."},"request_id":"req_011Cg2kLJg1uyVnQaddJVomH"}
=== variant=web_search_modify stream=True litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_base/litellm/__init__.py
turn 1 tool calls: [('web_search', 'srvtoolu_01Kx9WA2RSP'), ('get_weather', 'toolu_01NiCWxXH6H5JN')] | text: 
turn 1 psf keys: ['web_search_calls', 'web_search_results']
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0

Give Feedback / Get Help: https://github.com/BerriAI/litellm/issues/new
LiteLLM.Info: If you need to debug this error, use `litellm.turn_on_debug()'.

turn 2 error: BadRequestError litellm.BadRequestError: AnthropicException - b'{"type":"error","error":{"type":"invalid_request_error","message":"messages.2.content.1: unexpected `tool_use_id` found in `tool_result` blocks: srvtoolu_01Kx9WA2RSPmDUiveUUoUAxV. Each `tool_result` block must have a corresponding `tool_use` block in the previous message."},"request_id":"req_011Cg2kLerTk6ujNb6DmjEuM"}'
=== variant=cache_mark stream=False litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_base/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01JR2YeFJuf'), ('get_weather', 'toolu_01Jyu2wpYyApYP')] | text: 
turn 1 psf keys: ['citations', 'thinking_blocks']
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
client cache_control on: ['tool_search_tool_bm25']
turn 2 answer: It's **18°C and cloudy** in Paris right now.

I didn't follow the usual steps to get this, though. I ran the tool search and, in the same step, called a tool named `get_weather` without waiting to see | tool_calls: []
=== variant=cache_mark stream=True litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_base/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01R2Zh3Yzf7'), ('get_weather', 'toolu_01DRK4sCqKG547')] | text: 
turn 1 psf keys: []
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
client cache_control on: ['tool_search_tool_bm25']
turn 2 answer: It's **18°C and cloudy** in Paris right now.

I made a mistake in how I got this. I called a `get_weather` tool at the same time as the search, before the search had shown me that tool existed. The se | tool_calls: []

## regression loops, modify_params with no tool answers (SDK)
leg=before5 tree=/Users/mateo/Development/litellm-worktrees/lit9576_base commit=457b5d26c7
=== variant=modify_params_unanswered stream=False litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_base/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01HUKA8ehNq'), ('get_weather', 'toolu_01MRpdV2sfAY76')] | text: 
turn 1 psf keys: ['citations', 'thinking_blocks']
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: I couldn't get the weather for Paris because both of my tool calls were stopped before they returned anything.

1. **Tool search:** I searched my tools for "weather," but the search was interrupted, s | tool_calls: []
=== variant=modify_params_unanswered stream=True litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_base/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01A2spCFaBq'), ('get_weather', 'toolu_01AEeq7QCUpwB8')] | text: 
turn 1 psf keys: []
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: I don't have the Paris weather for you. Both tool calls were stopped before they returned anything.

1. **The tool search** for a weather tool was interrupted, so I don't know if a weather tool is eve | tool_calls: []

After (072aa83)

Every case answers on turn 2, tool_results holds the search result, and code_interpreter_results is absent. The web_search cases answer from the real results, and with modify_params and no tool answers only get_weather reads as interrupted

Raw after output, all fourteen cases
## SDK
=== completion.completion() stream=True on anthropic/claude-opus-5-5
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01MKxHkwdUh'), ('get_weather', 'toolu_01XENYLvHXUZCe')]
turn 1 provider_specific_fields.tool_results types: ['tool_search_tool_result']
turn 2 answer: It's currently 18°C (about 64°F) and cloudy in Paris. I got this from the `get_weather` tool, which turned up when I searched my tools for weather.
=== completion.completion() stream=False on anthropic/claude-opus-5-5
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01PwSAwgKuG'), ('get_weather', 'toolu_01KmwJ3HTtWjSo')]
turn 1 provider_specific_fields.tool_results types: ['tool_search_tool_result']
turn 2 answer: I found a weather tool and used it to check Paris: it's currently 18°C (about 64°F) and cloudy.
=== router.completion() stream=False on anthropic/claude-opus-5-5
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01XPDgAF8EH'), ('get_weather', 'toolu_018Pwutfks1BaP')]
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.
=== router.completion() stream=True on anthropic/claude-opus-5-5
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01T33kyvERg'), ('get_weather', 'toolu_016YUbLsuLg8TT')]
turn 1 provider_specific_fields.tool_results types: ['tool_search_tool_result']
turn 2 answer: It's currently 18°C (about 64°F) and cloudy in Paris.
## proxy non-stream (curl)
$ 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_01PV9YUyDQRSD2dy9JPXHxvt"},{"name":"get_weather","id":"toolu_01Si7M2EMbJc7fYmREoMiKjz"}],"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 checked Paris: it's currently 18°C (about 64°F) and cloudy.","error":""}
## proxy stream (openai SDK)
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01BwowXndfN'), ('get_weather', 'toolu_01NpwP5gLoqeqd')]
turn 1 provider_specific_fields.tool_results types: ['tool_search_tool_result']
turn 2 answer: It's currently 18°C (about 64°F) and cloudy in Paris.

## regression loops (SDK)
=== variant=answer_all stream=False litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_head/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01MuTn5799R'), ('get_weather', 'toolu_01UFG1AcCEMBr8')] | text: 
turn 1 psf keys: ['citations', 'thinking_blocks', 'tool_results']
turn 1 tool_results types: ['tool_search_tool_result']
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: I found a weather tool and checked Paris: it's currently 18°C (about 64°F) and cloudy. | tool_calls: []
=== variant=answer_all stream=True litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_head/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_011jPW2wNZj'), ('get_weather', 'toolu_01GLdApUoXejdL')] | text: 
turn 1 psf keys: ['tool_results']
turn 1 tool_results types: ['tool_search_tool_result']
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: In Paris it's currently 18°C (about 64°F) and cloudy. I got this from a weather tool I found by searching my available tools. | tool_calls: []
=== variant=modify_params stream=False litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_head/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01872iELKpk'), ('get_weather', 'toolu_019o6eYmmwZqF3')] | text: 
turn 1 psf keys: ['citations', 'thinking_blocks', 'tool_results']
turn 1 tool_results types: ['tool_search_tool_result']
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: It's currently 18°C (about 64°F) and cloudy in Paris. | tool_calls: []
=== variant=modify_params stream=True litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_head/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_018AvAZ4mQ1'), ('get_weather', 'toolu_0165Us1GwGH9VF')] | text: 
turn 1 psf keys: ['tool_results']
turn 1 tool_results types: ['tool_search_tool_result']
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: It's currently 18°C (about 64°F) and cloudy in Paris. | tool_calls: []
=== variant=search_only stream=False litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_head/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01Sz5g1sXkj')] | text: I searched once for a flight-booking tool and found nothing, so I can't book flights for you. As you asked, I'll stop he
turn 1 psf keys: ['citations', 'thinking_blocks', 'tool_results']
turn 1 tool_results types: ['tool_search_tool_result']
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: I don't have a tool that books flights. My one search for "book flight" came back with "18C and cloudy," which looks like weather data, and it didn't turn up any flight-booking tool. | tool_calls: []
=== variant=search_only stream=True litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_head/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_018QNaYaYMd')] | text: I searched once and found no tool that can book flights, so I'm stopping here as you asked.
turn 1 psf keys: ['tool_results']
turn 1 tool_results types: ['tool_search_tool_result']
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: I searched once and found no tool that books flights. The only result was "18C and cloudy", which looks like weather information, so I'm stopping here. | tool_calls: []
=== variant=web_search stream=False litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_head/litellm/__init__.py
turn 1 tool calls: [('web_search', 'srvtoolu_019cZyMG6tL'), ('get_weather', 'toolu_01PggCZdHc6qyo')] | text: 
turn 1 psf keys: ['citations', 'thinking_blocks', 'web_search_calls', 'web_search_results']
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: France's capital is Paris. It sits in the north-central part of the country and is France's center of commerce and culture.

Right now in Paris it's **18°C (about 64°F) and cloudy**. | tool_calls: []
=== variant=web_search stream=True litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_head/litellm/__init__.py
turn 1 tool calls: [('web_search', 'srvtoolu_01QMXLgejHq'), ('get_weather', 'toolu_01TyjJaNqHFzeV')] | text: 
turn 1 psf keys: ['web_search_calls', 'web_search_results']
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: The capital of France is Paris. Paris is the capital and most populous city of France. It sits on the Seine River in the north of the country, in the centre of the Île-de-France region.

**Weather in  | tool_calls: []
=== variant=web_search_modify stream=False litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_head/litellm/__init__.py
turn 1 tool calls: [('web_search', 'srvtoolu_01LbZLcMLMq'), ('get_weather', 'toolu_01Kk2uiwhLx8Xi')] | text: 
turn 1 psf keys: ['citations', 'thinking_blocks', 'web_search_calls', 'web_search_results']
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: France's capital is Paris. Situated in the north-central part of the country, Paris is France's center of commerce and culture.

The weather in Paris right now is **18°C (about 64°F) and cloudy**. | tool_calls: []
=== variant=web_search_modify stream=True litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_head/litellm/__init__.py
turn 1 tool calls: [('web_search', 'srvtoolu_013BBLSkeHh'), ('get_weather', 'toolu_01QoJstcqzcf3Y')] | text: 
turn 1 psf keys: ['web_search_calls', 'web_search_results']
turn 1 tool_results types: []
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: The capital of France is Paris. Paris is the capital and most populous city of France. It sits on the Seine River in the north of the country, in the centre of the Île-de-France region.

It's currentl | tool_calls: []
=== variant=cache_mark stream=False litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_head/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01FWuqxfT58'), ('get_weather', 'toolu_014gkX1gGH3YyF')] | text: 
turn 1 psf keys: ['citations', 'thinking_blocks', 'tool_results']
turn 1 tool_results types: ['tool_search_tool_result']
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
client cache_control on: ['tool_search_tool_bm25']
turn 2 answer: It's 18°C (about 64°F) and cloudy in Paris right now. I got this from the `get_weather` tool I found by searching my tools. | tool_calls: []
=== variant=cache_mark stream=True litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_head/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01QrKM1Thmh'), ('get_weather', 'toolu_01UGop351TnGTz')] | text: 
turn 1 psf keys: ['tool_results']
turn 1 tool_results types: ['tool_search_tool_result']
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
client cache_control on: ['tool_search_tool_bm25']
turn 2 answer: It's currently 18°C (about 64°F) and cloudy in Paris. I found this using a weather lookup tool from the tool search. | tool_calls: []
=== variant=tool_loop litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_head/litellm/__init__.py
executor called for: ['get_weather']
final answer: I found a weather tool and checked Paris: it's currently 18°C (about 64°F) and cloudy.
=== variant=modify_params_unanswered stream=False litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_head/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01DVhD4YBf6'), ('get_weather', 'toolu_01HaBj1LHkQqmZ')] | text: 
turn 1 psf keys: ['citations', 'thinking_blocks', 'tool_results']
turn 1 tool_results types: ['tool_search_tool_result']
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: I found a weather tool (`get_weather`) and asked it for Paris, but the request was stopped before it finished, so I didn't get any weather data back. I can try again if you'd like. | tool_calls: []
=== variant=modify_params_unanswered stream=True litellm.__file__=/Users/mateo/Development/litellm-worktrees/lit9576_head/litellm/__init__.py
turn 1 tool calls: [('tool_search_tool_bm25', 'srvtoolu_01QzrTr3SdN'), ('get_weather', 'toolu_01VqghSha1S9ec')] | text: 
turn 1 psf keys: ['tool_results']
turn 1 tool_results types: ['tool_search_tool_result']
turn 1 code_interpreter_results: <absent>
turn 1 thinking blocks: 0
turn 2 answer: I found a weather tool (`get_weather`) and asked it for Paris, but the call was stopped before it returned anything, so I don't have the weather yet.

I can run it again if you'd like. | tool_calls: []

Proxy QA, 2 workers with the worker pid per turn

A second run on a real proxy started from each worktree with --num_workers 2, main (9271edc) on :4001 and this PR (072aa83) on :4000, against the real Anthropic API on anthropic/claude-opus-5-5. A CustomLogger writes os.getpid() on every upstream call, so each case prints which worker served turn 1 and turn 2, and a case reruns until turn 2 lands on the other worker (the retries are kept in the output). It covers the tool search loop and a plain get_weather loop with no tool search, stream and non-stream. Turn 2 sends back the turn 1 assistant message as returned plus a tool answer for every toolu_ call

On main both tool search cases get the 400 and turn 1's tool_results is []. On this PR both answer, and the plain loop answers on both, so ordinary proxy users see no change. Claude Code was not driven here because it calls /v1/messages, which goes through litellm/llms/anthropic/pass_through/messages/ and never reaches the changed parser or anthropic_messages_pt

config.yaml, pid_logger.py and qa.sh
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:
  callbacks: pid_logger.proxy_handler_instance
general_settings:
  master_key: os.environ/LITELLM_QA_MASTER_KEY
import os

from litellm.integrations.custom_logger import CustomLogger


class PidLogger(CustomLogger):
    def log_pre_api_call(self, model, messages, kwargs):
        with open("/home/ubuntu/scratch/lit9576/pq/worker_pids.log", "a") as f:
            f.write(f"{os.getpid()} {kwargs.get('litellm_call_id')}\n")


proxy_handler_instance = PidLogger()
python litellm/proxy/proxy_cli.py --config config.yaml --port 4000 --num_workers 2   # from each worktree, :4001 for main
B=http://localhost:$1/v1/chat/completions
PIDLOG=/home/ubuntu/scratch/lit9576/pq/worker_pids.log
H=(-H "Authorization: Bearer $KEY" -H "Content-Type: application/json")
SEARCH_TOOLS='[{"type":"tool_search_tool_bm25_20251119","name":"tool_search_tool_bm25"},
 {"type":"function","defer_loading":true,"function":{"name":"get_weather","description":"Get the current weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}},
 {"type":"function","defer_loading":true,"function":{"name":"get_stock_price","description":"Get a stock price by ticker","parameters":{"type":"object","properties":{"ticker":{"type":"string"}},"required":["ticker"]}}}]'
PLAIN_TOOLS='[{"type":"function","function":{"name":"get_weather","description":"Get the current weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}]'
ASSEMBLE='{role:"assistant",
  content:(map(.choices[0].delta.content // "") | join("") | if . == "" then null else . end),
  tool_calls:(map(.choices[0].delta.tool_calls // []) | add | group_by(.index) | map({id:(map(.id // empty) | first), type:"function", function:{name:(map(.function.name // empty) | first), arguments:(map(.function.arguments // "") | join(""))}})),
  provider_specific_fields:(map(.choices[0].delta.provider_specific_fields // {}) | add)}'
run() { # $1=label $2=tools $3=prompt $4=stream
  U=$(jq -n --arg p "$3" '{role:"user",content:$p}')
  REQ=$(jq -n --argjson u "$U" --argjson t "$2" --argjson s $4 '{model:"claude-opus-5-5",messages:[$u],tools:$t,max_tokens:1024,stream:$s}')
  if [ "$4" = true ]; then
    MSG=$(curl -sN "$B" "${H[@]}" -d "$REQ" | grep '^data: {' | sed 's/^data: //' | jq -s "$ASSEMBLE")
  else
    MSG=$(curl -s "$B" "${H[@]}" -d "$REQ" | jq '.choices[0].message')
  fi
  W1=$(tail -1 "$PIDLOG" | cut -d' ' -f1)
  echo "== $1 stream=$4"
  echo "   turn 1 tool calls:    $(jq -c '[.tool_calls[]? | {name:.function.name, id:.id}]' <<<"$MSG")"
  echo "   turn 1 tool_results:  $(jq -c '[.provider_specific_fields.tool_results[]? | {type, tool_use_id}]' <<<"$MSG")"
  REPLIES=$(jq -c '[.tool_calls[]? | select(.id | startswith("srvtoolu_") | not) | {role:"tool",tool_call_id:.id,content:"18C and cloudy"}]' <<<"$MSG")
  REQ2=$(jq -n --argjson u "$U" --argjson m "$MSG" --argjson r "$REPLIES" --argjson t "$2" '{model:"claude-opus-5-5",messages:([$u,$m] + $r),tools:$t,max_tokens:300}')
  R2=$(curl -s "$B" "${H[@]}" -d "$REQ2")
  W2=$(tail -1 "$PIDLOG" | cut -d' ' -f1)
  echo "   workers:              turn 1 pid $W1, turn 2 pid $W2"
  echo "   turn 2:               $(jq -c 'if .error then {error:(.error.message|.[0:160])} else {finish_reason:.choices[0].finish_reason, content:(.choices[0].message.content // "" | .[0:100])} end' <<<"$R2")"
}
until_other_worker() { for try in 1 2 3 4; do OUT=$(run "$@"); echo "$OUT"; grep -Eq 'turn 1 pid ([0-9]+), turn 2 pid \1$' <<<"$OUT" || return; echo "   (same worker, retrying)"; done; }
for s in false true; do until_other_worker "tool search" "$SEARCH_TOOLS" "Search your tools for a weather tool and use it to get the weather in Paris" $s; done
for s in false true; do until_other_worker "plain tool call" "$PLAIN_TOOLS" "Use the get_weather tool to get the weather in Paris" $s; done
Raw output, main (before) then this PR (after)
$ ./qa.sh 4001
== tool search stream=false
   turn 1 tool calls:    [{"name":"tool_search_tool_bm25","id":"srvtoolu_01DAbs3Ck2vACcb1bFcKUREv"},{"name":"get_weather","id":"toolu_017ye2NJ3YEtZrYqi1VgCyK7"}]
   turn 1 tool_results:  []
   workers:              turn 1 pid 5468, turn 2 pid 5467
   turn 2:               {"error":"litellm.BadRequestError: AnthropicException - {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"messages.2: `tool_use` ids were found without `"}
== tool search stream=true
   turn 1 tool calls:    [{"name":"tool_search_tool_bm25","id":"srvtoolu_017Aczycau7zQbiLPJtfzLWC"},{"name":"get_weather","id":"toolu_01H49hSuVzbwP1T1peKH757s"}]
   turn 1 tool_results:  []
   workers:              turn 1 pid 5467, turn 2 pid 5468
   turn 2:               {"error":"litellm.BadRequestError: AnthropicException - {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"messages.2: `tool_use` ids were found without `"}
== plain tool call stream=false
   turn 1 tool calls:    [{"name":"get_weather","id":"toolu_01Bq8gabmvXKu4UXhTkjqfes"}]
   turn 1 tool_results:  []
   workers:              turn 1 pid 5467, turn 2 pid 5467
   turn 2:               {"finish_reason":"stop","content":"It's 18°C and cloudy in Paris right now."}
   (same worker, retrying)
== plain tool call stream=false
   turn 1 tool calls:    [{"name":"get_weather","id":"toolu_01XmGP32H5Z6sQEShYbxFfGj"}]
   turn 1 tool_results:  []
   workers:              turn 1 pid 5467, turn 2 pid 5467
   turn 2:               {"finish_reason":"stop","content":"It's 18°C and cloudy in Paris right now."}
   (same worker, retrying)
== plain tool call stream=false
   turn 1 tool calls:    [{"name":"get_weather","id":"toolu_0139HcdyLpU3LTtiM3nzfYVJ"}]
   turn 1 tool_results:  []
   workers:              turn 1 pid 5467, turn 2 pid 5467
   turn 2:               {"finish_reason":"stop","content":"Paris is 18°C (about 64°F) and cloudy right now."}
   (same worker, retrying)
== plain tool call stream=false
   turn 1 tool calls:    [{"name":"get_weather","id":"toolu_019ouU8DeqoYFkwkr9XsZ7D2"}]
   turn 1 tool_results:  []
   workers:              turn 1 pid 5468, turn 2 pid 5467
   turn 2:               {"finish_reason":"stop","content":"It's 18°C and cloudy in Paris right now."}
== plain tool call stream=true
   turn 1 tool calls:    [{"name":"get_weather","id":"toolu_01TEwyQ5qzkxx8iyDctuemKv"}]
   turn 1 tool_results:  []
   workers:              turn 1 pid 5468, turn 2 pid 5467
   turn 2:               {"finish_reason":"stop","content":"It's 18°C and cloudy in Paris right now."}
$ ./qa.sh 4000
== tool search stream=false
   turn 1 tool calls:    [{"name":"tool_search_tool_bm25","id":"srvtoolu_01Kye1bQQvwPqXagAMasq3ck"},{"name":"get_weather","id":"toolu_013SAuyzToX8SmTx42Ckt353"}]
   turn 1 tool_results:  [{"type":"tool_search_tool_result","tool_use_id":"srvtoolu_01Kye1bQQvwPqXagAMasq3ck"}]
   workers:              turn 1 pid 5461, turn 2 pid 5461
   turn 2:               {"finish_reason":"stop","content":"It's currently 18°C (about 64°F) and cloudy in Paris. I got this from a weather tool I found by sear"}
   (same worker, retrying)
== tool search stream=false
   turn 1 tool calls:    [{"name":"tool_search_tool_bm25","id":"srvtoolu_01Y5DtqLXdDoMwjoVdTVz286"},{"name":"get_weather","id":"toolu_01Sik3u3y8fxe7Y3ZuaxjVCS"}]
   turn 1 tool_results:  [{"type":"tool_search_tool_result","tool_use_id":"srvtoolu_01Y5DtqLXdDoMwjoVdTVz286"}]
   workers:              turn 1 pid 5461, turn 2 pid 5460
   turn 2:               {"finish_reason":"stop","content":"I found a weather tool and checked Paris: it's currently 18°C (about 64°F) and cloudy."}
== tool search stream=true
   turn 1 tool calls:    [{"name":"tool_search_tool_bm25","id":"srvtoolu_01FLTbCqEjDU2vSo7cVCFvjm"},{"name":"get_weather","id":"toolu_01APiXLJShsxTLWgkGMfdm1Q"}]
   turn 1 tool_results:  [{"type":"tool_search_tool_result","tool_use_id":"srvtoolu_01FLTbCqEjDU2vSo7cVCFvjm"}]
   workers:              turn 1 pid 5461, turn 2 pid 5460
   turn 2:               {"finish_reason":"stop","content":"It's currently 18°C (about 64°F) and cloudy in Paris. I found a weather tool by searching my tools a"}
== plain tool call stream=false
   turn 1 tool calls:    [{"name":"get_weather","id":"toolu_0187qCJ7NXHqwWWwQcuHYmUd"}]
   turn 1 tool_results:  []
   workers:              turn 1 pid 5461, turn 2 pid 5461
   turn 2:               {"finish_reason":"stop","content":"It's 18°C and cloudy in Paris right now."}
   (same worker, retrying)
== plain tool call stream=false
   turn 1 tool calls:    [{"name":"get_weather","id":"toolu_01Ne6c5Hrjfkp49no5AdezRQ"}]
   turn 1 tool_results:  []
   workers:              turn 1 pid 5461, turn 2 pid 5461
   turn 2:               {"finish_reason":"stop","content":"It's 18°C and cloudy in Paris right now."}
   (same worker, retrying)
== plain tool call stream=false
   turn 1 tool calls:    [{"name":"get_weather","id":"toolu_01Jtyd53s5Ub2qdueuxnJR7w"}]
   turn 1 tool_results:  []
   workers:              turn 1 pid 5460, turn 2 pid 5461
   turn 2:               {"finish_reason":"stop","content":"It's 18°C and cloudy in Paris right now."}
== plain tool call stream=true
   turn 1 tool calls:    [{"name":"get_weather","id":"toolu_01AHhK38vnE1NrAPdXsayRX4"}]
   turn 1 tool_results:  []
   workers:              turn 1 pid 5461, turn 2 pid 5461
   turn 2:               {"finish_reason":"stop","content":"It's 18°C and cloudy in Paris right now."}
   (same worker, retrying)
== plain tool call stream=true
   turn 1 tool calls:    [{"name":"get_weather","id":"toolu_01FunpPZ71NCJeaTPVsPW2Du"}]
   turn 1 tool_results:  []
   workers:              turn 1 pid 5460, turn 2 pid 5461
   turn 2:               {"finish_reason":"stop","content":"It's 18°C and cloudy in Paris right now."}

Type

🐛 Bug Fix
✅ Test

Caveats (if any)

Medium

Low

  • Where the TLDR's decision applies, Claude sees the client's answer and not the real server result
  • With modify_params, a request ending on an assistant turn with only server tool calls still gets the placeholder, and the cache control hook misses a mark on those calls
  • The proof does not cover the regex search tool or a thinking turn
  • fix(responses): translate OpenAI tool_search to Anthropic tool search for Claude models #45882 moves find_anthropic_server_tool_result, so the second to merge fixes a small factory.py conflict

Tests

test_anthropic_tool_search_result_wire.py runs the loop through the proxy against a scripted upstream, stream and non-stream, and checks that the second request has server_tool_use, the exact tool_search_tool_result, then tool_use. Both cases fail on 457b5d26c7

23 of 23 mutations fail the unit tests

Unit tests and mutations

The unit tests replace test_tool_search_tool_result_not_in_tool_results, which pinned the bug. A round trip test covers tool search and web_search with a client that answers only its own call, also answers the server call, or uses modify_params, and the kept result must go back right after its call. A replay test covers a search that found nothing, where the client's answer stays unless the user writes again, and each case must answer every tool_use and end on a user turn. A parse test checks that a tool search turn gets code_interpreter_results only when it also ran code. The cache control hook test counts a mark only on a server call that goes out as tool_use, and the run_tool_loop tests check that a search call is replayed and never executed, and that a turn with no server call goes back without provider_specific_fields

Mutations: Restore either skip, drop tool_results from find_anthropic_server_tool_result, put the result before its call, route the block into web_search_results in either mode, rebuild the server result even when the client answered, never rebuild it, never or always drop a client answer to a server call, count only tool rows as a later user turn, keep the dropped tool message, make the hook ignore dropped answers or client answers in either place, set code_interpreter_results on a search result or never set it in either mode, drop or always send provider_specific_fields in run_tool_loop's replay, run server calls through the executor, or send a search-only turn back in arun_tool_loop

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

Note

Medium Risk
Changes core Anthropic message transformation, streaming parsing, and tool-loop replay logic across many providers; incorrect edge-case handling could still produce invalid upstream message shapes or miscount cache breakpoints.

Overview
Fixes multi-turn Claude tool search loops that previously 400'd because tool_search_tool_result was dropped and the srvtoolu_ call was replayed without its matching result.

Response path: Streaming and non-streaming Anthropic parsing now retain tool_search_tool_result in provider_specific_fields.tool_results (without treating it as code execution). code_interpreter_results is only built when non–tool-search tool results exist.

Replay path: Message conversion tracks which tool IDs the client actually answered vs. cases where a kept server result should replace the client's tool message. Replays emit server_tool_use plus the stored result immediately after the call; redundant client answers are skipped when a later user/tool turn follows. If the client's answer is the only follow-up, the call stays plain tool_use so the request does not end on an assistant turn.

Tool loop & cache: run_tool_loop / arun_tool_loop execute only client tool calls, optionally preserving provider_specific_fields when server tools are replayed. The Anthropic cache-control hook counts breakpoints on server tool calls only when they are not client-answered and will be rebuilt as server tool use.

Large integration/unit test coverage was added for proxy providers, chaos, SDK, passthrough, and cache marks.

Reviewed by Cursor Bugbot for commit cd4213d. Bugbot is set up for automated code reviews on this repo. Configure here.

Video walkthrough (/rush, live two-worker proxy curl plus SDK Router, real Anthropic) https://berriaillm.slack.com/files/U0ATSFX0VK2/F0C9E7AA1PT/pr46440_tool_search_tutorial.mp4

…ys with its result

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@litereview

litereview Bot commented Oct 14, 2026

Copy link
Copy Markdown

Review already requested

code-review is already reviewing b23ae6dc5d6f. View existing 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.

@litereview

litereview Bot commented Oct 14, 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.

Checks and execution details
  • Passed · Real testing evidence (required): The rule applies because the PR changes LLM translation in litellm/llms/anthropic/chat/transformation.py, litellm/llms/anthropic/chat/handler.py and litellm/litellm_core_utils/prompt_templates/factory.py. Responses now keep tool_search_tool_result, and replay puts that block after its server_tool_use.

  • Manual E2E evidence: The PR description has raw before and after output for 14 two-turn cases against the real Anthropic API on anthropic/claude-opus-5-5. The cases go through litellm.completion, Router.completion and a 2-worker proxy, in stream and non-stream modes. The full scripts are included. Before (457b5d26c7), the cases fail with Anthropic 400 tool_use ids were found without tool_result blocks. After (072aa83442), turn 2 answers and tool_results holds tool_search_tool_result.

  • Head commit: The GitHub compare API shows the head (cd4213d4b5) is one commit ahead of 072aa83442. That commit touches only tests/integration/**, so the manual proof covers the implementation under review.

  • Fixture provenance: The scripted-upstream wire tests in tests/integration/providers/test_anthropic_tool_search_result_* use the same block shape the real API returned in that proof.

  • CI: Head CI is green, including llms-anthropic, unit passed and buildkite/e2e-tests.

  • Passed · Changed unit tests (optional): Ran uv run --frozen pytest tests/unit/test_tool_loop.py tests/unit/integrations/test_anthropic_cache_control_hook.py tests/unit/llms/anthropic/chat/test_anthropic_chat_handler.py tests/unit/llms/anthropic/chat/test_anthropic_chat_transformation.py -n 8 after uv sync --frozen --all-extras. Result: 1159 passed.

  • Passed · SDK integration test for tool loop replay (optional): Ran PYTHONPATH=tests uv run --frozen pytest tests/integration/sdk/test_tool_loop_server_tool_replay_sdk.py. Result: 4 passed.

  • Passed · Replay reproducer for anthropic_messages_pt (optional): Built a local script that sends an assistant turn with thinking, a srvtoolu_ search call and a client toolu_ call. With only the client answer, and with both answers, the output has server_tool_use, then the kept tool_search_tool_result, then tool_use. In both cases only the toolu_1 tool_result is sent back. When the client answers only the server call, the call goes back as tool_use, as the PR's stated decision describes.

  • Not run · Proxy integration shard (providers) run locally (optional): Not run locally: the proxy wire tests need the CircleCI rig with Postgres, Redis and the proxy (.circleci/scripts/run_integration.sh), and none of these exist in this sandbox. Head CI and the manual E2E proof cover this behavior.


View review · Reviewed cd4213d4b5aa

@codspeed

codspeed Bot commented Oct 14, 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_tool_search_result_roundtrip (cd4213d) with main (8302f00)

Open in CodSpeed

@codecov

codecov Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.30508% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/tool_loop.py 93.75% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

…l_search_result_roundtrip

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

# Conflicts:
#	tests/unit/llms/anthropic/chat/test_anthropic_chat_handler.py
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

…s://github.com/BerriAI/litellm into litellm_anthropic_tool_search_result_roundtrip

# Conflicts:
#	tests/unit/llms/anthropic/chat/test_anthropic_chat_handler.py
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

…client-answered marks, and replay it from run_tool_loop

modify_params no longer adds a placeholder answer for a server tool call whose result is kept, unless the call ends the request. The cache control hook counts a mark on a server tool call the client answered, since that call goes out as a plain tool_use. run_tool_loop sends provider_specific_fields back and runs only the client's tool calls.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

1 similar comment
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

…llows, scope run_tool_loop's replay, and keep code_interpreter_results off tool search turns
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@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

@litellm-stampbot

@litellm-stampbot

Copy link
Copy Markdown

litellm-stampbot: risk high

Not approved at 072aa83. risk is high, a human reviewer is needed.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

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

  • tier: high (confidence 0.84)
  • change_kind: default_behavior_change (confidence 0.93)
  • blast_radius: request_hot_path (confidence 0.41)
  • complexity: complex (confidence 0.99)

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
mateo-berri enabled auto-merge (squash) October 14, 2026 23:59
…ay, cache marks, pass-through logging and chaos
@greptile-apps

greptile-apps Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Automatic reviews are disabled for this repository.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

✅ 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 cd4213d. Configure here.

@mateo-berri
mateo-berri merged commit 9ba4cc4 into main Oct 15, 2026
89 checks passed
@mateo-berri
mateo-berri deleted the litellm_anthropic_tool_search_result_roundtrip branch October 15, 2026 01:52
mateo-berri added a commit that referenced this pull request Oct 15, 2026
…earch_items

Resolves tool_loop.py against #46440 so provider_specific_fields replay for an Anthropic server tool call and for a turn that carries tool search items, and restores seven bridge unit tests that the previous main merge dropped
devin-ai-integration Bot added a commit that referenced this pull request Oct 15, 2026
's client-answered replay beside the unanswered search-call drop

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
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.

2 participants