2024-05-27 20:25:25 -04:00
|
|
|
from typing import Any, Mapping, Sequence
|
|
|
|
|
2024-06-05 15:48:14 -04:00
|
|
|
import pytest
|
2024-06-04 10:00:05 -04:00
|
|
|
from agnext.application import SingleThreadedAgentRuntime
|
2024-06-18 14:53:18 -04:00
|
|
|
from agnext.core import BaseAgent, CancellationToken
|
2024-06-05 15:48:14 -04:00
|
|
|
|
2024-05-27 20:25:25 -04:00
|
|
|
|
2024-06-09 12:11:36 -07:00
|
|
|
class StatefulAgent(BaseAgent): # type: ignore
|
2024-06-18 14:53:18 -04:00
|
|
|
def __init__(self) -> None: # type: ignore
|
|
|
|
super().__init__("A stateful agent", [])
|
2024-05-27 20:25:25 -04:00
|
|
|
self.state = 0
|
|
|
|
|
|
|
|
@property
|
|
|
|
def subscriptions(self) -> Sequence[type]:
|
|
|
|
return []
|
|
|
|
|
2024-06-09 12:11:36 -07:00
|
|
|
async def on_message(self, message: Any, cancellation_token: CancellationToken) -> Any: # type: ignore
|
2024-05-27 20:25:25 -04:00
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
def save_state(self) -> Mapping[str, Any]:
|
|
|
|
return {"state": self.state}
|
|
|
|
|
|
|
|
def load_state(self, state: Mapping[str, Any]) -> None:
|
|
|
|
self.state = state["state"]
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
|
|
async def test_agent_can_save_state() -> None:
|
|
|
|
runtime = SingleThreadedAgentRuntime()
|
|
|
|
|
2024-06-18 14:53:18 -04:00
|
|
|
agent1_id = runtime.register_and_get("name1", StatefulAgent)
|
|
|
|
agent1: StatefulAgent = runtime._get_agent(agent1_id) # type: ignore
|
2024-05-27 20:25:25 -04:00
|
|
|
assert agent1.state == 0
|
|
|
|
agent1.state = 1
|
|
|
|
assert agent1.state == 1
|
|
|
|
|
|
|
|
agent1_state = agent1.save_state()
|
|
|
|
|
|
|
|
agent1.state = 2
|
|
|
|
assert agent1.state == 2
|
|
|
|
|
|
|
|
agent1.load_state(agent1_state)
|
|
|
|
assert agent1.state == 1
|
|
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
|
|
async def test_runtime_can_save_state() -> None:
|
|
|
|
runtime = SingleThreadedAgentRuntime()
|
|
|
|
|
2024-06-18 14:53:18 -04:00
|
|
|
agent1_id = runtime.register_and_get("name1", StatefulAgent)
|
|
|
|
agent1: StatefulAgent = runtime._get_agent(agent1_id) # type: ignore
|
2024-05-27 20:25:25 -04:00
|
|
|
assert agent1.state == 0
|
|
|
|
agent1.state = 1
|
|
|
|
assert agent1.state == 1
|
|
|
|
|
|
|
|
runtime_state = runtime.save_state()
|
|
|
|
|
|
|
|
runtime2 = SingleThreadedAgentRuntime()
|
2024-06-18 14:53:18 -04:00
|
|
|
agent2_id = runtime2.register_and_get("name1", StatefulAgent)
|
|
|
|
agent2: StatefulAgent = runtime2._get_agent(agent2_id) # type: ignore
|
|
|
|
|
2024-05-27 20:25:25 -04:00
|
|
|
runtime2.load_state(runtime_state)
|
|
|
|
assert agent2.state == 1
|
|
|
|
|
|
|
|
|
|
|
|
|