State/Session Management
In AgentScope, the “state” refers to the agent status in the running application, including its current system prompt, memory, context, equipped tools, and other information that change over time.
To manage the state of an application, AgentScope designs an automatic state registration system and session-level state management, which features:
Support automatic state registration for all variables inherited from
StateModuleSupport manual state registration with custom serialization/deserialization methods
Support session/application-level management
import asyncioimport jsonimport osfrom agentscope.agent import ReActAgentfrom agentscope.formatter import DashScopeChatFormatterfrom agentscope.memory import InMemoryMemoryfrom agentscope.message import Msgfrom agentscope.model import DashScopeChatModelfrom agentscope.module import StateModulefrom agentscope.session import JSONSessionfrom agentscope.tool import Toolkit
State Module
The StateModule class is the foundation for state management in AgentScope and provides three basic functions:
Method | Arguments | Description |
|---|---|---|
| attr_name,custom_to_json (optional),custom_from_json (optional) | Register an attribute as its state, with optional serialization/deserialization function. |
| - | Get the state dictionary of current object |
| state_dict,strict (optional) | Load the state dictionary to current object |
Within an object of StateModule, all the following attributes will be treated as parts of its state:
the attributes that inherit from
StateModulethe attributes registered by the
register_statemethod
Note the StateModule supports NESTED serialization and deserialization:
class ClassA(StateModule):def __init__(self) -> None:super().__init__()self.cnt = 123# register cnt attribute as stateself.register_state("cnt")class ClassB(StateModule):def __init__(self) -> None:super().__init__()# attribute "a" inherits from StateModuleself.a = ClassA()# register attribute "c" as state manuallyself.c = "Hello, world!"self.register_state("c")obj_b = ClassB()print("State of obj_b.a:")print(obj_b.a.state_dict())print("\nState of obj_b:")print(json.dumps(obj_b.state_dict(), indent=4))
State of obj_b.a:{'cnt': 123}State of obj_b:{"a": {"cnt": 123},"c": "Hello, world!"}
We can observe the state of obj_b contains the state of its attribute a automatically.
In AgentScope, the AgentBase, MemoryBase, LongTermMemoryBase and Toolkit classes all inherit from StateModule, thus supporting automatic and nested state management.
# Creating an agentagent = ReActAgent(name="Friday",sys_prompt="You're a assistant named Friday.",model=DashScopeChatModel(model_name="qwen-max",api_key=os.environ["DASHSCOPE_API_KEY"],),formatter=DashScopeChatFormatter(),memory=InMemoryMemory(),toolkit=Toolkit(),)initial_state = agent.state_dict()print("Initial state of the agent:")print(json.dumps(initial_state, indent=4))
Initial state of the agent:{"memory": {"content": []},"toolkit": {"active_groups": []},"_reasoning_hint_msgs": {"content": []},"name": "Friday","_sys_prompt": "You're a assistant named Friday."}
Then we change its state by generating a reply message:
async def example_agent_state() -> None:"""Example of agent state management"""await agent(Msg("user", "Hello, agent!", "user"))print("State of the agent after generating a reply:")print(json.dumps(agent.state_dict(), indent=4))asyncio.run(example_agent_state())
Friday: Hello! How can I assist you today?State of the agent after generating a reply:{"memory": {"content": [{"id": "Khy4PkCKynJWuEiTrRPnUN","name": "user","role": "user","content": "Hello, agent!","metadata": null,"timestamp": "2025-09-15 07:47:08.003"},{"id": "iCcxUJhQqyQk5n9mdAsGXx","name": "Friday","role": "assistant","content": [{"id": "WDeWuELtSoCxfcjxbRjQKQ","type": "tool_use","name": "generate_response","input": {"response": "Hello! How can I assist you today?"}}],"metadata": null,"timestamp": "2025-09-15 07:47:08.004"},{"id": "Au8rzJwz7RLHFmCxAn8Czo","name": "system","role": "system","content": [{"type": "tool_result","id": "WDeWuELtSoCxfcjxbRjQKQ","name": "generate_response","output": [{"type": "text","text": "Successfully generated response."}]}],"metadata": null,"timestamp": "2025-09-15 07:47:09.852"},{"id": "kfipufr5WD6ejHZ2w99qUg","name": "Friday","role": "assistant","content": "Hello! How can I assist you today?","metadata": null,"timestamp": "2025-09-15 07:47:09.852"}]},"toolkit": {"active_groups": []},"_reasoning_hint_msgs": {"content": []},"name": "Friday","_sys_prompt": "You're a assistant named Friday."}
Now we recover the state of the agent to its initial state:
agent.load_state_dict(initial_state)print("State after loading the initial state:")print(json.dumps(agent.state_dict(), indent=4))
State after loading the initial state:{"memory": {"content": []},"toolkit": {"active_groups": []},"_reasoning_hint_msgs": {"content": []},"name": "Friday","_sys_prompt": "You're a assistant named Friday."}
Session Management
In AgentScope, a session refers to a collection of StateModule in an application, e.g. multiple agents.
AgentScope provides a SessionBase class with two abstract methods for session management: save_session_state and load_session_state. Developers can implement these methods with their own storage solution.
In AgentScope, we provide a JSON based session class JSONSession that stores/loads the session state in/from a JSON file named with the session ID.
Here we show how to use the JSON based session management in AgentScope.
Saving Session State
# change the agent state by generating a reply messageasyncio.run(example_agent_state())print("\nState of agent:")print(json.dumps(agent.state_dict(), indent=4))
Friday: Hello! How can I assist you today?State of the agent after generating a reply:{"memory": {"content": [{"id": "A2tNHQ5VTmjzNXwQsitJWK","name": "user","role": "user","content": "Hello, agent!","metadata": null,"timestamp": "2025-09-15 07:47:09.855"},{"id": "DNw8JZDaZvrQSLY47yFgrR","name": "Friday","role": "assistant","content": [{"id": "AHsohAued8MBpW9XYuoNxW","type": "tool_use","name": "generate_response","input": {"response": "Hello! How can I assist you today?"}}],"metadata": null,"timestamp": "2025-09-15 07:47:09.855"},{"id": "PpD23DAz2tyXEBhum2agxM","name": "system","role": "system","content": [{"type": "tool_result","id": "AHsohAued8MBpW9XYuoNxW","name": "generate_response","output": [{"type": "text","text": "Successfully generated response."}]}],"metadata": null,"timestamp": "2025-09-15 07:47:11.992"},{"id": "6v9d7vhgsAh3QNDCcwxGmv","name": "Friday","role": "assistant","content": "Hello! How can I assist you today?","metadata": null,"timestamp": "2025-09-15 07:47:11.992"}]},"toolkit": {"active_groups": []},"_reasoning_hint_msgs": {"content": []},"name": "Friday","_sys_prompt": "You're a assistant named Friday."}State of agent:{"memory": {"content": [{"id": "A2tNHQ5VTmjzNXwQsitJWK","name": "user","role": "user","content": "Hello, agent!","metadata": null,"timestamp": "2025-09-15 07:47:09.855"},{"id": "DNw8JZDaZvrQSLY47yFgrR","name": "Friday","role": "assistant","content": [{"id": "AHsohAued8MBpW9XYuoNxW","type": "tool_use","name": "generate_response","input": {"response": "Hello! How can I assist you today?"}}],"metadata": null,"timestamp": "2025-09-15 07:47:09.855"},{"id": "PpD23DAz2tyXEBhum2agxM","name": "system","role": "system","content": [{"type": "tool_result","id": "AHsohAued8MBpW9XYuoNxW","name": "generate_response","output": [{"type": "text","text": "Successfully generated response."}]}],"metadata": null,"timestamp": "2025-09-15 07:47:11.992"},{"id": "6v9d7vhgsAh3QNDCcwxGmv","name": "Friday","role": "assistant","content": "Hello! How can I assist you today?","metadata": null,"timestamp": "2025-09-15 07:47:11.992"}]},"toolkit": {"active_groups": []},"_reasoning_hint_msgs": {"content": []},"name": "Friday","_sys_prompt": "You're a assistant named Friday."}
Then we save it to a session file:
session = JSONSession(session_id="session_2025-08-08", # Use the time as session idsave_dir="./user-bob/", # Use the username as the save directory)async def example_session() -> None:"""Example of session management."""await session.save_session_state(agent=agent,)print("The saved state:")with open(session.save_path, "r", encoding="utf-8") as f:print(json.dumps(json.load(f), indent=4))asyncio.run(example_session())
The saved state:{"agent": {"memory": {"content": [{"id": "A2tNHQ5VTmjzNXwQsitJWK","name": "user","role": "user","content": "Hello, agent!","metadata": null,"timestamp": "2025-09-15 07:47:09.855"},{"id": "DNw8JZDaZvrQSLY47yFgrR","name": "Friday","role": "assistant","content": [{"id": "AHsohAued8MBpW9XYuoNxW","type": "tool_use","name": "generate_response","input": {"response": "Hello! How can I assist you today?"}}],"metadata": null,"timestamp": "2025-09-15 07:47:09.855"},{"id": "PpD23DAz2tyXEBhum2agxM","name": "system","role": "system","content": [{"type": "tool_result","id": "AHsohAued8MBpW9XYuoNxW","name": "generate_response","output": [{"type": "text","text": "Successfully generated response."}]}],"metadata": null,"timestamp": "2025-09-15 07:47:11.992"},{"id": "6v9d7vhgsAh3QNDCcwxGmv","name": "Friday","role": "assistant","content": "Hello! How can I assist you today?","metadata": null,"timestamp": "2025-09-15 07:47:11.992"}]},"toolkit": {"active_groups": []},"_reasoning_hint_msgs": {"content": []},"name": "Friday","_sys_prompt": "You're a assistant named Friday."}}
Loading Session State
Now we load the session state from the saved file:
async def example_load_session() -> None:"""Example of loading session state."""# we first clear the memory of the agentawait agent.memory.clear()print("Current state of the agent:")print(json.dumps(agent.state_dict(), indent=4))# then we load the session stateawait session.load_session_state(# The keyword argument must be the same as the one used in `save_session_state`agent=agent,)print("After loading the session state:")print(json.dumps(agent.state_dict(), indent=4))asyncio.run(example_load_session())
Current state of the agent:{"memory": {"content": []},"toolkit": {"active_groups": []},"_reasoning_hint_msgs": {"content": []},"name": "Friday","_sys_prompt": "You're a assistant named Friday."}After loading the session state:{"memory": {"content": [{"id": "A2tNHQ5VTmjzNXwQsitJWK","name": "user","role": "user","content": "Hello, agent!","metadata": null,"timestamp": "2025-09-15 07:47:09.855"},{"id": "DNw8JZDaZvrQSLY47yFgrR","name": "Friday","role": "assistant","content": [{"id": "AHsohAued8MBpW9XYuoNxW","type": "tool_use","name": "generate_response","input": {"response": "Hello! How can I assist you today?"}}],"metadata": null,"timestamp": "2025-09-15 07:47:09.855"},{"id": "PpD23DAz2tyXEBhum2agxM","name": "system","role": "system","content": [{"type": "tool_result","id": "AHsohAued8MBpW9XYuoNxW","name": "generate_response","output": [{"type": "text","text": "Successfully generated response."}]}],"metadata": null,"timestamp": "2025-09-15 07:47:11.992"},{"id": "6v9d7vhgsAh3QNDCcwxGmv","name": "Friday","role": "assistant","content": "Hello! How can I assist you today?","metadata": null,"timestamp": "2025-09-15 07:47:11.992"}]},"toolkit": {"active_groups": []},"_reasoning_hint_msgs": {"content": []},"name": "Friday","_sys_prompt": "You're a assistant named Friday."}
Now we can see the agent state is restored to the saved state.
Total running time of the script: (0 minutes 4.000 seconds)
Download Jupyter notebook: task_state.ipynb
Download Python source code: task_state.py