AI Agent 的双层记忆架构:拆解 Google Cloud 的 AlloyDB + Memorystore 指南
💡 工具推荐:AI Token 计算器、AI SQL 优化器、AI 数据分析
LLM 是无状态的,而企业 Agent 要做的是跨天、跨会话的长时任务。当用户几天后回来,模型的上下文窗口是空的——除非你的应用能重建过去的上下文。很多团队的第一反应是「上下文填充」:把原始聊天记录、工具日志统统塞进提示词。这在早期还行,一上规模就崩:token 成本随每条消息翻倍,简单问题也要等 30 多秒,模型还会「中间遗忘」,把埋在大量文本里的关键指令漏掉。2026 年 10 月 2 日,Google Cloud 给出了一个更工程化的答案:用 Memorystore for Valkey 做短期缓冲、用 AlloyDB AI 做长期持久记忆的双层架构。本文拆解它、它的四种记忆类型,以及真实的基准数据。
短期缓冲放内存,长期事实进数据库——分工是关键
问题:有状态的工作流 vs 无状态的 LLM
据 Google Cloud 的描述,核心矛盾在于:Agent 被用于多轮对话和长时工作流,但 LLM 跨会话是无状态的;用户几天后回来,模型从空上下文开始,除非应用用「长期记忆」重建。常见的两个临时办法都不理想。一个是「上下文填充」——把能塞的都塞进 prompt,结果是 token 成本随消息数倍增、响应时间被拖到 30 秒以上、并因「中间遗忘」效应漏掉关键指令。另一个是「滚动摘要」——让模型定期把旧消息压成一段摘要,虽然能缩小 prompt,但基于 LLM 的摘要本质上是有损的:几轮压缩之后,细微但重要的细节会被当作背景噪音滤掉,再过几轮,Agent 就会悄悄打破你早先设定的约束。
# The architecture, in one object. Facts are from Google Cloud's
# blog post dated October 2, 2026.
TIERED_MEMORY = {
"short_term": {
"store": "Memorystore for Valkey",
"role": "token-bounded sliding window of active turns",
"why": "sub-millisecond, high-throughput lookups every turn",
},
"long_term": {
"store": "AlloyDB AI (PostgreSQL)",
"role": "facts, preferences and episodic memory across sessions",
"why": "transactional integrity, governance, hybrid retrieval",
},
"reported_effect": "up to 70% reduction in token spend",
}双层记忆架构
Google Cloud 推荐把记忆分成两层。短期会话缓冲:用 token 受限的滑动窗口,在内存里缓存当前活跃的对话轮次,让上下文窗口大小在多轮、甚至跨设备时保持稳定,同时保留最新消息——这一层需要每轮亚毫秒级、高吞吐的查找,因此适合用 Memorystore for Valkey。长期持久记忆:存储跨会话的重要事实、用户偏好和情景事实——这一层需要事务一致性、数据治理,以及对关系数据和向量的混合检索,这些由 AlloyDB AI 原生提供。Google Cloud 指出,虽然理论上可以把两层都放进关系库,但用内存缓存做短期层性能与扩展性更好:活跃缓冲高度易失、每轮都要高频更新,把这些写入放进内存键值缓存,可以避免关系库的写放大和表膨胀。
# The four memory types, mapped to their storage layer and life.
# Splitting short-term context from structured long-term rules is what
# keeps prompts lean without losing constraints.
MEMORY_TYPES = {
# type: (what it stores, tier, lifespan)
"buffer": ("recent raw conversation turns", "valkey", "active session"),
"summary": ("compacted older turns", "valkey", "multi-turn window"),
"episodic": ("past actions, events, tool output", "alloydb", "permanent"),
"entity_rule":("preferences, constraints, vetoes", "alloydb", "permanent"),
}
# Rule and constraint recall must not degrade as the conversation grows;
# that is exactly what naive context stuffing breaks.把高频写入交给内存缓存,避免关系库写放大
四种记忆类型
为了让长期状态可组织,Google Cloud 进一步把记忆分成四类:缓冲记忆(Buffer)存最近的原始对话轮次,放在 Valkey,生命周期是当前会话;摘要记忆(Summary)存压缩后的较旧轮次(即「压实」),也放在 Valkey,跨多轮窗口;情景记忆(Episodic)存过去的动作、事件与工具输出,放在 AlloyDB,永久保留;实体与规则记忆(Entity & rule)存用户偏好、约束与「否决项」,也放在 AlloyDB,永久保留。把短期对话上下文与结构化长期规则隔离之后,Agent 就能按需检索相关上下文,而不必用原始交互日志填满 token 窗口——这正是规则召回不会随轮次退化、而上下文填充会退化的原因。
# The read and write paths. Two coordinated flows keep the context
# window bounded while persisting everything that matters.
READ_PATH = [
"fetch the active sliding window from Memorystore for Valkey",
"normalise the query in-database with ai.generate",
"retrieve scoped entity rules + episodic facts via ai.hybrid_search",
]
WRITE_PATH = [
"cache the finished turn in Memorystore for Valkey",
"an async worker extracts structured entities from the exchange",
"write them to AlloyDB, where auto-embeddings run transactionally",
]
# AlloyDB AI: ai.initialize_embeddings (up to 3,000 embeddings/sec),
# ai.generate (run Gemini from SQL), ai.hybrid_search (RRF fusion).读写路径与数据库内能力
系统沿两条协同路径运行。读路径:用户提问时,应用从 Memorystore for Valkey 取活跃滑动窗口,用数据库内的 ai.generate 做查询规范化,再用 ai.hybrid_search 从 AlloyDB 检索限定范围的实体规则与相关情景事实。写路径:生成回答后,该轮次立即缓存到 Valkey;一个异步队列工作线程从这轮交互中抽取结构化实体,直接写入 AlloyDB,由事务性的自动向量嵌入当场计算并存储向量表示。AlloyDB AI 把核心 AI 能力嵌进了数据库引擎:ai.initialize_embeddings 以每秒最多 3000 条的速度为文本列自动生成嵌入,并用 incremental_refresh_mode => 'transactional' 在同一事务内保持更新;ai.generate 让你能从 SQL 直接调用 Gemini 等基础模型;ai.hybrid_search 则在内核里跑 Reciprocal Rank Fusion,把向量余弦相似度与 PostgreSQL 全文检索(BM25、RUM 或 GIN)合并成一次调用,并支持元数据过滤下推。
# The benchmark Google Cloud published across 45+ turns with heavy
# tool execution. Naive context stuffing vs tiered memory.
BENCH = {
"prompt_tokens_turn_45": {"stuffing": 747_033, "tiered": 83_262},
"latency_turn_45_s": {"stuffing": 33.5, "tiered": 6.7},
"cumulative_tokens": {"stuffing": 17_900_000, "tiered": 4_090_000},
"rule_recall": {"stuffing": "degrades", "tiered": "stable"},
}
def pct_smaller(old, new):
return round((old - new) / old * 100, 1)
pct_smaller(747_033, 83_262) # 88.9% smaller prompt
pct_smaller(17_900_000, 4_090_000) # 72.0% fewer session tokens实体抽取与混合检索都在数据库内部完成
基准数据:省了多少
Google Cloud 公布了它在多轮开发对话(45 轮以上、含大量工具执行)上的内部基准。相比朴素的上下文填充,分层记忆的收益相当具体:第 45 轮的活跃 prompt 从 747,033 token 降到 83,262 token,缩小 88.9%;第 45 轮的响应延迟从 33.5 秒降到 6.7 秒,快 80.0%;单轮等待时间从 33.5 秒降到 4.2 到 6.7 秒;整段会话的累计 token 从 1790 万降到 409 万,节省 72.0%;而规则与约束的召回不再随轮次退化,由 ACID 保证。Google Cloud 也明确提醒:这些数字来自模拟真实企业级 AI 结对编程助手的内部基准,实际收益会随 prompt 结构、查询频率和数据量变化。
# Governance you should wire in from day one. Multi-tenant agent
# memory is a security surface, not just a cache.
GOVERNANCE = [
"index user_id / project_id / scope columns in agent_entities",
"enforce PostgreSQL Row-Level Security (RLS) across tenants",
"use Parameterized Secure Views to blunt prompt-injection SQL",
"run scheduled compaction + time-based partition pruning",
"keep long-term memory behind the database, not in the prompt",
]
# Google Cloud ships an ADK Memory provider (ADKTieredMemoryProvider)
# and exposes long-term memory to agents as a tool (longterm_memory_tool).治理与多租户安全
把 Agent 记忆跑进企业生产,安全边界和访问控制不是可选项。Google Cloud 的建议是:在 agent_entities 中为用户、项目和范围列建立索引,并强制执行 PostgreSQL 行级安全(RLS),从而在同一数据库集群内隔离不同部门、团队和用户的记忆;参数化安全视图(PSV)提供另一层确定性的应用级安全,帮助抵御恶意提示和过宽泛的 SQL 查询。此外,还要做自动化的记忆生命周期管理:结合计划的 SQL 压实查询与基于时间的分区裁剪,让数据库占用和查询延迟长期可预测。落地路径也很清晰——延伸 ADK 的默认 Memory provider(如 ADKTieredMemoryProvider),并把长期记忆作为工具(如 longterm_memory_tool)暴露给 Agent,配套的 Codelab 提供了完整可跑的实现。
📌 常见问题 FAQ
Google Cloud 发布的是什么?
据 Google Cloud 2026 年 10 月 2 日的博客,它介绍了一种用 Memorystore for Valkey 做短期缓冲、用 AlloyDB AI 做长期持久记忆的双层 Agent 记忆架构,并称可最多降低 70% 的 token 支出。
为什么不能只用「上下文填充」?
据 Google Cloud,把原始聊天记录和工具日志都塞进 prompt 会导致 token 成本随消息数倍增、简单问题响应被拖到 30 秒以上,并因「中间遗忘」漏掉关键指令;滚动摘要虽然有损更小,但本质仍有损,几轮之后重要细节会被滤掉。
四种记忆类型分别是什么?
缓冲记忆(最近的原始轮次,Valkey,会话内)、摘要记忆(压缩的旧轮次,Valkey,多轮窗口)、情景记忆(过去的动作与工具输出,AlloyDB,永久)、实体与规则记忆(偏好、约束与否决项,AlloyDB,永久)。
基准数据说明了什么?
据其内部基准(45 轮以上的多轮开发对话),分层记忆把第 45 轮 prompt 从 747,033 token 降到 83,262(缩小 88.9%),延迟从 33.5 秒降到 6.7 秒,累计会话 token 从 1790 万降到 409 万(节省 72%),且规则召回不退化。实际结果会随负载变化。
生产环境要注意什么安全?
Google Cloud 建议在 agent_entities 中为用户、项目、范围列建索引并启用 PostgreSQL 行级安全(RLS)实现多租户隔离,使用参数化安全视图抵御恶意提示与过宽查询,并结合计划的 SQL 压实与基于时间的分区裁剪做记忆生命周期管理。
🔧 推荐工具
📚 参考资料
- Google Cloud Blog - Long-term AI agent memory in AlloyDB and Memorystore (2026-10-02)
- Google Cloud - AlloyDB AI product page
- Google Cloud - Memorystore for Valkey documentation
- Google - AlloyDB Agent Memory Codelab (hands-on tutorial)
- Google Cloud - Native hybrid vector similarity search (ai.hybrid_search)