Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(session): make jsonsession file read and write async (#1313)
qbc59e0135151aa
diff --git a/pyproject.toml b/pyproject.tomlindex dfcf65a69..1581431db 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -40,6 +40,7 @@ dependencies = ["sounddevice","sqlalchemy","python-frontmatter",+ "aiofiles",][project.optional-dependencies]diff --git a/src/agentscope/session/_json_session.py b/src/agentscope/session/_json_session.pyindex 04dc0f628..b83620637 100644--- a/src/agentscope/session/_json_session.py+++ b/src/agentscope/session/_json_session.py@@ -2,6 +2,7 @@"""The JSON session class."""import jsonimport os+import aiofilesfrom ._session_base import SessionBasefrom .._logging import logger@@ -63,13 +64,19 @@ class JSONSession(SessionBase):name: state_module.state_dict()for name, state_module in state_modules_mapping.items()}- with open(- self._get_save_path(session_id, user_id=user_id),+ session_save_path = self._get_save_path(session_id, user_id=user_id)+ async with aiofiles.open(+ session_save_path,"w",encoding="utf-8",errors="surrogatepass",- ) as file:- json.dump(state_dicts, file, ensure_ascii=False)+ ) as f:+ await f.write(json.dumps(state_dicts, ensure_ascii=False))++ logger.info(+ "Saved session state to %s successfully.",+ session_save_path,+ )async def load_session_state(self,@@ -93,13 +100,14 @@ class JSONSession(SessionBase):"""session_save_path = self._get_save_path(session_id, user_id=user_id)if os.path.exists(session_save_path):- with open(+ async with aiofiles.open(session_save_path,"r",encoding="utf-8",errors="surrogatepass",- ) as file:- states = json.load(file)+ ) as f:+ content = await f.read()+ states = json.loads(content)for name, state_module in state_modules_mapping.items():if name in states:diff --git a/tests/session_test.py b/tests/session_test.pyindex 0730c5cb5..6abd4f1c4 100644--- a/tests/session_test.py+++ b/tests/session_test.py@@ -79,6 +79,20 @@ class SessionTest(IsolatedAsyncioTestCase):agent2=agent2,)+ # Mutate local state to verify load really works+ agent1.name = "Changed"+ agent2.sys_prompt = "Changed prompt"++ # Load back+ await session.load_session_state(+ session_id="user_1",+ agent1=agent1,+ agent2=agent2,+ )++ self.assertEqual(agent1.name, "Friday")+ self.assertEqual(agent2.sys_prompt, "A helpful assistant.")+async def asyncTearDown(self) -> None:"""Clean up after the test."""# Remove the session file if it exists