fix(agent): 空字符串联合参数归一为 null (#7339)

This commit is contained in:
pyss56
2026-11-09 15:06:15 +08:00
committed by GitHub
parent 7baa3b6f94
commit b44af19e8d
2 changed files with 35 additions and 0 deletions

View File

@@ -236,6 +236,11 @@ def _normalize_union(value: Any, schema: dict[str, Any], definitions: dict[str,
exact = [item for item in alternatives if item.get("type") == _value_type(value)]
if len(exact) == 1:
return _normalize_value(value, exact[0], definitions, depth + 1)
# 空字符串表示模型未提供该值;仅在没有精确类型分支且联合含 null 时归一为 None,
# 保留 anyOf[string, null] 等以空字符串为合法值的语义。
if not exact and isinstance(value, str) and not value.strip():
if any(item.get("type") == "null" for item in alternatives):
return None
candidates = []
for option in exact or alternatives:
try:

View File

@@ -0,0 +1,30 @@
"""
验证 agent API 参数合同对空字符串联合参数的类型归一行为。
"""
from app.agent.api.arguments import _normalize_value
def test_empty_string_with_null_union_normalizes_to_none():
"""
空字符串在 anyOf[integer, null] 下表示模型未提供该值,归一为 None。
"""
schema = {"anyOf": [{"type": "integer"}, {"type": "null"}]}
assert _normalize_value("", schema, {}) is None
assert _normalize_value(" ", schema, {}) is None
def test_empty_string_with_string_union_is_preserved():
"""
anyOf[string, null] 的空字符串本身是合法值,不应被改成 None。
"""
schema = {"anyOf": [{"type": "string"}, {"type": "null"}]}
assert _normalize_value("", schema, {}) == ""
def test_integer_union_still_accepts_integer():
"""
正常整数输入不受空字符串容错影响。
"""
schema = {"anyOf": [{"type": "integer"}, {"type": "null"}]}
assert _normalize_value(3, schema, {}) == 3