Skip to content

The agent that grows with you

fix(gemini): drop JSON response_format alongside tools on pre-Gemini-3 models

teknium1b6d38fddd42e
diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.py
index c09d34ba695..85ce5f3659b 100644
--- a/agent/gemini_native_adapter.py
+++ b/agent/gemini_native_adapter.py
@@ -530,12 +530,9 @@ def build_gemini_request(
# Gemini 3+ both requires tool-call ids and accepts multimodal functionResponse parts.
is_gemini3 = gemini_requires_tool_call_ids(model)
contents, system_instruction = _build_gemini_contents(messages, include_tool_call_ids=is_gemini3, is_gemini3=is_gemini3)
+ gemini_tools = _translate_tools_to_gemini(tools, json_schema=tools_as_json_schema)
tool_config = _translate_tool_choice_to_gemini(tool_choice)
- optional = (
- ("systemInstruction", system_instruction),
- ("tools", _translate_tools_to_gemini(tools, json_schema=tools_as_json_schema)),
- ("toolConfig", tool_config),
- )
+ optional = (("systemInstruction", system_instruction), ("tools", gemini_tools), ("toolConfig", tool_config))
request: Dict[str, Any] = {"contents": contents, **{k: v for k, v in optional if v}}
# Key order is part of the wire format (prompt-cache parity): temperature, maxOutputTokens, topP, stop, thinking.
generation = (
@@ -545,10 +542,14 @@ def build_gemini_request(
)
json_output = _translate_response_format(response_format, json_schema=tools_as_json_schema)
# Gemini 400s when forced function calling (mode ANY, from ``tool_choice="required"`` or a named
- # function) is combined with a JSON responseMimeType — pre-Gemini-3 models reject JSON output
- # alongside function declarations at all. The forced call wins; JSON can come on a later turn.
- if json_output and (tool_config or {}).get("functionCallingConfig", {}).get("mode") == "ANY":
- logger.debug("Gemini: dropping JSON response_format — tool_choice forces function calling (mode ANY)")
+ # function) is combined with a JSON responseMimeType, and pre-Gemini-3 models reject JSON output
+ # alongside ANY function declarations ("Function calling with a response mime type:
+ # 'application/json' is unsupported"); only Gemini 3+ combines tools with structured output.
+ # The tools win; JSON can come on a later turn, and callers tolerate an unconstrained reply.
+ forced_call = (tool_config or {}).get("functionCallingConfig", {}).get("mode") == "ANY"
+ if json_output and (forced_call or (gemini_tools and not is_gemini3)):
+ logger.debug("Gemini: dropping JSON response_format — %s",
+ "tool_choice forces function calling (mode ANY)" if forced_call else "pre-Gemini-3 model with tools")
json_output = {}
request["generationConfig"] = {**{k: v for k, v in generation if v is not None}, **json_output}
return request
diff --git a/tests/agent/test_gemini_native_adapter.py b/tests/agent/test_gemini_native_adapter.py
index 403c9c50d28..71300354527 100644
--- a/tests/agent/test_gemini_native_adapter.py
+++ b/tests/agent/test_gemini_native_adapter.py
@@ -872,81 +872,47 @@ def test_response_without_thinking_tokens_keeps_its_output_count():
assert normalize_usage(usage, provider="google").reasoning_tokens == 0
-def test_build_gemini_request_translates_response_format():
- from agent.gemini_native_adapter import build_gemini_request
-
- schema = {"type": "object", "properties": {"ok": {"type": "boolean"}}, "required": ["ok"]}
- req = build_gemini_request(
- messages=[{"role": "user", "content": "hi"}],
- response_format={"type": "json_schema", "json_schema": {"name": "out", "schema": schema}},
- tools_as_json_schema=True,
- )
- assert req["generationConfig"]["responseMimeType"] == "application/json"
- assert req["generationConfig"]["responseJsonSchema"] == schema
-
-
-def test_build_gemini_request_json_object_sets_mime_type_only():
[email protected]("json_schema_surface, key", [(True, "responseJsonSchema"), (False, "responseSchema")])
+def test_build_gemini_request_translates_response_format_on_both_schema_surfaces(json_schema_surface, key):
+ """OpenAI response_format reaches generationConfig: full JSON Schema under ``responseJsonSchema`` on
+ v1beta, the OpenAPI subset under ``responseSchema`` elsewhere (with unsupported keys stripped)."""
from agent.gemini_native_adapter import build_gemini_request
- generation = build_gemini_request(
- messages=[{"role": "user", "content": "hi"}],
- response_format={"type": "json_object"},
- tools_as_json_schema=True,
- )["generationConfig"]
- assert generation["responseMimeType"] == "application/json"
- assert "responseJsonSchema" not in generation and "responseSchema" not in generation
-
-
-def test_build_gemini_request_response_schema_path_sanitizes_schema():
- """Non-v1beta surfaces (v1, Vertex express v1beta1) take the OpenAPI-subset responseSchema key."""
- from agent.gemini_native_adapter import build_gemini_request
-
- schema = {"type": "object", "properties": {"ok": {"type": "boolean"}}, "additionalProperties": False}
+ schema = {"type": "object", "properties": {"ok": {"type": "boolean"}}, "required": ["ok"], "additionalProperties": False}
generation = build_gemini_request(
messages=[{"role": "user", "content": "hi"}],
response_format={"type": "json_schema", "json_schema": {"name": "out", "schema": schema}},
- tools_as_json_schema=False,
- )["generationConfig"]
- assert "responseJsonSchema" not in generation
- assert generation["responseSchema"] == {"type": "object", "properties": {"ok": {"type": "boolean"}}}
-
-
-def test_build_gemini_request_json_schema_without_schema_key_falls_back_to_mime_type():
- from agent.gemini_native_adapter import build_gemini_request
-
- generation = build_gemini_request(
- messages=[{"role": "user", "content": "hi"}],
- response_format={"type": "json_schema", "json_schema": {"name": "out"}},
- tools_as_json_schema=True,
+ tools_as_json_schema=json_schema_surface,
)["generationConfig"]
assert generation["responseMimeType"] == "application/json"
- assert "responseJsonSchema" not in generation and "responseSchema" not in generation
+ assert generation[key]["properties"] == schema["properties"] and generation[key]["required"] == ["ok"]
+ assert ("additionalProperties" in generation[key]) is json_schema_surface
@pytest.mark.parametrize("tool_choice", ["required", {"type": "function", "function": {"name": "lookup"}}])
def test_build_gemini_request_drops_json_output_when_tool_choice_forces_calls(tool_choice):
- """Gemini 400s on forced function calling (mode ANY) combined with a JSON responseMimeType."""
+ """Gemini 400s on forced function calling (mode ANY) combined with a JSON responseMimeType, on every model."""
from agent.gemini_native_adapter import build_gemini_request
generation = build_gemini_request(
messages=[{"role": "user", "content": "hi"}],
tools=[{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}],
- tool_choice=tool_choice,
+ tool_choice=tool_choice, model="gemini-3-flash",
response_format={"type": "json_schema", "json_schema": {"name": "out", "schema": {"type": "object"}}},
tools_as_json_schema=True,
)["generationConfig"]
- assert "responseMimeType" not in generation
- assert "responseJsonSchema" not in generation and "responseSchema" not in generation
+ assert not {"responseMimeType", "responseJsonSchema", "responseSchema"} & set(generation)
-def test_build_gemini_request_keeps_json_output_when_tool_choice_is_auto():
[email protected]("model, keeps_json", [("gemini-2.5-flash", False), ("gemini-3-flash", True)])
+def test_build_gemini_request_tools_plus_json_output_only_on_gemini3(model, keeps_json):
+ """Pre-Gemini-3 rejects function declarations alongside a JSON mime type (HTTP 400 "Function calling
+ with a response mime type: 'application/json' is unsupported"); Gemini 3+ accepts the combination."""
from agent.gemini_native_adapter import build_gemini_request
generation = build_gemini_request(
messages=[{"role": "user", "content": "hi"}],
tools=[{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}],
- tool_choice="auto",
- response_format={"type": "json_object"},
- tools_as_json_schema=True,
+ tool_choice="auto", model=model, response_format={"type": "json_object"}, tools_as_json_schema=True,
)["generationConfig"]
- assert generation["responseMimeType"] == "application/json"
+ assert ("responseMimeType" in generation) is keeps_json