Repository navigation
fix(websearch-interception)!: stream native server-tool blocks to clients - #40967
Conversation
784e9eb to
ccc72ea
Compare
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
7c17424 to
1691aa4
Compare
Streaming native clients (Anthropic SDK, Claude Desktop, Claude Code) never received the server_tool_use and web_search_tool_result blocks the interception layer builds for them, so citation panels stayed empty and result counts read zero. Two gaps in the same flow: FakeAnthropicMessagesStreamIterator._create_content_block_chunks only knew text, thinking, redacted_thinking and tool_use; any other block type emitted a bare content_block_stop with no start and no payload, silently dropping the block from the fake stream. server_tool_use now streams as content_block_start plus input_json_delta and any other server-generated block rides whole in content_block_start, matching Anthropic's native streaming of these types. try_short_circuit_search only recognized a native client by finding a web_search_* tool in the tools list, but the pre-request and deployment hooks convert that tool to the LiteLLM standard shape before the short-circuit runs, recording the conversion in WEBSEARCH_EMIT_NATIVE_BLOCKS_KEY. The flag now counts as native too, so the synthetic response carries the native blocks on the converted path instead of only when hook ordering happens to leave the tool untouched. Fixes BerriAI#35333
1691aa4 to
0abfc2a
Compare
…r_tool_blocks # Conflicts: # tests/unit/llms/anthropic/messages/native/test_fake_stream_iterator.py
…cks when costing a /v1/messages response The short-circuit now returns native web search blocks, and the cost path validated the served body against a content union that only allowed text, tool_use and thinking blocks, so non-streaming requests answered 500
…r_tool_blocks # Conflicts: # tests/unit/integrations/websearch_interception/test_websearch_short_circuit.py
[High impact] The PR appears safe to merge, with no new actionable issue found SummaryThe PR returns native search blocks to Anthropic clients and preserves tool fields, redacted thinking, and citations when rebuilding streams
Reviews (10) · Last reviewed commit: "fix(guardrails): keep the block id when ..." · Reviewed by Greptile |
…/v1/messages reply
… citations when re-streaming a /v1/messages reply
…th a datetime start time
…ages and deliver stream rewrites past server_tool_use blocks Output guardrails now scan the native web search blocks the short-circuit emits, ahead of the reply text so guardrails that read the last text still scan the reply. A guardrail reply of a different length falls back to the reply-only write-back. Ended-stream tool call rewrites land on server_tool_use blocks too, the ended-stream scan key covers the result strings, and legacy-hook pipeline steps pass through the result strings their response view lacks. The wire test reads the streamed server_tool_use input from its input_json_delta.
… on streams instead of discarding the stream rewrite A legacy hook that masked a tool call's arguments on a buffered stream made the whole rewrite undeliverable, text included, so the original stream went out. With web search blocks in the stream that now hit any hook masking the search query. The adapter hands same-count tool-call rewrites to the translation's write-back, as a unified guardrail's already are, and still discards a rewrite that adds or drops a tool call.
…locks of a /v1/messages stream The legacy hook's view of a buffered Anthropic stream is rebuilt from the assembled ModelResponse, which keeps web_search_tool_result blocks only in provider-specific fields, so a hook masking result titles on a stream never saw them. The hook's view now carries those blocks, its rewrite of them goes back through the ended-stream write-back, and the adapter no longer needs to pass texts outside the hook's view through untouched.
|
Want your agent to iterate on Greptile's feedback? Try greploops. |
|
bugbot run |
…n-streaming reply
|
bugbot run |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 373df54. Configure here.
mateo-berri
left a comment
There was a problem hiding this comment.
LGTM. Thanks for the contribution!
Reopens #37318, closed by the default-branch cutover, retargeted to
mainper the discussionAnthropic-native clients like Claude Code searching through the proxy's web search interception got a plain text answer, so Claude Code showed zero searches. The direct search answer now opens with
server_tool_useandweb_search_tool_resultblocks like the Anthropic API, with snippets only in its text blockThe fake stream behind seven callers now keeps every
tool_usefield, redacted thinkingdataand text citations. Guardrails also scan the new blocks, and legacy post-call hook stream rewrites now reach the clientOriginal
Breaking change: with the native
web_searchtool, the direct search answer now opens with search blocks like the Anthropic API, so code readingcontent[0].textshould find the text block by typeTLDR
Problem this solves:
tool_usecaller, redacted thinkingdataand text citationsHow it solves it:
input_json_delta, citations ascitations_delta, and keeps every other block fieldserver_tool_useandweb_search_tool_resultblocksusage.server_tool_use.web_search_requestsstays unset, since litellm would bill it at the model's search price on top of the Tavily searchUser Flow
Before: an Anthropic-native client (Claude Code, the Anthropic SDK) that searches through the proxy sees no evidence a search ran
{"type": "web_search_20250305", "name": "web_search"}, streaming or notserver_tool_useand noweb_search_tool_resultDid 0 searchesand SDK code finds no search blocks, though the text quotes the searchAfter: the same request returns the full native block set
{"type": "web_search_20250305", "name": "web_search"}, streaming or notserver_tool_usecarrying the query, thenweb_search_tool_resultwith the results, then the text blockDid 1 searchandweb_search_tool_resultholds the result URLsRelevant issues
Fixes #35333, whose re-wrapped stream main already fixed in 0485b3f. This PR fixes the same missing blocks on the direct search answer
Linear ticket
Resolves LIT-9789
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Last updated: 373df54. QA ran on f674537, and on 80da78f for the Anthropic rows. Changes since QA: guardrail scans of search blocks, snippets sent once, and typed test helpers. Proof remains valid because this config attaches no guardrail and the Anthropic rows build no direct search answer. Verification: at 373df54, 189 focused unit tests pass and the no-guardrail Live PR risk cells match, also at its merge with main
Each tree runs a live proxy with
--num_workers 2in front ofbedrock/converse/us.anthropic.claude-sonnet-5-5and a real Tavily search, with Before on the merge base a66dc50. Clients are Claude Code 2.1.296 in its real TUI, curl, and the Anthropic Python SDK 2.3.0config.yaml
/v1/messagesnon-streaming/v1/messagesstreamingtool_usecallerserver_tool_usecallerClaude Code WebSearch
litellm --config config.yaml --port $PORT --num_workers 2ANTHROPIC_BASE_URL=http://127.0.0.1:$PORT ANTHROPIC_AUTH_TOKEN=$LITELLM_MASTER_KEY ANTHROPIC_DEFAULT_SONNET_MODEL=claude-sonnet-5-5 ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-sonnet-5-5 ANTHROPIC_DEFAULT_OPUS_MODEL=claude-sonnet-5-5 claude --model claude-sonnet-5-5Use your WebSearch tool to find the latest stable Python release, then tell me the version and cite your sources.and press EnterBefore (a66dc50), the search runs but Claude Code shows
Did 0 searches in 2sAfter (f674537), the same prompt shows
Did 1 search in 1s/v1/messages non-streaming and streaming with curl
Non-streaming
Before (a66dc50)
After (f674537)
Each search result carries its title and URL, and the snippets stay in the text block only, so a client that sends the turn back as history sends them once
Streaming
Before (a66dc50)
After (f674537)
Anthropic replies re-streamed through the fake stream
A second config points
claude-sonnet-5-5atanthropic/claude-sonnet-5-5withenabled_providers: ["anthropic"], so the interception makes one non-streaming call and re-streams Anthropic's reply. Every request below streams and carries theweb_searchtool, and the model answers without searching. Both proxies ran with--num_workers 2End-user code that reads a cited answer and a tool call made from code execution, run with
ANTHROPIC_BASE_URL=http://127.0.0.1:$PORT ANTHROPIC_API_KEY=$LITELLM_MASTER_KEY python sdk_case.pyBefore (a66dc50)
After (80da78f)
The same cited answer with curl
Before (a66dc50)
After (80da78f)
The same tool call with curl
Before (a66dc50)
After (80da78f)
A
server_tool_usefrom code execution keptcalleron both treesBefore (a66dc50)
After (80da78f)
Text-only guardrail on a streamed search
Bugbot found that a guardrail that rewrites only
textsleft the streamedserver_tool_usequery unmasked. This cell attaches a custom post_call guardrail that masks "python" intextsonly, through a policy pipeline on the same Bedrock model and Tavily search. The config and the guardrail are in the gistBefore the fix (8ea884d)
After (19336aa)
The merge base a66dc50 answers with a text block only, and the non-streaming reply masks the query at both commits
Observations
Type
🐛 Bug Fix
Caveats (if any)
Medium
usagestill reports zero searches, so SDK code reading it sees none next to aserver_tool_useblockLow
Live PR risk
Verdict at 373df54: safe to ship, also at its merge with main (a8cf0bbd41)
Breaking, backward incompatible, regression risk, dependency graph, not verified
The table is from 19336aa. At 373df54 every head cell answers 200 with one upstream request, the masking cells stay at 0, and the other counts move only with the search results. At its merge with main (a8cf0bbd41) the four legacy tool cells could not run because the Bedrock QA credentials expired, and they pass at 373df54 and at the earlier merge b14e46ee0c
Nothing that worked before breaks, and each change a client can see is the ticket's ask or a guardrail that now works. Every cell runs on both trees with 2 workers each, against Bedrock and Anthropic with a real Tavily search. The guardrails mask the word "python", and each count is how many matches reach the client. The counts per block, config and scripts are in this gist
Breaking
None. Every cell answered 200 on both trees, and the 22 wire tests pass at e6715ba
Backward incompatible
server_tool_useandweb_search_tool_resultbefore its text block. Approved by Shivam in the Expected section of LIT-9789, which asks for these blocksweb_search_tool_result, which that hook skips, so 33 matches reach the client. Same approval, and a unified guardrail scans them since 923b9d4/v1/messagesnow masks the search query, result titles and URLs, so a mask can change a result link. This is a control that now works, fixed in 923b9d4, and for a streamed query under a text-only guardrail in 19336aa and 373df54Regression risk
Dependency graph
/v1/messages/v1/messagesstream/v1/messages/v1/messagesThe ranking put
/v1/messagesstreaming and non-streaming first, then chat and responses streams with a legacy hook, then the SDK'santhropic_messages, then spend loggingNot verified
tool_usesearch block with asrvtoolu_id, since no rig route sends one, so a unit test covers itFinal Attestation
Bugbot summary