Skip to content

The agent that grows with you

fix(agent): canonicalize duplicate tool call arguments

fangliquanflqa55d29d9fb35
diff --git a/run_agent.py b/run_agent.py
index 41efbe35a0c..8326517472a 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -4877,13 +4877,23 @@ class AIAgent:
def _deduplicate_tool_calls(tool_calls: list) -> list:
"""Remove duplicate (tool_name, arguments) pairs within a single turn.
- Only the first occurrence of each unique pair is kept.
+ Valid JSON arguments are canonicalized so equivalent objects do not
+ evade deduplication merely because their keys or whitespace differ.
+ Malformed arguments retain their raw representation rather than being
+ repaired here. Only the first occurrence of each unique pair is kept.
Returns the original list if no duplicates were found.
"""
seen: set = set()
unique: list = []
for tc in tool_calls:
- key = (tc.function.name, tc.function.arguments)
+ arguments = tc.function.arguments
+ try:
+ arguments = json.dumps(
+ json.loads(arguments), separators=(",", ":"), sort_keys=True
+ )
+ except (TypeError, ValueError):
+ pass
+ key = (tc.function.name, arguments)
if key not in seen:
seen.add(key)
unique.append(tc)
diff --git a/tests/run_agent/test_agent_guardrails.py b/tests/run_agent/test_agent_guardrails.py
index c81b341b8bb..e94363089f7 100644
--- a/tests/run_agent/test_agent_guardrails.py
+++ b/tests/run_agent/test_agent_guardrails.py
@@ -181,6 +181,37 @@ class TestDeduplicateToolCalls:
out = AIAgent._deduplicate_tool_calls(tcs)
assert len(out) == 1
+ def test_duplicate_json_objects_with_reordered_keys_deduplicated(self):
+ first = make_tc(
+ "terminal",
+ '{"command":"printf hello >> out.log","timeout":10}',
+ )
+ second = make_tc(
+ "terminal",
+ '{"timeout":10,"command":"printf hello >> out.log"}',
+ )
+
+ out = AIAgent._deduplicate_tool_calls([first, second])
+
+ assert out == [first]
+
+ def test_distinct_json_arguments_are_preserved(self):
+ first = make_tc("terminal", '{"command":"one","timeout":10}')
+ second = make_tc("terminal", '{"timeout":10,"command":"two"}')
+
+ out = AIAgent._deduplicate_tool_calls([first, second])
+
+ assert out == [first, second]
+
+ def test_malformed_arguments_use_raw_string_for_deduplication(self):
+ first = make_tc("terminal", '{"command":"one"')
+ duplicate = make_tc("terminal", '{"command":"one"')
+ distinct = make_tc("terminal", '{ "command":"one"')
+
+ out = AIAgent._deduplicate_tool_calls([first, duplicate, distinct])
+
+ assert out == [first, distinct]
+