Skip to content

The agent that grows with you

feat(gemini): send full JSON Schema tool parameters via parametersJsonSchema

teknium743140cd8221
diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.py
index 98cca4a0e26..2c43bc89b83 100644
--- a/agent/gemini_native_adapter.py
+++ b/agent/gemini_native_adapter.py
@@ -21,7 +21,7 @@ import httpx
from agent.bounded_response import read_streaming_error_body
from agent.retry_utils import parse_retry_after_seconds
-from agent.gemini_schema import sanitize_gemini_tool_parameters
+from agent.gemini_schema import prepare_gemini_tool_parameters, sanitize_gemini_tool_parameters
logger = logging.getLogger(__name__)
@@ -102,6 +102,13 @@ def is_native_gemini_base_url(base_url: str) -> bool:
return "generativelanguage.googleapis.com" in normalized and not normalized.endswith("/openai")
+def gemini_accepts_parameters_json_schema(base_url: str) -> bool:
+ """``FunctionDeclaration.parametersJsonSchema`` exists only in the ``v1beta`` surface of
+ generativelanguage (absent from ``v1`` / ``v1alpha`` content.proto); other versions and
+ unknown proxies get the legacy ``parameters`` subset."""
+ return str(base_url or "").strip().rstrip("/").lower().endswith("/v1beta")
+
+
def probe_gemini_tier(
api_key: str, base_url: str = DEFAULT_GEMINI_BASE_URL, *, model: str = "gemini-3.7-flash", timeout: float = 10.0
) -> str:
@@ -329,7 +336,7 @@ def _build_gemini_contents(
return _merge_alternating(contents), ({"role": "system", "parts": [{"text": joined_system}]} if joined_system else None)
-def _function_declaration(tool: Any) -> Optional[Dict[str, Any]]:
+def _function_declaration(tool: Any, *, json_schema: bool = False) -> Optional[Dict[str, Any]]:
fn = (tool.get("function") or {}) if isinstance(tool, dict) else None
if not isinstance(fn, dict) or not (isinstance(fn.get("name"), str) and fn["name"]):
return None
@@ -337,12 +344,18 @@ def _function_declaration(tool: Any) -> Optional[Dict[str, Any]]:
if isinstance(fn.get("description"), str) and fn["description"]:
decl["description"] = fn["description"]
if isinstance(fn.get("parameters"), dict):
- decl["parameters"] = sanitize_gemini_tool_parameters(fn["parameters"])
+ # Full JSON Schema where the API version has the field (unions, bare arrays,
+ # $ref survive); the lossy OpenAPI subset elsewhere. Mutually exclusive on the wire.
+ if json_schema:
+ decl["parametersJsonSchema"] = prepare_gemini_tool_parameters(fn["parameters"])
+ else:
+ decl["parameters"] = sanitize_gemini_tool_parameters(fn["parameters"])
return decl
-def _translate_tools_to_gemini(tools: Any) -> List[Dict[str, Any]]:
- declarations = [d for d in map(_function_declaration, tools if isinstance(tools, list) else []) if d]
+def _translate_tools_to_gemini(tools: Any, *, json_schema: bool = False) -> List[Dict[str, Any]]:
+ declarations = [d for d in (_function_declaration(t, json_schema=json_schema)
+ for t in (tools if isinstance(tools, list) else [])) if d]
return [{"functionDeclarations": declarations}] if declarations else []
@@ -396,13 +409,14 @@ def _effective_gemini_max_output_tokens(max_tokens: Optional[int], thinking_conf
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 = "",
+ 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)
optional = (
- ("systemInstruction", system_instruction), ("tools", _translate_tools_to_gemini(tools)),
+ ("systemInstruction", system_instruction),
+ ("tools", _translate_tools_to_gemini(tools, json_schema=tools_as_json_schema)),
("toolConfig", _translate_tool_choice_to_gemini(tool_choice)),
)
request: Dict[str, Any] = {"contents": contents, **{k: v for k, v in optional if v}}
@@ -675,6 +689,7 @@ class GeminiNativeClient:
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,
+ tools_as_json_schema=gemini_accepts_parameters_json_schema(self.base_url),
)
model = bare_gemini_model_id(model)
url = f"{self.base_url}/models/{model}:"
diff --git a/agent/gemini_schema.py b/agent/gemini_schema.py
index 134667bbe9f..4355f9280ef 100644
--- a/agent/gemini_schema.py
+++ b/agent/gemini_schema.py
@@ -1,12 +1,22 @@
-"""Helpers for translating OpenAI-style tool schemas to Gemini's schema subset."""
+"""Tool-schema preparation for Gemini's native API.
+
+Two wire shapes: ``parametersJsonSchema`` (plain JSON Schema, v1beta only) gets a light
+normalizer (``prepare_gemini_tool_parameters``); the legacy ``parameters`` field accepts
+only the OpenAPI ``Schema`` subset and keeps the lossy translator
+(``sanitize_gemini_tool_parameters``) for API versions without the JSON Schema field.
+"""
from __future__ import annotations
+import copy
+import logging
import math
-from typing import Any, Dict
+from typing import Any, Dict, List, Optional
from tools.schema_sanitizer import _normalize_type_array
+logger = logging.getLogger(__name__)
+
# Gemini's ``FunctionDeclaration.parameters`` accepts only a subset of OpenAPI 3.0 /
# JSON Schema (the ``Schema`` object); everything else is stripped.
_GEMINI_SCHEMA_ALLOWED_KEYS = {
@@ -112,3 +122,77 @@ def sanitize_gemini_schema(schema: Any) -> Dict[str, Any]:
def sanitize_gemini_tool_parameters(parameters: Any) -> Dict[str, Any]:
"""Normalize tool parameters to a valid Gemini object schema."""
return sanitize_gemini_schema(parameters) or {"type": "object", "properties": {}}
+
+
+# ── parametersJsonSchema (full JSON Schema) ─────────────────────────────────
+#
+# The legacy translator is lossy: anyOf unions without an outer type, bare arrays,
+# $ref/$defs and additionalProperties had to be stripped or repaired, and one
+# unrepresentable construct 400s the ENTIRE request. Through parametersJsonSchema the
+# schema goes as-is; only same-document $refs are inlined (MCP pydantic / zod emit
+# them and Google rejects reference indirection) and root ``$schema`` is dropped.
+
+_EMPTY_OBJECT_SCHEMA: Dict[str, Any] = {"type": "object", "properties": {}}
+# Real tool schemas hold a handful of refs; the cap stops circular pydantic models
+# from expanding forever.
+_MAX_REF_EXPANSIONS = 256
+
+
+def _resolve_local_ref(root: Dict[str, Any], ref: str) -> Optional[Dict[str, Any]]:
+ """Resolve a same-document JSON pointer (``#/$defs/Foo``) against *root*."""
+ if not isinstance(ref, str) or not ref.startswith("#/"):
+ return None
+ node: Any = root
+ for raw_part in ref[2:].split("/"):
+ part = raw_part.replace("~1", "/").replace("~0", "~")
+ if not isinstance(node, dict) or part not in node:
+ return None
+ node = node[part]
+ return node if isinstance(node, dict) else None
+
+
+def _inline_refs(node: Any, root: Dict[str, Any], budget: List[int], stack: tuple = ()) -> Any:
+ """Recursively inline same-document ``$ref`` nodes; ``ValueError`` on an unresolvable
+ or circular reference or an exhausted budget (the caller then keeps the original)."""
+ if isinstance(node, list):
+ return [_inline_refs(item, root, budget, stack) for item in node]
+ if not isinstance(node, dict):
+ return node
+ ref = node.get("$ref")
+ if not isinstance(ref, str):
+ return {key: _inline_refs(value, root, budget, stack) for key, value in node.items()}
+ if ref in stack:
+ raise ValueError(f"circular $ref {ref!r}")
+ budget[0] -= 1
+ if budget[0] < 0:
+ raise ValueError("$ref expansion budget exhausted")
+ target = _resolve_local_ref(root, ref)
+ if target is None:
+ raise ValueError(f"unresolvable $ref {ref!r}")
+ inlined = _inline_refs(target, root, budget, stack + (ref,))
+ # JSON Schema: siblings of $ref (description, default, ...) apply alongside the
+ # referenced schema and win over it.
+ siblings = {k: v for k, v in node.items() if k != "$ref"}
+ return {**inlined, **_inline_refs(siblings, root, budget, stack)} if siblings else inlined
+
+
+def prepare_gemini_tool_parameters(parameters: Any) -> Dict[str, Any]:
+ """Full JSON Schema for ``parametersJsonSchema``: deep-copied, root ``$schema`` dropped,
+ same-document ``$ref`` inlined, object root guaranteed. A schema whose references
+ cannot all be resolved is sent untouched so the provider names the real problem."""
+ if not isinstance(parameters, dict) or not parameters:
+ return dict(_EMPTY_OBJECT_SCHEMA)
+ schema = copy.deepcopy(parameters)
+ schema.pop("$schema", None)
+ try:
+ schema = _inline_refs(schema, schema, [_MAX_REF_EXPANSIONS])
+ except ValueError as exc:
+ logger.debug("Gemini tool schema kept as-is ($ref inlining skipped): %s", exc)
+ return schema
+ schema.pop("$defs", None)
+ schema.pop("definitions", None)
+ if not schema:
+ return dict(_EMPTY_OBJECT_SCHEMA)
+ if schema.get("type") == "object" and "properties" not in schema:
+ schema["properties"] = {}
+ return schema
diff --git a/tests/agent/test_gemini_schema.py b/tests/agent/test_gemini_schema.py
index 075e620cea7..9de9f14d614 100644
--- a/tests/agent/test_gemini_schema.py
+++ b/tests/agent/test_gemini_schema.py
@@ -1,6 +1,9 @@
"""Tests for agent.gemini_schema — OpenAI→Gemini tool parameter translation."""
+import copy
+
from agent.gemini_schema import (
+ prepare_gemini_tool_parameters,
sanitize_gemini_schema,
sanitize_gemini_tool_parameters,
)
@@ -167,3 +170,71 @@ class TestSanitizeGeminiToolParameters:
assert "1440" in aad["description"]
# And the string-enum sibling is untouched.
assert cleaned["properties"]["action"]["enum"] == ["create_thread"]
+
+
+# ── parametersJsonSchema (full JSON Schema) path ─────────────────────────────
+
+class TestPrepareGeminiToolParameters:
+ def test_full_json_schema_survives_and_input_is_not_mutated(self):
+ params = {
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "type": "object",
+ "properties": {
+ "globs": {"anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}}]},
+ "bare_array": {"type": "array"},
+ "opts": {"type": "object", "additionalProperties": {"type": "string"}},
+ },
+ "required": ["globs"],
+ }
+ original = copy.deepcopy(params)
+ out = prepare_gemini_tool_parameters(params)
+ assert params == original
+ assert "$schema" not in out
+ assert out["properties"]["globs"]["anyOf"][1] == {"type": "array", "items": {"type": "string"}}
+ assert out["properties"]["bare_array"] == {"type": "array"}
+ assert out["properties"]["opts"]["additionalProperties"] == {"type": "string"}
+ assert prepare_gemini_tool_parameters({}) == {"type": "object", "properties": {}}
+
+ def test_local_refs_inlined_with_sibling_override_and_defs_dropped(self):
+ params = {
+ "type": "object",
+ "properties": {"user": {"$ref": "#/$defs/User", "description": "who"}},
+ "$defs": {"User": {"type": "object", "description": "generic", "properties": {
+ "tags": {"type": "array", "items": {"$ref": "#/$defs/Tag"}}}},
+ "Tag": {"type": "string"}},
+ }
+ out = prepare_gemini_tool_parameters(params)
+ assert "$defs" not in out
+ user = out["properties"]["user"]
+ assert user["description"] == "who"
+ assert user["properties"]["tags"]["items"] == {"type": "string"}
+
+ def test_unresolvable_or_circular_ref_passes_schema_through_untouched(self):
+ for defs in ({"Loop": {"type": "object", "properties": {"next": {"$ref": "#/$defs/Loop"}}}}, {}):
+ params = {"type": "object", "properties": {"p": {"$ref": "#/$defs/Loop"}}, "$defs": defs}
+ out = prepare_gemini_tool_parameters(params)
+ assert out["properties"]["p"] == {"$ref": "#/$defs/Loop"}
+ assert out["$defs"] == defs
+
+
+class TestAdapterWireShape:
+ _TOOLS = [{"type": "function", "function": {"name": "t", "parameters": {
+ "type": "object", "properties": {"g": {"anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}}]}}}}}]
+
+ def test_v1beta_sends_parameters_json_schema_other_versions_send_legacy_subset(self):
+ from agent.gemini_native_adapter import GeminiNativeClient
+
+ def decl(base_url):
+ client = GeminiNativeClient(api_key="k", base_url=base_url)
+ captured = {}
+ client._http = type("H", (), {"post": lambda self, url, json, headers, timeout: captured.update(json) or
+ type("R", (), {"status_code": 200, "json": lambda self: {"candidates": []}})()})()
+ client._create_chat_completion(model="gemini-2.5-flash", messages=[{"role": "user", "content": "hi"}], tools=self._TOOLS)
+ return captured["tools"][0]["functionDeclarations"][0]
+
+ beta = decl("https://generativelanguage.googleapis.com/v1beta")
+ assert "parameters" not in beta
+ assert beta["parametersJsonSchema"]["properties"]["g"]["anyOf"][1]["items"] == {"type": "string"}
+ v1 = decl("https://generativelanguage.googleapis.com/v1")
+ assert "parametersJsonSchema" not in v1
+ assert v1["parameters"]["properties"]["g"]["anyOf"] # legacy translator still applied