Skip to content

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

fix(_utils): keep nested arguments that schema-guided repair drops (#2712)

林SOb3cdee49c6b4
diff --git a/src/agentscope/_utils/_common.py b/src/agentscope/_utils/_common.py
index 1e94f9970..ff83e0fcf 100644
--- a/src/agentscope/_utils/_common.py
+++ b/src/agentscope/_utils/_common.py
@@ -92,6 +92,22 @@ def _normalize_local_path(path: str) -> str:
return os.path.abspath(os.path.expanduser(path))
+def _has_dropped_keys(original: Any, repaired: Any) -> bool:
+ """Whether any dict in ``repaired`` lost a key it has in ``original``."""
+ if isinstance(original, dict) and isinstance(repaired, dict):
+ return bool(original.keys() - repaired.keys()) or any(
+ _has_dropped_keys(original[key], value)
+ for key, value in repaired.items()
+ if key in original
+ )
+ if isinstance(original, list) and isinstance(repaired, list):
+ return any(
+ _has_dropped_keys(item, fixed)
+ for item, fixed in zip(original, repaired)
+ )
+ return False
+
+
def _json_loads_with_repair(
json_str: str,
schema: dict | None = None,
@@ -175,7 +191,7 @@ def _json_loads_with_repair(
res = parsed
if isinstance(res, dict):
- if isinstance(parsed, dict) and parsed.keys() - res.keys():
+ if isinstance(parsed, dict) and _has_dropped_keys(parsed, res):
# Dropping arguments, e.g. under `additionalProperties:
# false`, is a rewrite rather than a type repair.
res = parsed
diff --git a/tests/tool_argument_repair_test.py b/tests/tool_argument_repair_test.py
index 072532bf5..f36ab1ce6 100644
--- a/tests/tool_argument_repair_test.py
+++ b/tests/tool_argument_repair_test.py
@@ -113,6 +113,59 @@ class JsonLoadsWithRepairTest(unittest.TestCase):
),
{"count": "42", "verbse": True},
)
+ # ...also when the dropped argument sits in a nested object
+ self.assertDictEqual(
+ _json_loads_with_repair(
+ '{"opts": {"unit": "C", "verbse": true}}',
+ {
+ "type": "object",
+ "properties": {
+ "opts": {
+ "type": "object",
+ "properties": {"unit": {"type": "string"}},
+ "additionalProperties": False,
+ },
+ },
+ },
+ ),
+ {"opts": {"unit": "C", "verbse": True}},
+ )
+ # ...or in an object inside an array
+ self.assertDictEqual(
+ _json_loads_with_repair(
+ '{"items": [{"unit": "C", "verbse": true}]}',
+ {
+ "type": "object",
+ "properties": {
+ "items": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {"unit": {"type": "string"}},
+ "additionalProperties": False,
+ },
+ },
+ },
+ },
+ ),
+ {"items": [{"unit": "C", "verbse": True}]},
+ )
+ # Type repairs inside a nested object still happen
+ self.assertDictEqual(
+ _json_loads_with_repair(
+ '{"opts": {"unit": 123}}',
+ {
+ "type": "object",
+ "properties": {
+ "opts": {
+ "type": "object",
+ "properties": {"unit": {"type": "string"}},
+ },
+ },
+ },
+ ),
+ {"opts": {"unit": "123"}},
+ )
def test_empty_arguments_are_an_empty_object(self) -> None:
"""Test that an empty argument payload is parsed as no arguments."""