Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(llm): map web_search to native Responses tools for server-side search

宁凯d9962666a803
diff --git a/deeptutor/core/agentic/messages.py b/deeptutor/core/agentic/messages.py
index 853f15804..9284801e1 100644
--- a/deeptutor/core/agentic/messages.py
+++ b/deeptutor/core/agentic/messages.py
@@ -10,20 +10,27 @@ def assistant_message_with_tool_calls(
tool_calls: list[dict[str, Any]],
) -> dict[str, Any]:
"""Build the assistant message that precedes tool result messages."""
+ serialized: list[dict[str, Any]] = []
+ for tool_call in tool_calls:
+ entry: dict[str, Any] = {
+ "id": tool_call["id"],
+ "type": "function",
+ "function": {
+ "name": tool_call["name"],
+ "arguments": tool_call.get("arguments") or "{}",
+ },
+ }
+ # Keep provider markers (e.g. the server_executed flag on a native
+ # web_search call) so the Responses converter can replay the call as
+ # its native output-item type instead of a client-side function call.
+ fields = tool_call.get("provider_specific_fields")
+ if isinstance(fields, dict) and fields:
+ entry["provider_specific_fields"] = dict(fields)
+ serialized.append(entry)
return {
"role": "assistant",
"content": content or None,
- "tool_calls": [
- {
- "id": tool_call["id"],
- "type": "function",
- "function": {
- "name": tool_call["name"],
- "arguments": tool_call.get("arguments") or "{}",
- },
- }
- for tool_call in tool_calls
- ],
+ "tool_calls": serialized,
}
diff --git a/deeptutor/core/agentic/tool_dispatch.py b/deeptutor/core/agentic/tool_dispatch.py
index 2405b6fc3..86fdd0eec 100644
--- a/deeptutor/core/agentic/tool_dispatch.py
+++ b/deeptutor/core/agentic/tool_dispatch.py
@@ -120,6 +120,13 @@ async def dispatch_tool_calls(
tool_calls = tool_calls[:MAX_PARALLEL_TOOL_CALLS]
prepared, raw_args = _prepare_tool_args(tool_calls, context, kwarg_augmenter)
+ # Calls the provider already executed server-side (native Responses
+ # web_search). They must not run the local tool again: the search happened
+ # mid-generation and the answer's citations point at its results. Each one
+ # short-circuits to a stub result that carries the server's citations as
+ # sources, keeping the tool_call/role=tool pairing intact for the next
+ # model round.
+ server_executed = _server_executed_by_id(tool_calls)
# Collapse duplicates within this parallel batch. Models occasionally
# emit repeated tool_calls in one assistant message. For most tools,
# "duplicate" means same tool + same JSON-normalised args. For
@@ -172,6 +179,11 @@ async def dispatch_tool_calls(
tool_name=prepared[tool_index][1],
)
_tcid, tool_name, exec_args = prepared[tool_index]
+ if _tcid in server_executed:
+ return _server_executed_stub_result(
+ tool_name=tool_name,
+ fields=server_executed[_tcid],
+ )
rejection = await _reject_if_args_missing(
registry=registry,
tool_name=tool_name,
@@ -341,6 +353,68 @@ def _duplicate_stub_result(
}
+def _server_executed_by_id(
+ tool_calls: list[dict[str, Any]],
+) -> dict[str, dict[str, Any]]:
+ """Map call ids to provider fields for calls the server already executed.
+
+ Marks ride ``provider_specific_fields`` on the tool_call (see the
+ Responses parser's synthesized native web_search calls).
+ """
+ server_executed: dict[str, dict[str, Any]] = {}
+ for tc in tool_calls:
+ fields = tc.get("provider_specific_fields")
+ if not isinstance(fields, dict) or not fields.get("server_executed"):
+ continue
+ call_id = str(tc.get("id") or "").strip()
+ if call_id:
+ server_executed[call_id] = fields
+ return server_executed
+
+
+def _server_executed_stub_result(
+ *,
+ tool_name: str,
+ fields: dict[str, Any],
+) -> dict[str, Any]:
+ """Synthetic result for a provider-side executed call (native web_search).
+
+ The search ran on the server mid-generation; this stub exists so the
+ OpenAI tool-call/tool-message pairing stays intact and the citations
+ reach the frontend as sources. The text tells the model what happened so
+ it does not re-issue the search.
+ """
+ raw_citations = fields.get("citations") or []
+ citations = [
+ {"url": str(c.get("url") or ""), "title": str(c.get("title") or "")}
+ for c in raw_citations
+ if isinstance(c, dict) and str(c.get("url") or "").strip()
+ ]
+ sources = [{"type": "web", **citation} for citation in citations]
+ query = str(fields.get("query") or "")
+ result_text = json.dumps(
+ {
+ "server_executed": True,
+ "query": query,
+ "citations": citations,
+ "note": (
+ "This web search was performed server-side by the provider "
+ "during generation; cite these sources directly. Do not call "
+ "web_search again for the same query."
+ ),
+ },
+ ensure_ascii=False,
+ )
+ return {
+ "result_text": result_text,
+ "success": True,
+ "sources": sources,
+ "metadata": {"server_executed": True, "query": query, "citations": citations},
+ "terminate_turn": False,
+ "pause_for_user": None,
+ }
+
+
async def _reject_if_args_missing(
*,
registry: ToolLookup,
diff --git a/deeptutor/services/llm/provider_core/openai_compat_provider.py b/deeptutor/services/llm/provider_core/openai_compat_provider.py
index d1bf6b623..48899b154 100644
--- a/deeptutor/services/llm/provider_core/openai_compat_provider.py
+++ b/deeptutor/services/llm/provider_core/openai_compat_provider.py
@@ -475,7 +475,10 @@ class OpenAICompatProvider(LLMProvider):
body["reasoning"] = {"effort": reasoning_effort}
body["include"] = ["reasoning.encrypted_content"]
if tools:
- body["tools"] = convert_tools(tools)
+ body["tools"] = convert_tools(
+ tools,
+ native_web_search=bool(self._spec and self._spec.native_web_search),
+ )
body["tool_choice"] = tool_choice or "auto"
return body
diff --git a/deeptutor/services/llm/provider_core/openai_responses/converters.py b/deeptutor/services/llm/provider_core/openai_responses/converters.py
index 2e2f0fb31..6ace02e50 100644
--- a/deeptutor/services/llm/provider_core/openai_responses/converters.py
+++ b/deeptutor/services/llm/provider_core/openai_responses/converters.py
@@ -40,6 +40,23 @@ def convert_messages(messages: list[dict[str, Any]]) -> tuple[str, list[dict[str
for tool_call in msg.get("tool_calls", []) or []:
fn = tool_call.get("function") or {}
call_id, item_id = split_tool_call_id(tool_call.get("id"))
+ if _is_server_executed_tool_call(tool_call):
+ # Replay a server-executed native search as its own output
+ # item type. The matching role=tool message is skipped
+ # below: a server-executed call has no function output.
+ input_items.append(
+ {
+ "type": "web_search_call",
+ "id": item_id or call_id or f"ws_{idx}",
+ "status": "completed",
+ **(
+ {"action": {"type": "search", "query": fn.get("arguments")}}
+ if isinstance(fn.get("arguments"), str) and fn.get("arguments")
+ else {}
+ ),
+ }
+ )
+ continue
input_items.append(
{
"type": "function_call",
@@ -56,6 +73,16 @@ def convert_messages(messages: list[dict[str, Any]]) -> tuple[str, list[dict[str
output_text = (
content if isinstance(content, str) else json.dumps(content, ensure_ascii=False)
)
+ if any(
+ _is_server_executed_tool_call(tc) and split_tool_call_id(tc.get("id"))[0] == call_id
+ for assistant_msg in messages
+ if assistant_msg.get("role") == "assistant"
+ for tc in assistant_msg.get("tool_calls", []) or []
+ ):
+ # The function_call_output for a server-executed call does not
+ # exist on the wire — the result lives in the web_search_call
+ # item emitted above.
+ continue
input_items.append(
{"type": "function_call_output", "call_id": call_id, "output": output_text}
)
@@ -83,14 +110,29 @@ def convert_user_message(content: Any) -> dict[str, Any]:
return {"role": "user", "content": [{"type": "input_text", "text": ""}]}
-def convert_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
- """Convert OpenAI function calling schemas to Responses API tools."""
+def convert_tools(
+ tools: list[dict[str, Any]],
+ *,
+ native_web_search: bool = False,
+) -> list[dict[str, Any]]:
+ """Convert OpenAI function calling schemas to Responses API tools.
+
+ With ``native_web_search=True`` (providers whose Responses API performs
+ web searches server-side, e.g. DeepSeek), DeepTutor's ``web_search``
+ function tool is declared as the provider's native ``{"type":
+ "web_search"}`` tool instead of a function schema: the server runs the
+ search mid-generation and the response carries ``web_search_call`` items
+ with ``url_citation`` annotations rather than a function call.
+ """
converted: list[dict[str, Any]] = []
for tool in tools:
fn = (tool.get("function") or {}) if tool.get("type") == "function" else tool
name = fn.get("name")
if not name:
continue
+ if native_web_search and name == "web_search":
+ converted.append({"type": "web_search"})
+ continue
params = fn.get("parameters") or {}
converted.append(
{
@@ -103,6 +145,19 @@ def convert_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
return converted
+def _is_server_executed_tool_call(tool_call: dict[str, Any]) -> bool:
+ """True for a tool_call the provider already executed server-side.
+
+ Server-executed calls (native ``web_search``) must round-trip as their
+ native output-item type, not as a ``function_call``: replaying them as
+ function calls would claim the client ran a search the server actually
+ ran. The marker rides ``provider_specific_fields`` on the persisted
+ assistant tool_call.
+ """
+ fields = tool_call.get("provider_specific_fields")
+ return bool(isinstance(fields, dict) and fields.get("server_executed"))
+
+
def split_tool_call_id(tool_call_id: Any) -> tuple[str, str | None]:
"""Split a compound call_id|item_id tool id."""
if isinstance(tool_call_id, str) and tool_call_id:
diff --git a/deeptutor/services/llm/provider_core/openai_responses/parsing.py b/deeptutor/services/llm/provider_core/openai_responses/parsing.py
index 4a84f385d..ad7bb0ea7 100644
--- a/deeptutor/services/llm/provider_core/openai_responses/parsing.py
+++ b/deeptutor/services/llm/provider_core/openai_responses/parsing.py
@@ -21,6 +21,85 @@ FINISH_REASON_MAP = {
"cancelled": "error",
}
+# Output-item types a provider's server-side web search emits. OpenAI and
+# DeepSeek name the item "web_search_call"; "web_search" is accepted
+# defensively for providers that shorten it.
+_WEB_SEARCH_ITEM_TYPES = {"web_search_call", "web_search"}
+
+
+def _dump_model(value: Any) -> Any:
+ """Normalize an SDK object / dict into a plain dict."""
+ if isinstance(value, dict):
+ return value
+ dump = getattr(value, "model_dump", None)
+ return dump() if callable(dump) else vars(value)
+
+
+def _web_search_query_from_item(item: dict[str, Any]) -> str:
+ """Best-effort query extraction from a web_search_call output item."""
+ action = item.get("action")
+ if isinstance(action, dict):
+ query = action.get("query")
+ if isinstance(query, str) and query.strip():
+ return query.strip()
+ query = item.get("query")
+ if isinstance(query, str) and query.strip():
+ return query.strip()
+ return ""
+
+
+def _citation_from_annotation(annotation: Any) -> dict[str, str] | None:
+ """Extract {url, title} from a url_citation annotation, else None."""
+ if not isinstance(annotation, dict):
+ annotation = _dump_model(annotation)
+ if not isinstance(annotation, dict):
+ return None
+ if annotation.get("type") not in {None, "url_citation", "url"}:
+ return None
+ url = str(annotation.get("url") or "").strip()
+ if not url:
+ return None
+ return {"url": url, "title": str(annotation.get("title") or "")}
+
+
+def _citations_from_content_blocks(blocks: Any) -> list[dict[str, str]]:
+ """Collect url_citation annotations attached to message content blocks."""
+ citations: list[dict[str, str]] = []
+ for block in blocks or []:
+ block = _dump_model(block)
+ if not isinstance(block, dict):
+ continue
+ for annotation in block.get("annotations") or []:
+ citation = _citation_from_annotation(annotation)
+ if citation:
+ citations.append(citation)
+ return citations
+
+
+def _build_server_web_search_call(
+ *,
+ item_id: str,
+ query: str,
+ citations: list[dict[str, str]],
+) -> ToolCallRequest:
+ """Synthesize the tool_call a server-side web search reports as.
+
+ The search already ran on the provider: the call is marked
+ ``server_executed`` so the dispatcher returns a stub result (carrying the
+ citations as sources) instead of running the local ``web_search`` tool —
+ replaying the search client-side would double the work and could disagree
+ with the citations the answer text actually used.
+ """
+ fields: dict[str, Any] = {"server_executed": True, "citations": citations}
+ if query:
+ fields["query"] = query
+ return ToolCallRequest(
+ id=item_id,
+ name="web_search",
+ arguments={"query": query} if query else {},
+ provider_specific_fields=fields,
+ )
+
def map_finish_reason(status: str | None) -> str:
return FINISH_REASON_MAP.get(status or "completed", "stop")
@@ -189,6 +268,8 @@ async def consume_sse(
tool_calls: list[ToolCallRequest] = []
tool_call_buffers = _ToolCallBuffers()
finish_reason = "stop"
+ web_search_citations: list[dict[str, str]] = []
+ seen_web_search_items: set[str] = set()
async for event in iter_sse(response):
event_type = event.get("type")
@@ -209,6 +290,10 @@ async def consume_sse(
content += delta_text
if on_content_delta and delta_text:
await on_content_delta(delta_text)
+ elif event_type == "response.output_text.annotation.added":
+ citation = _citation_from_annotation(event.get("annotation"))
+ if citation:
+ web_search_citations.append(citation)
elif event_type == "response.function_call_arguments.delta":
tool_call_buffers.append(
event.get("delta") or "",
@@ -223,6 +308,19 @@ async def consume_sse(
)
elif event_type == "response.output_item.done":
item = event.get("item") or {}
+ if item.get("type") in _WEB_SEARCH_ITEM_TYPES:
+ item_id = str(item.get("id") or "")
+ if item_id and item_id not in seen_web_search_items:
+ seen_web_search_items.add(item_id)
+ tool_calls.append(
+ _build_server_web_search_call(
+ item_id=item_id,
+ query=_web_search_query_from_item(item),
+ citations=web_search_citations,
+ )
+ )
+ web_search_citations = []
+ continue
if item.get("type") == "function_call":
call_id = item.get("call_id")
if not call_id:
@@ -246,9 +344,42 @@ async def consume_sse(
elif event_type in {"error", "response.failed"}:
raise RuntimeError(f"Response failed: {_response_error_detail(event)[:500]}")
+ # Annotations usually stream with the answer text, i.e. AFTER the
+ # web_search_call item completes. Whatever is still unattached here
+ # belongs to the most recent search — merge it in rather than drop it.
+ if web_search_citations:
+ _merge_or_append_citations(
+ tool_calls,
+ citations=web_search_citations,
+ fallback_id=f"ws_tail_{len(tool_calls)}",
+ )
+
return content, tool_calls, finish_reason
+def _merge_or_append_citations(
+ tool_calls: list[ToolCallRequest],
+ *,
+ citations: list[dict[str, str]],
+ fallback_id: str,
+) -> None:
+ """Attach citations to the latest server-executed call, else synthesize one."""
+ existing = next(
+ (
+ tc
+ for tc in reversed(tool_calls)
+ if tc.provider_specific_fields and tc.provider_specific_fields.get("server_executed")
+ ),
+ None,
+ )
+ if existing is not None:
+ existing.provider_specific_fields["citations"].extend(citations)
+ else:
+ tool_calls.append(
+ _build_server_web_search_call(item_id=fallback_id, query="", citations=citations)
+ )
+
+
def parse_response_output(response: Any) -> LLMResponse:
"""Parse an SDK Response object into LLMResponse."""
if not isinstance(response, dict):
@@ -261,25 +392,45 @@ def parse_response_output(response: Any) -> LLMResponse:
reasoning_content: str | None = None
for item in output:
+ item = _dump_model(item)
if not isinstance(item, dict):
- dump = getattr(item, "model_dump", None)
- item = dump() if callable(dump) else vars(item)
+ continue
item_type = item.get("type")
if item_type == "message":
for block in item.get("content") or []:
+ block = _dump_model(block)
if not isinstance(block, dict):
- dump = getattr(block, "model_dump", None)
- block = dump() if callable(dump) else vars(block)
+ continue
if block.get("type") == "output_text":
content_parts.append(block.get("text") or "")
+ block_citations = _citations_from_content_blocks([block])
+ if block_citations:
+ # Annotations cite searches the server ran. Merge into
+ # the latest synthesized call when one exists (several
+ # message items can annotate one search), else
+ # synthesize one.
+ _merge_or_append_citations(
+ tool_calls,
+ citations=block_citations,
+ fallback_id=str(item.get("id") or f"ws_annot_{len(tool_calls)}"),
+ )
elif item_type == "reasoning":
for summary in item.get("summary") or []:
+ summary = _dump_model(summary)
if not isinstance(summary, dict):
- dump = getattr(summary, "model_dump", None)
- summary = dump() if callable(dump) else vars(summary)
+ continue
if summary.get("type") == "summary_text" and summary.get("text"):
reasoning_content = (reasoning_content or "") + summary["text"]
+ elif item_type in _WEB_SEARCH_ITEM_TYPES:
+ item_id = str(item.get("id") or f"ws_{len(tool_calls)}")
+ tool_calls.append(
+ _build_server_web_search_call(
+ item_id=item_id,
+ query=_web_search_query_from_item(item),
+ citations=_citations_from_content_blocks(item.get("results")),
+ )
+ )
elif item_type == "function_call":
call_id = item.get("call_id") or ""
item_id = item.get("id") or _ToolCallBuffers.PLACEHOLDER_ITEM_ID
@@ -318,6 +469,8 @@ async def consume_sdk_stream(
finish_reason = "stop"
usage: dict[str, int] = {}
reasoning_content: str | None = None
+ web_search_citations: list[dict[str, str]] = []
+ seen_web_search_items: set[str] = set()
async for event in stream:
event_type = getattr(event, "type", None)
@@ -338,6 +491,10 @@ async def consume_sdk_stream(
content += delta_text
if on_content_delta and delta_text:
await on_content_delta(delta_text)
+ elif event_type == "response.output_text.annotation.added":
+ citation = _citation_from_annotation(getattr(event, "annotation", None))
+ if citation:
+ web_search_citations.append(citation)
elif event_type == "response.function_call_arguments.delta":
tool_call_buffers.append(
getattr(event, "delta", "") or "",
@@ -352,6 +509,20 @@ async def consume_sdk_stream(
)
elif event_type == "response.output_item.done":
item = getattr(event, "item", None)
+ item_dict = _dump_model(item) if item is not None else None
+ if isinstance(item_dict, dict) and item_dict.get("type") in _WEB_SEARCH_ITEM_TYPES:
+ item_id = str(item_dict.get("id") or "")
+ if item_id and item_id not in seen_web_search_items:
+ seen_web_search_items.add(item_id)
+ tool_calls.append(
+ _build_server_web_search_call(
+ item_id=item_id,
+ query=_web_search_query_from_item(item_dict),
+ citations=web_search_citations,
+ )
+ )
+ web_search_citations = []
+ continue
if item and getattr(item, "type", None) == "function_call":
call_id = getattr(item, "call_id", None)
if not call_id:
@@ -385,4 +556,13 @@ async def consume_sdk_stream(
elif event_type in {"error", "response.failed"}:
raise RuntimeError(f"Response failed: {_response_error_detail(event)[:500]}")
+ # Same tail-merge as the SSE path: annotations stream after the search
+ # item completes, so attach whatever is still unattached.
+ if web_search_citations:
+ _merge_or_append_citations(
+ tool_calls,
+ citations=web_search_citations,
+ fallback_id=f"ws_tail_{len(tool_calls)}",
+ )
+
return content, tool_calls, finish_reason, usage, reasoning_content
diff --git a/deeptutor/services/provider_registry.py b/deeptutor/services/provider_registry.py
index 70d2f14c1..812a775f3 100644
--- a/deeptutor/services/provider_registry.py
+++ b/deeptutor/services/provider_registry.py
@@ -52,6 +52,12 @@ class ProviderSpec:
# explicit reasoning_effort, the provider auto-injects "high" so the
# thinking_style flag (e.g. extra_body.thinking.type=enabled) is sent.
reasoning_model_patterns: tuple[str, ...] = ()
+ # True when this provider's Responses API performs `web_search` on the
+ # server: the tool is declared as {"type": "web_search"} rather than a
+ # function schema, the server runs the search mid-generation, and the
+ # response carries web_search_call items plus url_citation annotations
+ # instead of a function call for the client to execute.
+ native_web_search: bool = False
@property
def mode(self) -> str:
@@ -324,6 +330,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
default_api_base="https://api.deepseek.com",
thinking_style="thinking_type",
reasoning_model_patterns=("deepseek-v4-pro", "deepseek-reasoner"),
+ native_web_search=True,
),
ProviderSpec(
name="gemini",
diff --git a/tests/services/llm/test_native_web_search.py b/tests/services/llm/test_native_web_search.py
new file mode 100644
index 000000000..d740955b0
--- /dev/null
+++ b/tests/services/llm/test_native_web_search.py
@@ -0,0 +1,325 @@
+"""Tests for native server-side web_search support (#846).
+
+Covers the three seams a native web search crosses:
+
+* ``convert_tools`` — DeepTutor's ``web_search`` function tool declared as the
+ provider's native ``{"type": "web_search"}`` tool.
+* history replay — a server-executed call round-trips as a ``web_search_call``
+ output item (not a function_call), with no function_call_output.
+* parsing — ``web_search_call`` output items and ``url_citation`` annotations
+ synthesize a marked ``web_search`` ToolCallRequest instead of a dispatchable
+ local function call.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from deeptutor.core.agentic.tool_dispatch import dispatch_tool_calls
+from deeptutor.core.context import UnifiedContext
+from deeptutor.core.stream_bus import StreamBus
+from deeptutor.services.llm.provider_core.openai_responses import (
+ consume_sse,
+ convert_messages,
+ convert_tools,
+)
+from deeptutor.services.llm.provider_core.openai_responses.parsing import (
+ parse_response_output,
+)
+
+
+class _SSEFixture:
+ def __init__(self, events: list[dict]) -> None:
+ self._events = events
+
+ async def aiter_lines(self):
+ for event in self._events:
+ yield f"data: {json.dumps(event)}"
+ yield ""
+
+
+class _ExecutedWebSearchTool:
+ """A local web_search stand-in that fails the test if executed."""
+
+ def get_definition(self):
+ class _Def:
+ name = "web_search"
+
+ return _Def()
+
+ async def execute(self, **kwargs):
+ raise AssertionError("server-executed web_search must not run locally")
+
+
+class _Registry:
+ def __init__(self, tool):
+ self._tool = tool
+
+ def get(self, name):
+ if name == "web_search":
+ return self._tool
+ raise KeyError(name)
+
+ async def execute(self, name, **kwargs):
+ tool = self.get(name)
+ return await tool.execute(**kwargs)
+
+
+class _Stream:
+ def __init__(self):
+ self.events: list[dict] = []
+
+ def __getattr__(self, name):
+ async def _emit(*args, **kwargs):
+ self.events.append({"event": name, **kwargs})
+
+ return _emit
+
+
+# ---------------------------------------------------------------------------
+# convert_tools: native mapping
+# ---------------------------------------------------------------------------
+
+
+class TestConvertToolsNativeWebSearch:
+ def test_web_search_maps_to_native_tool_when_enabled(self) -> None:
+ tools = [
+ {"type": "function", "function": {"name": "web_search", "parameters": {}}},
+ {"type": "function", "function": {"name": "rag", "parameters": {}}},
+ ]
+ converted = convert_tools(tools, native_web_search=True)
+ assert {"type": "web_search"} in converted
+ # Other tools keep their function schema.
+ assert {"type": "function", "name": "rag", "description": "", "parameters": {}} in converted
+ assert len(converted) == 2
+
+ def test_web_search_stays_a_function_by_default(self) -> None:
+ tools = [{"type": "function", "function": {"name": "web_search", "parameters": {}}}]
+ converted = convert_tools(tools)
+ assert converted == [
+ {"type": "function", "name": "web_search", "description": "", "parameters": {}}
+ ]
+
+
+# ---------------------------------------------------------------------------
+# convert_messages: server-executed history replay
+# ---------------------------------------------------------------------------
+
+
+class TestConvertMessagesServerExecutedReplay:
+ def test_server_executed_call_replays_as_web_search_item(self) -> None:
+ marker = {"server_executed": True, "citations": [{"url": "https://x", "title": "X"}]}
+ messages = [
+ {"role": "user", "content": "hi"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "ws_1",
+ "type": "function",
+ "function": {"name": "web_search", "arguments": "fft"},
+ "provider_specific_fields": marker,
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "ws_1", "name": "web_search", "content": "{}"},
+ ]
+ _, items = convert_messages(messages)
+ types = [item.get("type") for item in items]
+ assert "web_search_call" in types
+ assert "function_call" not in types
+ # The stub role=tool message must not produce a function_call_output.
+ assert "function_call_output" not in types
+ ws_item = next(item for item in items if item.get("type") == "web_search_call")
+ assert ws_item["id"] == "ws_1"
+ assert ws_item["status"] == "completed"
+
+ def test_regular_calls_keep_function_pairing(self) -> None:
+ messages = [
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {"name": "rag", "arguments": "{}"},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "name": "rag", "content": "ok"},
+ ]
+ _, items = convert_messages(messages)
+ assert [item["type"] for item in items] == ["function_call", "function_call_output"]
+
+
+# ---------------------------------------------------------------------------
+# parsing: web_search_call items + url_citation annotations
+# ---------------------------------------------------------------------------
+
+
+class TestParseServerExecutedWebSearch:
+ def test_parse_response_output_synthesizes_marked_call(self) -> None:
+ response = {
+ "output": [
+ {
+ "type": "web_search_call",
+ "id": "ws_abc",
+ "status": "completed",
+ "action": {"type": "search", "query": "cooley tukey fft"},
+ },
+ {
+ "type": "message",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "output_text",
+ "text": "FFT is O(N log N).",
+ "annotations": [
+ {
+ "type": "url_citation",
+ "url": "https://example.com/paper",
+ "title": "Cooley-Tukey",
+ }
+ ],
+ }
+ ],
+ },
+ ],
+ "status": "completed",
+ "usage": {"input_tokens": 10, "output_tokens": 5},
+ }
+ result = parse_response_output(response)
+ assert result.content == "FFT is O(N log N)."
+ assert len(result.tool_calls) == 1
+ call = result.tool_calls[0]
+ assert call.name == "web_search"
+ assert call.arguments == {"query": "cooley tukey fft"}
+ fields = call.provider_specific_fields or {}
+ assert fields["server_executed"] is True
+ assert fields["citations"] == [
+ {"url": "https://example.com/paper", "title": "Cooley-Tukey"}
+ ]
+
+ @pytest.mark.asyncio
+ async def test_sse_stream_collects_item_and_annotations(self) -> None:
+ events = [
+ {
+ "type": "response.output_item.added",
+ "item": {"type": "web_search_call", "id": "ws_1", "status": "in_progress"},
+ },
+ {
+ "type": "response.output_text.annotation.added",
+ "annotation": {"type": "url_citation", "url": "https://a", "title": "A"},
+ },
+ {
+ "type": "response.output_text.annotation.added",
+ "annotation": {"type": "url_citation", "url": "https://b", "title": "B"},
+ },
+ {"type": "response.output_text.delta", "delta": "hello"},
+ {
+ "type": "response.output_item.done",
+ "item": {
+ "type": "web_search_call",
+ "id": "ws_1",
+ "status": "completed",
+ "action": {"query": "test"},
+ },
+ },
+ ]
+ content, tool_calls, _ = await consume_sse(_SSEFixture(events))
+ assert content == "hello"
+ assert len(tool_calls) == 1
+ fields = tool_calls[0].provider_specific_fields or {}
+ assert fields["server_executed"] is True
+ assert fields["citations"] == [
+ {"url": "https://a", "title": "A"},
+ {"url": "https://b", "title": "B"},
+ ]
+
+ @pytest.mark.asyncio
+ async def test_sse_deduplicates_repeated_done_items(self) -> None:
+ events = [
+ {
+ "type": "response.output_item.done",
+ "item": {"type": "web_search_call", "id": "ws_1", "status": "completed"},
+ },
+ {
+ "type": "response.output_item.done",
+ "item": {"type": "web_search_call", "id": "ws_1", "status": "completed"},
+ },
+ ]
+ _, tool_calls, _ = await consume_sse(_SSEFixture(events))
+ assert len(tool_calls) == 1
+
+ @pytest.mark.asyncio
+ async def test_sse_annotations_after_item_done_are_kept(self) -> None:
+ # Realistic ordering: the search item completes first, then the answer
+ # text streams with its citations. The tail annotations must merge
+ # into the search's call, not be dropped.
+ events = [
+ {
+ "type": "response.output_item.done",
+ "item": {
+ "type": "web_search_call",
+ "id": "ws_1",
+ "status": "completed",
+ "action": {"query": "fft"},
+ },
+ },
+ {"type": "response.output_text.delta", "delta": "FFT is O(N log N)."},
+ {
+ "type": "response.output_text.annotation.added",
+ "annotation": {"type": "url_citation", "url": "https://a", "title": "A"},
+ },
+ ]
+ _, tool_calls, _ = await consume_sse(_SSEFixture(events))
+ assert len(tool_calls) == 1
+ call = tool_calls[0]
+ assert call.arguments == {"query": "fft"}
+ assert call.provider_specific_fields["citations"] == [{"url": "https://a", "title": "A"}]
+
+
+# ---------------------------------------------------------------------------
+# dispatch: server-executed calls never run the local tool
+# ---------------------------------------------------------------------------
+
+
+async def test_dispatch_short_circuits_server_executed_call() -> None:
+ tool_calls = [
+ {
+ "id": "ws_1",
+ "name": "web_search",
+ "arguments": json.dumps({"query": "fft"}),
+ "provider_specific_fields": {
+ "server_executed": True,
+ "query": "fft",
+ "citations": [{"url": "https://example.com", "title": "Example"}],
+ },
+ }
+ ]
+ stream = _Stream()
+ context = UnifiedContext(user_message="q", session_id="s", attachments=[])
+ outcome = await dispatch_tool_calls(
+ tool_calls=tool_calls,
+ context=context,
+ stream=stream,
+ source="chat",
+ stage="responding",
+ iteration_index=0,
+ registry=_Registry(_ExecutedWebSearchTool()),
+ )
+
+ # The local tool never ran (it raises AssertionError on execute).
+ assert len(outcome.tool_messages) == 1
+ message = outcome.tool_messages[0]
+ assert message["role"] == "tool"
+ assert message["tool_call_id"] == "ws_1"
+ payload = json.loads(message["content"])
+ assert payload["server_executed"] is True
+ assert payload["citations"] == [{"url": "https://example.com", "title": "Example"}]
+ assert outcome.sources == [{"type": "web", "url": "https://example.com", "title": "Example"}]