Skip to content

The agent that grows with you

fix(gemini): echo bridged tool_call name on the OpenAI-compatible path

Yong Li2e9435d2f619
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 6f94189bf03..e01ffcd4348 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -4546,6 +4546,60 @@ def sanitize_api_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]
"Pre-call sanitizer: removed %d duplicate tool_call_id reference(s)",
removed_dupes,
)
+
+ # 4. Align each tool result's wire-visible ``name`` with the function name
+ # of the call it answers. Google matches functionResponse.name against
+ # functionCall.name and rejects a mismatch with HTTP 400 "Request contains
+ # an invalid argument" (INVALID_ARGUMENT); behind an OpenAI-compatible
+ # gateway that surfaces only as a generic "Provider returned error".
+ #
+ # The mismatch is routine, not corruption. When tool_search defers
+ # MCP/plugin tools the model calls the bridge tool ``tool_call``, while
+ # ``make_tool_result_message()`` labels the result with the unwrapped
+ # internal tool name (``mcp__github__create_issue``) that dispatch, hooks,
+ # logging, and guardrails need. #72089 fixed exactly this for the native
+ # Gemini adapter, which now prefers ``tool_name_by_call_id`` over the
+ # result name; requests that reach Gemini through the OpenAI-compatible
+ # path (OpenRouter, Vertex/LiteLLM proxies, any OpenAI-shaped gateway) skip
+ # that translation entirely and still send the internal name on the wire.
+ #
+ # Normalizing here rather than in the OpenAI-compat serializer keeps it
+ # provider-agnostic: Gemini reaches Hermes under many model strings and
+ # base URLs, so sniffing for "is this really Google?" is unreliable, and
+ # every other provider either ignores the field or agrees with the call
+ # name. Runs on the per-call copy, so the stored trajectory keeps the real
+ # tool name for the session DB and the UI — only the wire payload changes.
+ # A no-op for the native Gemini path, which already resolves the same name.
+ call_names: Dict[str, str] = {}
+ for msg in messages:
+ if msg.get("role") == "assistant":
+ for tc in msg.get("tool_calls") or []:
+ cid = _ra().AIAgent._get_tool_call_id_static(tc)
+ nm = _ra().AIAgent._get_tool_call_name_static(tc)
+ if cid and nm:
+ call_names[cid] = nm
+ realigned = 0
+ aligned: List[Dict[str, Any]] = []
+ for msg in messages:
+ if msg.get("role") == "tool":
+ cid = (msg.get("tool_call_id") or "").strip()
+ expected = call_names.get(cid)
+ current = msg.get("name")
+ # Only rewrite a name that is present and disagrees. A result with
+ # no ``name`` is already valid for Gemini (the id pairs it), so
+ # leave it absent rather than inventing a field: clean transcripts
+ # must still pass through byte-identical for prompt caching.
+ if expected and current and current != expected:
+ msg = {**msg, "name": expected}
+ realigned += 1
+ aligned.append(msg)
+ if realigned:
+ messages = aligned
+ _ra().logger.debug(
+ "Pre-call sanitizer: realigned %d tool result name(s) with their "
+ "tool_call function name",
+ realigned,
+ )
return messages
diff --git a/tests/run_agent/test_message_sequence_repair.py b/tests/run_agent/test_message_sequence_repair.py
index 2461bdec70c..9bacbaae724 100644
--- a/tests/run_agent/test_message_sequence_repair.py
+++ b/tests/run_agent/test_message_sequence_repair.py
@@ -1388,3 +1388,77 @@ def test_sanitize_stubs_interrupted_first_occurrence_keeps_replay_pair():
assert out[5]["content"] == "real result"
+
+
+# ── Bridged tool_call: wire-visible response name must echo the call name ──
+# Google matches functionResponse.name against functionCall.name and rejects a
+# mismatch with HTTP 400 INVALID_ARGUMENT. #72089 fixed this for the native
+# Gemini adapter; requests reaching Gemini through an OpenAI-compatible
+# gateway (OpenRouter, Vertex/LiteLLM proxies) skip that translation, so the
+# chokepoint sanitizer has to hold the same invariant.
+
+
+def test_sanitize_realigns_bridged_tool_result_name_with_call_name():
+ """A tool_search-bridged result must go on the wire as ``tool_call``.
+
+ The executor labels the result with the unwrapped internal tool name for
+ dispatch/hooks/logging; Gemini sees that as a functionResponse whose name
+ does not match its functionCall and 400s.
+ """
+ from agent.agent_runtime_helpers import sanitize_api_messages
+
+ messages = [
+ {"role": "user", "content": "file an issue"},
+ {"role": "assistant", "content": "",
+ "tool_calls": [{"id": "call_1", "type": "function",
+ "function": {
+ "name": "tool_call",
+ "arguments": ('{"name": "mcp__github__create_issue",'
+ ' "arguments": {"title": "Bug"}}'),
+ }}]},
+ {"role": "tool", "name": "mcp__github__create_issue",
+ "tool_name": "mcp__github__create_issue",
+ "tool_call_id": "call_1", "content": '{"number": 123}'},
+ ]
+ out = sanitize_api_messages(list(messages))
+ result = [m for m in out if m.get("role") == "tool"][0]
+ assert result["name"] == "tool_call"
+ # The internal name stays available for the session DB / UI, and the
+ # caller's own message objects are untouched (per-call copy only).
+ assert result["tool_name"] == "mcp__github__create_issue"
+ assert messages[2]["name"] == "mcp__github__create_issue"
+
+
+def test_sanitize_leaves_matching_and_unpaired_tool_result_names_alone():
+ """Directly-called tools already agree; an unpaired name is left as-is."""
+ from agent.agent_runtime_helpers import sanitize_api_messages
+
+ messages = [
+ {"role": "user", "content": "weather?"},
+ {"role": "assistant", "content": None,
+ "tool_calls": [{"id": "call_1", "type": "function",
+ "function": {"name": "get_weather", "arguments": "{}"}}]},
+ {"role": "tool", "name": "get_weather",
+ "tool_call_id": "call_1", "content": "sunny"},
+ ]
+ out = sanitize_api_messages(list(messages))
+ assert [m["name"] for m in out if m.get("role") == "tool"] == ["get_weather"]
+
+
+def test_sanitize_does_not_invent_a_name_on_unnamed_tool_results():
+ """A result with no ``name`` is already valid — the id pairs it.
+
+ Adding the field would make clean transcripts non-identical on the wire
+ and needlessly perturb prompt caching.
+ """
+ from agent.agent_runtime_helpers import sanitize_api_messages
+
+ messages = [
+ {"role": "user", "content": "run it"},
+ {"role": "assistant", "content": None,
+ "tool_calls": [{"id": "call_1", "type": "function",
+ "function": {"name": "terminal", "arguments": "{}"}}]},
+ {"role": "tool", "tool_call_id": "call_1", "content": "ok"},
+ ]
+ out = sanitize_api_messages(list(messages))
+ assert out == messages