Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(agent): support structured output within the agent class (#2150)
DavdGao77318e01c6cf
diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.pyindex 859fb3f0d..2e0b1d793 100644--- a/src/agentscope/agent/_agent.py+++ b/src/agentscope/agent/_agent.py@@ -7,22 +7,23 @@ import refrom asyncio import Queuefrom copy import deepcopy-from datetime import datetime, timezone, tzinfo-from zoneinfo import ZoneInfo, ZoneInfoNotFoundError+from datetime import datetimefrom typing import (Any,AsyncGenerator,Sequence,- Literal,List,TYPE_CHECKING,+ Type,)import jsonschema+from pydantic import BaseModelfrom ._config import ContextConfig, ReActConfig, ModelConfig, InjectionConfigfrom ..state import AgentState-from ._utils import _ToolCallBatch+from ..state._state import ReplyContext+from ._utils import _ToolCallBatch, Acting, Exit, Reasoning, _resolve_timezonefrom .._logging import loggerfrom .._utils._common import (_generate_id,@@ -96,6 +97,7 @@ from ..permission import (PermissionDecision,PermissionRule,)+from ._structured_output_tool import _GenerateStructuredOutputfrom ..workspace import Offloader, WorkspaceBaseif TYPE_CHECKING:@@ -104,21 +106,6 @@ else:MiddlewareBase = Any-def _resolve_timezone(name: str) -> tzinfo:- """Resolve the given timezone name, falling back to UTC when the name is- invalid or the timezone database is unavailable, e.g. on Windows or slim- images without the ``tzdata`` package."""- try:- return ZoneInfo(name)- except (ZoneInfoNotFoundError, ValueError):- logger.warning(- "Failed to resolve the timezone %s, fallback to UTC. Install the "- "'tzdata' package if the timezone database is missing.",- repr(name),- )- return timezone.utc--class Agent:"""The agent class."""@@ -264,7 +251,9 @@ class Agent:| UserInterruptEvent| ExternalExecutionResultEvent| None = None,- ) -> AsyncGenerator[AgentEvent, None]:+ structured_schema: Type[BaseModel] | None = None,+ yield_final_msg: bool = False,+ ) -> AsyncGenerator[AgentEvent | Msg, None]:"""Reply to the given inputs and stream agent events.Args:@@ -273,9 +262,16 @@ class Agent:optional):The inputs that trigger this reply. See :meth:`reply` forthe full list of accepted variants.+ structured_schema (`Type[BaseModel] | None`, optional):+ The Pydantic model class that the reply's structured output+ must conform to. See :meth:`reply` for details.+ yield_final_msg (`bool`, defaults to `False`):+ If yield the final reply message. When requiring structured+ output, use this option to get the final message, and access+ it via the `structured_output` attribute.Yields:- `AgentEvent`:+ `AgentEvent | Msg`:Streamed events produced during the reply... note:: If requiring outside interaction for multiple tool calls@@ -283,9 +279,13 @@ class Agent:agent won't re-send the requiring events for the unconfirmedor unexecuted tool calls."""- async for chunk in self._reply(inputs=inputs):- if not isinstance(chunk, Msg):- yield chunk+ async for chunk in self._reply(+ inputs=inputs,+ structured_schema=structured_schema,+ ):+ if isinstance(chunk, Msg) and not yield_final_msg:+ continue+ yield chunkasync def reply(self,@@ -295,6 +295,7 @@ class Agent:| UserInterruptEvent| ExternalExecutionResultEvent| None = None,+ structured_schema: Type[BaseModel] | None = None,) -> Msg:"""Reply to the given inputs, consuming all streamed events.@@ -315,13 +316,20 @@ class Agent:reasoning-acting loop,- `None` if there is nothing new to feed in (e.g. justcontinue from the current state).+ structured_schema (`Type[BaseModel] | None`, optional):+ The Pydantic model class that the reply's structured output+ must conform to, with the validated result carried on the+ final message's ``structured_output`` attribute as a dict.Returns:`Msg`:A final reply message."""final_msg: Msg | None = None- async for evt_or_msg in self._reply(inputs=inputs):+ async for evt_or_msg in self._reply(+ inputs=inputs,+ structured_schema=structured_schema,+ ):if isinstance(evt_or_msg, Msg):final_msg = evt_or_msgif final_msg is None:@@ -625,10 +633,14 @@ class Agent:| UserInterruptEvent| ExternalExecutionResultEvent| None = None,+ structured_schema: Type[BaseModel] | None = None,) -> AsyncGenerator[AgentEvent | Msg, None]:"""Reply entry point (maybe wrapped by middleware)."""if not self._reply_middlewares:- async for item in self._reply_impl(inputs=inputs):+ async for item in self._reply_impl(+ inputs=inputs,+ structured_schema=structured_schema,+ ):yield itemelse:@@ -640,13 +652,20 @@ class Agent:| UserInterruptEvent| ExternalExecutionResultEvent| None = inputs,+ structured_schema: Type[BaseModel] | None = structured_schema,) -> AsyncGenerator[AgentEvent | Msg, None]:if index >= len(self._reply_middlewares):- async for item in self._reply_impl(inputs=inputs):+ async for item in self._reply_impl(+ inputs=inputs,+ structured_schema=structured_schema,+ ):yield itemelse:mw = self._reply_middlewares[index]- input_kwargs = {"inputs": inputs}+ input_kwargs = {+ "inputs": inputs,+ "structured_schema": structured_schema,+ }async def next_handler(**kwargs: Any,@@ -737,6 +756,7 @@ class Agent:| UserInterruptEvent| ExternalExecutionResultEvent| None = None,+ structured_schema: Type[BaseModel] | None = None,) -> AsyncGenerator[AgentEvent | Msg, None]:"""Core reply logic."""@@ -765,6 +785,13 @@ class Agent:event = Nonemsgs = inputs+ if event and structured_schema:+ logger.warning(+ "The given structured_schema is ignored when "+ "resuming with a HITL event; the parked reply's "+ "schema is used instead.",+ )+# Parked-interrupt short-circuit: only signal an INTERRUPTED# end when there is actual HITL work to close; otherwise the# session is effectively idle and the call is a silent no-op.@@ -797,8 +824,12 @@ class Agent:else:await self._handle_incoming_messages(msgs)# Update the context with the incoming message and state- self.state.reply_id = _generate_id()- self.state.cur_iter = 0+ self.state.reply_context = ReplyContext(+ reply_id=_generate_id(),+ cur_iter=0,+ structured_schema=structured_schema,+ structured_output=None,+ )yield ReplyStartEvent(session_id=self.state.session_id,@@ -806,157 +837,141 @@ class Agent:name=self.name,)+ # Update the structured output tool for new requirements or+ # from the previous reply+ await self.toolkit.remove_tool(_GenerateStructuredOutput.name)+ if self.state.reply_context.structured_schema:+ await self.toolkit.add_tool(+ _GenerateStructuredOutput(+ schema=self.state.reply_context.structured_schema,+ ),+ )+# =================================================================# Step 3: Enter the reasoning-acting loop until reaching max_iters# or no more tool calls to execute# =================================================================- while self.state.cur_iter < self.react_config.max_iters:+ final_msg: Msg | None = None+ while True:# =============================================================- # Step 3.1:+ # Step 3.1: Decide the next action based on the current state# =============================================================- action, data = self._check_next_action()- if action == "exit" and isinstance(data, Msg):- yield data- return+ next_action = self._next_action(final_msg)++ match next_action:+ case Exit(exit_msg=exit_msg, exit_events=exit_events):+ for exit_event in exit_events or []:+ yield exit_event+ if exit_msg:+ yield exit_msg+ return- # =============================================================- # Step 3.2: Execute reasoning if no more tools to be executed- # =============================================================- if action == "reasoning":- # Compressed the memory if needed before reasoning- await self.compress_context()+ case Reasoning(hint=hint, tool_choice=tool_choice):+ final_msg = None+ if hint:+ self.state.append_context(self.name, [hint])- # Inject runtime state if needed before reasoning- async for evt in self._inject_runtime_state():- yield evt+ # Compressed the memory if needed before reasoning+ await self.compress_context()++ # Inject runtime state if needed before reasoning+ async for evt in self._inject_runtime_state():+ yield evt++ # Perform reasoning+ interrupted = False+ async for evt in self._reasoning(+ tool_choice=tool_choice,+ ):+ if isinstance(evt, Msg):+ # Candidate final message; ``_next_action``+ # decides whether it ends the reply+ final_msg = evt+ continue++ if isinstance(evt, ModelCallEndEvent):+ interrupted = (+ evt.finished_reason+ == FinishedReason.INTERRUPTED+ )++ yield evt- # Perform reasoning- interrupted = False- async for evt in self._reasoning():- # Exit the loop when no tool calls generated and the- # reply message is generated- if isinstance(evt, Msg):+ if interrupted:end_event = ReplyEndEvent(session_id=self.state.session_id,reply_id=self.state.reply_id,- finished_reason=ReplyFinishedReason.COMPLETED,+ finished_reason=(+ ReplyFinishedReason.INTERRUPTED+ ),)- yield evtreturn- elif isinstance(evt, ModelCallEndEvent):- interrupted = (- evt.finished_reason- == FinishedReason.INTERRUPTED- )-- yield evt-- if interrupted:- end_event = ReplyEndEvent(- session_id=self.state.session_id,- reply_id=self.state.reply_id,- finished_reason=ReplyFinishedReason.INTERRUPTED,- )- return-- # =============================================================- # Step 3.3: Getting batches of tool calls to be executed- # - If not, finish loop by yielding RunFinishedEvent and exit- # - Otherwise, execute by batch and continue the loop- # =============================================================- for batch in await self._batch_tool_calls():- if batch.type == "sequential":- evt_generator = self._execute_sequential_tool_calls(- batch.tool_calls,- )+ case Acting(tool_calls=tool_calls):+ for batch in await self._batch_tool_calls(tool_calls):+ if batch.type == "sequential":+ evt_generator = (+ self._execute_sequential_tool_calls(+ batch.tool_calls,+ )+ )- elif batch.type == "concurrent":- evt_generator = self._execute_concurrent_tool_calls(- batch.tool_calls,- )+ elif batch.type == "concurrent":+ evt_generator = (+ self._execute_concurrent_tool_calls(+ batch.tool_calls,+ )+ )- else:- raise ValueError(- f"Invalid batch type: {batch.type}",- )+ else:+ raise ValueError(+ f"Invalid batch type: {batch.type}",+ )- break_execution_for_hitl = False- break_execution_for_interruption = False- break_message = ""- async for evt in evt_generator:- yield evt- if isinstance(- evt,- (- RequireUserConfirmEvent,- RequireExternalExecutionEvent,- ),- ):- break_execution_for_hitl = True- break_message = (- "Waiting for tool calls to be confirmed or "- "executed from outside ..."- )+ break_execution_for_hitl = False+ break_execution_for_interruption = False+ async for evt in evt_generator:+ yield evt+ if isinstance(+ evt,+ (+ RequireUserConfirmEvent,+ RequireExternalExecutionEvent,+ ),+ ):+ break_execution_for_hitl = True- elif (- isinstance(evt, ToolResultEndEvent)- and evt.state == ToolResultState.INTERRUPTED- ):- # Handle the interruption event- break_execution_for_interruption = True+ elif (+ isinstance(evt, ToolResultEndEvent)+ and evt.state+ == ToolResultState.INTERRUPTED+ ):+ # Handle the interruption event+ break_execution_for_interruption = True++ if break_execution_for_interruption:+ end_event = ReplyEndEvent(+ session_id=self.state.session_id,+ reply_id=self.state.reply_id,+ finished_reason=(+ ReplyFinishedReason.INTERRUPTED+ ),+ )+ return- if break_execution_for_interruption:- end_event = ReplyEndEvent(- session_id=self.state.session_id,- reply_id=self.state.reply_id,- finished_reason=ReplyFinishedReason.INTERRUPTED,- )- return+ if break_execution_for_hitl:+ break- # If it requires outside interaction stop executing the- # next batch and wait for outside trigger events- if break_execution_for_hitl:- yield AssistantMsg(- id=self.state.reply_id,- name=self.name,- content=break_message,- )- return+ if break_execution_for_hitl:+ # Stop executing the next batches, and go back to+ # ``_next_action``, which parks the reply on the+ # awaiting tool calls. The unfinished round isn't+ # counted into ``cur_iter``+ continue# Update iteration count after each round of reasoning-actingself.state.cur_iter += 1- # =================================================================- # Step 4: Handling the max iteration executed- # =================================================================- yield ExceedMaxItersEvent(- reply_id=self.state.reply_id,- name=self.name,- )- logger.warning(- "Agent %s exceeds the max iteration numbers %d. "- "Stop the react loop.",- self.name,- self.react_config.max_iters,- )-- # Mirror the normal-exit path so subscribers (e.g. SSE clients- # waiting on a terminal event) don't hang when the loop bails- # out on max_iters.- end_event = ReplyEndEvent(- session_id=self.state.session_id,- reply_id=self.state.reply_id,- finished_reason=ReplyFinishedReason.EXCEED_MAX_ITERS,- )-- yield AssistantMsg(- id=self.state.reply_id,- name=self.name,- content="Executed maximum iterations of reasoning-acting loop "- "without finishing the task.",- )-except asyncio.CancelledError:# Handle the CancelledError within the _reply_impl for the# agent middlewares@@ -971,23 +986,26 @@ class Agent:finally:if end_event is not None:- if (+ interrupted_end = (end_event.finished_reason== ReplyFinishedReason.INTERRUPTED- ):+ )+ if interrupted_end:# Handle the context when interruptionasync for _ in self._close_unfinished_tool_calls():yield _- # A fallback msg object+ yield end_event++ if interrupted_end:+ # The fallback msg goes last: Msg terminates the streamyield AssistantMsg(id=self.state.reply_id,name=self.name,content=self.react_config.interruption_message,+ finished_reason=ReplyFinishedReason.INTERRUPTED,)- yield end_event-async def _inject_runtime_state(self,) -> AsyncGenerator[HintBlockEvent, None]:@@ -1437,6 +1455,8 @@ class Agent:# Text only response messagecontent=list(completed_response.content),usage=final_usage,+ # The INTERRUPTED case is excluded by the branch condition+ finished_reason=ReplyFinishedReason.COMPLETED,)async def _check_incoming_event(@@ -1463,25 +1483,17 @@ class Agent:the reply id and iteration count should be updated for the newreply."""- awaiting_confirmations = []- awaiting_external_executions = []-- last_msg = self._get_last_msg()- if last_msg:- # The completed tool call ids- tool_result_ids = [- _.id for _ in last_msg.get_content_blocks("tool_result")- ]-- for tool_call in last_msg.get_content_blocks("tool_call"):- if tool_call.state == ToolCallState.ASKING:- awaiting_confirmations.append(tool_call.id)- elif (- tool_call.state == ToolCallState.SUBMITTED- and tool_call.id not in tool_result_ids- ):- # submitted but no result yet, i.e. external execution- awaiting_external_executions.append(tool_call.id)+ awaiting_tool_calls = self.state.get_awaiting_tool_calls(self.name)+ awaiting_confirmations = [+ _.id+ for _ in awaiting_tool_calls+ if _.state == ToolCallState.ASKING+ ]+ awaiting_external_executions = [+ _.id+ for _ in awaiting_tool_calls+ if _.state == ToolCallState.SUBMITTED+ ]# No incoming event but neededif event is None and (@@ -1660,13 +1672,14 @@ class Agent:self.state.context.append(msg)- async def _batch_tool_calls(self) -> list[_ToolCallBatch]:+ async def _batch_tool_calls(+ self,+ tool_calls: list[ToolCallBlock],+ ) -> list[_ToolCallBatch]:"""Batch the tool calls into a sequence of batches that should beexecuted **sequentially** or **concurrently** according to the toolproperties `is_concurrency_safe` and `is_read_only`."""- # All tool calls that haven't the corresponding results in the context- tool_calls = self._get_executable_tool_calls()# Batch the tool calls according to whether they can be executed# concurrently or not@@ -2892,36 +2905,15 @@ class Agent:if not persisted_blocks and msg_usage is None:return- if len(self.state.context) == 0:- self.state.context.append(- AssistantMsg(- id=self.state.reply_id,- name=self.name,- content=persisted_blocks,- usage=msg_usage,- ),- )- else:- last_msg = self.state.context[-1]- if last_msg.role == "assistant" and last_msg.name == self.name:- if isinstance(last_msg.content, str):- last_msg.content = [TextBlock(text=last_msg.content)]- last_msg.content.extend(persisted_blocks)- if msg_usage is not None:- if last_msg.usage is None:- last_msg.usage = msg_usage- else:- last_msg.usage.input_tokens += msg_usage.input_tokens- last_msg.usage.output_tokens += msg_usage.output_tokens+ self.state.append_context(self.name, persisted_blocks)++ tail = self.state.context[-1]+ if msg_usage is not None:+ if tail.usage is None:+ tail.usage = msg_usageelse:- self.state.context.append(- AssistantMsg(- id=self.state.reply_id,- name=self.name,- content=persisted_blocks,- usage=msg_usage,- ),- )+ tail.usage.input_tokens += msg_usage.input_tokens+ tail.usage.output_tokens += msg_usage.output_tokensdef _get_last_msg(self) -> Msg | None:"""Get the last message in the context that belongs to this agent."""@@ -2932,134 +2924,202 @@ class Agent:return last_msgreturn None- def _check_next_action(+ def _next_action(self,- ) -> (- tuple[Literal["exit"], Msg]- | tuple[Literal["reasoning"], None]- | tuple[Literal["acting"], None]- ):- """Check the next action for the agent-- Awaiting tool calls:- The tool calls waiting for the outside events (confirmation or- external execution results, state = "asking" or "submitted")- Executable tool calls:- The tool calls allowed by the incoming confirmation events and- haven't been executed yet (state = "allowed")-- The next action:-- | | Awaiting tool calls | No awaiting tool call |- | ------------------------ | ---------------------------- | ---------------------------- |- | Executable tool calls | Acting executable tool calls | Acting executable tool calls |- | No executable tool calls | Exit the _reply | Reasoning |+ final_msg: Msg | None = None,+ ) -> Reasoning | Acting | Exit:+ """Decide the next action from the current state. Read-only: all+ side effects are performed by the caller ``_reply_impl``."""++ # ===========================================================+ # Step 1: Check executable and awaiting tool calls+ # ===========================================================+ awaiting_tool_calls = self.state.get_awaiting_tool_calls(self.name)- Returns:- `tuple[Literal["exit"], Msg]`:- If there is no executable tool call and there are awaiting tool- calls, which means the agent is waiting for the outside events- and should not do anything before that, the next action is to- exit the _reply and wait for the outside events.- `tuple[Literal["reasoning"], None]`:- If there is no executable tool call and no awaiting tool call,- which means the agent has nothing to do in this iteration and- can continue reasoning for the next step.- `tuple[Literal["acting"], None]`:- If there are executable tool calls, which means the agent can- act by executing the tool calls.- """ # noqa: E501last_msg = self._get_last_msg()- if last_msg is None:- return "reasoning", None+ if last_msg is not None:+ # In case wrong tool call state, first filter with the results+ finished_ids = {+ _.id for _ in last_msg.get_content_blocks("tool_result")+ }+ # With awaiting tool calls, PENDING ones are blocked (e.g.+ # deduplicated in a batch) and wait; only ALLOWED ones execute+ executable_tool_calls = [+ _+ for _ in last_msg.get_content_blocks("tool_call")+ if _.id not in finished_ids+ and (+ _.state == ToolCallState.ALLOWED+ or (+ _.state == ToolCallState.PENDING+ and not awaiting_tool_calls+ )+ )+ ]+ if executable_tool_calls:+ # Next execute the tool calls+ return Acting(tool_calls=executable_tool_calls)- # In case wrong tool call state, first filter with the results- finished_ids = {- _.id for _ in last_msg.get_content_blocks("tool_result")- }- unfinished_tool_calls = [- _- for _ in last_msg.get_content_blocks("tool_call")- if _.id not in finished_ids- ]+ if awaiting_tool_calls:+ # Next wait for the permission or external execution to finish+ return Exit(+ # The reply doesn't finish yet+ exit_events=None,+ exit_msg=AssistantMsg(+ id=self.state.reply_id,+ name=self.name,+ # both confirmation or external execution+ content="I'm waiting for your permission or the "+ "external execution to finish.",+ ),+ )- # Find if there are executable or awaiting tool calls- awaiting_tool_calls: list[ToolCallBlock] = []- executable_tool_calls: list[ToolCallBlock] = []+ # ===========================================================+ # Step 2: Check structured output if no blocked tool calls+ # ===========================================================- confirming_names, asking_names = [], []- for _ in unfinished_tool_calls:- if _.state in [ToolCallState.PENDING, ToolCallState.ALLOWED]:- executable_tool_calls.append(_)+ # Structured output requirement and satisfaction+ required = self.state.reply_context.structured_schema is not None+ satisfied = self.state.reply_context.structured_output is not None- elif _.state == ToolCallState.ASKING:- asking_names.append(_.name)- awaiting_tool_calls.append(_)+ if required and satisfied:+ # Next return the structured output and finish the reply+ return Exit(+ exit_events=[+ ReplyEndEvent(+ session_id=self.state.session_id,+ reply_id=self.state.reply_id,+ finished_reason=ReplyFinishedReason.COMPLETED,+ ),+ ],+ exit_msg=AssistantMsg(+ id=self.state.reply_id,+ name=self.name,+ content="The required structured output is generated.",+ finished_reason=ReplyFinishedReason.COMPLETED,+ structured_output=deepcopy(+ self.state.reply_context.structured_output,+ ),+ ),+ )- elif _.state == ToolCallState.SUBMITTED:- confirming_names.append(_.name)- awaiting_tool_calls.append(_)+ elif required and not satisfied:+ # Maybe the model needs futher reasoning-acting to+ # generate the structured output+ tool_choice = None+ suffix = (+ "Call it when you are ready to generate the final "+ "structured output."+ )- if executable_tool_calls:- return "acting", None+ # Allow extra grace iterations for structured generation+ if (+ self.state.cur_iter+ >= self.react_config.max_iters+ + self.react_config.structured_output_grace_iters+ ):+ return Exit(+ exit_events=[+ ExceedMaxItersEvent(+ reply_id=self.state.reply_id,+ name=self.name,+ ),+ ReplyEndEvent(+ session_id=self.state.session_id,+ reply_id=self.state.reply_id,+ finished_reason=(+ ReplyFinishedReason.EXCEED_MAX_ITERS+ ),+ ),+ ],+ exit_msg=AssistantMsg(+ id=self.state.reply_id,+ name=self.name,+ content="The maximum reasoning-acting iterations "+ "are exceeded.",+ finished_reason=ReplyFinishedReason.EXCEED_MAX_ITERS,+ ),+ )- if awaiting_tool_calls:- # Prepare the message- evt = ["I'm waiting for "]- if asking_names:- evt += [- f"user confirmation for {len(asking_names)} tool calls",- ]-- if confirming_names:- if evt:- evt += [", and "]- evt += [- f"external execution results for {len(confirming_names)} "- f"tool calls",- ]-- text = "".join(evt) + "."-- return "exit", AssistantMsg(- name=self.name,- content=[TextBlock(text=text)],+ if self.state.cur_iter >= self.react_config.max_iters:+ # Must call the structured output tool and return the+ # structured output+ tool_choice = ToolChoice(+ mode=_GenerateStructuredOutput.name,+ )+ suffix = (+ "You have reached the maximum reasoning-acting "+ "iterations, so call this tool at once to generate "+ "the final structured output."+ )++ # Next continue reasoning with injected hint+ return Reasoning(+ hint=HintBlock(+ hint=[+ TextBlock(+ text=(+ "<system-reminder>You're required to "+ "generate structured output by calling the "+ f"'{_GenerateStructuredOutput.name}' tool. "+ f"{suffix}</system-reminder>"+ ),+ ),+ ],+ source='{"label": "System", "sublabel": '+ '"Structured Output Requirement"}',+ ),+ tool_choice=tool_choice,)- return "reasoning", None+ # ===========================================================+ # Step 3: Exit with the final message, or continue reasoning+ # ===========================================================- def _get_executable_tool_calls(self) -> list[ToolCallBlock]:- """Get tool calls from the last message that to be executed, which- means we should reserve the tool calls that:+ # The last reasoning produced a text-only final message+ if final_msg is not None:+ return Exit(+ exit_events=[+ ReplyEndEvent(+ session_id=self.state.session_id,+ reply_id=self.state.reply_id,+ finished_reason=ReplyFinishedReason.COMPLETED,+ ),+ ],+ exit_msg=final_msg,+ )- 1. doesn't have results yet, **and**- 2. haven't been submitted for external execution (state != "submitted")- """- last_msg = self._get_last_msg()- if last_msg is None:- return []-- # The tool results- result_ids = {_.id for _ in last_msg.get_content_blocks("tool_result")}- # The tool calls that doesn't have results yet- tool_calls_wo_results = [- _- for _ in last_msg.get_content_blocks("tool_call")- if _.id not in result_ids- ]+ if self.state.cur_iter >= self.react_config.max_iters:+ logger.warning(+ "Agent %s exceeds the max iteration numbers %d. "+ "Stop the react loop.",+ self.name,+ self.react_config.max_iters,+ )- # Filter the ones that are "submitted", which already report the- # external execution requirement- pending_tool_calls = [- _- for _ in tool_calls_wo_results- if _.state- in [- ToolCallState.PENDING,- ToolCallState.ALLOWED,- ]- ]- return pending_tool_calls+ return Exit(+ exit_events=[+ ExceedMaxItersEvent(+ reply_id=self.state.reply_id,+ name=self.name,+ ),+ ReplyEndEvent(+ session_id=self.state.session_id,+ reply_id=self.state.reply_id,+ finished_reason=ReplyFinishedReason.EXCEED_MAX_ITERS,+ ),+ ],+ exit_msg=AssistantMsg(+ id=self.state.reply_id,+ name=self.name,+ content="The maximum reasoning-acting iterations are "+ "exceeded.",+ finished_reason=ReplyFinishedReason.EXCEED_MAX_ITERS,+ ),+ )++ # By default, continue reasoning+ return Reasoning()async def _convert_chat_response_to_event(self,diff --git a/src/agentscope/agent/_config.py b/src/agentscope/agent/_config.pyindex f40f266d8..75ce585da 100644--- a/src/agentscope/agent/_config.py+++ b/src/agentscope/agent/_config.py@@ -290,6 +290,18 @@ class ReActConfig(BaseModel):)"""The maximum number of iterations for the reasoning-acting loop."""+ structured_output_grace_iters: int = Field(+ title="Grace Iters for Structured Output",+ description=(+ "The grace iterations for structured output when exceeding the "+ "max iterations"+ ),+ default=5,+ gt=0,+ )+ """The extra iterations allowed beyond ``max_iters`` to generate the+ required structured output."""+stop_on_reject: bool = Field(title="Rejection Handling",default=False,diff --git a/src/agentscope/agent/_structured_output_tool.py b/src/agentscope/agent/_structured_output_tool.pynew file mode 100644index 000000000..baa327bb2--- /dev/null+++ b/src/agentscope/agent/_structured_output_tool.py@@ -0,0 +1,165 @@+# -*- coding: utf-8 -*-+"""The builtin tool used to generate the required structured output."""+from copy import deepcopy+from typing import Any, Generator, List, Type++from jsonschema import Draft202012Validator, validators+from pydantic import BaseModel, ValidationError++from ..permission._context import PermissionContext+from ..permission._decision import PermissionDecision+from ..permission._types import PermissionBehavior++from ..tool._utils import _remove_title_field+from ..message import TextBlock, ToolResultState+from ..tool._base import ToolBase, ToolMiddlewareBase+from ..tool._response import ToolChunk+from ..state import AgentState+++def _extend_with_default(validator_class: Any) -> Any:+ """Extend a jsonschema validator to fill the schema-declared defaults+ into the instance during validation."""+ validate_properties = validator_class.VALIDATORS["properties"]++ def set_defaults(+ validator: Any,+ properties: dict,+ instance: Any,+ schema: dict,+ ) -> Generator[Any, None, None]:+ for prop, subschema in properties.items():+ if isinstance(instance, dict) and "default" in subschema:+ instance.setdefault(prop, deepcopy(subschema["default"]))+ yield from validate_properties(validator, properties, instance, schema)++ return validators.extend(validator_class, {"properties": set_defaults})+++_DefaultFillingValidator = _extend_with_default(Draft202012Validator)+++class _GenerateStructuredOutput(ToolBase):+ """The builtin tool used to generate structured output."""++ name = "GenerateStructuredOutput"++ description = """Generate the required structured output by this tool.++This tool is equipped only when you're required to generate structured output.+The input schema represents the required structured output.+When you are ready to generate a structured output, call this tool with the+structured output as input.+When you're equipped this tool, you MUST end your response with calling this+tool. Once this tool is called, your current response is finished and the+structured output is sent to the user.++# When to Use This Tool+- When you collect enough resources and information.+"""+ is_state_injected = True+ is_concurrency_safe = True+ is_read_only = True++ def __init__(+ self,+ schema: Type[BaseModel] | dict,+ middlewares: List[ToolMiddlewareBase] | None = None,+ ) -> None:+ """Initialize the tool with a model class or a JSON schema dict."""+ super().__init__(middlewares=middlewares)+ self.schema = schema++ @property+ def input_schema(self) -> dict: # type: ignore[override]+ """The input schema of this tool."""+ if isinstance(self.schema, type):+ return _remove_title_field(self.schema.model_json_schema())+ return _remove_title_field(deepcopy(self.schema))++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """The generate structured output tool is always allowed+ to be called."""+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message=f"{self.name} is always allowed.",+ )++ async def call( # type: ignore[override]+ self,+ _agent_state: AgentState,+ **kwargs: Any,+ ) -> ToolChunk:+ """Validate the given structured output and record it in the agent+ state. The tool input fields (defined by the required schema) arrive+ as keyword arguments."""++ schema = _agent_state.reply_context.structured_schema+ if not schema:+ return ToolChunk(+ content=[+ TextBlock(+ text="No structured output is required for now.",+ ),+ ],+ state=ToolResultState.SUCCESS,+ )++ if isinstance(schema, type):+ # In-process: validate with the model class itself+ try:+ validated = schema.model_validate(kwargs)+ # Custom validators may raise arbitrary exceptions+ except Exception as e: # pylint: disable=broad-exception-caught+ if isinstance(e, ValidationError):+ message = "; ".join(+ f"{'.'.join(str(_) for _ in err['loc'])}: "+ f"{err['msg']}"+ for err in e.errors()+ )+ else:+ message = str(e)+ return ToolChunk(+ content=[+ TextBlock(+ text="ValidationError: Structured output "+ f"validation failed with error: {message}",+ ),+ ],+ state=ToolResultState.ERROR,+ )+ _agent_state.reply_context.structured_output = (+ validated.model_dump(mode="json")+ )+ else:+ # Reloaded state: only the JSON schema dict remains, and the+ # validation fills the schema-declared defaults into ``kwargs``+ validator = _DefaultFillingValidator(schema)+ errors = list(validator.iter_errors(kwargs))+ if errors:+ messages = "; ".join(+ f"{_.json_path}: {_.message}" for _ in errors+ )+ return ToolChunk(+ content=[+ TextBlock(+ text="ValidationError: Structured output "+ f"validation failed with error: {messages}",+ ),+ ],+ state=ToolResultState.ERROR,+ )+ _agent_state.reply_context.structured_output = kwargs++ return ToolChunk(+ content=[+ TextBlock(+ text="Structured output generated successfully.",+ ),+ ],+ state=ToolResultState.SUCCESS,+ )diff --git a/src/agentscope/agent/_utils.py b/src/agentscope/agent/_utils.pyindex 2c3889a7e..100749a2d 100644--- a/src/agentscope/agent/_utils.py+++ b/src/agentscope/agent/_utils.py@@ -2,8 +2,14 @@"""The utility classes used in building the agent class."""from dataclasses import dataclassfrom typing import Literal+from datetime import timezone, tzinfo+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError+from pydantic import BaseModel-from ..message import ToolCallBlock+from ..tool import ToolChoice+from ..message import ToolCallBlock, HintBlock, Msg+from ..event import AgentEvent+from .._logging import logger@dataclass@@ -15,3 +21,38 @@ class _ToolCallBatch:"""The batch type"""tool_calls: list[ToolCallBlock]"""The list of tool calls in the batch."""+++class Acting(BaseModel):+ """Next action: execute the given tool calls."""++ tool_calls: list[ToolCallBlock]+++class Reasoning(BaseModel):+ """Next action: another model call, with optional hint and tool choice."""++ hint: HintBlock | None = None+ tool_choice: ToolChoice | None = None+++class Exit(BaseModel):+ """Next action: end the reply."""++ exit_msg: Msg+ exit_events: list[AgentEvent] | None = None+++def _resolve_timezone(name: str) -> tzinfo:+ """Resolve the given timezone name, falling back to UTC when the name is+ invalid or the timezone database is unavailable, e.g. on Windows or slim+ images without the ``tzdata`` package."""+ try:+ return ZoneInfo(name)+ except (ZoneInfoNotFoundError, ValueError):+ logger.warning(+ "Failed to resolve the timezone %s, fallback to UTC. Install the "+ "'tzdata' package if the timezone database is missing.",+ repr(name),+ )+ return timezone.utcdiff --git a/src/agentscope/message/_base.py b/src/agentscope/message/_base.pyindex 543842bed..73009865b 100644--- a/src/agentscope/message/_base.py+++ b/src/agentscope/message/_base.py@@ -68,6 +68,10 @@ class Msg(BaseModel):"""The message class in AgentScope, responsible for information storageand transmission among different agents."""+ # =========================================================================+ # The fields that will be fed into the context+ # =========================================================================+name: str"""The name of the sender."""content: list[ContentBlock]@@ -76,20 +80,38 @@ class Msg(BaseModel):"""The role of the sender."""id: str = Field(default_factory=_generate_id)"""The message identifier."""++ # =========================================================================+ # The fields that record the message metadata (creation time, current+ # usage and additional metadata).+ # =========================================================================+metadata: dict = Field(default_factory=dict)"""The metadata of the message"""created_at: str = Field(default_factory=lambda: datetime.now().isoformat())"""The creation time of the message"""+ usage: Usage | None = Field(default=None)+ """The token usage information of the message"""++ # =========================================================================+ # The fields used for workflow control, including the finished time,+ # reason, error message and structured output.+ # =========================================================================+finished_at: str | None = Field(default=None)"""The finished time of the message"""finished_reason: ReplyFinishedReason | None = Field(default=None)"""Terminal reason of this reply (error / interrupted /exceed_max_iters). ``None`` until a ``REPLY_END`` event is applied."""+ structured_output: dict | None = Field(default=None)+ """The structured output of the reply. Populated only when a structured+ output is requested via ``reply(..., structured_schema=...)`` and+ successfully generated; ``None`` otherwise, e.g. not requested, or the+ reply ends (interrupted / error / exceed_max_iters) before the output+ is generated."""error: ErrorInfo | None = Field(default=None)"""Structured error info, populated only when``finished_reason == ReplyFinishedReason.ERROR``."""- usage: Usage | None = Field(default=None)- """The token usage information of the message"""@model_validator(mode="after")def validate_role_content(self) -> Self:@@ -493,6 +515,7 @@ def UserMsg(metadata: dict | None = None,created_at: str | None = None,finished_at: str | None = None,+ finished_reason: ReplyFinishedReason | None = None,id: str | None = None, # pylint: disable=redefined-builtin) -> Msg:"""Create a user message with role ``"user"``.@@ -513,6 +536,9 @@ def UserMsg(finished_at (`str | None`, optional):ISO-format timestamp for when the message was finished. Defaults tothe same value as ``created_at`` when not provided.+ finished_reason (`ReplyFinishedReason | None`, optional):+ The reason the message was finished. Defaults to ``None`` when not+ provided.id (`str | None`, optional):A unique identifier for the message. A random UUID hex string isgenerated when not provided.@@ -531,6 +557,7 @@ def UserMsg(metadata=metadata or {},created_at=created_at,finished_at=finished_at,+ finished_reason=finished_reason,id=id or _generate_id(),)@@ -541,6 +568,8 @@ def AssistantMsg(metadata: dict | None = None,created_at: str | None = None,finished_at: str | None = None,+ finished_reason: ReplyFinishedReason | None = None,+ structured_output: dict | None = None,id: str | None = None, # pylint: disable=redefined-builtinusage: Usage | None = None,) -> Msg:@@ -562,6 +591,10 @@ def AssistantMsg(finished_at (`str | None`, optional):ISO-format timestamp for when the message was finished. Not set bydefault for assistant messages.+ structured_output (`dict | None`, optional):+ The structured output carried by the assistant message.+ finished_reason (`ReplyFinishedReason | None`, optional):+ The finished reason for the assistant message.id (`str | None`, optional):A unique identifier for the message. A random UUID hex string isgenerated when not provided.@@ -579,6 +612,8 @@ def AssistantMsg(metadata=metadata or {},created_at=created_at or datetime.now().isoformat(),finished_at=finished_at,+ finished_reason=finished_reason,+ structured_output=structured_output,id=id or _generate_id(),usage=usage,)@@ -590,6 +625,7 @@ def SystemMsg(metadata: dict | None = None,created_at: str | None = None,finished_at: str | None = None,+ finished_reason: ReplyFinishedReason | None = None,id: str | None = None, # pylint: disable=redefined-builtin) -> Msg:"""Create a system message with role ``"system"``.@@ -610,6 +646,8 @@ def SystemMsg(finished_at (`str | None`, optional):ISO-format timestamp for when the message was finished. Defaults tothe same value as ``created_at`` when not provided.+ finished_reason (`ReplyFinishedReason | None`, optional):+ The finished reason for the system message.id (`str | None`, optional):A unique identifier for the message. A random UUID hex string isgenerated when not provided.@@ -628,5 +666,6 @@ def SystemMsg(metadata=metadata or {},created_at=created_at,finished_at=finished_at,+ finished_reason=finished_reason,id=id or _generate_id(),)diff --git a/src/agentscope/state/__init__.py b/src/agentscope/state/__init__.pyindex d9db1c58b..13f47eca7 100644--- a/src/agentscope/state/__init__.py+++ b/src/agentscope/state/__init__.py@@ -1,11 +1,13 @@# -*- coding: utf-8 -*-"""The agent state module in agentscope."""-from ._state import AgentState, TaskContext+from ._state import AgentState, TaskContext, ReplyContext, ToolContextfrom ._task import Task__all__ = ["Task","TaskContext",+ "ReplyContext",+ "ToolContext","AgentState",]diff --git a/src/agentscope/state/_state.py b/src/agentscope/state/_state.pyindex 3f3b6765d..667afd7d6 100644--- a/src/agentscope/state/_state.py+++ b/src/agentscope/state/_state.py@@ -1,8 +1,8 @@# -*- coding: utf-8 -*-"""The agent state class."""-from typing import Any+from typing import Any, Type-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, field_serializer, model_validatorimport aiofiles.os@@ -146,6 +146,33 @@ class TaskContext(BaseModel):"""The task context."""+class ReplyContext(BaseModel):+ """The context of the current agent reply."""++ reply_id: str = Field(default_factory=_generate_id)+ """The id of the current reply, which is also used as the id of the+ final message of the reply."""++ cur_iter: int = 0+ """The current iteration of the agent's reasoning-acting loop in this+ reply."""++ structured_schema: Type[BaseModel] | dict | None = None+ """The reply's structured output requirement, a pydantic model class in+ process and serialized as its JSON schema dict."""++ @field_serializer("structured_schema")+ def _serialize_structured_schema(+ self,+ value: Type[BaseModel] | dict | None,+ ) -> dict | None:+ """Serialize a schema class into its JSON schema dict."""+ return value.model_json_schema() if isinstance(value, type) else value++ structured_output: dict | None = None+ """The structured output generated within this reply."""++class AgentState(BaseModel):"""The agent state that should be saved and loaded from storage."""@@ -156,13 +183,57 @@ class AgentState(BaseModel):summary: str | list[TextBlock | DataBlock] = """""The compressed summary of the context, which will be prepended to thecontext when fed into the LLM."""+context: list[Msg] = Field(default_factory=list)"""The uncompressed conversation context, which will be fed into the LLM"""- reply_id: str = Field(default_factory=_generate_id)- """The id of the current reply, which is also used as the id of the- final message of the reply."""- cur_iter: int = 0- """The current iteration of the agent's reasoning-acting loop."""++ # =================================================================+ # For backword compatibility+ # =================================================================+ @model_validator(mode="before")+ @classmethod+ def _migrate_legacy_reply_fields(cls, data: Any) -> Any:+ """Migrate the top-level ``reply_id``/``cur_iter`` fields (the+ pre-``reply_context`` storage format) into ``reply_context``, so+ that the states saved by previous versions load correctly."""+ if isinstance(data, dict) and (+ "reply_id" in data or "cur_iter" in data+ ):+ data = dict(data)+ reply_context = dict(data.get("reply_context") or {})+ for key in ("reply_id", "cur_iter"):+ if key in data and key not in reply_context:+ reply_context[key] = data.pop(key)+ data["reply_context"] = reply_context+ return data++ @property+ def reply_id(self) -> str:+ """The reply id of the current reply."""+ return self.reply_context.reply_id++ @reply_id.setter+ def reply_id(self, value: str) -> None:+ """Set the reply id of the current reply."""+ self.reply_context.reply_id = value++ @property+ def cur_iter(self) -> int:+ """The current iteration of the agent's reasoning-acting loop in+ this reply."""+ return self.reply_context.cur_iter++ @cur_iter.setter+ def cur_iter(self, value: int) -> None:+ """Set the current iteration of the agent's reasoning-acting loop in+ this reply."""+ self.reply_context.cur_iter = value++ # =================================================================+ # The reply context+ # =================================================================+ reply_context: ReplyContext = Field(default_factory=ReplyContext)+ """The reply related context."""# =================================================================# The permission context@@ -236,16 +307,33 @@ class AgentState(BaseModel):`bool`:``True`` when at least one such tool call is pending."""+ return bool(self.get_awaiting_tool_calls(name))++ def get_awaiting_tool_calls(self, name: str) -> list[ToolCallBlock]:+ """Get the tail assistant message's tool calls still awaiting an+ outside response — an ``ASKING`` user confirmation or a+ ``SUBMITTED`` external execution with no matching tool result yet.++ Args:+ name (`str`):+ Only messages authored by this agent name are inspected;+ observed messages from other agents are ignored.++ Returns:+ `list[ToolCallBlock]`:+ The awaiting tool call blocks, empty if none.+ """if not self.context:- return False+ return []last_msg = self.context[-1]if last_msg.role != "assistant" or last_msg.name != name:- return False+ return []result_ids = {b.id for b in last_msg.get_content_blocks("tool_result")}- return any(- tc.state == ToolCallState.ASKING+ return [+ tc+ for tc in last_msg.get_content_blocks("tool_call")+ if tc.state == ToolCallState.ASKINGor (tc.state == ToolCallState.SUBMITTED and tc.id not in result_ids)- for tc in last_msg.get_content_blocks("tool_call")- )+ ]diff --git a/src/agentscope/tool/_toolkit.py b/src/agentscope/tool/_toolkit.pyindex 06133b8b4..3747248f6 100644--- a/src/agentscope/tool/_toolkit.py+++ b/src/agentscope/tool/_toolkit.py@@ -612,3 +612,60 @@ class Toolkit:def clear(self) -> None:"""Clear the registered tools, skills and MCPs."""self.tool_groups.clear()++ async def add_tool(+ self,+ tool: ToolBase | list[ToolBase],+ group_name: str = "basic",+ ) -> None:+ """Add tool to the toolkit on-the-fly.++ Args:+ tool (`ToolBase | list[ToolBase]`):+ The tool to be added.+ group_name (`str`):+ The group name of the tool to be added.+ """++ new_tools = tool if isinstance(tool, list) else [tool]++ for group in self.tool_groups:+ if group.name == group_name:+ existing_tools = {_.name for _ in group.tools}+ for new_tool in new_tools:+ if new_tool.name in existing_tools:+ logger.warning(+ "Duplicate tool name '%s' found in group '%s', "+ "overwriting it.",+ new_tool.name,+ group.name,+ )+ # override the existing tool+ group.tools = [+ t for t in group.tools if t.name != new_tool.name+ ] + [new_tool]+ else:+ group.tools.append(new_tool)+ existing_tools.add(new_tool.name)++ return++ raise ValueError(+ f"Cannot find group '{group_name}' in toolkit, only "+ f"{[_.name for _ in self.tool_groups]} are available.",+ )++ async def remove_tool(self, tool_name: str | list[str]) -> None:+ """Remove tool from the toolkit on-the-fly.++ Args:+ tool_name (`str | list[str]`):+ The name of the tool to be removed.+ """+ if isinstance(tool_name, str):+ tool_name = [tool_name]++ for group in self.tool_groups:+ group.tools = [+ tool for tool in group.tools if tool.name not in tool_name+ ]diff --git a/tests/agent_basic_test.py b/tests/agent_basic_test.pyindex d3f9f07c7..1411f60f0 100644--- a/tests/agent_basic_test.py+++ b/tests/agent_basic_test.py@@ -23,6 +23,7 @@ from agentscope.message import (ToolCallBlock,UserMsg,)+from agentscope.types import ReplyFinishedReasonclass MockSequentialTool(ToolBase):@@ -131,6 +132,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"metadata": {},"name": "Friday",@@ -311,6 +313,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -344,7 +347,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):],"created_at": AnyString(),"finished_at": None,- "finished_reason": None,+ "finished_reason": ReplyFinishedReason.COMPLETED,+ "structured_output": None,"error": None,"id": AnyString(),"metadata": {},@@ -368,6 +372,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):"metadata": {},"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -397,6 +402,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):"metadata": {},"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -505,6 +511,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):"metadata": {},"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -548,7 +555,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):],"created_at": AnyString(),"finished_at": None,- "finished_reason": None,+ "finished_reason": ReplyFinishedReason.COMPLETED,+ "structured_output": None,"error": None,"id": AnyString(),"metadata": {},@@ -572,6 +580,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):"metadata": {},"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -601,6 +610,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):"metadata": {},"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -647,7 +657,8 @@ class AgentBasicTest(IsolatedAsyncioTestCase):"id": AnyString(),"created_at": AnyString(),"finished_at": None,- "finished_reason": None,+ "finished_reason": ReplyFinishedReason.COMPLETED,+ "structured_output": None,"error": None,"metadata": {},"name": "Friday",@@ -907,6 +918,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -1162,6 +1174,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -1450,6 +1463,7 @@ class AgentBasicTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{diff --git a/tests/agent_interrupt_test.py b/tests/agent_interrupt_test.pyindex abaaaa369..7fa681fe9 100644--- a/tests/agent_interrupt_test.py+++ b/tests/agent_interrupt_test.py@@ -153,6 +153,7 @@ def _msg_base(name: str = "Friday") -> dict[str, Any]:"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"metadata": {},"name": name,@@ -167,6 +168,7 @@ def _user_msg_dict(content: str) -> dict[str, Any]:"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"metadata": {},"name": "user",diff --git a/tests/agent_structured_output_test.py b/tests/agent_structured_output_test.pynew file mode 100644index 000000000..fbbfec188--- /dev/null+++ b/tests/agent_structured_output_test.py@@ -0,0 +1,480 @@+# -*- coding: utf-8 -*-+"""Test the agent-level structured output."""+from typing import Any+from unittest.async_case import IsolatedAsyncioTestCase++from pydantic import BaseModel+from utils import AnyString, MockModel++from agentscope.agent import Agent, InjectionConfig, ReActConfig+from agentscope.model import ChatResponse+from agentscope.state import AgentState+from agentscope.tool import ToolBase, Toolkit, ToolChunk+from agentscope.permission import (+ PermissionDecision,+ PermissionBehavior,+ PermissionContext,+)+from agentscope.message import TextBlock, ToolCallBlock, UserMsg+from agentscope.event import UserConfirmResultEvent, ConfirmResult+++class WeatherReport(BaseModel):+ """The structured output schema used in the tests."""++ city: str+ temperature: float+++class WeatherReportWithUnit(BaseModel):+ """The structured output schema with a defaulted field."""++ city: str+ unit: str = "celsius"+++class MockConfirmTool(ToolBase):+ """A mock tool that requires user confirmation."""++ name: str = "mock_confirm_tool"+ description: str = "A mock tool requiring user confirmation"+ input_schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "input": {"type": "string", "description": "Input string"},+ },+ "required": ["input"],+ }+ is_concurrency_safe: bool = False+ is_read_only: bool = False+ is_external_tool: bool = False+ is_mcp: bool = False++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """Check permissions for the tool usage."""+ return PermissionDecision(+ behavior=PermissionBehavior.ASK,+ decision_reason="Mock tool requires user confirmation",+ message="Mock tool requires user confirmation",+ )++ # pylint: disable=redefined-builtin+ async def __call__(self, input: str, **kwargs: Any) -> ToolChunk:+ """Execute the tool."""+ return ToolChunk(+ content=[TextBlock(text=f"Confirm result: {input}")],+ )+++class AgentStructuredOutputTest(IsolatedAsyncioTestCase):+ """Test the agent-level structured output."""++ async def asyncSetUp(self) -> None:+ """The async setup method."""+ self.model = MockModel()+ self.agent = Agent(+ name="Friday",+ system_prompt="You are a helpful assistant.",+ model=self.model,+ toolkit=Toolkit(),+ # The runtime state injection is covered by agent_injection_test,+ # turn it off here to keep the assertions focused.+ injection_config=InjectionConfig(inject_runtime_state=False),+ )+ self.structured_tool_call = ChatResponse(+ content=[+ ToolCallBlock(+ id="structured_call_1",+ name="GenerateStructuredOutput",+ input='{"city": "Hangzhou", "temperature": 25.0}',+ ),+ ],+ is_last=True,+ )+ self.text_response = ChatResponse(+ content=[TextBlock(text="Let me think more.")],+ is_last=True,+ )++ async def test_structured_reply(self) -> None:+ """A structured reply calls the builtin tool and carries the+ validated output on the final message."""+ self.model.set_responses([self.structured_tool_call])++ 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": None,+ "content": [+ {+ "type": "text",+ "id": AnyString(),+ "text": "The required structured output is generated.",+ },+ ],+ },+ )+ self.assertDictEqual(+ self.agent.state.reply_context.model_dump(),+ {+ "reply_id": self.agent.state.reply_id,+ "cur_iter": 2,+ "structured_schema": WeatherReport.model_json_schema(),+ "structured_output": {"city": "Hangzhou", "temperature": 25.0},+ },+ )++ async def test_defaults_and_extra_fields(self) -> None:+ """In process the model class validates the output directly, so+ defaults are filled and extra fields are dropped."""+ self.model.set_responses(+ [+ ChatResponse(+ content=[+ ToolCallBlock(+ id="structured_call_1",+ name="GenerateStructuredOutput",+ input='{"city": "Hangzhou", "note": "sunny"}',+ ),+ ],+ is_last=True,+ ),+ ],+ )++ res = await self.agent.reply(+ UserMsg(name="user", content="Weather in Hangzhou?"),+ structured_schema=WeatherReportWithUnit,+ )++ self.assertDictEqual(+ res.structured_output,+ {"city": "Hangzhou", "unit": "celsius"},+ )++ async def test_validation_error_retry(self) -> None:+ """An invalid structured output produces an error tool result, and+ the model retries in the next reasoning round."""+ self.model.set_responses(+ [+ ChatResponse(+ content=[+ ToolCallBlock(+ id="structured_call_0",+ name="GenerateStructuredOutput",+ input='{"city": "Hangzhou", "temperature": "hot"}',+ ),+ ],+ is_last=True,+ ),+ self.structured_tool_call,+ ],+ )++ res = await self.agent.reply(+ UserMsg(name="user", content="Weather in Hangzhou?"),+ structured_schema=WeatherReport,+ )++ self.assertDictEqual(+ res.structured_output,+ {"city": "Hangzhou", "temperature": 25.0},+ )+ assistant_msg = self.agent.state.context[-1]+ tool_results = [+ block.model_dump()+ for block in assistant_msg.get_content_blocks("tool_result")+ ]+ self.assertListEqual(+ tool_results,+ [+ {+ "type": "tool_result",+ "id": "structured_call_0",+ "name": "GenerateStructuredOutput",+ "output": "Input validation failed for tool "+ "'GenerateStructuredOutput': 'hot' is not of type "+ "'number'",+ "state": "error",+ "metadata": {},+ },+ {+ "type": "tool_result",+ "id": "structured_call_1",+ "name": "GenerateStructuredOutput",+ "output": [+ {+ "type": "text",+ "id": AnyString(),+ "text": "Structured output generated "+ "successfully.",+ },+ ],+ "state": "success",+ "metadata": {},+ },+ ],+ )++ async def test_forced_generation_at_max_iters(self) -> None:+ """Once ``max_iters`` is reached, the agent forces the structured+ output tool call within the grace iterations."""+ self.agent.react_config = ReActConfig(max_iters=1)+ self.model.set_responses(+ [self.text_response, self.structured_tool_call],+ )++ res = await self.agent.reply(+ UserMsg(name="user", content="Weather in Hangzhou?"),+ structured_schema=WeatherReport,+ )++ self.assertDictEqual(+ res.structured_output,+ {"city": "Hangzhou", "temperature": 25.0},+ )+ self.assertEqual(res.finished_reason, "completed")+ self.assertEqual(self.model.cnt, 2)++ async def test_grace_iters_exhausted(self) -> None:+ """The reply exits with EXCEED_MAX_ITERS and no structured output+ when the grace iterations are exhausted."""+ self.agent.react_config = ReActConfig(+ max_iters=1,+ structured_output_grace_iters=1,+ )+ self.model.set_responses([self.text_response, self.text_response])++ 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": "exceed_max_iters",+ "structured_output": None,+ "error": None,+ "metadata": {},+ "name": "Friday",+ "role": "assistant",+ "usage": None,+ "content": [+ {+ "type": "text",+ "id": AnyString(),+ "text": "The maximum reasoning-acting iterations "+ "are exceeded.",+ },+ ],+ },+ )++ async def test_tool_mount_and_unmount(self) -> None:+ """The builtin tool is mounted for structured replies (without+ duplicate warnings) and unmounted for plain replies."""+ # The agent mutates the response blocks in place (e.g. the tool+ # call state), so each reply needs a freshly built response+ self.model.set_responses(+ [+ ChatResponse(+ content=[+ ToolCallBlock(+ id="structured_call_1",+ name="GenerateStructuredOutput",+ input='{"city": "Hangzhou", "temperature": 25.0}',+ ),+ ],+ is_last=True,+ ),+ ],+ )+ with self.assertNoLogs("as", "WARNING"):+ await self.agent.reply(+ UserMsg(name="user", content="Weather in Hangzhou?"),+ structured_schema=WeatherReport,+ )+ self.assertIsNotNone(+ await self.agent.toolkit.get_tool("GenerateStructuredOutput"),+ )++ # A second structured reply re-mounts the tool without warnings+ self.model.set_responses(+ [+ ChatResponse(+ content=[+ ToolCallBlock(+ id="structured_call_2",+ name="GenerateStructuredOutput",+ input='{"city": "Shanghai", "temperature": 28.0}',+ ),+ ],+ is_last=True,+ ),+ ],+ )+ with self.assertNoLogs("as", "WARNING"):+ await self.agent.reply(+ UserMsg(name="user", content="Weather in Shanghai?"),+ structured_schema=WeatherReport,+ )++ # A plain reply unmounts the tool+ self.model.set_responses(+ [ChatResponse(content=[TextBlock(text="Hello!")], is_last=True)],+ )+ await self.agent.reply(UserMsg(name="user", content="Hi"))+ self.assertIsNone(+ await self.agent.toolkit.get_tool("GenerateStructuredOutput"),+ )++ async def test_schema_survives_state_serialization(self) -> None:+ """The schema persists across HITL park, state dump/load and resume+ as a JSON schema dict, which fills defaults and keeps extras."""+ self.agent.toolkit = Toolkit(tools=[MockConfirmTool()])+ self.model.set_responses(+ [+ ChatResponse(+ content=[+ ToolCallBlock(+ id="confirm_call_1",+ name="mock_confirm_tool",+ input='{"input": "test"}',+ ),+ ],+ is_last=True,+ ),+ ],+ )++ # The reply parks on the user confirmation+ res = await self.agent.reply(+ UserMsg(name="user", content="Weather in Hangzhou?"),+ structured_schema=WeatherReportWithUnit,+ )+ self.assertIsNone(res.finished_reason)++ # Reload the state from its JSON dump into a new agent+ restored_state = AgentState.model_validate_json(+ self.agent.state.model_dump_json(),+ )+ self.assertDictEqual(+ restored_state.reply_context.structured_schema,+ WeatherReportWithUnit.model_json_schema(),+ )++ model = MockModel()+ model.set_responses(+ [+ ChatResponse(+ content=[+ ToolCallBlock(+ id="structured_call_1",+ name="GenerateStructuredOutput",+ input='{"city": "Hangzhou", "note": "sunny"}',+ ),+ ],+ is_last=True,+ ),+ ],+ )+ agent = Agent(+ name="Friday",+ system_prompt="You are a helpful assistant.",+ model=model,+ toolkit=Toolkit(tools=[MockConfirmTool()]),+ state=restored_state,+ injection_config=InjectionConfig(inject_runtime_state=False),+ )++ # Resume WITHOUT re-providing the schema+ res = await agent.reply(+ UserConfirmResultEvent(+ reply_id=restored_state.reply_id,+ confirm_results=[+ ConfirmResult(+ confirmed=True,+ tool_call=ToolCallBlock(+ id="confirm_call_1",+ name="mock_confirm_tool",+ input='{"input": "test"}',+ ),+ ),+ ],+ ),+ )+ self.assertEqual(res.finished_reason, "completed")+ self.assertDictEqual(+ res.structured_output,+ {"city": "Hangzhou", "note": "sunny", "unit": "celsius"},+ )++ async def test_schema_ignored_on_resume(self) -> None:+ """A schema given with a HITL resume event only warns, and the+ reply continues with the parked schema."""+ self.agent.toolkit = Toolkit(tools=[MockConfirmTool()])+ self.model.set_responses(+ [+ ChatResponse(+ content=[+ ToolCallBlock(+ id="confirm_call_1",+ name="mock_confirm_tool",+ input='{"input": "test"}',+ ),+ ],+ is_last=True,+ ),+ self.structured_tool_call,+ ],+ )+ res = await self.agent.reply(+ UserMsg(name="user", content="Weather in Hangzhou?"),+ structured_schema=WeatherReport,+ )+ self.assertIsNone(res.finished_reason)++ with self.assertLogs("as", "WARNING"):+ res = await self.agent.reply(+ UserConfirmResultEvent(+ reply_id=self.agent.state.reply_id,+ confirm_results=[+ ConfirmResult(+ confirmed=True,+ tool_call=ToolCallBlock(+ id="confirm_call_1",+ name="mock_confirm_tool",+ input='{"input": "test"}',+ ),+ ),+ ],+ ),+ structured_schema=WeatherReportWithUnit,+ )+ self.assertEqual(res.finished_reason, "completed")+ self.assertDictEqual(+ res.structured_output,+ {"city": "Hangzhou", "temperature": 25.0},+ )diff --git a/tests/compress_context_test.py b/tests/compress_context_test.pyindex 7e30b0ba4..ae1fab988 100644--- a/tests/compress_context_test.py+++ b/tests/compress_context_test.py@@ -227,6 +227,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"name": "User","role": "user",@@ -245,6 +246,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"name": "Friday","role": "assistant",@@ -268,6 +270,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"name": "Friday","role": "assistant",@@ -286,6 +289,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"name": "User","role": "user",@@ -334,6 +338,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"name": "User","role": "user",@@ -352,6 +357,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"name": "Friday","role": "assistant",@@ -380,6 +386,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"name": "User","role": "user",@@ -427,6 +434,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"name": "User","role": "user",@@ -445,6 +453,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"name": "Friday","role": "assistant",@@ -468,6 +477,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"name": "Friday","role": "assistant",@@ -486,6 +496,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"name": "User","role": "user",@@ -533,6 +544,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"name": "User","role": "user",@@ -556,6 +568,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"name": "Friday","role": "assistant",@@ -579,6 +592,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"name": "User","role": "user",@@ -629,6 +643,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"name": "Friday","role": "assistant",@@ -652,6 +667,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"name": "User","role": "user",@@ -739,6 +755,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"name": "User","role": "user",@@ -757,6 +774,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"name": "Friday","role": "assistant",@@ -819,6 +837,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"name": "Friday","role": "assistant",@@ -837,6 +856,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"name": "User","role": "user",@@ -928,6 +948,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"name": "Friday","role": "assistant",@@ -946,6 +967,7 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"name": "User","role": "user",diff --git a/tests/event_to_message_test.py b/tests/event_to_message_test.pyindex 4799d2af9..484faab0f 100644--- a/tests/event_to_message_test.py+++ b/tests/event_to_message_test.py@@ -173,6 +173,7 @@ class EventToMessageTest(IsolatedAsyncioTestCase):"created_at": _created_at,"finished_at": finished_at,"finished_reason": finished_reason,+ "structured_output": None,"error": None,"content": content,"usage": usage,diff --git a/tests/hitl_external_execution_test.py b/tests/hitl_external_execution_test.pyindex 0a3833b9a..39f1bdc98 100644--- a/tests/hitl_external_execution_test.py+++ b/tests/hitl_external_execution_test.py@@ -186,6 +186,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"metadata": {},"name": "Friday",@@ -372,6 +373,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -446,6 +448,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -611,6 +614,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -734,6 +738,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -927,6 +932,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -1042,6 +1048,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -1229,6 +1236,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -1319,6 +1327,7 @@ class AgentExternalExecutionTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{diff --git a/tests/hitl_user_confirmation_test.py b/tests/hitl_user_confirmation_test.pyindex ed3557fa2..030d9dac0 100644--- a/tests/hitl_user_confirmation_test.py+++ b/tests/hitl_user_confirmation_test.py@@ -279,6 +279,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"metadata": {},"name": "Friday",@@ -404,6 +405,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -485,6 +487,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -673,6 +676,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -814,6 +818,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -1039,6 +1044,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -1166,6 +1172,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -1502,6 +1509,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):],"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,},{@@ -1610,6 +1618,7 @@ class AgentUserConfirmationTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"metadata": {},"name": "user",diff --git a/tests/message_test.py b/tests/message_test.pyindex d9b7f245f..13087a8dc 100644--- a/tests/message_test.py+++ b/tests/message_test.py@@ -43,6 +43,7 @@ class MessageTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"usage": None,},@@ -67,6 +68,7 @@ class MessageTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"usage": None,},@@ -125,6 +127,7 @@ class MessageTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": AnyString(),"finished_reason": None,+ "structured_output": None,"error": None,"usage": None,},@@ -152,6 +155,7 @@ class MessageTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"usage": None,},@@ -180,6 +184,7 @@ class MessageTest(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"usage": None,},diff --git a/tests/middleware_test.py b/tests/middleware_test.pyindex 93896f0e3..761252c0b 100644--- a/tests/middleware_test.py+++ b/tests/middleware_test.py@@ -110,10 +110,12 @@ class TestMiddleware(IsolatedAsyncioTestCase):"mw1_TEXT_BLOCK_END","mw2_MODEL_CALL_END","mw1_MODEL_CALL_END",- "mw2_msg",- "mw1_msg",+ # The final Msg is the terminal item of the reply stream,+ # emitted after REPLY_END"mw2_REPLY_END","mw1_REPLY_END",+ "mw2_msg",+ "mw1_msg","mw2_post","mw1_post",]@@ -189,6 +191,10 @@ class TestMiddleware(IsolatedAsyncioTestCase):"mw1_MODEL_CALL_END","mw2_msg","mw1_msg",+ # The reasoning generator now completes naturally instead of+ # being aborted by an early return, so the post hooks run+ "mw2_post",+ "mw1_post",]self.assertListEqual(self.execution_log, expected)@@ -495,6 +501,9 @@ class TestMiddleware(IsolatedAsyncioTestCase):"multi_system_prompt","multi_model_call_pre","multi_model_call_post",+ # The reasoning generator now completes naturally instead of+ # being aborted by an early return, so its post hook runs+ "multi_reasoning_post","multi_reply_post",]self.assertListEqual(self.execution_log, expected)diff --git a/tests/service_inbox_middleware_test.py b/tests/service_inbox_middleware_test.pyindex 857419b7c..ae6c28981 100644--- a/tests/service_inbox_middleware_test.py+++ b/tests/service_inbox_middleware_test.py@@ -286,6 +286,7 @@ class TestInboxMiddlewareInjection(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"usage": None,},@@ -346,6 +347,7 @@ class TestInboxMiddlewareInjection(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"usage": None,},@@ -386,6 +388,7 @@ class TestInboxMiddlewareInjection(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"usage": None,},diff --git a/tests/workspace_local_test.py b/tests/workspace_local_test.pyindex d9f2f9796..559177aa7 100644--- a/tests/workspace_local_test.py+++ b/tests/workspace_local_test.py@@ -981,6 +981,7 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"usage": None,}@@ -1126,8 +1127,10 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):'"id":"text_block_a"}''],"role":"user","id":"msg_a","metadata":{},''"created_at":"2026-01-01T00:00:00",'+ '"usage":null,''"finished_at":"2026-01-01T00:00:00",'- '"finished_reason":null,"error":null,"usage":null}'+ '"finished_reason":null,"structured_output":null,'+ '"error":null}')self.assertEqual(content_after_first,@@ -1170,8 +1173,10 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):+ '"}''],"role":"assistant","id":"' + assistant_1.id + '",''"metadata":{},"created_at":"' + assistant_1.created_at + '",'+ '"usage":null,''"finished_at":null,'- '"finished_reason":null,"error":null,"usage":null}'+ '"finished_reason":null,"structured_output":null,'+ '"error":null}')expected_user_msg_b_json = ('{"name":"user","content":['@@ -1179,8 +1184,10 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):'"id":"text_block_b"}''],"role":"user","id":"msg_b","metadata":{},''"created_at":"2026-01-02T00:00:00",'+ '"usage":null,''"finished_at":"2026-01-02T00:00:00",'- '"finished_reason":null,"error":null,"usage":null}'+ '"finished_reason":null,"structured_output":null,'+ '"error":null}')self.assertEqual(content_after_second,@@ -1230,6 +1237,7 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):"created_at": AnyString(),"finished_at": None,"finished_reason": None,+ "structured_output": None,"error": None,"usage": None,}