Skip to content

Your lightweight open-source personal agent.

fix: 执行 null 参数的类型和枚举校验

Shuhan Si9ea3268dfb1f
diff --git a/nanobot/agent/tools/base.py b/nanobot/agent/tools/base.py
index e88e52ef1..4618af2e8 100644
--- a/nanobot/agent/tools/base.py
+++ b/nanobot/agent/tools/base.py
@@ -76,7 +76,11 @@ class Schema(ABC):
t = Schema.resolve_json_schema_type(raw_type)
if nullable and val is None:
+ if "enum" in schema and val not in schema["enum"]:
+ return [f"{label} must be one of {schema['enum']}"]
return []
+ if (raw_type == "null" or raw_type == ["null"]) and val is not None:
+ return [f"{label} should be null"]
if isinstance(raw_type, list):
types = [item for item in cast(list[Any], raw_type) if item != "null"]
if len(types) > 1:
diff --git a/tests/tools/test_tool_validation.py b/tests/tools/test_tool_validation.py
index d3ff4cc78..0c2da1653 100644
--- a/tests/tools/test_tool_validation.py
+++ b/tests/tools/test_tool_validation.py
@@ -918,6 +918,36 @@ def test_resolve_type_union_with_null() -> None:
assert Tool._resolve_type(["string", "null"]) == "string"
[email protected]("raw_type", ["null", ["null"]])
[email protected]("value", ["", 0, False, [], {}])
+def test_null_only_schema_rejects_non_null_values(raw_type, value) -> None:
+ schema = {"type": raw_type}
+ assert Schema.validate_json_schema_value(value, schema, "value") == [
+ "value should be null"
+ ]
+ assert Schema.validate_json_schema_value(None, schema) == []
+
+
+ "schema",
+ [
+ {"type": ["string", "null"], "enum": ["fast"]},
+ {"type": "string", "nullable": True, "enum": ["fast"]},
+ {"type": ["integer", "null"], "enum": [1]},
+ ],
+)
+def test_nullable_schema_still_enforces_enum(schema) -> None:
+ assert Schema.validate_json_schema_value(None, schema, "mode") == [
+ f"mode must be one of {schema['enum']}"
+ ]
+ assert Schema.validate_json_schema_value(None, {**schema, "enum": [None]}) == []
+
+
+def test_nullable_string_schema_enforces_enum() -> None:
+ assert StringSchema(nullable=True, enum=["fast"]).validate_value(None)
+ assert StringSchema(nullable=True, enum=["fast", None]).validate_value(None) == []
+
+
def test_resolve_type_only_null() -> None:
"""Union type ['null'] resolves to None (no non-null type)."""
assert Tool._resolve_type(["null"]) is None