方法介绍
AsyncMemoryClient 是 MemoryClient 的异步版本,提供与同步客户端完全一致的数据面方法,所有方法均为异步方法,使用 await 调用。适用于异步编程框架(如 FastAPI、LangChain 异步回调),避免阻塞等待网络响应。导入
from tencentdb_agent_memory.v3 import AsyncMemoryClient
使用示例
import asynciofrom tencentdb_agent_memory.v3 import AsyncMemoryClientasync def main():async with AsyncMemoryClient(endpoint="https://memory.tdai.tencentyun.com",api_key="sk-xxxxxxxxxxxxxxxx",service_id="tdai-mem-xxxxxxxx",team_id="team-abc123",agent_id="agt-xyz789",user_id="usr-456",session_id="agent-main:sess-001",) as client:# 写入对话result = await client.add_conversation(messages=[{"role": "user", "content": "帮我查一下上周的会议纪要"},],)print(f"受理 {result['total_count']} 条消息")# 检索记忆memories = await client.search_conversation(query="会议纪要",limit=5,)for msg in memories["messages"]:print(f"[score={msg['score']:.2f}] {msg['content']}")asyncio.run(main())
初始化参数
参数名 | 类型 | 必填 | 描述说明 |
endpoint | str | 是 | Memory 服务接入地址 |
api_key | str | 是 | API Key,格式 sk-... |
service_id | str | 否 | 实例 ID |
team_id | str | 是 | 团队 ID |
agent_id | str | 是 | Agent ID |
user_id | str | 是 | 用户 ID |
session_id | str | 否 | 默认会话 ID。 说明: add_conversation 写入时,构造或调用至少一处必须提供,否则抛出 ValueError。调用时传 None 不会清除构造值,跨 session 查询请用 with_isolation(session_id=None) |
task_id | str | 否 | 默认 Task ID |
timeout | float | 否 | 请求超时时间(秒),默认 30 |
verify | bool | 否 | 是否验证 SSL 证书,默认 False |
stub | Stub | 否 | 自定义网络传输通道,用于测试场景 |
与同步版的差异
维度 | MemoryClient | AsyncMemoryClient |
方法签名 | 全部相同 | 全部相同 |
返回类型 | Dict[str, Any] | Coroutine[Any, Any, Dict[str, Any]] |
网络传输通道 | httpx.Client | httpx.AsyncClient |
上下文管理器 | 同步 with | 异步 async with |
close() | 同步调用 | 异步 await 调用 |
with_isolation() | 同步调用,返回同步客户端 | 同步调用,返回异步客户端副本 |