Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: keep web search source links for unsloth start claude (#12307)

Nilay74e53b070234
diff --git a/studio/backend/core/inference/anthropic_compat.py b/studio/backend/core/inference/anthropic_compat.py
index 0e140b6351d..a47e0a558bb 100644
--- a/studio/backend/core/inference/anthropic_compat.py
+++ b/studio/backend/core/inference/anthropic_compat.py
@@ -10,9 +10,12 @@ Pure functions plus stateful stream emitters; no FastAPI, no I/O.
from __future__ import annotations
import json
+import re
import uuid
from typing import Any, Optional, Union
+from core.inference.tool_loop_controller import is_tool_error
+
def openai_finish_to_anthropic_stop(finish_reason, had_tool_calls = False) -> str:
"""Map an OpenAI finish_reason to an Anthropic stop_reason.
@@ -31,13 +34,51 @@ def openai_finish_to_anthropic_stop(finish_reason, had_tool_calls = False) -> st
return "end_turn"
-def anthropic_tool_use_id(upstream_id = None) -> str:
- """Return an Anthropic-style tool_use id (prefix 'toolu_'). Reuses an
- upstream id only if it already starts with 'toolu_'; otherwise mints a fresh
- 'toolu_<24 hex>'."""
- if upstream_id and isinstance(upstream_id, str) and upstream_id.startswith("toolu_"):
+def anthropic_tool_use_id(upstream_id = None, prefix = "toolu_") -> str:
+ """Return an Anthropic tool id: the upstream id if it already starts with
+ ``prefix``, else a fresh '<prefix><24 hex>'."""
+ if upstream_id and isinstance(upstream_id, str) and upstream_id.startswith(prefix):
return upstream_id
- return f"toolu_{uuid.uuid4().hex[:24]}"
+ return f"{prefix}{uuid.uuid4().hex[:24]}"
+
+
+_WEB_SEARCH_HIT = re.compile(r"^Title: (.*)\nURL: (\S+)", re.MULTILINE)
+
+
+def web_search_tool_result_content(
+ result: str, arguments: Optional[dict] = None
+) -> Union[list, dict]:
+ """``content`` of a web_search_tool_result: the search hits, the page a ``url`` call fetched,
+ or the API's error object when the tool failed."""
+ if is_tool_error(result):
+ return {"type": "web_search_tool_result_error", "error_code": "unavailable"}
+ fetched = str((arguments or {}).get("url") or "").strip()
+ if fetched:
+ hits = [(fetched, fetched)] if result.strip() else []
+ else:
+ hits = _WEB_SEARCH_HIT.findall(result)
+ return [
+ {
+ "type": "web_search_result",
+ "title": title.strip(),
+ "url": url,
+ "encrypted_content": "",
+ "page_age": None,
+ }
+ for title, url in hits
+ ]
+
+
+def _web_search_result_text(content: Any) -> str:
+ """Render a replayed web_search_tool_result ``content`` in web_search's own output format."""
+ if isinstance(content, dict):
+ return f"Search failed: {content.get('error_code', 'unavailable')}"
+ hits = [
+ f"Title: {hit.get('title', '')}\nURL: {hit['url']}"
+ for hit in content or []
+ if isinstance(hit, dict) and hit.get("url")
+ ]
+ return "\n\n---\n\n".join(hits) or "No results found."
TOOL_RESULT_IMAGE_OMITTED = "[image omitted: this model cannot view images]"
@@ -168,10 +209,27 @@ def anthropic_messages_to_openai(
if role == "assistant":
# Assistant content: text + tool_use (no images in Anthropic's model), plus replayed thinking when
- # preservation is requested.
+ # preservation is requested. A web search pair splits the turn the way Studio's tool loop ran it: the
+ # call, its result as a tool message, then what followed.
text_parts: list[str] = []
tool_calls: list[dict] = []
thinking_parts: list[str] = []
+ server_calls: dict[str, dict] = {}
+ flushed = False
+
+ def _flush_assistant() -> None:
+ msg_dict: dict[str, Any] = {"role": "assistant"}
+ if text_parts:
+ msg_dict["content"] = "\n".join(text_parts)
+ if thinking_parts:
+ msg_dict["reasoning_content"] = "\n\n".join(thinking_parts)
+ if tool_calls:
+ msg_dict["tool_calls"] = list(tool_calls)
+ result.append(msg_dict)
+ text_parts.clear()
+ tool_calls.clear()
+ thinking_parts.clear()
+
for block in content:
b = block if isinstance(block, dict) else block.model_dump()
btype = b.get("type", "")
@@ -192,14 +250,31 @@ def anthropic_messages_to_openai(
},
}
)
- msg_dict: dict[str, Any] = {"role": "assistant"}
- if text_parts:
- msg_dict["content"] = "\n".join(text_parts)
- if thinking_parts:
- msg_dict["reasoning_content"] = "\n\n".join(thinking_parts)
- if tool_calls:
- msg_dict["tool_calls"] = tool_calls
- result.append(msg_dict)
+ elif btype == "server_tool_use":
+ server_calls[b.get("id")] = b
+ elif btype == "web_search_tool_result" and b.get("tool_use_id") in server_calls:
+ call = server_calls.pop(b["tool_use_id"])
+ tool_calls.append(
+ {
+ "id": b["tool_use_id"],
+ "type": "function",
+ "function": {
+ "name": call.get("name") or "web_search",
+ "arguments": json.dumps(call.get("input") or {}),
+ },
+ }
+ )
+ _flush_assistant()
+ result.append(
+ {
+ "role": "tool",
+ "tool_call_id": b["tool_use_id"],
+ "content": _web_search_result_text(b.get("content")),
+ }
+ )
+ flushed = True
+ if text_parts or tool_calls or thinking_parts or not flushed:
+ _flush_assistant()
continue
if role == "user":
@@ -556,6 +631,7 @@ class AnthropicStreamEmitter:
# consumers can correlate them.
self._open_tool_use_id: Optional[str] = None
self._open_tool_args_sent: bool = False
+ self._open_tool_args: dict = {}
self._prev_text: str = ""
# <think> routing: the generator folds reasoning_content into the cumulative text as <think>...</think> markup
# (the UI chat parses it), but Anthropic clients expect typed thinking blocks. Split the markup back out: text
@@ -843,10 +919,14 @@ class AnthropicStreamEmitter:
self._open_tool_use_id = None
self._open_tool_args_sent = False
+ web_search = event.get("tool_name") == "web_search"
self._alloc_block_index()
self._open_tool_call_id = tool_call_id
- self._open_tool_use_id = anthropic_tool_use_id(tool_call_id)
+ self._open_tool_use_id = anthropic_tool_use_id(
+ tool_call_id, "srvtoolu_" if web_search else "toolu_"
+ )
self._open_tool_args_sent = False
+ self._open_tool_args = {}
events.append(
build_anthropic_sse_event(
"content_block_start",
@@ -854,7 +934,7 @@ class AnthropicStreamEmitter:
"type": "content_block_start",
"index": self.block_index,
"content_block": {
- "type": "tool_use",
+ "type": "server_tool_use" if web_search else "tool_use",
"id": self._open_tool_use_id,
"name": event.get("tool_name", ""),
"input": {},
@@ -871,6 +951,7 @@ class AnthropicStreamEmitter:
if self._open_tool_args_sent:
return []
self._open_tool_args_sent = True
+ self._open_tool_args = args
return [
build_anthropic_sse_event(
"content_block_delta",
@@ -892,19 +973,40 @@ class AnthropicStreamEmitter:
# Reuse the id published in content_block_start; fall back to mapping the raw id only if no tool_start preceded
# this end.
tool_use_id = self._open_tool_use_id or anthropic_tool_use_id(event.get("tool_call_id", ""))
+ tool_args, self._open_tool_args = self._open_tool_args, {}
self._open_tool_call_id = None
self._open_tool_use_id = None
self._open_tool_args_sent = False
- events.append(
- build_anthropic_sse_event(
- "tool_result",
- {
- "type": "tool_result",
- "tool_use_id": tool_use_id,
- "content": event.get("result", ""),
- },
+ if event.get("tool_name") == "web_search":
+ self._alloc_block_index()
+ events.append(
+ build_anthropic_sse_event(
+ "content_block_start",
+ {
+ "type": "content_block_start",
+ "index": self.block_index,
+ "content_block": {
+ "type": "web_search_tool_result",
+ "tool_use_id": tool_use_id,
+ "content": web_search_tool_result_content(
+ event.get("result", ""), tool_args
+ ),
+ },
+ },
+ )
+ )
+ events.append(self._close_block())
+ else:
+ events.append(
+ build_anthropic_sse_event(
+ "tool_result",
+ {
+ "type": "tool_result",
+ "tool_use_id": tool_use_id,
+ "content": event.get("result", ""),
+ },
+ )
)
- )
# Reset text tracking for the next synthesis turn; the next content delta opens a fresh text (or thinking)
# block lazily, and the new turn may legitimately open with its own leading <think> block.
self._prev_text = ""
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index e04eab53edb..9dd446d418a 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -3890,6 +3890,19 @@ class AnthropicResponseToolUseBlock(BaseModel):
input: dict
+class AnthropicResponseServerToolUseBlock(BaseModel):
+ type: Literal["server_tool_use"] = "server_tool_use"
+ id: str
+ name: str
+ input: dict
+
+
+class AnthropicResponseWebSearchToolResultBlock(BaseModel):
+ type: Literal["web_search_tool_result"] = "web_search_tool_result"
+ tool_use_id: str
+ content: Union[list[dict], dict]
+
+
class AnthropicResponseThinkingBlock(BaseModel):
type: Literal["thinking"] = "thinking"
thinking: str
@@ -3901,6 +3914,8 @@ class AnthropicResponseThinkingBlock(BaseModel):
AnthropicResponseBlock = Union[
AnthropicResponseTextBlock,
AnthropicResponseToolUseBlock,
+ AnthropicResponseServerToolUseBlock,
+ AnthropicResponseWebSearchToolResultBlock,
AnthropicResponseThinkingBlock,
]
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 4efb5953582..8c06305b070 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -3693,9 +3693,11 @@ from models.inference import (
ResponsesResponse,
AnthropicMessagesRequest,
AnthropicMessagesResponse,
+ AnthropicResponseServerToolUseBlock,
AnthropicResponseTextBlock,
AnthropicResponseThinkingBlock,
AnthropicResponseToolUseBlock,
+ AnthropicResponseWebSearchToolResultBlock,
AnthropicUsage,
CreateOpenAIContainerBody,
DeleteOpenAIContainerBody,
@@ -3714,6 +3716,7 @@ from core.inference.anthropic_compat import (
openai_finish_to_anthropic_stop,
anthropic_tool_use_id,
build_anthropic_sse_event,
+ web_search_tool_result_content,
AnthropicStreamEmitter,
AnthropicPassthroughEmitter,
)
@@ -7244,7 +7247,10 @@ def _monitor_anthropic_payload(
return None
if event_type == "content_block_start":
content_block = data.get("content_block") or {}
- if isinstance(content_block, dict) and content_block.get("type") == "tool_use":
+ if isinstance(content_block, dict) and content_block.get("type") in (
+ "tool_use",
+ "server_tool_use",
+ ):
index = _monitor_anthropic_index(data)
_ANTHROPIC_MONITOR_TOOL_BLOCKS.setdefault(monitor_id, {})[index] = False
api_monitor.append_reply(monitor_id, _monitor_call_text(content_block.get("name")))
@@ -7316,7 +7322,7 @@ def _monitor_anthropic_content_blocks(content: Any) -> str:
continue
if block.get("type") == "text" and isinstance(block.get("text"), str):
parts.append(block["text"])
- elif block.get("type") == "tool_use":
+ elif block.get("type") in ("tool_use", "server_tool_use"):
parts.append(_monitor_call_text(block.get("name"), block.get("input")))
return "".join(parts)
@@ -38043,7 +38049,9 @@ def _anthropic_tool_response_from_events(
baseline, not turn N's final length.
"""
content_blocks: list = []
- tool_blocks_by_id: dict[str, AnthropicResponseToolUseBlock] = {}
+ tool_blocks_by_id: dict[
+ str, Union[AnthropicResponseToolUseBlock, AnthropicResponseServerToolUseBlock]
+ ] = {}
usage = {}
prev_text = ""
captured_finish_reason = None
@@ -38093,8 +38101,13 @@ def _anthropic_tool_response_from_events(
if event.get("tool_name") and not existing_tool_block.name:
existing_tool_block.name = event["tool_name"]
else:
- tool_block = AnthropicResponseToolUseBlock(
- id = anthropic_tool_use_id(tool_call_id),
+ block_cls, id_prefix = (
+ (AnthropicResponseServerToolUseBlock, "srvtoolu_")
+ if event["tool_name"] == "web_search"
+ else (AnthropicResponseToolUseBlock, "toolu_")
+ )
+ tool_block = block_cls(
+ id = anthropic_tool_use_id(tool_call_id, id_prefix),
name = event["tool_name"],
input = arguments,
)
@@ -38105,6 +38118,18 @@ def _anthropic_tool_response_from_events(
elif etype == "tool_end":
prev_text = ""
_span_guard.tool_end()
+ # Done with this call: text-parsed calls restart at call_0 each iteration, so a later
+ # call may reuse its id and must open a block of its own.
+ search_call = tool_blocks_by_id.pop(event.get("tool_call_id"), None)
+ if isinstance(search_call, AnthropicResponseServerToolUseBlock):
+ content_blocks.append(
+ AnthropicResponseWebSearchToolResultBlock(
+ tool_use_id = search_call.id,
+ content = web_search_tool_result_content(
+ event.get("result", ""), search_call.input
+ ),
+ )
+ )
# Server-executed: no longer pending a client action (see above).
ends_on_tool_use = False
elif etype == "metadata":
diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.py
index 133eb7f9f49..80ce02e5072 100644
--- a/studio/backend/tests/test_anthropic_messages.py
+++ b/studio/backend/tests/test_anthropic_messages.py
@@ -117,6 +117,50 @@ def _tool_result_event(**overrides):
}
+_WEB_SEARCH_RESULT = (
+ "Title: Releases · ggml-org/llama.cpp\n"
+ "URL: https://github.com/ggml-org/llama.cpp/releases\n"
+ "Snippet: b9999 (2026-09-28)"
+ "\n\n---\n\n"
+ "Title: llama.cpp - Wikipedia\n"
+ "URL: https://en.wikipedia.org/wiki/Llama.cpp\n"
+ "Snippet: llama.cpp is an open source library."
+ "\n\n---\n\nIMPORTANT: These are only short snippets."
+)
+_WEB_SEARCH_HITS = [
+ {
+ "type": "web_search_result",
+ "title": "Releases · ggml-org/llama.cpp",
+ "url": "https://github.com/ggml-org/llama.cpp/releases",
+ "encrypted_content": "",
+ "page_age": None,
+ },
+ {
+ "type": "web_search_result",
+ "title": "llama.cpp - Wikipedia",
+ "url": "https://en.wikipedia.org/wiki/Llama.cpp",
+ "encrypted_content": "",
+ "page_age": None,
+ },
+]
+_WEB_SEARCH_ERROR = {"type": "web_search_tool_result_error", "error_code": "unavailable"}
+_FETCHED_URL = "https://github.com/ggml-org/llama.cpp"
+_WEB_SEARCH_OUTCOMES = [
+ ({"query": "llama.cpp"}, "No results found.", []),
+ (
+ {"query": "llama.cpp"},
+ "Search failed: the search engines did not respond.",
+ _WEB_SEARCH_ERROR,
+ ),
+ (
+ {"url": _FETCHED_URL},
+ "# llama.cpp\nTitle: quoted page text\nURL: https://example.com",
+ [{**_WEB_SEARCH_HITS[0], "title": _FETCHED_URL, "url": _FETCHED_URL}],
+ ),
+ ({"url": _FETCHED_URL}, "Failed to fetch URL: HTTP 404 Not Found", _WEB_SEARCH_ERROR),
+]
+
+
def _tool_result_turn(
*,
role = "user",
@@ -482,7 +526,8 @@ def test_anthropic_emitter_holds_back_partial_think_tag():
assert _emitter_client_text(events) == "Out"
-def test_streamed_anthropic_tool_use_records_api_monitor_reply(monkeypatch):
[email protected]("block_type", ["tool_use", "server_tool_use"])
+def test_streamed_anthropic_tool_use_records_api_monitor_reply(monkeypatch, block_type):
import routes.inference as inf_mod
monitor = ApiMonitor(max_entries = 3)
@@ -499,7 +544,7 @@ def test_streamed_anthropic_tool_use_records_api_monitor_reply(monkeypatch):
"type": "content_block_start",
"index": 0,
"content_block": {
- "type": "tool_use",
+ "type": block_type,
"id": "toolu_1",
"name": "lookup",
"input": {},
@@ -795,6 +840,63 @@ class TestAnthropicMessagesToOpenAI:
assert tc["function"]["name"] == "web_search"
assert json.loads(tc["function"]["arguments"]) == {"query": "test"}
+ def test_replayed_web_search_becomes_call_and_result(self):
+ call = {"type": "server_tool_use", "name": "web_search", "input": {"query": "llama.cpp"}}
+ msgs = [
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "text", "text": "Searching."},
+ {**call, "id": "srvtoolu_fetch", "name": "web_fetch"},
+ {**call, "id": "srvtoolu_1"},
+ {
+ "type": "web_search_tool_result",
+ "tool_use_id": "srvtoolu_1",
+ "content": _WEB_SEARCH_HITS,
+ },
+ {"type": "text", "text": "It is b9999."},
+ {"type": "tool_use", "id": "tu_1", "name": "lookup", "input": {}},
+ ],
+ }
+ ]
+ search, result, answer = anthropic_messages_to_openai(msgs)
+
+ assert search["content"] == "Searching."
+ assert [tc["id"] for tc in search["tool_calls"]] == ["srvtoolu_1"]
+ assert result == {
+ "role": "tool",
+ "tool_call_id": "srvtoolu_1",
+ "content": (
+ "Title: Releases · ggml-org/llama.cpp\n"
+ "URL: https://github.com/ggml-org/llama.cpp/releases"
+ "\n\n---\n\n"
+ "Title: llama.cpp - Wikipedia\n"
+ "URL: https://en.wikipedia.org/wiki/Llama.cpp"
+ ),
+ }
+ assert answer["content"] == "It is b9999."
+ assert [tc["id"] for tc in answer["tool_calls"]] == ["tu_1"]
+
+ @pytest.mark.parametrize(
+ "content, text",
+ [([], "No results found."), (_WEB_SEARCH_ERROR, "Search failed: unavailable")],
+ )
+ def test_replayed_web_search_without_hits_ends_on_its_result(self, content, text):
+ # No ``input``: an unvalidated replayed block must not fail the request.
+ search_only = [
+ {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search"},
+ {"type": "web_search_tool_result", "tool_use_id": "srvtoolu_1", "content": content},
+ ]
+ call, result = anthropic_messages_to_openai([{"role": "assistant", "content": search_only}])
+
+ assert call["tool_calls"][0]["function"]["arguments"] == "{}"
+ assert result == {"role": "tool", "tool_call_id": "srvtoolu_1", "content": text}
+
+ def test_empty_assistant_turn_is_kept(self):
+ assert anthropic_messages_to_openai([{"role": "assistant", "content": []}]) == [
+ {"role": "assistant"}
+ ]
+
def test_tool_result_maps_to_tool_role(self):
msgs = [_tool_result_turn(tool_use_id = "tu_1", content = "Result text")]
result = anthropic_messages_to_openai(msgs)
@@ -1681,6 +1783,74 @@ class TestAnthropicStreamEmitter:
parsed = json.loads(events[1].split("data: ")[1])
assert parsed["delta"]["text"] == "After tool"
+ def _web_search_stream(
+ self,
+ result,
+ arguments = None,
+ ):
+ e = AnthropicStreamEmitter()
+ events = e.start("msg_1", "m")
+ events += e.feed(
+ _tool_event(
+ tool_name = "web_search",
+ arguments = arguments or {"query": "llama.cpp latest release"},
+ )
+ )
+ events += e.feed(_tool_result_event(tool_name = "web_search", result = result))
+ events += e.feed({"type": "content", "text": "The latest release is b9999."})
+ events += e.finish("end_turn")
+ return events, [json.loads(ev.split("data: ")[1]) for ev in events]
+
+ def test_web_search_streams_as_server_tool_with_source_links(self):
+ events, payloads = self._web_search_stream(_WEB_SEARCH_RESULT)
+ starts = [p for p in payloads if p["type"] == "content_block_start"]
+ stops = [p["index"] for p in payloads if p["type"] == "content_block_stop"]
+ blocks = [p["content_block"] for p in starts]
+
+ assert [b["type"] for b in blocks] == ["server_tool_use", "web_search_tool_result", "text"]
+ assert blocks[0]["id"].startswith("srvtoolu_")
+ assert blocks[0]["name"] == "web_search"
+ assert blocks[1] == {
+ "type": "web_search_tool_result",
+ "tool_use_id": blocks[0]["id"],
+ "content": _WEB_SEARCH_HITS,
+ }
+ assert stops == [p["index"] for p in starts] == [0, 1, 2]
+ assert {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {
+ "type": "input_json_delta",
+ "partial_json": json.dumps({"query": "llama.cpp latest release"}),
+ },
+ } in payloads
+ assert not any(ev.startswith("event: tool_result") for ev in events)
+ assert _emitter_client_text(events) == "The latest release is b9999."
+
+ def test_consecutive_web_searches_reusing_a_call_id_stay_separate(self):
+ e = AnthropicStreamEmitter()
+ events = e.start("msg_1", "m")
+ for i, url in enumerate(["https://e.com/0", "https://e.com/1"]):
+ events += e.feed(_tool_event(tool_name = "web_search", arguments = {"url": url}))
+ events += e.feed(_tool_result_event(tool_name = "web_search", result = f"page {i}"))
+ payloads = [json.loads(ev.split("data: ")[1]) for ev in events]
+ first, first_result, second, second_result = [
+ p["content_block"] for p in payloads if p["type"] == "content_block_start"
+ ]
+
+ assert first["id"] != second["id"]
+ assert first_result["tool_use_id"] == first["id"]
+ assert second_result["tool_use_id"] == second["id"]
+ assert second_result["content"][0]["url"] == "https://e.com/1"
+
+ @pytest.mark.parametrize("arguments, result, content", _WEB_SEARCH_OUTCOMES)
+ def test_web_search_result_content_by_outcome(self, arguments, result, content):
+ _, payloads = self._web_search_stream(result, arguments)
+ blocks = [p["content_block"] for p in payloads if p["type"] == "content_block_start"]
+
+ assert [b["type"] for b in blocks] == ["server_tool_use", "web_search_tool_result", "text"]
+ assert blocks[1]["content"] == content
+
# =====================================================================
# Non-streaming tool response tests
@@ -1861,6 +2031,76 @@ class TestAnthropicToolNonStreaming:
assert tool_blocks[0]["name"] == "render_html"
assert tool_blocks[0]["input"] == {"code": "<!doctype html><html></html>"}
+ def test_web_search_returns_server_tool_blocks_with_source_links(self):
+ def _run_gen():
+ yield _tool_event(tool_name = "web_search", arguments = {"query": "llama.cpp release"})
+ yield _tool_result_event(tool_name = "web_search", result = _WEB_SEARCH_RESULT)
+ yield {"type": "content", "text": "The latest release is b9999."}
+
+ response = asyncio.run(
+ _anthropic_tool_non_streaming(_connected_request(), _run_gen, "msg_1", "m")
+ )
+ body = json.loads(response.body)
+ call, result, text = body["content"]
+
+ assert call["type"] == "server_tool_use"
+ assert call["id"].startswith("srvtoolu_")
+ assert call["input"] == {"query": "llama.cpp release"}
+ assert result == {
+ "type": "web_search_tool_result",
+ "tool_use_id": call["id"],
+ "content": _WEB_SEARCH_HITS,
+ }
+ assert text == {"type": "text", "text": "The latest release is b9999."}
+ assert body["stop_reason"] == "end_turn"
+
+ def test_consecutive_web_searches_reusing_a_call_id_stay_separate(self):
+ # Text-parsed calls restart at call_0 on every tool-loop iteration.
+ def _run_gen():
+ for i, query in enumerate(["first", "second"]):
+ yield _tool_event(tool_name = "web_search", arguments = {"query": query})
+ yield _tool_result_event(
+ tool_name = "web_search", result = f"Title: T{i}\nURL: https://e.com/{i}"
+ )
+
+ response = asyncio.run(
+ _anthropic_tool_non_streaming(_connected_request(), _run_gen, "msg_1", "m")
+ )
+ first, first_result, second, second_result = json.loads(response.body)["content"]
+
+ assert [first["input"], second["input"]] == [{"query": "first"}, {"query": "second"}]
+ assert first["id"] != second["id"]
+ assert first_result["tool_use_id"] == first["id"]
+ assert second_result["tool_use_id"] == second["id"]
+ assert second_result["content"][0]["url"] == "https://e.com/1"
+
+ def test_consecutive_tool_calls_reusing_a_call_id_keep_their_own_input(self):
+ def _run_gen():
+ for code in ["print(1)", "print(2)"]:
+ yield _tool_event(arguments = {"code": code})
+ yield _tool_result_event()
+
+ response = asyncio.run(
+ _anthropic_tool_non_streaming(_connected_request(), _run_gen, "msg_1", "m")
+ )
+ blocks = json.loads(response.body)["content"]
+
+ assert [b["input"] for b in blocks] == [{"code": "print(1)"}, {"code": "print(2)"}]
+
+ @pytest.mark.parametrize("arguments, result, content", _WEB_SEARCH_OUTCOMES)
+ def test_web_search_result_content_by_outcome(self, arguments, result, content):
+ def _run_gen():
+ yield _tool_event(tool_name = "web_search", arguments = arguments)
+ yield _tool_result_event(tool_name = "web_search", result = result)
+
+ response = asyncio.run(
+ _anthropic_tool_non_streaming(_connected_request(), _run_gen, "msg_1", "m")
+ )
+ call, search_result = json.loads(response.body)["content"]
+
+ assert search_result["tool_use_id"] == call["id"]
+ assert search_result["content"] == content
+
def test_display_strip_gates_on_declared_tools(self):
# A final answer containing NAME[ARGS]{json} is gated on the declared tools: undeclared
# ``foo`` markup is prose and survives, the declared web_search rehearsal strips.