Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
perf(model): replace O(n²) string concat with O(n) fragment join in stream accumulation (#2158)
qbc27b6a0d2a2af
diff --git a/src/agentscope/model/_base.py b/src/agentscope/model/_base.pyindex 54b65db98..c031823bf 100644--- a/src/agentscope/model/_base.py+++ b/src/agentscope/model/_base.py@@ -13,6 +13,7 @@ from pydantic import BaseModelfrom ._model_response import StructuredResponse, ChatResponse, FinishedReasonfrom ._model_card import ModelCard+from ._utils import _StreamAccumulatorfrom .._logging import loggerfrom .._utils._common import _json_loads_with_repairfrom ..credential import CredentialBase@@ -232,17 +233,11 @@ class ChatModelBase:if isinstance(res, ChatResponse):return res- # The accumulated chat response- acc_res = ChatResponse(- content=[],- is_last=True,- finished_reason=FinishedReason.COMPLETED,- )-async def _stream() -> AsyncGenerator[ChatResponse, None]:"""The wrapper around model calling."""# For backward compatibilityyield_acc_res = True+ acc_res = _StreamAccumulator()try:async for chunk in res:if not chunk.is_last:@@ -266,7 +261,7 @@ class ChatModelBase:yield_acc_res = Trueif yield_acc_res:- yield acc_res+ yield acc_res.build()return _stream()@@ -594,19 +589,17 @@ class ChatModelBase:# avoid duplicating the retry logic in ``__call__``), we must# replicate that accumulation here, otherwise the stream may# end without ever producing an ``is_last=True`` chunk.- acc_res = ChatResponse(- content=[],- is_last=True,- finished_reason=FinishedReason.COMPLETED,- )+ acc_res = _StreamAccumulator()+async for chunk in res:if chunk.is_last:completed_response = chunkbreakacc_res.append_chat_response(chunk)acc_res.id = chunk.id+if completed_response is None:- completed_response = acc_res+ completed_response = acc_res.build()else:completed_response = resdiff --git a/src/agentscope/model/_utils.py b/src/agentscope/model/_utils.pynew file mode 100644index 000000000..10cf74a77--- /dev/null+++ b/src/agentscope/model/_utils.py@@ -0,0 +1,280 @@+# -*- coding: utf-8 -*-+"""Internal utilities for the model module."""+import base64+from typing import Any, Self, TypeAlias++from pydantic import Field++from ._model_response import ChatResponse, FinishedReason+from ._model_usage import ChatUsage+from .._logging import logger+from ..message import (+ Base64Source,+ DataBlock,+ TextBlock,+ ThinkingBlock,+ ToolCallBlock,+ URLSource,+)+++class _AccTextBlock(TextBlock):+ """The accumulating counterpart of ``TextBlock``, whose ``text`` field+ holds the incremental fragments until they are joined in ``build``."""++ text: list[str] = Field( # type: ignore[assignment]+ default_factory=list,+ )++ def append(self, block: TextBlock) -> None:+ """Collect one delta block in constant time.++ Args:+ block (`TextBlock`):+ The delta block to collect.+ """+ self.text.append(block.text)++ def build(self) -> TextBlock:+ """Join the fragments into a plain ``TextBlock``."""+ return TextBlock(**{**self.model_dump(), "text": "".join(self.text)})+++class _AccThinkingBlock(ThinkingBlock):+ """The accumulating counterpart of ``ThinkingBlock``, whose ``thinking``+ field holds the incremental fragments until they are joined in+ ``build``."""++ thinking: list[str] = Field( # type: ignore[assignment]+ default_factory=list,+ )++ def append(self, block: ThinkingBlock) -> None:+ """Collect one delta block in constant time.++ Args:+ block (`ThinkingBlock`):+ The delta block to collect.+ """+ self.thinking.append(block.thinking)+ # Provider-specific extras (e.g. Anthropic's ``signature``) are+ # often only emitted on the closing delta of the block.+ for key, value in (block.model_extra or {}).items():+ if value is not None:+ setattr(self, key, value)++ def build(self) -> ThinkingBlock:+ """Join the fragments into a plain ``ThinkingBlock``."""+ return ThinkingBlock(+ **{**self.model_dump(), "thinking": "".join(self.thinking)},+ )+++class _AccToolCallBlock(ToolCallBlock):+ """The accumulating counterpart of ``ToolCallBlock``, whose ``input``+ field holds the incremental JSON fragments until they are joined in+ ``build``."""++ input: list[str] = Field( # type: ignore[assignment]+ default_factory=list,+ )++ def append(self, block: ToolCallBlock) -> None:+ """Collect one delta block in constant time.++ Args:+ block (`ToolCallBlock`):+ The delta block to collect.+ """+ self.input.append(block.input)+ # Most providers carry ``name`` on the opening delta only, but some+ # send an empty one first and fill the name in afterwards.+ if not self.name and block.name:+ self.name = block.name++ def build(self) -> ToolCallBlock:+ """Join the fragments into a plain ``ToolCallBlock``."""+ return ToolCallBlock(+ **{**self.model_dump(), "input": "".join(self.input)},+ )+++class _AccBase64Source(Base64Source):+ """The accumulating counterpart of ``Base64Source`` for audio streams,+ whose ``data`` field holds the raw decoded bytes of each delta.++ Base64 strings cannot be concatenated directly: a delta whose byte+ length is not a multiple of three is padded with ``=``, and everything+ after that padding is silently dropped on decoding. So each delta is+ decoded on arrival and the bytes are encoded once in ``build``.+ """++ data: list[bytes] = Field( # type: ignore[assignment]+ default_factory=list,+ )++ def append(self, source: Base64Source) -> None:+ """Decode one delta source and collect its raw bytes.++ Args:+ source (`Base64Source`):+ The delta source to collect.+ """+ if source.data:+ self.data.append(base64.b64decode(source.data))++ def build(self) -> Base64Source:+ """Join the raw bytes and base64-encode them once."""+ return Base64Source(+ data=base64.b64encode(b"".join(self.data)).decode("ascii"),+ media_type=self.media_type,+ )+++class _AccDataBlock(DataBlock):+ """The accumulating counterpart of ``DataBlock``.++ Only ``audio/*`` is a streamable delta whose concatenation is+ well-defined. Other media types and URL sources are standalone assets,+ so the latest delta replaces the previous one.+ """++ source: ( # type: ignore[assignment]+ _AccBase64Source | Base64Source | URLSource+ )++ def append(self, block: DataBlock) -> None:+ """Collect one delta block in constant time.++ Args:+ block (`DataBlock`):+ The delta block to collect.+ """+ if block.name is not None:+ self.name = block.name++ source = block.source+ if (+ isinstance(self.source, _AccBase64Source)+ and isinstance(source, Base64Source)+ and source.media_type == self.source.media_type+ ):+ self.source.append(source)++ elif isinstance(source, Base64Source) and source.media_type.startswith(+ "audio/",+ ):+ # A new audio stream starts here, either because this is the+ # first delta or because the media type changed mid-stream.+ self.source = _AccBase64Source(+ data=[],+ media_type=source.media_type,+ )+ self.source.append(source)++ else:+ # Standalone asset: the latest delta replaces the previous one+ self.source = source++ def build(self) -> DataBlock:+ """Join the fragments into a plain ``DataBlock``."""+ source = self.source+ return DataBlock(+ **{+ **self.model_dump(),+ "source": (+ source.build()+ if isinstance(source, _AccBase64Source)+ else source+ ),+ },+ )+++_AccBlock: TypeAlias = (+ _AccTextBlock | _AccThinkingBlock | _AccToolCallBlock | _AccDataBlock+)+++class _StreamAccumulator:+ """Accumulates the streaming ``ChatResponse`` deltas of one model call.++ Each block keeps its deltas in a fragment list that is joined exactly+ once in ``build``, which makes the accumulation O(n) in the total+ payload size. The ``ChatResponse.append_chat_response`` it replaces+ grows the blocks with ``block.field += delta`` instead, which is+ O(n^2) for large payloads (e.g. tool call arguments of 100k+ chars)+ and can block the event loop long enough to drop the connection.+ """++ def __init__(self) -> None:+ """Initialize an empty accumulator."""+ # Keyed by block id, the insertion order is the block order+ self._blocks: dict[str, _AccBlock] = {}++ self.id: str | None = None+ """The id of the latest delta, if any."""++ self.usage: ChatUsage | None = None+ """The usage of the latest delta that reported one, if any."""++ self.finished_reason: FinishedReason = FinishedReason.COMPLETED+ """The finished reason to report in ``build``."""++ def append_chat_response(self, chat_response: ChatResponse) -> Self:+ """Collect one delta chunk in constant time per block.++ Args:+ chat_response (`ChatResponse`):+ The streaming delta chunk to collect.+ """+ for block in chat_response.content:+ acc = self._blocks.get(block.id)+ if acc is not None and acc.type != block.type:+ logger.warning(+ "Block %s changed its type from %s to %s during "+ "streaming, dropping the accumulated fragments.",+ block.id,+ acc.type,+ block.type,+ )+ acc = None++ if acc is None:+ # Seed the accumulator with every field of the delta, so+ # that the ones it does not accumulate are carried over.+ fields = block.model_dump()+ if isinstance(block, TextBlock):+ acc = _AccTextBlock(**{**fields, "text": []})+ elif isinstance(block, ThinkingBlock):+ acc = _AccThinkingBlock(**{**fields, "thinking": []})+ elif isinstance(block, ToolCallBlock):+ acc = _AccToolCallBlock(**{**fields, "input": []})+ else:+ # ``source`` is not emptied here, ``append`` replaces+ # it with a byte accumulator for audio streams.+ acc = _AccDataBlock(**fields)+ self._blocks[block.id] = acc++ # The type check above guarantees the accumulator and the+ # delta block are of the same kind.+ acc.append(block) # type: ignore[arg-type]++ if chat_response.usage:+ self.usage = chat_response.usage++ return self++ def build(self) -> ChatResponse:+ """Join the fragments of every block into a final response."""+ kwargs: dict[str, Any] = {}+ if self.id is not None:+ kwargs["id"] = self.id++ return ChatResponse(+ content=[_.build() for _ in self._blocks.values()],+ is_last=True,+ usage=self.usage,+ finished_reason=self.finished_reason,+ **kwargs,+ )diff --git a/tests/model_base_test.py b/tests/model_base_test.pyindex 06709cae5..81d4a9066 100644--- a/tests/model_base_test.py+++ b/tests/model_base_test.py@@ -2,12 +2,21 @@"""Unit tests for :class:`agentscope.model.ChatModelBase.__call__` — theretry / accumulation / interrupt wrapper around ``_call_api``."""import asyncio+import base64from unittest.async_case import IsolatedAsyncioTestCasefrom utils import AnyString, MockModel-from agentscope.message import TextBlock, ThinkingBlock, ToolCallBlock, UserMsg-from agentscope.model import ChatResponse, FinishedReason+from agentscope.message import (+ Base64Source,+ DataBlock,+ TextBlock,+ ThinkingBlock,+ ToolCallBlock,+ URLSource,+ UserMsg,+)+from agentscope.model import ChatResponse, ChatUsage, FinishedReasondef _dump(chat_response: ChatResponse) -> dict:@@ -468,5 +477,594 @@ class ChatModelBaseCallTest(IsolatedAsyncioTestCase):],)+ # ------------------------------------------------------------------+ # 7) stream with large tool call arguments — O(n) accumulation+ # ------------------------------------------------------------------+ async def test_stream_large_tool_call_linear_accumulation(+ self,+ ) -> None:+ """A large tool call argument (simulating write_file with many+ fragments) must be accumulated in O(n) time. We verify the+ final accumulated content is correct with 10000 fragments."""+ num_chunks = 10000+ fragment = "x" * 100 # 100 chars per chunk++ deltas = [+ ChatResponse(+ content=[+ ToolCallBlock(+ id="tool-big",+ name="write_file",+ input=fragment,+ ),+ ],+ is_last=False,+ id=f"chunk-{i}",+ )+ for i in range(num_chunks)+ ]+ self.model.set_responses([deltas])++ gen = await self.model(messages=self.messages)+ last_chunk = None+ async for chunk in gen:+ last_chunk = chunk++ self.assertDictEqual(+ _dump(last_chunk),+ _expected(+ content=[+ {+ "type": "tool_call",+ "id": "tool-big",+ "name": "write_file",+ "input": fragment * num_chunks,+ "state": "pending",+ "suggested_rules": [],+ },+ ],+ is_last=True,+ finished_reason=FinishedReason.COMPLETED,+ ),+ )++ # ------------------------------------------------------------------+ # 8) stream with is_last=True — no acc_res needed+ # ------------------------------------------------------------------+ async def test_stream_with_final_chunk_no_acc_res(self) -> None:+ """When the model stream produces a final chunk with+ is_last=True, acc_res should NOT be yielded (the model+ provides the complete response itself)."""+ deltas = [+ ChatResponse(+ content=[TextBlock(text="hello", id="t1")],+ is_last=False,+ id="chunk-1",+ ),+ ChatResponse(+ content=[TextBlock(text=" world", id="t1")],+ is_last=False,+ id="chunk-2",+ ),+ # Model provides its own final complete response+ ChatResponse(+ content=[TextBlock(text="hello world", id="t1")],+ is_last=True,+ id="chunk-final",+ ),+ ]+ self.model.set_responses([deltas])++ gen = await self.model(messages=self.messages)+ collected = [_dump(c) async for c in gen]++ # Only 3 chunks: 2 deltas + 1 model-provided final+ # (NOT 4 — no acc_res appended)+ self.assertListEqual(+ collected,+ [+ _expected(+ content=[+ {"type": "text", "text": "hello", "id": "t1"},+ ],+ is_last=False,+ ),+ _expected(+ content=[+ {+ "type": "text",+ "text": " world",+ "id": "t1",+ },+ ],+ is_last=False,+ ),+ _expected(+ content=[+ {+ "type": "text",+ "text": "hello world",+ "id": "t1",+ },+ ],+ is_last=True,+ ),+ ],+ )++ # ------------------------------------------------------------------+ # 9) stream mixed block types — normal completion (happy path)+ # ------------------------------------------------------------------+ async def test_stream_mixed_blocks_normal_completion(self) -> None:+ """Mixed block types (thinking + text + tool_call) in a+ normal stream completion (no CancelledError). The final+ accumulated response must contain all blocks in order with+ correctly joined fragments."""+ deltas = [+ # thinking part 1+ ChatResponse(+ content=[+ ThinkingBlock(thinking="step 1: ", id="think-1"),+ ],+ is_last=False,+ id="chunk-1",+ ),+ # thinking part 2+ ChatResponse(+ content=[+ ThinkingBlock(thinking="analyze", id="think-1"),+ ],+ is_last=False,+ id="chunk-2",+ ),+ # text part 1+ ChatResponse(+ content=[TextBlock(text="I will ", id="text-1")],+ is_last=False,+ id="chunk-3",+ ),+ # text part 2+ ChatResponse(+ content=[TextBlock(text="help you", id="text-1")],+ is_last=False,+ id="chunk-4",+ ),+ # tool_call part 1+ ChatResponse(+ content=[+ ToolCallBlock(+ id="tool-1",+ name="search",+ input='{"query":',+ ),+ ],+ is_last=False,+ id="chunk-5",+ ),+ # tool_call part 2+ ChatResponse(+ content=[+ ToolCallBlock(+ id="tool-1",+ name="search",+ input='"hello"}',+ ),+ ],+ is_last=False,+ id="chunk-6",+ ),+ ]+ self.model.set_responses([deltas])++ gen = await self.model(messages=self.messages)+ collected = [_dump(c) async for c in gen]++ self.assertListEqual(+ collected,+ [+ _expected(+ content=[+ {+ "type": "thinking",+ "thinking": "step 1: ",+ "id": "think-1",+ },+ ],+ is_last=False,+ ),+ _expected(+ content=[+ {+ "type": "thinking",+ "thinking": "analyze",+ "id": "think-1",+ },+ ],+ is_last=False,+ ),+ _expected(+ content=[+ {+ "type": "text",+ "text": "I will ",+ "id": "text-1",+ },+ ],+ is_last=False,+ ),+ _expected(+ content=[+ {+ "type": "text",+ "text": "help you",+ "id": "text-1",+ },+ ],+ is_last=False,+ ),+ _expected(+ content=[+ {+ "type": "tool_call",+ "id": "tool-1",+ "name": "search",+ "input": '{"query":',+ "state": "pending",+ "suggested_rules": [],+ },+ ],+ is_last=False,+ ),+ _expected(+ content=[+ {+ "type": "tool_call",+ "id": "tool-1",+ "name": "search",+ "input": '"hello"}',+ "state": "pending",+ "suggested_rules": [],+ },+ ],+ is_last=False,+ ),+ # accumulated final — all blocks merged+ _expected(+ content=[+ {+ "type": "thinking",+ "thinking": "step 1: analyze",+ "id": "think-1",+ },+ {+ "type": "text",+ "text": "I will help you",+ "id": "text-1",+ },+ {+ "type": "tool_call",+ "id": "tool-1",+ "name": "search",+ "input": '{"query":"hello"}',+ "state": "pending",+ "suggested_rules": [],+ },+ ],+ is_last=True,+ finished_reason=FinishedReason.COMPLETED,+ ),+ ],+ )++ # ------------------------------------------------------------------+ # 10) stream audio data block — raw bytes joined, encoded once+ # ------------------------------------------------------------------+ async def test_stream_audio_data_block_accumulation(self) -> None:+ """Audio deltas must accumulate as raw bytes. Joining the base64+ strings instead would silently truncate at the first padded+ fragment, so the decoded result is checked against the+ concatenated raw bytes."""+ raw = [b"ab", b"cd", b"ef"] # each encodes to a '='-padded string+ deltas = [+ ChatResponse(+ content=[+ DataBlock(+ id="audio-1",+ source=Base64Source(+ data=base64.b64encode(part).decode("ascii"),+ media_type="audio/wav",+ ),+ # Providers name the asset on the opening delta+ name="out.wav" if i == 0 else None,+ ),+ ],+ is_last=False,+ id=f"chunk-{i}",+ )+ for i, part in enumerate(raw)+ ]+ self.model.set_responses([deltas])++ gen = await self.model(messages=self.messages)+ last_chunk = None+ async for chunk in gen:+ last_chunk = chunk++ self.assertDictEqual(+ _dump(last_chunk),+ _expected(+ content=[+ {+ "type": "data",+ "id": "audio-1",+ "source": {+ "type": "base64",+ "data": base64.b64encode(b"".join(raw)).decode(+ "ascii",+ ),+ "media_type": "audio/wav",+ },+ "name": "out.wav",+ },+ ],+ is_last=True,+ finished_reason=FinishedReason.COMPLETED,+ ),+ )++ # ------------------------------------------------------------------+ # 11) stream non-audio data block — the latest delta wins+ # ------------------------------------------------------------------+ async def test_stream_non_audio_data_block_latest_wins(self) -> None:+ """Non-audio media are standalone assets rather than streamable+ deltas, so byte concatenation is meaningless and the latest+ delta must replace the previous one."""+ deltas = [+ ChatResponse(+ content=[+ DataBlock(+ id="img-1",+ source=Base64Source(+ data="AAAA",+ media_type="image/png",+ ),+ ),+ ],+ is_last=False,+ id="chunk-1",+ ),+ ChatResponse(+ content=[+ DataBlock(+ id="img-1",+ source=Base64Source(+ data="BBBB",+ media_type="image/png",+ ),+ ),+ ],+ is_last=False,+ id="chunk-2",+ ),+ ChatResponse(+ content=[+ DataBlock(+ id="url-1",+ source=URLSource(+ url="https://example.com/a.png",+ media_type="image/png",+ ),+ ),+ ],+ is_last=False,+ id="chunk-3",+ ),+ ]+ self.model.set_responses([deltas])++ gen = await self.model(messages=self.messages)+ last_chunk = None+ async for chunk in gen:+ last_chunk = chunk++ self.assertDictEqual(+ _dump(last_chunk),+ _expected(+ content=[+ {+ "type": "data",+ "id": "img-1",+ "source": {+ "type": "base64",+ "data": "BBBB",+ "media_type": "image/png",+ },+ "name": None,+ },+ {+ "type": "data",+ "id": "url-1",+ "source": {+ "type": "url",+ "url": "https://example.com/a.png",+ "media_type": "image/png",+ },+ "name": None,+ },+ ],+ is_last=True,+ finished_reason=FinishedReason.COMPLETED,+ ),+ )++ # ------------------------------------------------------------------+ # 12) stream data block whose media type switches mid-stream+ # ------------------------------------------------------------------+ async def test_stream_data_block_media_type_switch(self) -> None:+ """A media type change makes the accumulated fragments+ incompatible with the incoming delta, so they are dropped and+ the latest delta wins."""+ deltas = [+ ChatResponse(+ content=[+ DataBlock(+ id="audio-1",+ source=Base64Source(+ data=base64.b64encode(b"old").decode("ascii"),+ media_type="audio/wav",+ ),+ ),+ ],+ is_last=False,+ id="chunk-1",+ ),+ ChatResponse(+ content=[+ DataBlock(+ id="audio-1",+ source=Base64Source(+ data=base64.b64encode(b"new").decode("ascii"),+ media_type="audio/mpeg",+ ),+ ),+ ],+ is_last=False,+ id="chunk-2",+ ),+ ]+ self.model.set_responses([deltas])++ gen = await self.model(messages=self.messages)+ last_chunk = None+ async for chunk in gen:+ last_chunk = chunk++ self.assertDictEqual(+ _dump(last_chunk),+ _expected(+ content=[+ {+ "type": "data",+ "id": "audio-1",+ "source": {+ "type": "base64",+ "data": base64.b64encode(b"new").decode("ascii"),+ "media_type": "audio/mpeg",+ },+ "name": None,+ },+ ],+ is_last=True,+ finished_reason=FinishedReason.COMPLETED,+ ),+ )++ # ------------------------------------------------------------------+ # 13) stream thinking whose signature arrives on the closing delta+ # ------------------------------------------------------------------+ async def test_stream_thinking_signature_on_closing_delta(self) -> None:+ """Provider-specific extras (e.g. Anthropic's ``signature``) are+ often emitted only on the closing delta and must survive into+ the accumulated block."""+ deltas = [+ ChatResponse(+ content=[ThinkingBlock(thinking="step ", id="think-1")],+ is_last=False,+ id="chunk-1",+ ),+ ChatResponse(+ content=[ThinkingBlock(thinking="one", id="think-1")],+ is_last=False,+ id="chunk-2",+ ),+ ChatResponse(+ content=[+ ThinkingBlock(+ thinking="",+ id="think-1",+ signature="sig-abc",+ ),+ ],+ is_last=False,+ id="chunk-3",+ ),+ ]+ self.model.set_responses([deltas])++ gen = await self.model(messages=self.messages)+ last_chunk = None+ async for chunk in gen:+ last_chunk = chunk++ self.assertDictEqual(+ _dump(last_chunk),+ _expected(+ content=[+ {+ "type": "thinking",+ "thinking": "step one",+ "id": "think-1",+ "signature": "sig-abc",+ },+ ],+ is_last=True,+ finished_reason=FinishedReason.COMPLETED,+ ),+ )++ # ------------------------------------------------------------------+ # 14) stream usage carried by a trailing usage-only chunk+ # ------------------------------------------------------------------+ async def test_stream_usage_absorbed_into_accumulated(self) -> None:+ """OpenAI-compatible APIs emit a trailing usage-only chunk with+ no content. It must not be surfaced to the consumer, but its+ usage must land on the accumulated response."""+ deltas = [+ ChatResponse(+ content=[TextBlock(text="hello", id="t1")],+ is_last=False,+ id="chunk-1",+ ),+ ChatResponse(+ content=[],+ is_last=False,+ id="chunk-2",+ usage=ChatUsage(input_tokens=3, output_tokens=7, time=0.5),+ ),+ ]+ self.model.set_responses([deltas])++ gen = await self.model(messages=self.messages)+ collected = [_dump(c) async for c in gen]++ # The usage-only carrier chunk is absorbed, not forwarded+ self.assertListEqual(+ collected,+ [+ _expected(+ content=[+ {"type": "text", "text": "hello", "id": "t1"},+ ],+ is_last=False,+ ),+ _expected(+ content=[+ {"type": "text", "text": "hello", "id": "t1"},+ ],+ is_last=True,+ finished_reason=FinishedReason.COMPLETED,+ usage={+ "input_tokens": 3,+ "output_tokens": 7,+ "time": 0.5,+ "cache_creation_input_tokens": 0,+ "cache_input_tokens": 0,+ "type": "chat",+ "metadata": None,+ },+ ),+ ],+ )+async def asyncTearDown(self) -> None:"""The async teardown method."""