写入并召回第一条记忆

更新时间:
复制 MD 格式

本示例使用 Python SDK 创建结构化记忆库,写入一段对话,并跨会话召回服务抽取的长期记忆。

前提条件

  • 已创建 AgentStorage 实例,记忆库将创建在该实例中。

  • 已获得 AgentStorage 名称、访问地址(endpoint)和 API Key。

步骤1:安装 SDK

pip install "tablestore-agent-storage>=1.0.10"

步骤2:创建客户端和记忆库

from tablestore_agent_storage import AgentStorageClient

client = AgentStorageClient(
    api_key="<your-api-key>",
    ots_endpoint="https://<instance>.<region>.ots.aliyuncs.com",
    ots_instance_name="<instance-name>",
)

client.create_memory_store({
    "memoryStoreName": "agent_memory",
    "description": "Agent 长期记忆",
})

未指定记忆库类型时,默认创建以消息为输入、输出结构化记忆的记忆库。需要显式选择输出时,请使用 inputType 和 outputTypes;inputType 创建后不可修改。

步骤3:写入消息

scope = {
    "appId": "shopping-app",
    "tenantId": "user-001",
    "agentId": "shopping-assistant",
    "runId": "session-001",
}

response = client.add_memories({
    "memoryStoreName": "agent_memory",
    "scope": scope,
    "messages": [
        {"role": "user", "content": "我平时喝美式咖啡,不加糖。"},
        {"role": "assistant", "content": "好的,我会记住你的饮品偏好。"},
    ],
    "sync": True,
})
print(response.get("memoryIds", []))

服务先保存原始消息,再抽取长期记忆。示例使用 sync=True 便于立即验证;同步写入完成后,响应的 memoryIds 数组直接返回生成的长期记忆 ID,没有生成长期记忆时返回空数组。生产写入通常保持默认异步模式,并使用响应中的 requestId 查询抽取任务。

步骤4:跨会话检索长期记忆

response = client.search_memories({
    "memoryStoreName": "agent_memory",
    "scope": {
        "appId": "shopping-app",
        "tenantId": "user-001",
        "agentId": "shopping-assistant",
        "runId": "*",
    },
    "query": "用户喝咖啡有什么偏好?",
    "topK": 5,
})

for item in response.get("results", []):
    print(f"[{item['score']:.4f}] {item['unit']['text']}")

runId="*" 表示在同一应用、用户和 Agent 下跨会话检索。索引刷新可能带来短暂延迟;如果同步写入后第一次没有结果,请稍后重试。

步骤5:将结果交给 Agent

只选择与当前任务相关的少量记忆加入模型上下文。例如:

已知用户偏好:
- 用户平时喝美式咖啡,不加糖。

请基于这些偏好回答当前问题;如果记忆与当前请求冲突,以用户本轮明确表达为准。

不要把整个记忆库直接拼接到提示词中。应保留每条结果的记忆 ID、Scope 和得分,以便纠错和审计。

下一步