Skip to content

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

fix(llm): make native web search terminal and model-scoped

Bingxi Zhao (Frank)159edefaac48
diff --git a/deeptutor/core/agentic/client.py b/deeptutor/core/agentic/client.py
index 1c7870254..a88bc5d8b 100644
--- a/deeptutor/core/agentic/client.py
+++ b/deeptutor/core/agentic/client.py
@@ -318,6 +318,16 @@ def _build_native_provider_adapter(config: LLMClientConfig, spec: Any) -> Any |
# Reuse the services provider: it already converts messages, tools,
# streaming events and token limits for the Responses API.
return _build_direct_openai_adapter(config, spec)
+ native_web_search_models = {
+ str(name).strip().lower()
+ for name in getattr(spec, "native_web_search_models", ())
+ if str(name).strip()
+ }
+ if model.split("/")[-1] in native_web_search_models and not config.api_version:
+ # DeepSeek's native web search is a Responses-only capability. Route
+ # the supported model through the provider adapter; sibling models
+ # stay on the ordinary Chat Completions client.
+ return _build_direct_openai_adapter(config, spec)
builder = _NATIVE_ADAPTER_BUILDERS.get(spec.backend)
return builder(config, spec) if builder else None
@@ -379,6 +389,7 @@ class _ProviderOpenAIAdapter:
_openai_tool_call(tool_call, index=index)
for index, tool_call in enumerate(response.tool_calls or [])
],
+ provider_specific_fields=response.provider_specific_fields,
),
finish_reason=(
"tool_calls" if response.tool_calls else response.finish_reason or "stop"
@@ -467,6 +478,7 @@ class _ProviderOpenAIStream:
"tool_calls" if response.tool_calls else response.finish_reason or "stop"
),
usage=response.usage or None,
+ provider_specific_fields=response.provider_specific_fields,
)
)
except Exception as exc:
@@ -499,6 +511,7 @@ def _openai_stream_chunk(
index: int = 0,
finish_reason: str | None = None,
usage: dict[str, int] | None = None,
+ provider_specific_fields: dict[str, Any] | None = None,
) -> Any:
tool_calls = None
if tool_call is not None:
@@ -508,6 +521,7 @@ def _openai_stream_chunk(
SimpleNamespace(
delta=SimpleNamespace(content=content, tool_calls=tool_calls),
finish_reason=finish_reason,
+ provider_specific_fields=provider_specific_fields,
)
],
usage=usage,
diff --git a/deeptutor/core/agentic/messages.py b/deeptutor/core/agentic/messages.py
index 9284801e1..853f15804 100644
--- a/deeptutor/core/agentic/messages.py
+++ b/deeptutor/core/agentic/messages.py
@@ -10,27 +10,20 @@ 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": serialized,
+ "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
+ ],
}
diff --git a/deeptutor/core/agentic/tool_dispatch.py b/deeptutor/core/agentic/tool_dispatch.py
index 86fdd0eec..2405b6fc3 100644
--- a/deeptutor/core/agentic/tool_dispatch.py
+++ b/deeptutor/core/agentic/tool_dispatch.py
@@ -120,13 +120,6 @@ 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
@@ -179,11 +172,6 @@ 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,
@@ -353,68 +341,6 @@ 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/base.py b/deeptutor/services/llm/provider_core/base.py
index 656bf6278..4d7cac0c5 100644
--- a/deeptutor/services/llm/provider_core/base.py
+++ b/deeptutor/services/llm/provider_core/base.py
@@ -52,6 +52,7 @@ class LLMResponse:
usage: dict[str, int] = field(default_factory=dict)
reasoning_content: str | None = None
thinking_blocks: list[dict[str, Any]] | None = None
+ provider_specific_fields: dict[str, Any] = field(default_factory=dict)
@property
def has_tool_calls(self) -> bool:
diff --git a/deeptutor/services/llm/provider_core/openai_compat_provider.py b/deeptutor/services/llm/provider_core/openai_compat_provider.py
index 48899b154..a24c418ad 100644
--- a/deeptutor/services/llm/provider_core/openai_compat_provider.py
+++ b/deeptutor/services/llm/provider_core/openai_compat_provider.py
@@ -360,8 +360,11 @@ class OpenAICompatProvider(LLMProvider):
self,
model: str | None,
reasoning_effort: str | None,
+ tools: list[dict[str, Any]] | None = None,
) -> bool:
spec = self._spec
+ if self._uses_native_web_search(model, tools):
+ return self._responses_circuit_allows(model, reasoning_effort)
if spec and spec.name not in {"openai", "github_copilot"}:
return False
if spec is None or spec.name != "github_copilot":
@@ -376,6 +379,13 @@ class OpenAICompatProvider(LLMProvider):
if not wants_responses:
return False
+ return self._responses_circuit_allows(model, reasoning_effort)
+
+ def _responses_circuit_allows(
+ self,
+ model: str | None,
+ reasoning_effort: str | None,
+ ) -> bool:
circuit_key = _responses_circuit_key(model, self.default_model, reasoning_effort)
failures = self._responses_failures.get(circuit_key, 0)
if failures >= _RESPONSES_FAILURE_THRESHOLD:
@@ -384,6 +394,25 @@ class OpenAICompatProvider(LLMProvider):
return False
return True
+ def _uses_native_web_search(
+ self,
+ model: str | None,
+ tools: list[dict[str, Any]] | None,
+ ) -> bool:
+ patterns = {
+ str(name).strip().lower()
+ for name in getattr(self._spec, "native_web_search_models", ())
+ if str(name).strip()
+ }
+ model_name = (model or self.default_model or "").strip().lower().split("/")[-1]
+ if model_name not in patterns:
+ return False
+ return any(
+ ((tool.get("function") or {}).get("name") == "web_search")
+ for tool in tools or []
+ if isinstance(tool, dict) and tool.get("type") == "function"
+ )
+
def _record_responses_failure(self, model: str | None, reasoning_effort: str | None) -> None:
circuit_key = _responses_circuit_key(model, self.default_model, reasoning_effort)
failures = self._responses_failures.get(circuit_key, 0) + 1
@@ -477,7 +506,7 @@ class OpenAICompatProvider(LLMProvider):
if tools:
body["tools"] = convert_tools(
tools,
- native_web_search=bool(self._spec and self._spec.native_web_search),
+ native_web_search=self._uses_native_web_search(model, tools),
)
body["tool_choice"] = tool_choice or "auto"
return body
@@ -715,7 +744,7 @@ class OpenAICompatProvider(LLMProvider):
**extra_kwargs: Any,
) -> LLMResponse:
try:
- if self._should_use_responses_api(model, reasoning_effort):
+ if self._should_use_responses_api(model, reasoning_effort, tools):
try:
body = self._build_responses_body(
messages,
@@ -808,7 +837,7 @@ class OpenAICompatProvider(LLMProvider):
request_kwargs.update({k: v for k, v in extra_kwargs.items() if v is not None})
idle_timeout_s = 90
try:
- if self._should_use_responses_api(model, reasoning_effort):
+ if self._should_use_responses_api(model, reasoning_effort, tools):
try:
body = self._build_responses_body(
messages,
@@ -836,6 +865,18 @@ class OpenAICompatProvider(LLMProvider):
except StopAsyncIteration:
break
+ native_output_items: list[dict[str, Any]] = []
+ native_citations: list[dict[str, Any]] = []
+
+ def _collect_provider_event(
+ kind: str,
+ payload: dict[str, Any],
+ ) -> None:
+ if kind == "output_item":
+ native_output_items.append(payload)
+ elif kind == "citation":
+ native_citations.append(payload)
+
(
content,
tool_calls,
@@ -846,6 +887,7 @@ class OpenAICompatProvider(LLMProvider):
_timed_stream(),
on_content_delta,
on_reasoning_delta=on_reasoning_delta,
+ on_provider_event=_collect_provider_event,
)
self._record_responses_success(model, reasoning_effort)
return LLMResponse(
@@ -854,6 +896,14 @@ class OpenAICompatProvider(LLMProvider):
finish_reason=finish_reason,
usage=usage,
reasoning_content=reasoning_content,
+ provider_specific_fields=(
+ {
+ "native_output_items": native_output_items,
+ "citations": native_citations,
+ }
+ if native_output_items or native_citations
+ else {}
+ ),
)
except Exception as responses_error:
if self._spec and self._spec.name == "github_copilot":
diff --git a/deeptutor/services/llm/provider_core/openai_responses/converters.py b/deeptutor/services/llm/provider_core/openai_responses/converters.py
index 6ace02e50..27ea2979d 100644
--- a/deeptutor/services/llm/provider_core/openai_responses/converters.py
+++ b/deeptutor/services/llm/provider_core/openai_responses/converters.py
@@ -40,23 +40,6 @@ 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",
@@ -73,16 +56,6 @@ 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}
)
@@ -145,19 +118,6 @@ def convert_tools(
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 ad7bb0ea7..3bb095120 100644
--- a/deeptutor/services/llm/provider_core/openai_responses/parsing.py
+++ b/deeptutor/services/llm/provider_core/openai_responses/parsing.py
@@ -35,19 +35,6 @@ def _dump_model(value: Any) -> Any:
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):
@@ -76,31 +63,6 @@ def _citations_from_content_blocks(blocks: Any) -> list[dict[str, str]]:
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")
@@ -262,13 +224,13 @@ async def iter_sse(response: httpx.Response) -> AsyncGenerator[dict[str, Any], N
async def consume_sse(
response: httpx.Response,
on_content_delta: Callable[[str], Awaitable[None]] | None = None,
+ on_provider_event: Callable[[str, dict[str, Any]], None] | None = None,
) -> tuple[str, list[ToolCallRequest], str]:
"""Consume a Responses API SSE stream."""
content = ""
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):
@@ -292,8 +254,8 @@ async def consume_sse(
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)
+ if citation and on_provider_event:
+ on_provider_event("citation", citation)
elif event_type == "response.function_call_arguments.delta":
tool_call_buffers.append(
event.get("delta") or "",
@@ -312,14 +274,8 @@ async def consume_sse(
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 = []
+ if on_provider_event:
+ on_provider_event("output_item", dict(item))
continue
if item.get("type") == "function_call":
call_id = item.get("call_id")
@@ -344,42 +300,9 @@ 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):
@@ -390,6 +313,8 @@ def parse_response_output(response: Any) -> LLMResponse:
content_parts: list[str] = []
tool_calls: list[ToolCallRequest] = []
reasoning_content: str | None = None
+ native_output_items: list[dict[str, Any]] = []
+ native_citations: list[dict[str, str]] = []
for item in output:
item = _dump_model(item)
@@ -404,17 +329,7 @@ def parse_response_output(response: Any) -> LLMResponse:
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)}"),
- )
+ native_citations.extend(_citations_from_content_blocks([block]))
elif item_type == "reasoning":
for summary in item.get("summary") or []:
summary = _dump_model(summary)
@@ -423,14 +338,12 @@ def parse_response_output(response: Any) -> LLMResponse:
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")),
- )
- )
+ # This action already ran inside the provider and accompanies a
+ # terminal answer. Preserve it verbatim as provider metadata; do
+ # not synthesize a local ToolCallRequest and trigger a fake second
+ # agent-loop round.
+ native_output_items.append(dict(item))
+ native_citations.extend(_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
@@ -448,12 +361,19 @@ def parse_response_output(response: Any) -> LLMResponse:
usage = token_counts(response.get("usage"), prompt="input_tokens", completion="output_tokens")
finish_reason = map_finish_reason(response.get("status"))
+ provider_specific_fields: dict[str, Any] = {}
+ if native_output_items or native_citations:
+ provider_specific_fields = {
+ "native_output_items": native_output_items,
+ "citations": native_citations,
+ }
return LLMResponse(
content="".join(content_parts) or None,
tool_calls=tool_calls,
finish_reason=finish_reason,
usage=usage,
reasoning_content=reasoning_content if isinstance(reasoning_content, str) else None,
+ provider_specific_fields=provider_specific_fields,
)
@@ -461,6 +381,7 @@ async def consume_sdk_stream(
stream: Any,
on_content_delta: Callable[[str], Awaitable[None]] | None = None,
on_reasoning_delta: Callable[[str], Awaitable[None]] | None = None,
+ on_provider_event: Callable[[str, dict[str, Any]], None] | None = None,
) -> tuple[str, list[ToolCallRequest], str, dict[str, int], str | None]:
"""Consume an SDK async stream from client.responses.create(stream=True)."""
content = ""
@@ -469,7 +390,6 @@ 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:
@@ -493,8 +413,8 @@ async def consume_sdk_stream(
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)
+ if citation and on_provider_event:
+ on_provider_event("citation", citation)
elif event_type == "response.function_call_arguments.delta":
tool_call_buffers.append(
getattr(event, "delta", "") or "",
@@ -514,14 +434,8 @@ async def consume_sdk_stream(
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 = []
+ if on_provider_event:
+ on_provider_event("output_item", dict(item_dict))
continue
if item and getattr(item, "type", None) == "function_call":
call_id = getattr(item, "call_id", None)
@@ -556,13 +470,4 @@ 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 812a775f3..399aaaec5 100644
--- a/deeptutor/services/provider_registry.py
+++ b/deeptutor/services/provider_registry.py
@@ -52,12 +52,10 @@ 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
+ # Exact model ids whose Responses API executes `web_search` server-side.
+ # Exact matching is intentional: providers often expose Responses only on
+ # one model even when sibling models share the same family prefix.
+ native_web_search_models: tuple[str, ...] = ()
@property
def mode(self) -> str:
@@ -330,7 +328,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,
+ native_web_search_models=("deepseek-v4-flash",),
),
ProviderSpec(
name="gemini",
diff --git a/tests/services/llm/test_native_web_search.py b/tests/services/llm/test_native_web_search.py
index d740955b0..ffeb7449a 100644
--- a/tests/services/llm/test_native_web_search.py
+++ b/tests/services/llm/test_native_web_search.py
@@ -1,33 +1,35 @@
"""Tests for native server-side web_search support (#846).
-Covers the three seams a native web search crosses:
+Covers the four 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.
+* provider gating — only DeepSeek's supported Responses model takes this path.
+* parsing — ``web_search_call`` remains provider metadata and the answer is
+ terminal; no fake local tool call is synthesized.
+* streaming — the provider's complete action object and citations are retained.
"""
from __future__ import annotations
import json
+from types import SimpleNamespace
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.core.agentic import client as client_module
+from deeptutor.core.agentic.client import LLMClientConfig
+from deeptutor.services.llm.provider_core.openai_compat_provider import (
+ OpenAICompatProvider,
+)
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,
)
+from deeptutor.services.provider_registry import find_by_name
class _SSEFixture:
@@ -40,42 +42,25 @@ class _SSEFixture:
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 _SDKStream:
+ def __init__(self, events: list[SimpleNamespace]) -> None:
+ self._events = events
+ def __aiter__(self):
+ return self
-class _Stream:
- def __init__(self):
- self.events: list[dict] = []
+ async def __anext__(self):
+ if not self._events:
+ raise StopAsyncIteration
+ return self._events.pop(0)
- def __getattr__(self, name):
- async def _emit(*args, **kwargs):
- self.events.append({"event": name, **kwargs})
- return _emit
+_TOOLS = [
+ {
+ "type": "function",
+ "function": {"name": "web_search", "parameters": {"type": "object"}},
+ }
+]
# ---------------------------------------------------------------------------
@@ -104,56 +89,133 @@ class TestConvertToolsNativeWebSearch:
# ---------------------------------------------------------------------------
-# convert_messages: server-executed history replay
+# provider and adapter gating
# ---------------------------------------------------------------------------
-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"]
+def _provider(model: str) -> OpenAICompatProvider:
+ return OpenAICompatProvider(
+ api_key="test-key",
+ api_base="https://api.deepseek.com",
+ default_model=model,
+ spec=find_by_name("deepseek"),
+ provider_name="deepseek",
+ )
+
+
+def test_only_supported_deepseek_model_uses_responses_for_native_search() -> None:
+ assert _provider("deepseek-v4-flash")._should_use_responses_api(
+ "deepseek-v4-flash", None, _TOOLS
+ )
+ assert not _provider("deepseek-v4-pro")._should_use_responses_api(
+ "deepseek-v4-pro", None, _TOOLS
+ )
+ assert not _provider("deepseek-v4-flash")._should_use_responses_api(
+ "deepseek-v4-flash", None, None
+ )
+
+
+def test_native_mapping_is_model_scoped() -> None:
+ flash_body = _provider("deepseek-v4-flash")._build_responses_body(
+ [{"role": "user", "content": "latest news"}],
+ _TOOLS,
+ "deepseek-v4-flash",
+ 256,
+ 0.7,
+ None,
+ None,
+ )
+ pro_body = _provider("deepseek-v4-pro")._build_responses_body(
+ [{"role": "user", "content": "latest news"}],
+ _TOOLS,
+ "deepseek-v4-pro",
+ 256,
+ 0.7,
+ None,
+ None,
+ )
+ assert flash_body["tools"] == [{"type": "web_search"}]
+ assert pro_body["tools"][0]["type"] == "function"
+
+
+def test_agent_client_routes_only_supported_model_through_provider_adapter(monkeypatch) -> None:
+ sentinel = object()
+ monkeypatch.setattr(
+ client_module,
+ "_build_direct_openai_adapter",
+ lambda *_args, **_kwargs: sentinel,
+ )
+ spec = find_by_name("deepseek")
+ assert spec is not None
+ flash = LLMClientConfig(
+ binding="deepseek",
+ model="deepseek-v4-flash",
+ api_key="k",
+ base_url="https://api.deepseek.com",
+ )
+ pro = LLMClientConfig(
+ binding="deepseek",
+ model="deepseek-v4-pro",
+ api_key="k",
+ base_url="https://api.deepseek.com",
+ )
+ assert client_module._build_native_provider_adapter(flash, spec) is sentinel
+ assert client_module._build_native_provider_adapter(pro, spec) is None
+
+
+async def test_provider_stream_returns_native_search_as_terminal_metadata() -> None:
+ provider = _provider("deepseek-v4-flash")
+ action = {"type": "open_page", "url": "https://example.com/current"}
+ events = [
+ SimpleNamespace(
+ type="response.output_item.done",
+ item=SimpleNamespace(
+ type="web_search_call",
+ id="ws_1",
+ status="completed",
+ action=action,
+ ),
+ ),
+ SimpleNamespace(type="response.output_text.delta", delta="Current answer."),
+ SimpleNamespace(
+ type="response.completed",
+ response=SimpleNamespace(
+ status="completed",
+ usage={"input_tokens": 4, "output_tokens": 2},
+ ),
+ ),
+ ]
+ captured_body: dict = {}
+
+ async def create(**body):
+ captured_body.update(body)
+ return _SDKStream(events)
+
+ provider._client = SimpleNamespace(
+ responses=SimpleNamespace(create=create),
+ chat=SimpleNamespace(completions=SimpleNamespace()),
+ )
+
+ result = await provider.chat_stream(
+ messages=[{"role": "user", "content": "What changed today?"}],
+ tools=_TOOLS,
+ model="deepseek-v4-flash",
+ max_tokens=256,
+ )
+
+ assert captured_body["tools"] == [{"type": "web_search"}]
+ assert result.content == "Current answer."
+ assert result.finish_reason == "stop"
+ assert result.tool_calls == []
+ assert result.provider_specific_fields["native_output_items"] == [
+ {
+ "type": "web_search_call",
+ "id": "ws_1",
+ "status": "completed",
+ "action": action,
+ }
+ ]
# ---------------------------------------------------------------------------
@@ -162,14 +224,17 @@ class TestConvertMessagesServerExecutedReplay:
class TestParseServerExecutedWebSearch:
- def test_parse_response_output_synthesizes_marked_call(self) -> None:
+ def test_parse_response_output_preserves_action_without_tool_loop(self) -> None:
response = {
"output": [
{
"type": "web_search_call",
"id": "ws_abc",
"status": "completed",
- "action": {"type": "search", "query": "cooley tukey fft"},
+ "action": {
+ "type": "open_page",
+ "url": "https://example.com/paper",
+ },
},
{
"type": "message",
@@ -194,12 +259,9 @@ class TestParseServerExecutedWebSearch:
}
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 result.tool_calls == []
+ fields = result.provider_specific_fields
+ assert fields["native_output_items"] == [response["output"][0]]
assert fields["citations"] == [
{"url": "https://example.com/paper", "title": "Cooley-Tukey"}
]
@@ -226,16 +288,19 @@ class TestParseServerExecutedWebSearch:
"type": "web_search_call",
"id": "ws_1",
"status": "completed",
- "action": {"query": "test"},
+ "action": {"type": "find_in_page", "pattern": "FFT"},
},
},
]
- content, tool_calls, _ = await consume_sse(_SSEFixture(events))
+ provider_events: list[tuple[str, dict]] = []
+ content, tool_calls, _ = await consume_sse(
+ _SSEFixture(events),
+ on_provider_event=lambda kind, payload: provider_events.append((kind, payload)),
+ )
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"] == [
+ assert tool_calls == []
+ assert provider_events[-1] == ("output_item", events[-1]["item"])
+ assert [payload for kind, payload in provider_events if kind == "citation"] == [
{"url": "https://a", "title": "A"},
{"url": "https://b", "title": "B"},
]
@@ -252,14 +317,18 @@ class TestParseServerExecutedWebSearch:
"item": {"type": "web_search_call", "id": "ws_1", "status": "completed"},
},
]
- _, tool_calls, _ = await consume_sse(_SSEFixture(events))
- assert len(tool_calls) == 1
+ provider_events: list[tuple[str, dict]] = []
+ _, tool_calls, _ = await consume_sse(
+ _SSEFixture(events),
+ on_provider_event=lambda kind, payload: provider_events.append((kind, payload)),
+ )
+ assert tool_calls == []
+ assert len(provider_events) == 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.
+ # text streams with its citations. Both remain provider metadata.
events = [
{
"type": "response.output_item.done",
@@ -276,50 +345,13 @@ class TestParseServerExecutedWebSearch:
"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"}]
+ provider_events: list[tuple[str, dict]] = []
+ _, tool_calls, _ = await consume_sse(
+ _SSEFixture(events),
+ on_provider_event=lambda kind, payload: provider_events.append((kind, payload)),
+ )
+ assert tool_calls == []
+ assert provider_events == [
+ ("output_item", events[0]["item"]),
+ ("citation", {"url": "https://a", "title": "A"}),
+ ]