Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
Add example for SQLite-based session management (#740)
DavdGao933a88e616da
diff --git a/README.md b/README.mdindex a9616f9e5..972699c5e 100644--- a/README.md+++ b/README.md@@ -356,6 +356,7 @@ as_studio- [MCP](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/agent_with_mcp)- [Structured Output](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/structured_output)- [Long-Term Memory](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/long_term_memory)+ - [Session with SQLite](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/session_with_sqlite)## ⚖️ Licensediff --git a/README_zh.md b/README_zh.mdindex 95c1ab8c0..3aca570a0 100644--- a/README_zh.md+++ b/README_zh.md@@ -358,6 +358,7 @@ as_studio- [MCP](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/agent_with_mcp)- [结构化输出](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/structured_output)- [长期记忆](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/long_term_memory)+ - [基于DB的会话管理](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/session_with_sqlite)## ⚖️ 许可diff --git a/examples/functionality/session_with_sqlite/README.md b/examples/functionality/session_with_sqlite/README.mdnew file mode 100644index 000000000..e442b51c1--- /dev/null+++ b/examples/functionality/session_with_sqlite/README.md@@ -0,0 +1,25 @@+# Session Management with Sqlite DB++This example demonstrates how to implement session management with a database backend. We use SQLite for simplicity,+but the approach can be adapted for other databases.++Specifically, we implement a ``SqliteSession`` class that persists and retrieves session data from a SQLite table.+The table schema includes fields for session ID, session data (stored as JSON), and timestamps for creation and last+update.++We will create a simple agent and chat with it, then store the session data in the SQLite database. Then in the+``test_load_session`` function, we will load the session data from the database and continue the chat.++## Quick Start++Install agentscope from Pypi or source code.++```bash+pip install agentscope+```++Run the example by the following command++```bash+python main.py+```\ No newline at end of filediff --git a/examples/functionality/session_with_sqlite/main.py b/examples/functionality/session_with_sqlite/main.pynew file mode 100644index 000000000..a7487a227--- /dev/null+++ b/examples/functionality/session_with_sqlite/main.py@@ -0,0 +1,76 @@+# -*- coding: utf-8 -*-+"""The main entry point for the session with SQLite example."""+import asyncio+import os++from sqlite_session import SqliteSession++from agentscope.agent import ReActAgent+from agentscope.formatter import DashScopeChatFormatter+from agentscope.message import Msg+from agentscope.model import DashScopeChatModel++SQLITE_PATH = "./session.db"+++async def save_session() -> None:+ """Create an agent, chat with it, and save its state to 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(),+ )++ # Chat with it to generate some state+ await agent(+ Msg("user", "What's the capital of America?", "user"),+ )++ # Save the session state by SqliteSession+ session = SqliteSession(SQLITE_PATH, "user_alice")++ # Save the agent state by the given key "friday_of_alice"+ # 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(),+ )++ # 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("Trying to create an agent and save its state to SQLite...")+asyncio.run(save_session())++print("\nTrying to create a new agent and load the state from SQLite...")+asyncio.run(load_session())diff --git a/examples/functionality/session_with_sqlite/sqlite_session.py b/examples/functionality/session_with_sqlite/sqlite_session.pynew file mode 100644index 000000000..ebb47d5c5--- /dev/null+++ b/examples/functionality/session_with_sqlite/sqlite_session.py@@ -0,0 +1,105 @@+# -*- coding: utf-8 -*-+"""The SQLite session class."""+import json+import sqlite3++from agentscope.module import StateModule+from agentscope.session import SessionBase+++class SqliteSession(SessionBase):+ """A session that uses SQLite for storage."""++ 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_path++ async def save_session_state(+ self,+ **state_modules_mapping: StateModule,+ ) -> None:+ """Save the session state to the SQLite database."""+ with sqlite3.connect(self.sqlite_path) as conn:+ cursor = conn.cursor()+ # Prepare the session data as a dictionary+ session_data = {+ name: module.state_dict()+ for name, module in state_modules_mapping.items()+ }++ json_data = json.dumps(session_data)++ cursor.execute(+ """+ CREATE TABLE IF NOT EXISTS as_session (+ session_id TEXT,+ session_data JSON,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (session_id)+ )+ """,+ )++ # Insert or replace the session data+ cursor.execute(+ """+ INSERT INTO as_session (session_id, session_data, updated_at)+ VALUES (?, json(?), CURRENT_TIMESTAMP)+ ON CONFLICT(session_id) DO UPDATE SET+ session_data = excluded.session_data,+ updated_at = excluded.updated_at+ """,+ (self.session_id, json_data),+ )+ conn.commit()+ cursor.close()++ async def load_session_state(+ self,+ **state_modules_mapping: StateModule,+ ) -> None:+ """Get the state dictionary from the SQLite database.++ Args:+ **state_modules_mapping (`list[StateModule]`):+ The list of state modules to be loaded.+ """+ 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.",+ )++ 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.",+ )+ cursor.close()