Skip to content

The agent that grows with you

fix(xai): alias the reserved tool_search bridge name on chat completions

liuhao10245e2f8b986562
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index 8b8abc2023a..d0a33d34297 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -1957,6 +1957,42 @@ def build_api_kwargs(agent, api_messages: list, tools_for_api: list | None = Non
# ── chat_completions (default) ─────────────────────────────────────
_ct = agent._get_transport()
+ # xAI's chat-completions endpoint reserves the function name
+ # ``tool_search`` for its native server-side tool and rejects the whole
+ # request when the client Tool Search bridge declares it (HTTP 400
+ # "The function name tool_search is reserved for the tool_search tool",
+ # #95003) — same reserved-name class the codex_responses branch above
+ # already sanitizes tools for (#27197). Rename the bridge's wire
+ # declaration to an alias; normalize_response maps model calls back.
+ # Deep-copy first (the #27907 in-place-mutation lesson): tools_for_api
+ # aliases agent.tools, and renaming in place would corrupt the shared
+ # per-agent tool registry for every later non-xAI request.
+ _is_xai_chat = (
+ agent.provider in {"xai", "xai-oauth"}
+ or agent._base_url_hostname == "api.x.ai"
+ )
+ if _is_xai_chat and tools_for_api:
+ try:
+ import copy as _copy_xai
+
+ from agent.transports.chat_completions import (
+ _rename_tool_search_bridge_for_xai,
+ )
+
+ _has_bridge = any(
+ (t.get("function") or {}).get("name") == "tool_search"
+ for t in tools_for_api
+ if isinstance(t, dict)
+ )
+ if _has_bridge:
+ tools_for_api = _copy_xai.deepcopy(tools_for_api)
+ tools_for_api = _rename_tool_search_bridge_for_xai(tools_for_api)
+ except Exception as exc:
+ logger.warning(
+ "%s⚠️ Failed to alias tool_search bridge for xAI: %s",
+ getattr(agent, "log_prefix", ""), exc,
+ )
+
# Provider detection flags
_is_qwen = agent._is_qwen_portal()
_is_or = agent._is_openrouter_url()
diff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.py
index f8a191ceecc..4e557bd427b 100644
--- a/agent/transports/chat_completions.py
+++ b/agent/transports/chat_completions.py
@@ -27,6 +27,43 @@ from agent.prompt_builder import DEVELOPER_ROLE_MODELS
from agent.transports.base import ProviderTransport
from agent.transports.types import NormalizedResponse, ToolCall, Usage
+# xAI's chat-completions API reserves the function name ``tool_search`` for
+# its own server-side tool and rejects any request declaring a client
+# function with that name (HTTP 400 "The function name tool_search is
+# reserved for the tool_search tool", #95003). The Tool Search bridge
+# (tools/tool_search.py) assembles its client-side discovery tool under the
+# same literal name for every provider, so Grok providers are unusable
+# whenever the bridge is active. Mirror the web_search treatment in
+# transports/codex.py (_rename_client_web_search_for_xai): alias the wire
+# declaration and map the alias back in normalize_response. The alias value
+# matches _CODEX_TOOL_SEARCH_ALIAS from the Codex-side fix for the same
+# reserved-name class (#83122) so the two transports stay consistent.
+_XAI_TOOL_SEARCH_ALIAS = "hermes_tool_search"
+
+
+def _rename_tool_search_bridge_for_xai(
+ tools: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ """Rename the client ``tool_search`` bridge declaration to a wire alias.
+
+ Only the wire name changes: descriptions, schemas, and the other two
+ bridge names (``tool_describe`` / ``tool_call`` — not reserved by xAI)
+ pass through untouched. The alias is mapped back to ``tool_search`` in
+ ``normalize_response`` before dispatch.
+ """
+ rewritten: list[dict[str, Any]] = []
+ for tool in tools:
+ if (
+ isinstance(tool, dict)
+ and (tool.get("function") or {}).get("name") == "tool_search"
+ ):
+ aliased = dict(tool)
+ aliased["function"] = {**tool["function"], "name": _XAI_TOOL_SEARCH_ALIAS}
+ rewritten.append(aliased)
+ else:
+ rewritten.append(tool)
+ return rewritten
+
def _static_prompt_instructions(messages: list[dict[str, Any]]) -> str:
"""Return the stable system/developer prefix used for cache routing.
@@ -925,6 +962,13 @@ class ChatCompletionsTransport(ProviderTransport):
# preserve an explicit blank name for Hermes's recovery path.
if tc_function is None or function_name is None:
continue
+ # Map the xAI wire alias back to the bridge's real name.
+ # Unconditional is correct here: ``hermes_tool_search`` only
+ # exists on the wire because _rename_tool_search_bridge_for_xai
+ # put it there (xAI rejects the literal ``tool_search``), so
+ # any model call carrying the alias is a bridge invocation.
+ if function_name == _XAI_TOOL_SEARCH_ALIAS:
+ function_name = "tool_search"
function_arguments = getattr(tc_function, "arguments", None)
# Preserve provider-specific extras on the tool call.
# Gemini 3 thinking models attach extra_content with
diff --git a/tests/agent/transports/test_chat_completions_xai_tool_search_alias.py b/tests/agent/transports/test_chat_completions_xai_tool_search_alias.py
new file mode 100644
index 00000000000..b0764e13139
--- /dev/null
+++ b/tests/agent/transports/test_chat_completions_xai_tool_search_alias.py
@@ -0,0 +1,94 @@
+"""Tests for the xAI ``tool_search`` reserved-name alias (#95003).
+
+xAI's chat-completions API reserves the function name ``tool_search`` for
+its native server-side tool and rejects the whole request when the client
+Tool Search bridge declares it (HTTP 400 "The function name tool_search is
+reserved for the tool_search tool"). The fix mirrors the web_search treatment
+in ``transports/codex.py``: rename the bridge's wire declaration to
+``hermes_tool_search`` for xAI targets and map the alias back to
+``tool_search`` in ``normalize_response`` so dispatch is unchanged.
+"""
+
+from types import SimpleNamespace
+
+import pytest
+
+from agent.transports import get_transport
+from agent.transports.chat_completions import (
+ _XAI_TOOL_SEARCH_ALIAS,
+ _rename_tool_search_bridge_for_xai,
+)
+
+
+def transport():
+ import agent.transports.chat_completions # noqa: F401
+ return get_transport("chat_completions")
+
+
+class TestRenameToolSearchBridgeForXai:
+ def test_tool_search_renamed_alias_value(self):
+ tools = [{
+ "type": "function",
+ "function": {
+ "name": "tool_search",
+ "description": "Search deferred tools",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }]
+ out = _rename_tool_search_bridge_for_xai(tools)
+ assert out[0]["function"]["name"] == _XAI_TOOL_SEARCH_ALIAS
+ assert out[0]["function"]["name"] == "hermes_tool_search"
+
+ def test_schema_and_description_untouched(self):
+ fn = {
+ "name": "tool_search",
+ "description": "Search the deferred tool catalog",
+ "parameters": {"type": "object", "properties": {"query": {"type": "string"}}},
+ }
+ out = _rename_tool_search_bridge_for_xai([{"type": "function", "function": fn}])
+ assert out[0]["function"]["description"] == fn["description"]
+ assert out[0]["function"]["parameters"] == fn["parameters"]
+
+ def test_sibling_bridge_names_not_reserved(self):
+ # xAI's error names only tool_search; tool_describe / tool_call stay
+ # on the wire unchanged so the model keeps calling them directly.
+ tools = [
+ {"type": "function", "function": {"name": "tool_describe"}},
+ {"type": "function", "function": {"name": "tool_call"}},
+ ]
+ out = _rename_tool_search_bridge_for_xai(tools)
+ assert [t["function"]["name"] for t in out] == ["tool_describe", "tool_call"]
+
+ def test_ordinary_tools_untouched(self):
+ tools = [{"type": "function", "function": {"name": "web_search"}}]
+ out = _rename_tool_search_bridge_for_xai(tools)
+ assert out[0]["function"]["name"] == "web_search"
+
+ def test_input_not_mutated(self):
+ # The helper feeds a deep-copied list on the helper-layer path, but
+ # pin copy semantics anyway: the shared per-agent tool registry must
+ # never see the alias (#27907 lesson).
+ tools = [{"type": "function", "function": {"name": "tool_search"}}]
+ _rename_tool_search_bridge_for_xai(tools)
+ assert tools[0]["function"]["name"] == "tool_search"
+
+
+def _fake_response(tool_name):
+ tc = SimpleNamespace(
+ id="call_1",
+ function=SimpleNamespace(name=tool_name, arguments='{"query": "x"}'),
+ )
+ msg = SimpleNamespace(tool_calls=[tc], reasoning=None, reasoning_content=None)
+ choice = SimpleNamespace(message=msg, finish_reason="tool_calls")
+ return SimpleNamespace(choices=[choice], usage=None)
+
+
+class TestNormalizeResponseMapsAliasBack:
+ def test_alias_call_maps_back_to_bridge_name(self, transport):
+ resp = transport.normalize_response(_fake_response(_XAI_TOOL_SEARCH_ALIAS))
+ assert resp.tool_calls[0].name == "tool_search"
+
+ def test_ordinary_call_name_preserved(self, transport):
+ resp = transport.normalize_response(_fake_response("tool_describe"))
+ assert resp.tool_calls[0].name == "tool_describe"