Skip to content

Build and run agents you can see, understand and trust.

fix(gemini): sanitize nullable type arrays (#2437)

Todde90f1c759289
diff --git a/src/agentscope/model/_gemini/_model.py b/src/agentscope/model/_gemini/_model.py
index 37f0607f4..c07902f03 100644
--- a/src/agentscope/model/_gemini/_model.py
+++ b/src/agentscope/model/_gemini/_model.py
@@ -22,6 +22,14 @@ else:
GenerateContentResponse = Any
+def _is_null_schema(schema: Any) -> bool:
+ """Return whether a schema represents only JSON null."""
+ return isinstance(schema, dict) and schema.get("type") in (
+ "null",
+ ["null"],
+ )
+
+
def _sanitize_schema_for_gemini(schema: Any) -> Any:
"""Sanitize a JSON schema to be compatible with the Gemini API.
@@ -32,6 +40,11 @@ def _sanitize_schema_for_gemini(schema: Any) -> Any:
- ``additionalProperties``: removed entirely.
- ``const``: converted to an equivalent single-value ``enum``,
since Gemini's ``Schema`` model does not support ``const``.
+ - ``type`` arrays containing ``"null"``: simplified to the single
+ non-null type or converted to ``anyOf`` for multiple non-null
+ types, matching nullable JSON Schema emitted by Pydantic and
+ OpenAPI 3.1. Multi-type arrays with an existing ``anyOf`` raise
+ ``ValueError`` rather than dropping conjunctive constraints.
- ``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
@@ -63,8 +76,22 @@ def _sanitize_schema_for_gemini(schema: Any) -> Any:
# functionDeclaration property type. Some MCP servers emit
# {"type": "null"} directly (not wrapped in anyOf) for parameters that
# accept None — rewrite it to "object" so it round-trips through the API.
- if schema.get("type") == "null":
+ if _is_null_schema(schema):
schema["type"] = "object"
+ elif isinstance(schema.get("type"), list):
+ non_null_types = [v for v in schema["type"] if v != "null"]
+ if len(non_null_types) == 1:
+ schema["type"] = non_null_types[0]
+ elif non_null_types:
+ if "anyOf" in schema:
+ raise ValueError(
+ "Cannot safely sanitize Gemini schema with both a "
+ "multi-type nullable type array and anyOf.",
+ )
+ schema.pop("type")
+ schema["anyOf"] = [{"type": type_} for type_ in non_null_types]
+ else:
+ schema["type"] = "object"
# Remove additionalProperties — not supported by Gemini
schema.pop("additionalProperties", None)
@@ -78,7 +105,7 @@ def _sanitize_schema_for_gemini(schema: Any) -> Any:
# 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"}]
+ non_null = [v for v in any_of if not _is_null_schema(v)]
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
diff --git a/tests/model_gemini_test.py b/tests/model_gemini_test.py
index d0ce125f9..b21dcbdd0 100644
--- a/tests/model_gemini_test.py
+++ b/tests/model_gemini_test.py
@@ -763,6 +763,91 @@ class TestGeminiSchemaUtils(unittest.TestCase):
{"type": "object"},
)
+ def test_sanitize_inlines_nullable_type_array(self) -> None:
+ """JSON Schema type arrays with null are inlined for Gemini."""
+ self.assertEqual(
+ _sanitize_schema_for_gemini(
+ {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": ["string", "null"],
+ "description": "Optional name",
+ },
+ },
+ },
+ ),
+ {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Optional name",
+ },
+ },
+ },
+ )
+
+ def test_sanitize_converts_nullable_union_type_array_to_anyof(
+ self,
+ ) -> None:
+ """Nullable type arrays with multiple non-null types use anyOf."""
+ self.assertEqual(
+ _sanitize_schema_for_gemini(
+ {
+ "type": ["string", "integer", "null"],
+ "description": "String or integer identifier",
+ },
+ ),
+ {
+ "anyOf": [
+ {"type": "string"},
+ {"type": "integer"},
+ ],
+ "description": "String or integer identifier",
+ },
+ )
+
+ def test_sanitize_rejects_ambiguous_type_array_with_anyof(
+ self,
+ ) -> None:
+ """Existing anyOf constraints are not overwritten silently."""
+ with self.assertRaisesRegex(
+ ValueError,
+ "multi-type nullable type array and anyOf",
+ ):
+ _sanitize_schema_for_gemini(
+ {
+ "type": ["string", "integer", "null"],
+ "anyOf": [
+ {"enum": ["auto"]},
+ {"enum": [0]},
+ {"type": "null"},
+ ],
+ },
+ )
+
+ def test_sanitize_inlines_annotated_null_anyof(self) -> None:
+ """Annotated null schemas in anyOf are treated as null branches."""
+ self.assertEqual(
+ _sanitize_schema_for_gemini(
+ {
+ "description": "Optional name",
+ "anyOf": [
+ {"type": "string"},
+ {
+ "type": "null",
+ "description": "No value",
+ },
+ ],
+ },
+ ),
+ {
+ "type": "string",
+ "description": "Optional name",
+ },
+ )
+
def test_sanitize_pydantic_optional_list_dict(self) -> None:
"""End-to-end: Pydantic Optional[list[dict]] schema is cleaned."""
result = _sanitize_schema_for_gemini(