ADK 的数据库记忆服务¶
Supported in ADKPython
adk-database-memory 是 ADK Python 的一个即插即用的持久化 BaseMemoryService,基于异步 SQLAlchemy 构建。此集成使用你自己的数据库为 ADK 智能体提供跨会话持久化记忆:在开发中使用 SQLite,在生产中使用 Postgres 或 MySQL。
使用场景¶
- 个性化助手:跨会话累积长期用户偏好、事实和过去的决策,以便智能体在需要时回忆。
- 支持和任务智能体:跨工单和设备持久化对话历史,以便用户返回时上下文始终可用。
- 自托管部署:当 Vertex AI 记忆库不可用时(本地部署、离线环境、非 GCP 云),将记忆保存在你已使用的数据库上。
- 本地开发:使用 SQLite 实现零配置持久化记忆(重启后数据保留),然后在生产环境中将连接字符串切换到 Postgres。
前提条件¶
- Python 3.10 或更高版本
- 受支持的数据库:SQLite、PostgreSQL 或 MySQL / MariaDB
安装¶
将包与数据库驱动程序一起安装:
pip install "adk-database-memory[sqlite]" # SQLite(通过 aiosqlite)
pip install "adk-database-memory[postgres]" # PostgreSQL(通过 asyncpg)
pip install "adk-database-memory[mysql]" # MySQL / MariaDB(通过 aiomysql)
核心包不包含任何数据库驱动程序。选择与你后端匹配的额外依赖项,或自行安装你自己的异步驱动程序。
与智能体一起使用¶
该服务实现了 google.adk.memory.base_memory_service.BaseMemoryService,因此它可以无缝接入任何接受 memory_service 的 ADK Runner:
import asyncio
from adk_database_memory import DatabaseMemoryService
from google.adk.agents import Agent
from google.adk.runners import InMemoryRunner
memory = DatabaseMemoryService("sqlite+aiosqlite:///memory.db")
agent = Agent(
name="assistant",
model="gemini-flash-latest",
instruction="You are a helpful assistant.",
)
async def main():
async with memory:
# 运行智能体,将会话持久化到记忆
runner = InMemoryRunner(agent=agent, app_name="my_app")
session = await runner.session_service.create_session(app_name="my_app", user_id="u1")
# 会话完成后:
await memory.add_session_to_memory(session)
# 后续,为新查询回忆相关记忆:
result = await memory.search_memory(
app_name="my_app",
user_id="u1",
query="我们之前关于定价模型做出了什么决定?",
)
for entry in result.memories:
print(entry.author, entry.timestamp, entry.content)
asyncio.run(main())
支持的后端¶
| 后端 | 连接 URL 示例 | 额外依赖 |
|---|---|---|
| SQLite | sqlite+aiosqlite:///memory.db |
[sqlite] |
| SQLite(内存中) | sqlite+aiosqlite:///:memory: |
[sqlite] |
| PostgreSQL | postgresql+asyncpg://user:pass@host/db |
[postgres] |
| MySQL / MariaDB | mysql+aiomysql://user:pass@host/db |
[mysql] |
| 任何异步 SQLAlchemy 方言 | 取决于驱动程序 | 自带 |
API¶
| 方法 | 描述 |
|---|---|
add_session_to_memory(session) |
索引已完成会话中的每个事件。 |
add_events_to_memory(app_name, user_id, events, ...) |
索引显式的事件片段(用于流式摄入)。 |
search_memory(app_name, user_id, query) |
返回 MemoryEntry 对象,其索引关键词与查询重叠,范围限定在给定的应用和用户内。 |
首次写入时,服务会创建一个单表(adk_memory_entries),并在 (app_name, user_id) 上建立索引。JSON 内容在 PostgreSQL 上存储为 JSONB,在 MySQL 上存储为 LONGTEXT,在 SQLite 上存储为 TEXT。
检索使用与 ADK 中的内存中记忆服务和 Firestore 记忆服务相同的关键词提取和匹配方法。如需基于嵌入的回忆,请将此包与 Vertex AI 记忆库或向量存储配合使用。