.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "tutorial/task_state.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_tutorial_task_state.py: .. _state: 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 ``StateModule`` - Support **manual state registration** with custom serialization/deserialization methods - Support **session/application-level management** .. GENERATED FROM PYTHON SOURCE LINES 16-29 .. code-block:: Python import asyncio import json import os from agentscope.agent import ReActAgent from agentscope.formatter import DashScopeChatFormatter from agentscope.memory import InMemoryMemory from agentscope.message import Msg from agentscope.model import DashScopeChatModel from agentscope.module import StateModule from agentscope.session import JSONSession from agentscope.tool import Toolkit .. GENERATED FROM PYTHON SOURCE LINES 30-61 State Module ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``StateModule`` class is the foundation for state management in AgentScope and provides three basic functions: .. list-table:: Methods of ``StateModule`` :header-rows: 1 * - Method - Arguments - Description * - ``register_state`` - | ``attr_name``, | ``custom_to_json`` (optional), | ``custom_from_json`` (optional) - Register an attribute as its state, with optional serialization/deserialization function. * - ``state_dict`` - \- - Get the state dictionary of current object * - ``load_state_dict`` - | ``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 ``StateModule`` - the **attributes** registered by the ``register_state`` method Note the ``StateModule`` supports **NESTED** serialization and deserialization: .. GENERATED FROM PYTHON SOURCE LINES 61-91 .. code-block:: Python class ClassA(StateModule): def __init__(self) -> None: super().__init__() self.cnt = 123 # register cnt attribute as state self.register_state("cnt") class ClassB(StateModule): def __init__(self) -> None: super().__init__() # attribute "a" inherits from StateModule self.a = ClassA() # register attribute "c" as state manually self.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)) .. rst-class:: sphx-glr-script-out .. code-block:: none State of obj_b.a: {'cnt': 123} State of obj_b: { "a": { "cnt": 123 }, "c": "Hello, world!" } .. GENERATED FROM PYTHON SOURCE LINES 92-96 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. .. GENERATED FROM PYTHON SOURCE LINES 96-115 .. code-block:: Python # Creating an agent agent = 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)) .. rst-class:: sphx-glr-script-out .. code-block:: none Initial state of the agent: { "memory": { "content": [] }, "toolkit": { "active_groups": [] }, "name": "Friday", "_sys_prompt": "You're a assistant named Friday." } .. GENERATED FROM PYTHON SOURCE LINES 116-118 Then we change its state by generating a reply message: .. GENERATED FROM PYTHON SOURCE LINES 118-130 .. code-block:: Python 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()) .. rst-class:: sphx-glr-script-out .. code-block:: none Friday: Hello! How can I assist you today? State of the agent after generating a reply: { "memory": { "content": [ { "id": "6EHLrAVim9zMR6ySBfVEAE", "name": "user", "role": "user", "content": "Hello, agent!", "metadata": null, "timestamp": "2025-08-15 10:13:28.256" }, { "id": "ewQnxZrgSdPEtQLewcuaJZ", "name": "Friday", "role": "assistant", "content": [ { "id": "c9FQJTJBi6oLFmnt6sQQRs", "type": "tool_use", "name": "generate_response", "input": { "response": "Hello! How can I assist you today?" } } ], "metadata": null, "timestamp": "2025-08-15 10:13:28.257" }, { "id": "ZwFNgJcSUYodkCvSjTR3s5", "name": "system", "role": "system", "content": [ { "type": "tool_result", "id": "c9FQJTJBi6oLFmnt6sQQRs", "name": "generate_response", "output": [ { "type": "text", "text": "Successfully generated response." } ] } ], "metadata": null, "timestamp": "2025-08-15 10:13:29.641" }, { "id": "KC34kT5RREa9uaBq937NgM", "name": "Friday", "role": "assistant", "content": "Hello! How can I assist you today?", "metadata": null, "timestamp": "2025-08-15 10:13:29.641" } ] }, "toolkit": { "active_groups": [] }, "name": "Friday", "_sys_prompt": "You're a assistant named Friday." } .. GENERATED FROM PYTHON SOURCE LINES 131-133 Now we recover the state of the agent to its initial state: .. GENERATED FROM PYTHON SOURCE LINES 133-139 .. code-block:: Python agent.load_state_dict(initial_state) print("State after loading the initial state:") print(json.dumps(agent.state_dict(), indent=4)) .. rst-class:: sphx-glr-script-out .. code-block:: none State after loading the initial state: { "memory": { "content": [] }, "toolkit": { "active_groups": [] }, "name": "Friday", "_sys_prompt": "You're a assistant named Friday." } .. GENERATED FROM PYTHON SOURCE LINES 140-157 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 ----------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 157-164 .. code-block:: Python # change the agent state by generating a reply message asyncio.run(example_agent_state()) print("\nState of agent:") print(json.dumps(agent.state_dict(), indent=4)) .. rst-class:: sphx-glr-script-out .. code-block:: none Friday: Hello! How can I assist you today? State of the agent after generating a reply: { "memory": { "content": [ { "id": "DYPE9DyivDK9stghdM2TWC", "name": "user", "role": "user", "content": "Hello, agent!", "metadata": null, "timestamp": "2025-08-15 10:13:29.644" }, { "id": "WXEB3u2rRuctLSFZUUYZ6U", "name": "Friday", "role": "assistant", "content": [ { "id": "8WH5TyRNaFm6TX5Xr2Y9RQ", "type": "tool_use", "name": "generate_response", "input": { "response": "Hello! How can I assist you today?" } } ], "metadata": null, "timestamp": "2025-08-15 10:13:29.644" }, { "id": "XQ3YqvVpUBouzMpEzq8Q7D", "name": "system", "role": "system", "content": [ { "type": "tool_result", "id": "8WH5TyRNaFm6TX5Xr2Y9RQ", "name": "generate_response", "output": [ { "type": "text", "text": "Successfully generated response." } ] } ], "metadata": null, "timestamp": "2025-08-15 10:13:30.765" }, { "id": "BN3CQ3fj4vRJJeoY2bjwRS", "name": "Friday", "role": "assistant", "content": "Hello! How can I assist you today?", "metadata": null, "timestamp": "2025-08-15 10:13:30.765" } ] }, "toolkit": { "active_groups": [] }, "name": "Friday", "_sys_prompt": "You're a assistant named Friday." } State of agent: { "memory": { "content": [ { "id": "DYPE9DyivDK9stghdM2TWC", "name": "user", "role": "user", "content": "Hello, agent!", "metadata": null, "timestamp": "2025-08-15 10:13:29.644" }, { "id": "WXEB3u2rRuctLSFZUUYZ6U", "name": "Friday", "role": "assistant", "content": [ { "id": "8WH5TyRNaFm6TX5Xr2Y9RQ", "type": "tool_use", "name": "generate_response", "input": { "response": "Hello! How can I assist you today?" } } ], "metadata": null, "timestamp": "2025-08-15 10:13:29.644" }, { "id": "XQ3YqvVpUBouzMpEzq8Q7D", "name": "system", "role": "system", "content": [ { "type": "tool_result", "id": "8WH5TyRNaFm6TX5Xr2Y9RQ", "name": "generate_response", "output": [ { "type": "text", "text": "Successfully generated response." } ] } ], "metadata": null, "timestamp": "2025-08-15 10:13:30.765" }, { "id": "BN3CQ3fj4vRJJeoY2bjwRS", "name": "Friday", "role": "assistant", "content": "Hello! How can I assist you today?", "metadata": null, "timestamp": "2025-08-15 10:13:30.765" } ] }, "toolkit": { "active_groups": [] }, "name": "Friday", "_sys_prompt": "You're a assistant named Friday." } .. GENERATED FROM PYTHON SOURCE LINES 165-166 Then we save it to a session file: .. GENERATED FROM PYTHON SOURCE LINES 166-187 .. code-block:: Python session = JSONSession( session_id="session_2025-08-08", # Use the time as session id save_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()) .. rst-class:: sphx-glr-script-out .. code-block:: none The saved state: { "agent": { "memory": { "content": [ { "id": "DYPE9DyivDK9stghdM2TWC", "name": "user", "role": "user", "content": "Hello, agent!", "metadata": null, "timestamp": "2025-08-15 10:13:29.644" }, { "id": "WXEB3u2rRuctLSFZUUYZ6U", "name": "Friday", "role": "assistant", "content": [ { "id": "8WH5TyRNaFm6TX5Xr2Y9RQ", "type": "tool_use", "name": "generate_response", "input": { "response": "Hello! How can I assist you today?" } } ], "metadata": null, "timestamp": "2025-08-15 10:13:29.644" }, { "id": "XQ3YqvVpUBouzMpEzq8Q7D", "name": "system", "role": "system", "content": [ { "type": "tool_result", "id": "8WH5TyRNaFm6TX5Xr2Y9RQ", "name": "generate_response", "output": [ { "type": "text", "text": "Successfully generated response." } ] } ], "metadata": null, "timestamp": "2025-08-15 10:13:30.765" }, { "id": "BN3CQ3fj4vRJJeoY2bjwRS", "name": "Friday", "role": "assistant", "content": "Hello! How can I assist you today?", "metadata": null, "timestamp": "2025-08-15 10:13:30.765" } ] }, "toolkit": { "active_groups": [] }, "name": "Friday", "_sys_prompt": "You're a assistant named Friday." } } .. GENERATED FROM PYTHON SOURCE LINES 188-191 Loading Session State ----------------------------------------- Now we load the session state from the saved file: .. GENERATED FROM PYTHON SOURCE LINES 191-213 .. code-block:: Python async def example_load_session() -> None: """Example of loading session state.""" # we first clear the memory of the agent await agent.memory.clear() print("Current state of the agent:") print(json.dumps(agent.state_dict(), indent=4)) # then we load the session state await 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()) .. rst-class:: sphx-glr-script-out .. code-block:: none Current state of the agent: { "memory": { "content": [] }, "toolkit": { "active_groups": [] }, "name": "Friday", "_sys_prompt": "You're a assistant named Friday." } After loading the session state: { "memory": { "content": [ { "id": "DYPE9DyivDK9stghdM2TWC", "name": "user", "role": "user", "content": "Hello, agent!", "metadata": null, "timestamp": "2025-08-15 10:13:29.644" }, { "id": "WXEB3u2rRuctLSFZUUYZ6U", "name": "Friday", "role": "assistant", "content": [ { "id": "8WH5TyRNaFm6TX5Xr2Y9RQ", "type": "tool_use", "name": "generate_response", "input": { "response": "Hello! How can I assist you today?" } } ], "metadata": null, "timestamp": "2025-08-15 10:13:29.644" }, { "id": "XQ3YqvVpUBouzMpEzq8Q7D", "name": "system", "role": "system", "content": [ { "type": "tool_result", "id": "8WH5TyRNaFm6TX5Xr2Y9RQ", "name": "generate_response", "output": [ { "type": "text", "text": "Successfully generated response." } ] } ], "metadata": null, "timestamp": "2025-08-15 10:13:30.765" }, { "id": "BN3CQ3fj4vRJJeoY2bjwRS", "name": "Friday", "role": "assistant", "content": "Hello! How can I assist you today?", "metadata": null, "timestamp": "2025-08-15 10:13:30.765" } ] }, "toolkit": { "active_groups": [] }, "name": "Friday", "_sys_prompt": "You're a assistant named Friday." } .. GENERATED FROM PYTHON SOURCE LINES 214-216 Now we can see the agent state is restored to the saved state. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 2.520 seconds) .. _sphx_glr_download_tutorial_task_state.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: task_state.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: task_state.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: task_state.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_