Skip to content

The agent that grows with you

fix(agent): copy-on-write for SDK-object tool calls in _repair_invalid_tool_call_names

teknium162277ebe2956
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 479409312df..d92f0cb7955 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -2690,8 +2690,8 @@ def _repair_invalid_tool_call_names(messages: List[Dict[str, Any]]) -> None:
dispatch loop keeps for it); an invalid one (``multi_tool_use.parallel``, a shell command a weak
fallback model put in ``name``) is coerced deterministically, because one such stored turn 400s
every later request on a strict endpoint and pins the session to the fallback model (#51944).
- Dict tool calls are rewritten copy-on-write so a shallow per-call copy never edits persisted
- history; tool results follow via ``_realign_tool_result_names``."""
+ Tool calls are rewritten copy-on-write (an SDK object becomes a dict copy) so a shallow per-call
+ copy never edits persisted history; tool results follow via ``_realign_tool_result_names``."""
for msg in messages:
if msg.get("role") != "assistant":
continue
@@ -2710,14 +2710,18 @@ def _repair_invalid_tool_call_names(messages: List[Dict[str, Any]]) -> None:
"Pre-call sanitizer: repairing tool_call with invalid function.name %r -> %r (id=%s)",
(name or "")[:80], coerced, _ra().AIAgent._get_tool_call_id_static(tc),
)
+ if tcs is msg.get("tool_calls"):
+ tcs = msg["tool_calls"] = list(tcs)
if isinstance(tc, dict):
- if tcs is msg.get("tool_calls"):
- tcs = msg["tool_calls"] = list(tcs)
fn = {**fn, "name": coerced} if isinstance(fn, dict) else {"name": coerced, "arguments": "{}"}
tcs[idx] = {**tc, "function": fn}
- elif fn is not None and hasattr(fn, "name"):
- with contextlib.suppress(Exception):
- fn.name = coerced
+ else:
+ args = getattr(fn, "arguments", None) if fn is not None else None
+ tcs[idx] = {
+ "id": _ra().AIAgent._get_tool_call_id_static(tc),
+ "type": "function",
+ "function": {"name": coerced, "arguments": args if isinstance(args, str) else "{}"},
+ }
def _drop_results_without_ids(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
diff --git a/tests/agent/test_agent_guardrails.py b/tests/agent/test_agent_guardrails.py
index 6dbcda3d135..0e7aed9e9b0 100644
--- a/tests/agent/test_agent_guardrails.py
+++ b/tests/agent/test_agent_guardrails.py
@@ -122,6 +122,20 @@ class TestSanitizeApiMessages:
assert stored_call["function"]["name"] == "multi_tool_use.parallel"
assert out[1]["name"] == "multi_tool_use_parallel"
+ def test_invalid_sdk_object_tool_call_name_coerced_without_mutation(self):
+ """An SDK-object tool call with an invalid name is replaced by a dict copy on the per-call
+ copy; the stored object's ``function.name`` is never mutated in place."""
+ fn = types.SimpleNamespace(name="multi_tool_use.parallel", arguments='{"x": 1}')
+ tc_obj = types.SimpleNamespace(id="c1", function=fn)
+ stored = {"role": "assistant", "tool_calls": [tc_obj]}
+ out = AIAgent._sanitize_api_messages([dict(stored), tool_result("c1")])
+ assert out[0]["tool_calls"][0] == {
+ "id": "c1", "type": "function",
+ "function": {"name": "multi_tool_use_parallel", "arguments": '{"x": 1}'},
+ }
+ assert fn.name == "multi_tool_use.parallel"
+ assert stored["tool_calls"][0] is tc_obj
+
def test_sdk_object_tool_calls(self):
tc_obj = types.SimpleNamespace(id="c6", function=types.SimpleNamespace(