Skip to content

Build and run agents you can see, understand and trust.

fix(sop): write out what a step actually kept (#2616)

DavdGao07f881e7f928
diff --git a/src/agentscope/sop/_engine.py b/src/agentscope/sop/_engine.py
index c2116bd9d..0725ea00a 100644
--- a/src/agentscope/sop/_engine.py
+++ b/src/agentscope/sop/_engine.py
@@ -65,7 +65,12 @@ class SOPEngine:
@property
def phase(self) -> SOPPhase:
- """Where the run stands overall."""
+ """Where the run stands overall.
+
+ Returns:
+ `SOPPhase`:
+ The run state's phase, worked out from its steps.
+ """
return self.state.phase
async def reply_stream(
diff --git a/src/agentscope/sop/_schema.py b/src/agentscope/sop/_schema.py
index f773d3da1..3c6a58676 100644
--- a/src/agentscope/sop/_schema.py
+++ b/src/agentscope/sop/_schema.py
@@ -43,7 +43,23 @@ class AgentLike(PipelineProtocol, Protocol):
structured_schema: Type[BaseModel] | None = None,
yield_final_msg: bool = False,
) -> AsyncGenerator[AgentEvent | Msg, None]:
- """Reply to the given inputs and stream what happens."""
+ """Reply to the given inputs and stream what happens.
+
+ Args:
+ inputs:
+ What to reply to, or the answer a parked reply was
+ waiting for. ``None`` continues from what is already
+ in context.
+ structured_schema (`Type[BaseModel] | None`, optional):
+ What the reply must end in, if anything.
+ yield_final_msg (`bool`, defaults to `False`):
+ Whether to yield the finished reply as well as the
+ events that built it.
+
+ Yields:
+ `AgentEvent | Msg`:
+ What happens as it happens.
+ """
class SOPStepBase(ABC):
@@ -102,6 +118,10 @@ class SOPStepBase(ABC):
This step's record in the run. Read it to pick up where
the last call stopped; write its phase, submission and
verdicts as the attempt goes.
+
+ Yields:
+ `AgentEvent | Msg`:
+ What the attempt does as it does it.
"""
def record(
@@ -116,6 +136,17 @@ class SOPStepBase(ABC):
A refusal clears the submission, so the next attempt starts from
the work rather than from the judging. Whether there is a next
attempt is the engine's call.
+
+ Args:
+ state (`SOPStepRunState`):
+ The step's record in the run, which this writes to.
+ passed (`bool`):
+ Whether the attempt is accepted.
+ message (`str`, defaults to `""`):
+ Why it was refused, handed to the executor verbatim
+ on the next attempt.
+ verifier (`str`, defaults to `""`):
+ Who decided.
"""
state.verifications.append(
VerificationResult(
diff --git a/src/agentscope/sop/_state.py b/src/agentscope/sop/_state.py
index 4aaecdb72..961964179 100644
--- a/src/agentscope/sop/_state.py
+++ b/src/agentscope/sop/_state.py
@@ -8,7 +8,13 @@ ever lives on a step object.
"""
from enum import StrEnum
-from pydantic import BaseModel, ConfigDict, Field
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ SerializeAsAny,
+ computed_field,
+)
from ..message import DataBlock, Msg, TextBlock
from .._utils._common import _generate_id, _generate_timestamp
@@ -109,15 +115,30 @@ class SOPRunState(BaseModel):
inputs: list[Msg] = Field(default_factory=list)
"""What the run was started with, and what its first step reads."""
- steps: list[SOPStepRunState] = Field(default_factory=list)
- """How each step is going, in the order the SOP declares them."""
+ steps: list[SerializeAsAny[SOPStepRunState]] = Field(
+ default_factory=list,
+ )
+ """How each step is going, in the order the SOP declares them.
+
+ Serialized as whatever each step actually kept, so the extra a
+ :attr:`~._schema.SOPStepBase.state_type` subclass adds is written
+ out rather than trimmed back to this base."""
created_at: str = Field(default_factory=_generate_timestamp)
"""When the run was created."""
+ @computed_field # type: ignore[misc]
@property
def phase(self) -> SOPPhase:
- """Where the run stands, worked out from its steps."""
+ """Where the run stands, worked out from its steps.
+
+ Dumped alongside the stored fields so a reader can sort runs
+ by it without replaying every step.
+
+ Returns:
+ `SOPPhase`:
+ How far along the run as a whole is.
+ """
phases = [_.phase for _ in self.steps]
if not phases or all(_ is SOPPhase.PENDING for _ in phases):
return SOPPhase.PENDING
diff --git a/tests/sop_engine_test.py b/tests/sop_engine_test.py
index 60554c4cb..9952b52ed 100644
--- a/tests/sop_engine_test.py
+++ b/tests/sop_engine_test.py
@@ -17,13 +17,19 @@ from agentscope.event import (
RequireUserConfirmEvent,
UserConfirmResultEvent,
)
-from agentscope.message import AssistantMsg, ToolCallBlock, UserMsg
+from agentscope.message import (
+ AssistantMsg,
+ TextBlock,
+ ToolCallBlock,
+ UserMsg,
+)
from agentscope.sop import (
SOP,
SOPEngine,
SOPRunState,
SOPPhase,
SOPStep,
+ SOPStepBase,
SOPStepRunState,
)
from agentscope.types import ReplyFinishedReason
@@ -68,6 +74,29 @@ def _answer() -> UserConfirmResultEvent:
)
+class _NoteState(SOPStepRunState):
+ """A step state that remembers one thing more than the base."""
+
+ note: str = ""
+
+
+class _Noting(SOPStepBase):
+ """A step that keeps that one thing and passes."""
+
+ state_type = _NoteState
+
+ async def reply_stream( # pylint: disable=invalid-overridden-method
+ self,
+ inputs: Any,
+ state: Any,
+ ) -> AsyncGenerator[Any, None]:
+ """Note something, hand something over, and pass."""
+ yield _finished("noting", {})
+ state.note = "kept"
+ state.submission = [TextBlock(type="text", text="done")]
+ self.record(state, True)
+
+
class _Scripted:
"""An ``AgentLike`` that replays one scripted reply per call."""
@@ -222,6 +251,7 @@ class SOPEngineTest(IsolatedAsyncioTestCase):
],
},
],
+ "phase": SOPPhase.COMPLETED,
},
)
@@ -436,6 +466,61 @@ class SOPEngineTest(IsolatedAsyncioTestCase):
self.assertEqual(engine2.phase, SOPPhase.COMPLETED)
+ async def test_a_step_that_remembers_more_survives_storage(
+ self,
+ ) -> None:
+ """What a ``state_type`` subclass keeps is written out and read
+ back."""
+ sop = SOP(
+ name="demo",
+ description="d",
+ steps=[_Noting("A", "do a")],
+ )
+ engine = SOPEngine(sop)
+ await self._drive(engine)
+
+ self.assertDictEqual(
+ engine.state.model_dump(mode="json"),
+ {
+ "id": AnyString(),
+ "inputs": [],
+ "steps": [
+ {
+ "phase": "completed",
+ "given": [],
+ "submission": [
+ {
+ "type": "text",
+ "text": "done",
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ ],
+ "verifications": [
+ {
+ "passed": True,
+ "message": "",
+ "verifier": "",
+ "created_at": AnyString(),
+ },
+ ],
+ "note": "kept",
+ },
+ ],
+ "created_at": AnyString(),
+ "phase": "completed",
+ },
+ )
+
+ engine2 = SOPEngine(
+ SOP(name="demo", description="d", steps=[_Noting("A", "do a")]),
+ SOPRunState.model_validate_json(engine.state.model_dump_json()),
+ )
+
+ self.assertIsInstance(engine2.state.steps[0], _NoteState)
+ self.assertEqual(engine2.state.steps[0].note, "kept")
+
async def test_a_run_from_an_edited_sop_is_refused(self) -> None:
"""Editing the SOP retires the runs of the old one."""
sop = SOP(