Skip to content

The agent that grows with you

fix(agent): accumulate streamed tool arguments linearly

fangliquan390c27c6db16
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index 8fa0c18f8d4..dcdc3a79974 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -4244,6 +4244,7 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=
_conn_cap = min(_base_timeout, 60.0) if _provider_timeout_cfg is not None else 30.0
content_parts: list = []
tool_calls_acc: dict = {}
+ tool_argument_parts: dict[int, list[str]] = {}
tool_gen_notified: set = set()
# Ollama-compatible endpoints reuse index 0 for every tool call
# in a parallel batch, distinguishing them only by id. Track
@@ -4350,7 +4351,12 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=
last_chunk_time["t"] = time.time()
return True
+ def _materialize_tool_arguments() -> None:
+ for index, parts in tool_argument_parts.items():
+ tool_calls_acc[index]["function"]["arguments"] = "".join(parts)
+
def _relay_final_response() -> dict[str, Any]:
+ _materialize_tool_arguments()
tool_calls = [tool_calls_acc[index] for index in sorted(tool_calls_acc)]
return {
"model": model_name,
@@ -4619,6 +4625,7 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=
"function": {"name": "", "arguments": ""},
"extra_content": None,
}
+ tool_argument_parts[idx] = []
entry = tool_calls_acc[idx]
tc_id = getattr(tc_delta, "id", None)
if tc_id is not None:
@@ -4642,7 +4649,7 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=
entry["function"]["name"] = function_name
function_arguments = getattr(tc_function, "arguments", None)
if function_arguments:
- entry["function"]["arguments"] += function_arguments
+ tool_argument_parts[idx].append(function_arguments)
extra = getattr(tc_delta, "extra_content", None)
if extra is None and hasattr(tc_delta, "model_extra"):
extra = (tc_delta.model_extra if isinstance(tc_delta.model_extra, dict) else {}).get("extra_content")
@@ -4718,6 +4725,7 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=
mock_tool_calls = None
has_truncated_tool_args = False
if tool_calls_acc:
+ _materialize_tool_arguments()
mock_tool_calls = []
for idx in sorted(tool_calls_acc):
tc = tool_calls_acc[idx]
diff --git a/tests/run_agent/test_streaming.py b/tests/run_agent/test_streaming.py
index e5b0471e64b..1eda813e777 100644
--- a/tests/run_agent/test_streaming.py
+++ b/tests/run_agent/test_streaming.py
@@ -305,6 +305,57 @@ class TestStreamingAccumulator:
assert tc[0].function.name == "terminal"
assert tc[0].function.arguments == '{"command": "ls"}'
+ @patch("run_agent.AIAgent._create_request_openai_client")
+ @patch("run_agent.AIAgent._close_request_openai_client")
+ def test_tool_argument_deltas_are_collected_without_concatenating_each_chunk(
+ self, mock_close, mock_create
+ ):
+ """Large tool arguments must not rebuild the accumulated string per delta."""
+ from run_agent import AIAgent
+
+ class AppendOnlyChunk(str):
+ def __radd__(self, other):
+ raise AssertionError("tool argument delta was concatenated eagerly")
+
+ chunks = [
+ _make_stream_chunk(tool_calls=[
+ _make_tool_call_delta(
+ index=0, tc_id="call_123", name="write_file"
+ )
+ ]),
+ _make_stream_chunk(tool_calls=[
+ _make_tool_call_delta(
+ index=0, arguments=AppendOnlyChunk('{"path":"out.txt",')
+ )
+ ]),
+ _make_stream_chunk(tool_calls=[
+ _make_tool_call_delta(
+ index=0, arguments=AppendOnlyChunk('"content":"hello"}')
+ )
+ ]),
+ _make_stream_chunk(finish_reason="tool_calls"),
+ ]
+ mock_client = MagicMock()
+ mock_client.chat.completions.create.return_value = iter(chunks)
+ mock_create.return_value = mock_client
+ agent = AIAgent(
+ api_key="test-key",
+ base_url="https://openrouter.ai/api/v1",
+ model="test/model",
+ quiet_mode=True,
+ skip_context_files=True,
+ skip_memory=True,
+ )
+ agent.api_mode = "chat_completions"
+ agent._interrupt_requested = False
+
+ response = agent._interruptible_streaming_api_call({})
+
+ tool_call = response.choices[0].message.tool_calls[0]
+ assert tool_call.function.arguments == (
+ '{"path":"out.txt","content":"hello"}'
+ )
+