Skip to content

The agent that grows with you

fix(gemini): wire response_format into native Gemini generationConfig

Gabby Ong03a7bf3047c5
diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.py
index 35385fb6779..c09d34ba695 100644
--- a/agent/gemini_native_adapter.py
+++ b/agent/gemini_native_adapter.py
@@ -503,18 +503,38 @@ def _effective_gemini_max_output_tokens(max_tokens: Optional[int], thinking_conf
return requested
+def _translate_response_format(response_format: Any, *, json_schema: bool = False) -> Dict[str, Any]:
+ """OpenAI ``response_format`` → Gemini ``generationConfig`` JSON-output keys.
+
+ Full-JSON-Schema ``responseJsonSchema`` exists only on the generativelanguage ``v1beta``
+ surface (same gate as ``parametersJsonSchema``); ``v1`` / ``v1alpha``, Vertex express
+ ``v1beta1`` and unknown proxies take the OpenAPI-subset ``responseSchema`` path.
+ """
+ if not isinstance(response_format, dict) or response_format.get("type") not in ("json_object", "json_schema"):
+ return {}
+ spec = response_format.get("json_schema") if response_format.get("type") == "json_schema" else None
+ # A ``json_schema`` spec with no ``schema`` key has nothing to constrain with (the Anthropic
+ # translator bails the same way) — ask for JSON and let the model shape it.
+ schema = spec.get("schema") if isinstance(spec, dict) else None
+ if not isinstance(schema, dict):
+ return {"responseMimeType": "application/json"}
+ key, prep = ("responseJsonSchema", prepare_gemini_tool_parameters) if json_schema else ("responseSchema", sanitize_gemini_tool_parameters)
+ return {"responseMimeType": "application/json", key: prep(schema)}
+
+
def build_gemini_request(
*, messages: List[Dict[str, Any]], tools: Any = None, tool_choice: Any = None, temperature: Optional[float] = None,
max_tokens: Optional[int] = None, top_p: Optional[float] = None, stop: Any = None, thinking_config: Any = None,
- model: str = "", tools_as_json_schema: bool = False,
+ response_format: Any = None, model: str = "", tools_as_json_schema: bool = False,
) -> Dict[str, Any]:
# 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)
+ 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", _translate_tool_choice_to_gemini(tool_choice)),
+ ("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.
@@ -523,7 +543,14 @@ def build_gemini_request(
("topP", top_p), ("stopSequences", (stop if isinstance(stop, list) else [str(stop)]) if stop else None),
("thinkingConfig", _normalize_thinking_config(thinking_config)),
)
- request["generationConfig"] = {k: v for k, v in generation if v is not None}
+ 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)")
+ json_output = {}
+ request["generationConfig"] = {**{k: v for k, v in generation if v is not None}, **json_output}
return request
@@ -824,12 +851,14 @@ class GeminiNativeClient:
def _create_chat_completion(
self, *, model: str = "gemini-3.7-flash", messages: Optional[List[Dict[str, Any]]] = None, stream: bool = False,
tools: Any = None, tool_choice: Any = None, temperature: Optional[float] = None, max_tokens: Optional[int] = None,
- top_p: Optional[float] = None, stop: Any = None, extra_body: Optional[Dict[str, Any]] = None, timeout: Any = None, **_: Any,
+ top_p: Optional[float] = None, stop: Any = None, response_format: Any = None, extra_body: Optional[Dict[str, Any]] = None,
+ timeout: Any = None, **_: Any,
) -> Any:
extra = extra_body if isinstance(extra_body, dict) else {}
request = build_gemini_request(
messages=messages or [], tools=tools, tool_choice=tool_choice, temperature=temperature, max_tokens=max_tokens,
- top_p=top_p, stop=stop, thinking_config=extra.get("thinking_config") or extra.get("thinkingConfig"), model=model,
+ top_p=top_p, stop=stop, thinking_config=extra.get("thinking_config") or extra.get("thinkingConfig"),
+ response_format=response_format or extra.get("response_format"), model=model,
tools_as_json_schema=gemini_accepts_parameters_json_schema(self.base_url),
)
model = bare_gemini_model_id(model)
diff --git a/tests/agent/test_gemini_native_adapter.py b/tests/agent/test_gemini_native_adapter.py
index 145cc4289e1..403c9c50d28 100644
--- a/tests/agent/test_gemini_native_adapter.py
+++ b/tests/agent/test_gemini_native_adapter.py
@@ -870,3 +870,83 @@ def test_response_without_thinking_tokens_keeps_its_output_count():
assert usage.completion_tokens == visible
assert usage.prompt_tokens + usage.completion_tokens == usage.total_tokens
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():
+ 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}
+ 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,
+ )["generationConfig"]
+ assert generation["responseMimeType"] == "application/json"
+ assert "responseJsonSchema" not in generation and "responseSchema" not in generation
+
+
[email protected]("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."""
+ 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,
+ 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
+
+
+def test_build_gemini_request_keeps_json_output_when_tool_choice_is_auto():
+ 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,
+ )["generationConfig"]
+ assert generation["responseMimeType"] == "application/json"