Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
Remove the argument session_id from the constructor to support different sessions (#767)
DavdGao922c64b7bec1
diff --git a/docs/tutorial/en/src/task_state.py b/docs/tutorial/en/src/task_state.pyindex 379ee5f54..3b54fadbf 100644--- a/docs/tutorial/en/src/task_state.py+++ b/docs/tutorial/en/src/task_state.py@@ -166,19 +166,19 @@ print(json.dumps(agent.state_dict(), indent=4))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+ save_dir="./", # The dir used to save the session files)async def example_session() -> None:"""Example of session management."""await session.save_session_state(+ session_id="user_1", # Use the name as the session idagent=agent,)print("The saved state:")- with open(session.save_path, "r", encoding="utf-8") as f:+ with open("./user_1.json", "r", encoding="utf-8") as f:print(json.dumps(json.load(f), indent=4))@@ -201,6 +201,7 @@ async def example_load_session() -> None:# then we load the session stateawait session.load_session_state(+ session_id="user_1",# The keyword argument must be the same as the one used in `save_session_state`agent=agent,)diff --git a/docs/tutorial/zh_CN/src/task_state.py b/docs/tutorial/zh_CN/src/task_state.pyindex 0084eb97d..89a0d64b3 100644--- a/docs/tutorial/zh_CN/src/task_state.py+++ b/docs/tutorial/zh_CN/src/task_state.py@@ -162,8 +162,7 @@ print(json.dumps(agent.state_dict(), indent=4, ensure_ascii=False))# 然后我们将其保存到会话文件中:session = JSONSession(- session_id="session_2025-08-08", # 使用时间作为会话 ID- save_dir="./user-bob/", # 使用用户名作为保存目录+ save_dir="./", # 保存所有session文件的目录)@@ -172,11 +171,12 @@ async def example_session() -> None:# 可以保存多个状态,只需要输入的对象为 `StateModule` 的子类。await session.save_session_state(+ session_id="user_bob",agent=agent,)print("保存的状态:")- with open(session.save_path, "r", encoding="utf-8") as f:+ with open("./user_bob.json", "r", encoding="utf-8") as f:print(json.dumps(json.load(f), indent=4, ensure_ascii=False))@@ -200,6 +200,7 @@ async def example_load_session() -> None:# 从会话文件中加载状态await session.load_session_state(+ session_id="user_bob",# 这里使用的关键词参数必须与 `save_session_state` 中的参数一致agent=agent,)@@ -207,6 +208,8 @@ async def example_load_session() -> None:print(json.dumps(agent.state_dict(), indent=4, ensure_ascii=False))+asyncio.run(example_load_session())+# %%# 此时我们可以观察到智能体的状态已经恢复到之前保存的状态。#diff --git a/examples/functionality/session_with_sqlite/main.py b/examples/functionality/session_with_sqlite/main.pyindex a7487a227..a451db90a 100644--- a/examples/functionality/session_with_sqlite/main.py+++ b/examples/functionality/session_with_sqlite/main.py@@ -13,8 +13,16 @@ from agentscope.model import DashScopeChatModelSQLITE_PATH = "./session.db"-async def save_session() -> None:- """Create an agent, chat with it, and save its state to SQLite."""+async def main(username: str, query: str) -> None:+ """Create an agent, load from session, chat with it, and save its state+ to SQLite.++ Args:+ username (`str`):+ The username to identify the session.+ query (`str`):+ The user input query.+ """agent = ReActAgent(name="friday",@@ -26,51 +34,43 @@ async def save_session() -> None:formatter=DashScopeChatFormatter(),)+ # Create the SQLite session+ session = SqliteSession(SQLITE_PATH)++ # Load the agent state by the given key "friday_of_user"+ # The load_session_state supports multiple state modules+ await session.load_session_state(+ session_id=username,+ friday_of_user=agent,+ )+# Chat with it to generate some stateawait agent(- Msg("user", "What's the capital of America?", "user"),+ Msg("user", query, "user"),)- # Save the session state by SqliteSession- session = SqliteSession(SQLITE_PATH, "user_alice")-- # Save the agent state by the given key "friday_of_alice"+ # Save the agent state by the given key "friday_of_user"# Also support multiple state modules (e.g. multiple agents)- await session.save_session_state(friday_of_alice=agent)---async def load_session() -> None:- """Create a new agent and load the previous state from SQLite."""-- agent = ReActAgent(- name="friday",- sys_prompt="You are a helpful assistant named Friday.",- model=DashScopeChatModel(- model_name="qwen-max",- api_key=os.environ["DASHSCOPE_API_KEY"],- ),- formatter=DashScopeChatFormatter(),+ await session.save_session_state(+ session_id=username,+ friday_of_user=agent,)- # Save the session state by SqliteSession- session = SqliteSession(SQLITE_PATH, "user_alice")-- # Load the agent state by the given key "friday_of_alice"- # The load_session_state supports multiple state modules- await session.load_session_state(friday_of_alice=agent)-- # Continue the chat, the agent should remember the previous state- await agent(- Msg(- "user",- "What's my last question and your answer?",- "user",- ),- )+print("User named Alice chats with the agent ...")+asyncio.run(main("alice", "What's the capital of America?"))-print("Trying to create an agent and save its state to SQLite...")-asyncio.run(save_session())+print("User named Bob chats with the agent ...")+asyncio.run(main("bob", "What's the capital of China?"))-print("\nTrying to create a new agent and load the state from SQLite...")-asyncio.run(load_session())+print(+ "\nNow, let's recover the session for Alice and ask about what the user "+ "asked before.",+)+asyncio.run(+ main(+ "alice",+ "What did I ask you before, what's your answer and how many "+ "questions have I asked you?",+ ),+)diff --git a/examples/functionality/session_with_sqlite/sqlite_session.py b/examples/functionality/session_with_sqlite/sqlite_session.pyindex ebb47d5c5..94ebc13b2 100644--- a/examples/functionality/session_with_sqlite/sqlite_session.py+++ b/examples/functionality/session_with_sqlite/sqlite_session.py@@ -1,8 +1,10 @@# -*- coding: utf-8 -*-"""The SQLite session class."""import json+import osimport sqlite3+from agentscope import loggerfrom agentscope.module import StateModulefrom agentscope.session import SessionBase@@ -13,22 +15,18 @@ class SqliteSession(SessionBase):def __init__(self,sqlite_path: str,- session_id: str,) -> None:"""Initialize the session.Args:sqlite_path (`str`):The path to the SQLite database file.- session_id (`str`):- The unique identifier for the session, e.g. the user ID."""- super().__init__(session_id)-self.sqlite_path = sqlite_pathasync def save_session_state(self,+ session_id: str,**state_modules_mapping: StateModule,) -> None:"""Save the session state to the SQLite database."""@@ -63,43 +61,107 @@ class SqliteSession(SessionBase):session_data = excluded.session_data,updated_at = excluded.updated_at""",- (self.session_id, json_data),+ (session_id, json_data),)conn.commit()cursor.close()async def load_session_state(self,+ session_id: str,+ allow_not_exist: bool = True,**state_modules_mapping: StateModule,) -> None:"""Get the state dictionary from the SQLite database.Args:+ session_id (`str`):+ The session id.+ allow_not_exist (`bool`, defaults to `True`):+ Whether to allow the session to not exist. If `False`, raises+ an error if the session does not exist.**state_modules_mapping (`list[StateModule]`):The list of state modules to be loaded."""+ if not os.path.exists(self.sqlite_path):+ if allow_not_exist:+ logger.info(+ "SQLite database %s does not exist. "+ "Skipping load for session_id %s.",+ self.sqlite_path,+ session_id,+ )+ return+ raise ValueError(+ "Failed to load session state because the SQLite database "+ f"file '{self.sqlite_path}' does not exist.",+ )+with sqlite3.connect(self.sqlite_path) as conn:cursor = conn.cursor()- # Query the session data- cursor.execute(- "SELECT session_data FROM as_session WHERE session_id = ?",- (self.session_id,),- )- row = cursor.fetchone()- if row is None:- raise ValueError(- f"Failed to load session state for session_id "- f"{self.session_id} does not exist.",+ try:+ # If the table does not exist, return+ cursor.execute(+ """+ SELECT name FROM sqlite_master WHERE type='table' AND+ name='as_session';+ """,)+ if cursor.fetchone() is None:+ if allow_not_exist:+ logger.info(+ "Session table does not exist in database %s. "+ "Skipping load for session_id %s.",+ self.sqlite_path,+ session_id,+ )+ return- session_data = json.loads(row[0])+ raise ValueError(+ "Failed to load session state because the session "+ "table 'as_session' does not exist in database "+ f"{self.sqlite_path}.",+ )++ # Query the session data+ cursor.execute(+ "SELECT session_data FROM as_session WHERE session_id = ?",+ (session_id,),+ )+ row = cursor.fetchone()++ if row is None:+ if allow_not_exist:+ logger.info(+ "Session_id %s does not exist in database %s. "+ "Skip loading.",+ session_id,+ self.sqlite_path,+ )+ return- for name, module in state_modules_mapping.items():- if name in session_data:- module.load_state_dict(session_data[name])- else:raise ValueError(- f"State module '{name}' not found in session data.",+ f"Failed to load session state for session_id "+ f"{session_id} does not exist.",)- cursor.close()++ session_data = json.loads(row[0])++ for name, module in state_modules_mapping.items():+ if name in session_data:+ module.load_state_dict(session_data[name])+ else:+ raise ValueError(+ f"State module '{name}' not found in session "+ "data.",+ )+ logger.info(+ "Load session state for session_id %s from "+ "database %s successfully.",+ session_id,+ self.sqlite_path,+ )++ finally:+ cursor.close()diff --git a/src/agentscope/session/_json_session.py b/src/agentscope/session/_json_session.pyindex caba6a06f..c37b3527e 100644--- a/src/agentscope/session/_json_session.py+++ b/src/agentscope/session/_json_session.py@@ -4,37 +4,62 @@ import jsonimport osfrom ._session_base import SessionBase+from .._logging import loggerfrom ..module import StateModuleclass JSONSession(SessionBase):"""The JSON session class."""- def __init__(self, session_id: str, save_dir: str) -> None:+ def __init__(+ self,+ session_id: str | None = None,+ save_dir: str = "./",+ ) -> None:"""Initialize the JSON session class.Args:session_id (`str`):- The session id.- save_dir (`str`):+ The session id, deprecated and move to the `save_session_state`+ and `load_session_state` methods to support different session+ ids.+ save_dir (`str`, defaults to `"./"):The directory to save the session state."""- super().__init__(session_id=session_id)self.save_dir = save_dir- @property- def save_path(self) -> str:- """The path to save the session state."""+ if session_id is not None:+ logger.warning(+ "The `session_id` argument in the JSONSession constructor is "+ "deprecated and will be removed in future versions. Please "+ "pass the `session_id` to the `save_session_state` and "+ "`load_session_state` methods instead.",+ )++ def _get_save_path(self, session_id: str) -> str:+ """The path to save the session state.++ Args:+ session_id (`str`):+ The session id.++ Returns:+ `str`:+ The path to save the session state.+ """os.makedirs(self.save_dir, exist_ok=True)- return os.path.join(self.save_dir, f"{self.session_id}.json")+ return os.path.join(self.save_dir, f"{session_id}.json")async def save_session_state(self,+ session_id: str,**state_modules_mapping: StateModule,) -> None:"""Load the state dictionary from a JSON file.Args:+ session_id (`str`):+ The session id.**state_modules_mapping (`dict[str, StateModule]`):A dictionary mapping of state module names to their instances."""@@ -42,28 +67,51 @@ class JSONSession(SessionBase):name: state_module.state_dict()for name, state_module in state_modules_mapping.items()}- with open(self.save_path, "w", encoding="utf-8") as file:+ with open(+ self._get_save_path(session_id),+ "w",+ encoding="utf-8",+ ) as file:json.dump(state_dicts, file, ensure_ascii=False)async def load_session_state(self,+ session_id: str,+ allow_not_exist: bool = True,**state_modules_mapping: StateModule,) -> None:"""Get the state dictionary to be saved to a JSON file.Args:+ session_id (`str`):+ The session id.+ allow_not_exist (`bool`, defaults to `True`):+ Whether to allow the session to not exist. If `False`, raises+ an error if the session does not exist.state_modules_mapping (`list[StateModule]`):The list of state modules to be loaded."""- if os.path.exists(self.save_path):- with open(self.save_path, "r", encoding="utf-8") as file:+ session_save_path = self._get_save_path(session_id)+ if os.path.exists(session_save_path):+ with open(session_save_path, "r", encoding="utf-8") as file:states = json.load(file)for name, state_module in state_modules_mapping.items():if name in states:state_module.load_state_dict(states[name])+ logger.info(+ "Load session state from %s successfully.",+ session_save_path,+ )++ elif allow_not_exist:+ logger.info(+ "Session file %s does not exist. Skip loading session state.",+ session_save_path,+ )+else:raise ValueError(- f"Failed to load session state for file {self.save_path} "+ f"Failed to load session state for file {session_save_path} ""does not exist.",)diff --git a/src/agentscope/session/_session_base.py b/src/agentscope/session/_session_base.pyindex 09193ef46..f7834d5a3 100644--- a/src/agentscope/session/_session_base.py+++ b/src/agentscope/session/_session_base.py@@ -1,7 +1,6 @@# -*- coding: utf-8 -*-"""The session base class in agentscope."""from abc import abstractmethod-from typing import Anyfrom ..module import StateModule@@ -9,21 +8,26 @@ from ..module import StateModuleclass SessionBase:"""The base class for session in agentscope."""- session_id: str- """The session id"""-- def __init__(self, session_id: str) -> None:- """Initialize the session base class"""-- self.session_id = session_id-@abstractmethodasync def save_session_state(self,+ session_id: str,**state_modules_mapping: StateModule,) -> None:- """Save the session state"""+ """Save the session state++ Args:+ session_id (`str`):+ The session id.+ **state_modules_mapping (`dict[str, StateModule]`):+ A dictionary mapping of state module names to their instances.+ """@abstractmethod- async def load_session_state(self, *args: Any, **kwargs: Any) -> None:+ async def load_session_state(+ self,+ session_id: str,+ allow_not_exist: bool = True,+ **state_modules_mapping: StateModule,+ ) -> None:"""Load the session state"""diff --git a/tests/session_test.py b/tests/session_test.pyindex 8cae45d00..2f58104d1 100644--- a/tests/session_test.py+++ b/tests/session_test.py@@ -52,7 +52,6 @@ class SessionTest(IsolatedAsyncioTestCase):async def test_session_base(self) -> None:"""Test the SessionBase class."""session = JSONSession(- "user_1",save_dir="./",)@@ -74,7 +73,11 @@ class SessionTest(IsolatedAsyncioTestCase):),)- await session.save_session_state(agent1=agent1, agent2=agent2)+ await session.save_session_state(+ session_id="user_1",+ agent1=agent1,+ agent2=agent2,+ )async def asyncTearDown(self) -> None:"""Clean up after the test."""