Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(gemini): add _sanitize_schema_for_gemini to strip Gemini-incompatible JSON Schema constructs (#1886)
qbc5bc79ee264f2
diff --git a/src/agentscope/model/_gemini/_model.py b/src/agentscope/model/_gemini/_model.pyindex 66fde201e..0b491954e 100644--- a/src/agentscope/model/_gemini/_model.py+++ b/src/agentscope/model/_gemini/_model.py@@ -76,6 +76,78 @@ def _flatten_json_schema(schema: dict) -> dict:return _resolve_ref(schema)+def _sanitize_schema_for_gemini(schema: Any) -> Any:+ """Sanitize a JSON schema to be compatible with the Gemini API.++ Gemini API does not support certain JSON Schema constructs. This+ function removes or rewrites the following:++ - ``additionalProperties``: removed entirely.+ - ``anyOf`` containing a ``{"type": "null"}`` entry: simplified to+ the single non-null type. If there is exactly one non-null+ alternative it is inlined directly; otherwise the ``anyOf`` is+ kept but the null entry is dropped.+ - All nested sub-schemas (``properties``, ``items``, ``$defs``,+ etc.) are processed recursively.++ Args:+ schema (`Any`):+ The JSON schema to sanitize. Non-dict values are returned+ unchanged; lists are recursively sanitized element-wise.++ Returns:+ `Any`:+ A sanitized copy of the schema, or the original value if it+ is not a dict or list.+ """+ if not isinstance(schema, dict):+ if isinstance(schema, list):+ return [_sanitize_schema_for_gemini(v) for v in schema]+ return schema++ schema = dict(schema)++ # Remove additionalProperties — not supported by Gemini+ schema.pop("additionalProperties", None)++ # Simplify anyOf that only differs by a null type, e.g. Optional[X]+ if "anyOf" in schema and isinstance(schema["anyOf"], list):+ any_of = schema["anyOf"]+ non_null = [v for v in any_of if v != {"type": "null"}]+ if len(non_null) < len(any_of): # at least one null entry removed+ if len(non_null) == 1:+ # Inline the single non-null type, preserving outer keys+ merged = dict(_sanitize_schema_for_gemini(non_null[0]))+ for k, v in schema.items():+ if k != "anyOf":+ merged.setdefault(k, v)+ return merged+ elif non_null:+ schema["anyOf"] = [+ _sanitize_schema_for_gemini(v) for v in non_null+ ]+ else:+ del schema["anyOf"]++ # Recursively process nested object schemas+ for key in ["properties", "patternProperties", "$defs"]:+ if key in schema and isinstance(schema[key], dict):+ schema[key] = {+ k: _sanitize_schema_for_gemini(v)+ for k, v in schema[key].items()+ }++ for key in ["items", "not", "if", "then", "else"]:+ if key in schema:+ schema[key] = _sanitize_schema_for_gemini(schema[key])++ for key in ["allOf", "oneOf", "anyOf"]:+ if key in schema and isinstance(schema[key], list):+ schema[key] = [_sanitize_schema_for_gemini(v) for v in schema[key]]++ return schema++class GeminiChatModel(ChatModelBase):"""The Google Gemini chat model."""@@ -524,8 +596,8 @@ class GeminiChatModel(ChatModelBase):continuefunc = schema["function"].copy()if "parameters" in func:- func["parameters"] = _flatten_json_schema(- func["parameters"],+ func["parameters"] = _sanitize_schema_for_gemini(+ _flatten_json_schema(func["parameters"]),)function_declarations.append(func)fmt_tools = [{"function_declarations": function_declarations}]diff --git a/tests/model_gemini_test.py b/tests/model_gemini_test.pyindex f587d5ee0..ad91ee9f1 100644--- a/tests/model_gemini_test.py+++ b/tests/model_gemini_test.py@@ -15,6 +15,10 @@ from utils import AnyStringfrom agentscope.message import TextBlock, ToolCallBlock, ThinkingBlockfrom agentscope.model import GeminiChatModel+from agentscope.model._gemini._model import (+ _flatten_json_schema,+ _sanitize_schema_for_gemini,+)from agentscope.credential import GeminiCredentialfrom agentscope.tool import ToolChoice@@ -531,3 +535,119 @@ class TestGeminiFormatTools(unittest.TestCase):fmt_tools, fmt_choice = self.model._format_tools(_FT_TOOLS, None)self.assertEqual(fmt_tools, _FT_TOOLS_GEMINI)self.assertIsNone(fmt_choice)+++# ---------------------------------------------------------------------------+# Tests for _sanitize_schema_for_gemini and _flatten_json_schema+# ---------------------------------------------------------------------------+++class TestGeminiSchemaUtils(unittest.TestCase):+ """Tests for _sanitize_schema_for_gemini and _flatten_json_schema."""++ def test_sanitize_removes_additional_properties_and_inlines_optional(+ self,+ ) -> None:+ """additionalProperties removed; anyOf[X, null] inlined to X."""+ self.assertEqual(+ _sanitize_schema_for_gemini(+ {+ "description": "x",+ "anyOf": [{"type": "string"}, {"type": "null"}],+ },+ ),+ {"type": "string", "description": "x"},+ )+ self.assertEqual(+ _sanitize_schema_for_gemini(+ {"type": "object", "additionalProperties": False},+ ),+ {"type": "object"},+ )++ def test_sanitize_pydantic_optional_list_dict(self) -> None:+ """End-to-end: Pydantic Optional[list[dict]] schema is cleaned."""+ result = _sanitize_schema_for_gemini(+ {+ "type": "object",+ "additionalProperties": False,+ "properties": {+ "actions": {+ "description": "List of actions",+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": True,+ },+ },+ {"type": "null"},+ ],+ },+ },+ },+ )+ self.assertEqual(+ result,+ {+ "type": "object",+ "properties": {+ "actions": {+ "type": "array",+ "description": "List of actions",+ "items": {"type": "object"},+ },+ },+ },+ )++ def test_flatten_resolves_ref_and_removes_defs(self) -> None:+ """$ref inlined with extra keys merged; $defs removed."""+ self.assertEqual(+ _flatten_json_schema(+ {+ "$defs": {"Name": {"type": "string"}},+ "properties": {+ "name": {+ "$ref": "#/$defs/Name",+ "description": "The name",+ },+ },+ },+ ),+ {+ "properties": {+ "name": {"type": "string", "description": "The name"},+ },+ },+ )++ def test_flatten_circular_ref_returns_placeholder(self) -> None:+ """Circular $ref produces a placeholder without infinite recursion."""+ self.assertEqual(+ _flatten_json_schema(+ {+ "$defs": {+ "Node": {+ "type": "object",+ "properties": {"child": {"$ref": "#/$defs/Node"}},+ },+ },+ "properties": {"root": {"$ref": "#/$defs/Node"}},+ },+ ),+ {+ "properties": {+ "root": {+ "type": "object",+ "properties": {+ "child": {+ "type": "object",+ "description": "(circular: Node)",+ },+ },+ },+ },+ },+ )