DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(chat): assign streamed tool-call ids instead of appending them
Bingxi Zhao (Frank)9e4233c3ae77
diff --git a/deeptutor/agents/chat/agent_loop.py b/deeptutor/agents/chat/agent_loop.pyindex 2fdd42bd4..868e04f10 100644--- a/deeptutor/agents/chat/agent_loop.py+++ b/deeptutor/agents/chat/agent_loop.py@@ -38,6 +38,7 @@ from deeptutor.agents._shared.capability_result import emit_capability_resultfrom deeptutor.agents.chat.context_budget import LLMRequestSnapshotfrom deeptutor.agents.chat.dsml_tool_calls import DSMLStreamFilter, extract_dsml_tool_callsfrom deeptutor.core.agentic.messages import assistant_message_with_tool_calls+from deeptutor.core.agentic.tool_call_stream import ToolCallAccumulatorfrom deeptutor.core.agentic.tool_dispatch import DispatchOutcomefrom deeptutor.core.agentic.usage import message_content_chars, record_streamed_usagefrom deeptutor.core.context import UnifiedContext@@ -656,7 +657,7 @@ class AgentLoop:# once, only after a successful attempt.usage_seen: Any = Nonetext_parts: list[str] = []- tool_acc: dict[int, dict[str, str]] = {}+ tool_acc = ToolCallAccumulator()output_chars = 0finish_reason = ""think_filter = InlineThinkFilter()@@ -724,25 +725,7 @@ class AgentLoop:await _emit_segments(think_filter.feed(visible_content))for tc_delta in getattr(delta, "tool_calls", None) or []:- index = int(getattr(tc_delta, "index", 0) or 0)- acc = tool_acc.setdefault(- index,- {"id": "", "name": "", "arguments": ""},- )- tcid = getattr(tc_delta, "id", None)- if tcid:- acc["id"] += str(tcid)- fn = getattr(tc_delta, "function", None)- if fn is None:- continue- name = getattr(fn, "name", None)- arguments = getattr(fn, "arguments", None)- if name:- acc["name"] += str(name)- output_chars += len(str(name))- if arguments:- acc["arguments"] += str(arguments)- output_chars += len(str(arguments))+ output_chars += tool_acc.feed(tc_delta)except Exception as exc:if not is_transient_transport_error(exc):raise@@ -824,15 +807,7 @@ class AgentLoop:output_chars=output_chars,)- tool_calls = [- {- "id": data.get("id") or f"call_{idx}",- "name": data.get("name", ""),- "arguments": data.get("arguments") or "{}",- }- for idx, data in sorted(tool_acc.items())- if data.get("name")- ]+ tool_calls = tool_acc.collected()# Fallback: a DeepSeek deployment without native function calling emits# its tool calls as DSML markup in the content channel instead of asdiff --git a/deeptutor/capabilities/explore_context/explorer.py b/deeptutor/capabilities/explore_context/explorer.pyindex 1e430d82b..a85f6d0a9 100644--- a/deeptutor/capabilities/explore_context/explorer.py+++ b/deeptutor/capabilities/explore_context/explorer.py@@ -37,6 +37,7 @@ from deeptutor.core.agentic import (dispatch_tool_calls,)from deeptutor.core.agentic.messages import assistant_message_with_tool_calls+from deeptutor.core.agentic.tool_call_stream import ToolCallAccumulatorfrom deeptutor.core.context import UnifiedContextfrom deeptutor.core.stream_bus import StreamBusfrom deeptutor.core.trace import build_trace_metadata, merge_trace_metadata, new_call_id@@ -277,7 +278,7 @@ class ContextExplorer:kwargs["tool_choice"] = "auto"text_parts: list[str] = []- tool_acc: dict[int, dict[str, str]] = {}+ tool_acc = ToolCallAccumulator()output_chars = 0response_stream = await client.chat.completions.create(**kwargs)try:@@ -304,37 +305,14 @@ class ContextExplorer:content, source=EXPLORE_SOURCE, stage=EXPLORE_STAGE, metadata=chunk_meta)for tc in getattr(delta, "tool_calls", None) or []:- index = int(getattr(tc, "index", 0) or 0)- acc = tool_acc.setdefault(index, {"id": "", "name": "", "arguments": ""})- tcid = getattr(tc, "id", None)- if tcid:- acc["id"] += str(tcid)- fn = getattr(tc, "function", None)- if fn is None:- continue- name = getattr(fn, "name", None)- arguments = getattr(fn, "arguments", None)- if name:- acc["name"] += str(name)- output_chars += len(str(name))- if arguments:- acc["arguments"] += str(arguments)- output_chars += len(str(arguments))+ output_chars += tool_acc.feed(tc)finally:close = getattr(response_stream, "close", None)if callable(close):with suppress(Exception):await close()- tool_calls = [- {- "id": data.get("id") or f"call_{idx}",- "name": data.get("name", ""),- "arguments": data.get("arguments") or "{}",- }- for idx, data in sorted(tool_acc.items())- if data.get("name")- ]+ tool_calls = tool_acc.collected()return _CallResult(text="".join(text_parts), tool_calls=tool_calls, output_chars=output_chars)diff --git a/deeptutor/core/agentic/labeled_step.py b/deeptutor/core/agentic/labeled_step.pyindex 56a6fd312..3f8a7cfb1 100644--- a/deeptutor/core/agentic/labeled_step.py+++ b/deeptutor/core/agentic/labeled_step.py@@ -44,6 +44,7 @@ from deeptutor.core.agentic.labels import (classify_label,strip_label_probe_prefix,)+from deeptutor.core.agentic.tool_call_stream import ToolCallAccumulatorfrom deeptutor.core.agentic.usage import (UsageTracker,message_content_chars,@@ -171,7 +172,7 @@ async def run_labeled_step(saw_pre_label_think = Falsesub_trace_opened = Falsecontent_acc: list[str] = []- tc_acc: dict[int, dict[str, Any]] = {}+ tc_acc = ToolCallAccumulator()usage_seen: Any = Noneoutput_chars_seen = 0finish_reason_seen: str | None = None@@ -492,19 +493,7 @@ async def run_labeled_step(await _emit_text(text)for tc_delta in getattr(delta, "tool_calls", None) or []:- fn_for_chars = getattr(tc_delta, "function", None)- output_chars_seen += len(str(getattr(fn_for_chars, "name", "") or ""))- output_chars_seen += len(str(getattr(fn_for_chars, "arguments", "") or ""))- idx = getattr(tc_delta, "index", 0)- entry = tc_acc.setdefault(idx, {"id": "", "name": "", "arguments": ""})- if getattr(tc_delta, "id", None):- entry["id"] = tc_delta.id- fn = getattr(tc_delta, "function", None)- if fn is not None:- if getattr(fn, "name", None):- entry["name"] = entry["name"] + fn.name- if getattr(fn, "arguments", None):- entry["arguments"] = entry["arguments"] + fn.arguments+ output_chars_seen += tc_acc.feed(tc_delta)finally:close = getattr(response_stream, "close", None)if callable(close):@@ -561,6 +550,6 @@ async def run_labeled_step(# pre-label thinking.if binding or saw_pre_label_think:text = clean_thinking_tags(text, binding, model)- ordered_tool_calls = [tc_acc[k] for k in sorted(tc_acc.keys())]+ ordered_tool_calls = tc_acc.ordered()ordered_tool_calls = [tc for tc in ordered_tool_calls if tc.get("name")]return LabeledStepResult(label=label, text=text, tool_calls=ordered_tool_calls)diff --git a/deeptutor/core/agentic/tool_call_stream.py b/deeptutor/core/agentic/tool_call_stream.pynew file mode 100644index 000000000..f47844ce4--- /dev/null+++ b/deeptutor/core/agentic/tool_call_stream.py@@ -0,0 +1,84 @@+"""Accumulate OpenAI-compatible streaming tool-call deltas.++Three call sites replay the same provider wire protocol — the chat agent+loop, the explore capability, and the labeled step runner — so the rule for+each field is stated here once instead of being restated per site:++* ``id`` and ``name`` arrive **complete** on whichever delta carries them.+ A provider may repeat them on every subsequent chunk. Assign, never append.+* ``arguments`` arrives as **fragments** that must be concatenated.++Appending a complete field is issue #937: a router that re-sent ``id`` on+every chunk grew it to 47241 characters, far past the 64-character limit the+provider itself enforces, so the round died with HTTP 400 and the user got+the "could not produce a useful response" fallback. The same append also+corrupted ``name`` into ``toolnametoolnametoolname``, which no registry can+resolve — latent for that reporter's gateway, fatal for any gateway that+repeats the name.++The services-layer provider keeps its own accumulator+(``openai_compat_provider._accum_tc``): it already applies these same rules+and reads deltas that may be plain dicts rather than SDK objects, so folding+it in here would widen the blast radius without fixing anything.+"""++from __future__ import annotations++from typing import Any++__all__ = ["ToolCallAccumulator"]+++class ToolCallAccumulator:+ """Fold a stream of ``delta.tool_calls`` entries into whole tool calls."""++ def __init__(self) -> None:+ self._parts: dict[int, dict[str, str]] = {}++ def feed(self, tc_delta: Any) -> int:+ """Fold one tool-call delta in; return the characters it contributed.++ The count covers ``name`` and ``arguments`` only, matching what+ callers bill as provider output.+ """+ index = int(getattr(tc_delta, "index", 0) or 0)+ part = self._parts.setdefault(index, {"id": "", "name": "", "arguments": ""})++ tcid = getattr(tc_delta, "id", None)+ if tcid:+ part["id"] = str(tcid)++ fn = getattr(tc_delta, "function", None)+ if fn is None:+ return 0++ chars = 0+ name = getattr(fn, "name", None)+ if name:+ part["name"] = str(name)+ chars += len(str(name))+ arguments = getattr(fn, "arguments", None)+ if arguments:+ part["arguments"] += str(arguments)+ chars += len(str(arguments))+ return chars++ def ordered(self) -> list[dict[str, str]]:+ """Every accumulated part, in provider index order, unfiltered."""+ return [self._parts[key] for key in sorted(self._parts)]++ def collected(self) -> list[dict[str, str]]:+ """Dispatchable tool calls: named parts only, with defaults applied.++ A provider that streams arguments but never an ``id`` still needs one+ to correlate the result message, hence the positional fallback.+ """+ return [+ {+ "id": part.get("id") or f"call_{index}",+ "name": part.get("name", ""),+ "arguments": part.get("arguments") or "{}",+ }+ for index, part in sorted(self._parts.items())+ if part.get("name")+ ]diff --git a/tests/core/agentic/test_tool_call_stream.py b/tests/core/agentic/test_tool_call_stream.pynew file mode 100644index 000000000..3694c8222--- /dev/null+++ b/tests/core/agentic/test_tool_call_stream.py@@ -0,0 +1,121 @@+"""Streaming tool-call accumulation (issue #937).++A router in front of an OpenAI-compatible provider re-sent the *complete*+``id`` on every delta chunk instead of only on the first. The chat loop+appended it, so the id grew one copy per chunk — the reporter observed 551,+754, 870, 1566, 9715, 17864 and 47241 characters — and once past the+provider's own 64-character ceiling every round died with HTTP 400+``Invalid 'messages[i].tool_calls[0].id': string too long``. The forced-finish+call died the same way, so the turn surfaced as "I could not produce a useful+response from the model output."++What is pinned here is the per-field rule, because the fields disagree:+``id`` and ``name`` arrive whole and must be assigned, ``arguments`` arrives+in fragments and must be concatenated. Both directions matter — assigning+``arguments`` would silently truncate every call to its last chunk.+"""++from __future__ import annotations++from deeptutor.core.agentic.tool_call_stream import ToolCallAccumulator+++class _Fn:+ def __init__(self, name: str | None = None, arguments: str | None = None) -> None:+ self.name = name+ self.arguments = arguments+++class _Delta:+ """One ``delta.tool_calls`` entry as the OpenAI SDK shapes it."""++ def __init__(+ self,+ index: int = 0,+ id: str | None = None,+ name: str | None = None,+ arguments: str | None = None,+ ) -> None:+ self.index = index+ self.id = id+ self.function = _Fn(name, arguments)+++def test_gateway_repeating_id_and_name_per_chunk_stays_within_api_limits() -> None:+ """The #937 provider: every chunk carries the whole id and name."""+ acc = ToolCallAccumulator()+ for fragment in ('{"topic"', ': "tuple', ' unpacking"}'):+ acc.feed(_Delta(id="call_9x2f", name="mastery_quiz", arguments=fragment))++ (call,) = acc.collected()+ assert call["id"] == "call_9x2f"+ assert len(call["id"]) <= 64+ # The append also corrupted the name into an unresolvable+ # ``mastery_quizmastery_quizmastery_quiz``.+ assert call["name"] == "mastery_quiz"+ assert call["arguments"] == '{"topic": "tuple unpacking"}'+++def test_spec_compliant_stream_concatenates_only_arguments() -> None:+ """The ordinary shape: id and name once, arguments in fragments."""+ acc = ToolCallAccumulator()+ acc.feed(_Delta(id="call_1", name="rag_search", arguments='{"q":'))+ acc.feed(_Delta(arguments='"decorators"'))+ acc.feed(_Delta(arguments="}"))++ assert acc.collected() == [+ {"id": "call_1", "name": "rag_search", "arguments": '{"q":"decorators"}'}+ ]+++def test_parallel_calls_stay_separated_by_index() -> None:+ acc = ToolCallAccumulator()+ acc.feed(_Delta(index=0, id="call_a", name="rag_search", arguments='{"q":"a"}'))+ acc.feed(_Delta(index=1, id="call_b", name="web_search", arguments='{"q":'))+ acc.feed(_Delta(index=1, arguments='"b"}'))++ assert acc.collected() == [+ {"id": "call_a", "name": "rag_search", "arguments": '{"q":"a"}'},+ {"id": "call_b", "name": "web_search", "arguments": '{"q":"b"}'},+ ]+++def test_feed_bills_name_and_arguments_but_not_the_id() -> None:+ """Callers add the return value to the provider's output-char total."""+ acc = ToolCallAccumulator()+ assert acc.feed(_Delta(id="call_long_identifier", name="ab", arguments="cde")) == 5+ assert acc.feed(_Delta(index=0)) == 0+++def test_argumentless_call_still_dispatches_valid_json() -> None:+ acc = ToolCallAccumulator()+ acc.feed(_Delta(id="call_1", name="mastery_status"))++ assert acc.collected() == [{"id": "call_1", "name": "mastery_status", "arguments": "{}"}]+++def test_call_without_a_provider_id_gets_a_positional_one() -> None:+ """The result message needs an id to correlate against."""+ acc = ToolCallAccumulator()+ acc.feed(_Delta(index=2, name="rag_search", arguments="{}"))++ assert acc.collected() == [{"id": "call_2", "name": "rag_search", "arguments": "{}"}]+++def test_arguments_without_a_name_are_not_dispatchable() -> None:+ acc = ToolCallAccumulator()+ acc.feed(_Delta(id="call_1", arguments='{"q":"x"}'))++ assert acc.collected() == []+ # ``ordered`` is the unfiltered view the labeled-step runner reports on.+ assert acc.ordered() == [{"id": "call_1", "name": "", "arguments": '{"q":"x"}'}]+++def test_absent_index_is_coerced_so_parts_stay_sortable() -> None:+ """A provider that omits ``index`` used to seed a ``None`` dict key,+ which made the final ``sorted()`` raise once any real index appeared."""+ acc = ToolCallAccumulator()+ acc.feed(_Delta(index=None, id="call_1", name="rag_search", arguments="{}")) # type: ignore[arg-type]+ acc.feed(_Delta(index=1, id="call_2", name="web_search", arguments="{}"))++ assert [call["id"] for call in acc.collected()] == ["call_1", "call_2"]