Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(agent): preserve reply usage in final messages (#2562)
guanyi liu15ac00291e2f
diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.pyindex 1bd217a65..b79267e25 100644--- a/src/agentscope/agent/_agent.py+++ b/src/agentscope/agent/_agent.py@@ -735,10 +735,20 @@ class Agent:# Clear the read tool cacheawait self._clear_unreserved_read_cache(msgs_to_reserve)+ # The current reply msg may be fully compressed, so keep its usage+ current_reply_usage = self._get_reply_usage()+# Update the context and summaryself.state.summary = new_summaryself.state.context = msgs_to_reserve+ if (+ current_reply_usage is not None+ and self._get_reply_usage() is None+ ):+ self.state.append_context(self.name, [])+ self.state.context[-1].usage = current_reply_usage+# The compression call is not covered by the model call events,# so record its cost on the context tail to keep it in the token# accounting@@ -1293,6 +1303,7 @@ class Agent:id=self.state.reply_id,name=self.name,content=self.react_config.interruption_message,+ usage=self._get_reply_usage(),finished_reason=ReplyFinishedReason.INTERRUPTED,)@@ -1823,27 +1834,12 @@ class Agent:)and not has_only_thinking_blocks):- last_ctx = self._get_last_msg()- final_usage = (- Usage(- input_tokens=last_ctx.usage.input_tokens,- output_tokens=last_ctx.usage.output_tokens,- cache_input_tokens=(- last_ctx.usage.cache_input_tokens or 0- ),- cache_creation_input_tokens=(- last_ctx.usage.cache_creation_input_tokens or 0- ),- )- if last_ctx is not None and last_ctx.usage is not None- else None- )yield AssistantMsg(id=self.state.reply_id,name=self.name,# Text only response messagecontent=list(completed_response.content),- usage=final_usage,+ usage=self._get_reply_usage(),# The INTERRUPTED case is excluded by the branch conditionfinished_reason=ReplyFinishedReason.COMPLETED,)@@ -3488,6 +3484,17 @@ class Agent:return last_msgreturn None+ def _get_reply_usage(self) -> Usage | None:+ """Get a copy of the accumulated usage for the current reply."""+ last_msg = self._get_last_msg()+ if (+ last_msg is None+ or last_msg.id != self.state.reply_id+ or last_msg.usage is None+ ):+ return None+ return last_msg.usage.model_copy()+def _next_action(self,final_msg: Msg | None = None,@@ -3560,6 +3567,7 @@ class Agent:id=self.state.reply_id,name=self.name,content="The required structured output is generated.",+ usage=self._get_reply_usage(),finished_reason=ReplyFinishedReason.COMPLETED,structured_output=deepcopy(self.state.reply_context.structured_output,@@ -3606,6 +3614,7 @@ class Agent:name=self.name,content="The maximum reasoning-acting iterations ""are exceeded.",+ usage=self._get_reply_usage(),finished_reason=ReplyFinishedReason.EXCEED_MAX_ITERS,),)@@ -3740,6 +3749,7 @@ class Agent:name=self.name,content="The maximum reasoning-acting iterations are ""exceeded.",+ usage=self._get_reply_usage(),finished_reason=ReplyFinishedReason.EXCEED_MAX_ITERS,),)diff --git a/tests/agent_basic_test.py b/tests/agent_basic_test.pyindex b00ed6fe3..4cd35f313 100644--- a/tests/agent_basic_test.py+++ b/tests/agent_basic_test.py@@ -6,7 +6,7 @@ from unittest.async_case import IsolatedAsyncioTestCasefrom utils import AnyString, MockModelfrom agentscope.agent import Agent, ContextConfig, InjectionConfig, ReActConfig-from agentscope.model import ChatResponse, ChatUsage+from agentscope.model import ChatResponse, ChatUsage, FinishedReasonfrom agentscope.tool import (ToolBase,Toolkit,@@ -1093,10 +1093,24 @@ class AgentBasicTest(IsolatedAsyncioTestCase):ChatResponse(content=[ThinkingBlock(thinking="First thought")],is_last=True,+ usage=ChatUsage(+ input_tokens=80,+ output_tokens=40,+ time=0.1,+ cache_input_tokens=5,+ cache_creation_input_tokens=2,+ ),),ChatResponse(content=[ThinkingBlock(thinking="Second thought")],is_last=True,+ usage=ChatUsage(+ input_tokens=100,+ output_tokens=50,+ time=0.2,+ cache_input_tokens=7,+ cache_creation_input_tokens=3,+ ),),],)@@ -1110,6 +1124,12 @@ class AgentBasicTest(IsolatedAsyncioTestCase):{**self._get_msg_base(),"finished_reason": ReplyFinishedReason.EXCEED_MAX_ITERS,+ "usage": {+ "input_tokens": 180,+ "output_tokens": 90,+ "cache_input_tokens": 12,+ "cache_creation_input_tokens": 5,+ },"content": [{"type": "text",@@ -1123,6 +1143,85 @@ class AgentBasicTest(IsolatedAsyncioTestCase):},)+ async def test_interrupted_reply_preserves_usage(self) -> None:+ """An interrupted final message carries the model usage."""+ self.model.set_responses(+ [+ ChatResponse(+ content=[TextBlock(text="Partial response")],+ is_last=True,+ usage=ChatUsage(+ input_tokens=80,+ output_tokens=40,+ time=0.1,+ cache_input_tokens=5,+ cache_creation_input_tokens=2,+ ),+ finished_reason=FinishedReason.INTERRUPTED,+ ),+ ],+ )++ msg = await self.agent.reply(+ UserMsg(name="user", content="Continue"),+ )++ self.assertDictEqual(+ msg.model_dump(),+ {+ **self._get_msg_base(),+ "finished_reason": ReplyFinishedReason.INTERRUPTED,+ "usage": {+ "input_tokens": 80,+ "output_tokens": 40,+ "cache_input_tokens": 5,+ "cache_creation_input_tokens": 2,+ },+ "content": [+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": (+ "I notice the interruption. How can I help you?"+ ),+ },+ ],+ },+ )++ async def test_reply_does_not_reuse_previous_usage(self) -> None:+ """A reply with no new context does not reuse prior usage."""+ self.model.set_responses(+ [+ ChatResponse(+ content=[TextBlock(text="First response")],+ is_last=True,+ usage=ChatUsage(+ input_tokens=80,+ output_tokens=40,+ time=0.1,+ cache_input_tokens=5,+ cache_creation_input_tokens=2,+ ),+ ),+ ChatResponse(content=[], is_last=True),+ ],+ )++ await self.agent.reply(UserMsg(name="user", content="Start"))+ msg = await self.agent.reply()++ self.assertDictEqual(+ msg.model_dump(),+ {+ **self._get_msg_base(),+ "finished_reason": ReplyFinishedReason.COMPLETED,+ "content": [],+ },+ )+async def test_streaming_sequential_tool_calls(self) -> None:"""Test the streaming model inference with tool calls generated.diff --git a/tests/agent_structured_output_test.py b/tests/agent_structured_output_test.pyindex 0c0b7151f..6b1aead2e 100644--- a/tests/agent_structured_output_test.py+++ b/tests/agent_structured_output_test.py@@ -7,7 +7,7 @@ from pydantic import BaseModelfrom utils import AnyString, MockModelfrom agentscope.agent import Agent, InjectionConfig, ReActConfig-from agentscope.model import ChatResponse+from agentscope.model import ChatResponse, ChatUsagefrom agentscope.state import AgentStatefrom agentscope.tool import ToolBase, Toolkit, ToolChunkfrom agentscope.permission import (@@ -144,6 +144,84 @@ class AgentStructuredOutputTest(IsolatedAsyncioTestCase):},)+ async def test_structured_reply_preserves_accumulated_usage(self) -> None:+ """A structured reply exposes usage from every model call."""+ self.model.set_responses(+ [+ ChatResponse(+ content=[TextBlock(text="Let me think more.")],+ is_last=True,+ usage=ChatUsage(+ input_tokens=80,+ output_tokens=40,+ time=0.1,+ cache_input_tokens=5,+ cache_creation_input_tokens=2,+ ),+ ),+ ChatResponse(+ content=[+ ToolCallBlock(+ id="structured_call_1",+ name="GenerateStructuredOutput",+ input=(+ '{"city": "Hangzhou", ' '"temperature": 25.0}'+ ),+ ),+ ],+ is_last=True,+ usage=ChatUsage(+ input_tokens=100,+ output_tokens=50,+ time=0.2,+ cache_input_tokens=7,+ cache_creation_input_tokens=3,+ ),+ ),+ ],+ )++ res = await self.agent.reply(+ UserMsg(name="user", content="Weather in Hangzhou?"),+ structured_schema=WeatherReport,+ )++ self.assertDictEqual(+ res.model_dump(),+ {+ "id": self.agent.state.reply_id,+ "created_at": AnyString(),+ "finished_at": None,+ "finished_reason": "completed",+ "structured_output": {+ "city": "Hangzhou",+ "temperature": 25.0,+ },+ "error": None,+ "metadata": {},+ "name": "Friday",+ "role": "assistant",+ "usage": {+ "input_tokens": 180,+ "output_tokens": 90,+ "cache_input_tokens": 12,+ "cache_creation_input_tokens": 5,+ },+ "content": [+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": (+ "The required structured output is generated."+ ),+ },+ ],+ },+ )+ self.assertEqual(self.model.cnt, 2)+async def test_defaults_and_extra_fields(self) -> None:"""In process the model class validates the output directly, sodefaults are filled and extra fields are dropped."""@@ -175,6 +253,23 @@ class AgentStructuredOutputTest(IsolatedAsyncioTestCase):async def test_validation_error_retry(self) -> None:"""An invalid structured output produces an error tool result, andthe model retries in the next reasoning round."""+ valid_structured_tool_call = ChatResponse(+ content=[+ ToolCallBlock(+ id="structured_call_1",+ name="GenerateStructuredOutput",+ input='{"city": "Hangzhou", "temperature": 25.0}',+ ),+ ],+ is_last=True,+ usage=ChatUsage(+ input_tokens=100,+ output_tokens=50,+ time=0.2,+ cache_input_tokens=7,+ cache_creation_input_tokens=3,+ ),+ )self.model.set_responses([ChatResponse(@@ -186,8 +281,15 @@ class AgentStructuredOutputTest(IsolatedAsyncioTestCase):),],is_last=True,+ usage=ChatUsage(+ input_tokens=80,+ output_tokens=40,+ time=0.1,+ cache_input_tokens=5,+ cache_creation_input_tokens=2,+ ),),- self.structured_tool_call,+ valid_structured_tool_call,],)@@ -241,6 +343,40 @@ class AgentStructuredOutputTest(IsolatedAsyncioTestCase):},],)+ self.assertDictEqual(+ res.model_dump(),+ {+ "id": self.agent.state.reply_id,+ "created_at": AnyString(),+ "finished_at": None,+ "finished_reason": "completed",+ "structured_output": {+ "city": "Hangzhou",+ "temperature": 25.0,+ },+ "error": None,+ "metadata": {},+ "name": "Friday",+ "role": "assistant",+ "usage": {+ "input_tokens": 180,+ "output_tokens": 90,+ "cache_input_tokens": 12,+ "cache_creation_input_tokens": 5,+ },+ "content": [+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": (+ "The required structured output is generated."+ ),+ },+ ],+ },+ )async def test_forced_generation_at_max_iters(self) -> None:"""Once ``max_iters`` is reached, the agent forces the structured@@ -269,7 +405,32 @@ class AgentStructuredOutputTest(IsolatedAsyncioTestCase):max_iters=1,structured_output_grace_iters=1,)- self.model.set_responses([self.text_response, self.text_response])+ self.model.set_responses(+ [+ ChatResponse(+ content=[TextBlock(text="First attempt")],+ is_last=True,+ usage=ChatUsage(+ input_tokens=80,+ output_tokens=40,+ time=0.1,+ cache_input_tokens=5,+ cache_creation_input_tokens=2,+ ),+ ),+ ChatResponse(+ content=[TextBlock(text="Second attempt")],+ is_last=True,+ usage=ChatUsage(+ input_tokens=100,+ output_tokens=50,+ time=0.2,+ cache_input_tokens=7,+ cache_creation_input_tokens=3,+ ),+ ),+ ],+ )res = await self.agent.reply(UserMsg(name="user", content="Weather in Hangzhou?"),@@ -288,7 +449,12 @@ class AgentStructuredOutputTest(IsolatedAsyncioTestCase):"metadata": {},"name": "Friday","role": "assistant",- "usage": None,+ "usage": {+ "input_tokens": 180,+ "output_tokens": 90,+ "cache_input_tokens": 12,+ "cache_creation_input_tokens": 5,+ },"content": [{"type": "text",diff --git a/tests/compress_context_test.py b/tests/compress_context_test.pyindex 7246fa88f..c491a6c4f 100644--- a/tests/compress_context_test.py+++ b/tests/compress_context_test.py@@ -2666,6 +2666,81 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):],)+ async def test_context_compression_preserves_current_reply_usage(+ self,+ ) -> None:+ """Compression preserves usage from a fully compressed reply."""+ model = MockModel(context_size=100)+ agent = Agent(+ name="Friday",+ system_prompt="hi",+ model=model,+ context_config=ContextConfig(+ trigger_ratio=0.5,+ reserve_ratio=0.4,+ ),+ injection_config=InjectionConfig(inject_runtime_state=False),+ toolkit=Toolkit(),+ )+ agent.state.reply_id = "current-reply"+ agent.state.context = [+ AssistantMsg(+ "Friday",+ [TextBlock(text="x" * 1000)],+ id="current-reply",+ usage=Usage(+ input_tokens=80,+ output_tokens=40,+ cache_input_tokens=5,+ cache_creation_input_tokens=2,+ ),+ ),+ ]+ model.set_structured_response(+ StructuredResponse(+ content={+ "task_overview": "1",+ "current_state": "2",+ "important_discoveries": "3",+ "next_steps": "4",+ "context_to_preserve": "5",+ },+ usage=ChatUsage(+ input_tokens=10,+ output_tokens=5,+ time=0.1,+ cache_input_tokens=1,+ cache_creation_input_tokens=1,+ ),+ ),+ )++ await agent.compress_context()++ self.assertListEqual(+ [_.model_dump() for _ in agent.state.context],+ [+ {+ "id": "current-reply",+ "created_at": AnyString(),+ "finished_at": None,+ "finished_reason": None,+ "structured_output": None,+ "error": None,+ "name": "Friday",+ "role": "assistant",+ "content": [],+ "metadata": {},+ "usage": {+ "input_tokens": 90,+ "output_tokens": 45,+ "cache_input_tokens": 6,+ "cache_creation_input_tokens": 3,+ },+ },+ ],+ )+async def test_summary_failure_truncates_context(self) -> None:"""Summary failures fall back to lossy context truncation."""agent, _ = _make_failing_compression_agent()