agent-sleep
🧠 agent-sleep
面向 AI 智能体的持久经验整合与决策支持。
一个轻量级、与框架无关的 Python 库和 MCP 服务器,提供持久的经验整合和决策支持信号,宿主智能体可据此跨会话进行调整——其灵感来自生物大脑利用睡眠周期将清醒时的经验整合为持久的程序性规则和教训的方式。
问题:“智能体失忆症”
每个现代 AI 智能体框架(LangChain、AutoGen、CrewAI、OpenAI Assistants)都饱受 智能体失忆症 之苦:
每一次新的聊天或子智能体运行都完全从零开始。
当智能体在周一遇到错误或发现代码库约定时,它会在周二重复完全相同的错误。
向量数据库(RAG)只能搜索静态文档——它们无法从运行时经验中学习。
Related MCP server: Recall
MCP 快速入门 — 10 秒
这是主要的使用路径。
agent-sleep以 MCP 服务器形式提供,因此任何支持 MCP 的智能体(Antigravity、Claude Desktop、Cursor、Cline)都可以在不编写任何代码的情况下使用它。
步骤 1 — 安装并生成配置
# Option A: zero-install (recommended)
uvx agent-sleep-mcp
# Option B: install first, then run the init helper
pip install "agent-sleep[mcp]"
agent-sleep init # prints the correct config snippet for your platformagent-sleep init 会自动检测你的操作系统,并打印出可粘贴到 MCP 客户端配置文件中的 JSON 片段。无需手动编辑。
步骤 2 — 粘贴配置片段
init 命令会精确打印需要粘贴的内容和位置。以下是在 macOS 上针对 Claude Desktop 的示例输出:
{
"mcpServers": {
"agent-sleep": {
"command": "uvx",
"args": ["agent-sleep-mcp"]
}
}
}将其粘贴到 ~/Library/Application Support/Claude/claude_desktop_config.json 中,重启 Claude,就完成了。
步骤 3 — 让智能体使用它
"Before we start, check your memory for anything relevant to this task."
"Record that we use pytest fixtures — not unittest — in this project."
"Run a sleep consolidation so you remember today's lessons next session."记忆会自动存储在你项目目录下的 .agent_sleep/memory.db 中(默认被 gitignore 忽略)。
检查已存储的内容 — CLI
你无需通过 LLM 就能查看智能体学到了什么:
# See all memories and rules for the current project
agent-sleep show
# Clear a project's memory (with confirmation prompt)
agent-sleep reset
# Target a specific scope or DB
agent-sleep show --scope my_api --db /path/to/memory.db工作原理:三阶段流水线
[ ONLINE EXECUTION PHASE ]
Agent executes tool calls
│
▼
┌──────────────────────────────────────────────┐
│ 1. EPISODIC RECORDING │
│ memory.record_episode(...) │ Fast, minimal overhead.
│ Records goal, action, outcome, errors. │ Stores execution events.
└──────────────────────┬───────────────────────┘
│
(Session ends / Agent idle)
│
▼
[ OFFLINE SLEEP CONSOLIDATION ]
┌──────────────────────────────────────────────┐
│ 2. SLEEP CONSOLIDATOR (8-Stage Pipeline) │
│ SleepConsolidator.run(session_id) │
│ │
│ • Priority Replay (prediction error) │
│ • Deterministic Episodic Distillation │ Grounding first:
│ • Procedural Recipe Extraction │ distills facts & lessons
│ • How-Memory Trajectory Abstraction │ before optional LLM
│ • Behavioral Rule Promotion (seen ≥2x) │ generalization passes.
│ • Epistemic Status (observed vs verified)│
│ • Episodic Compression over time │
│ • Self-Competence EMA Tracking │
└──────────────────────┬───────────────────────┘
│
(Next session / New task)
│
▼
[ ONLINE SELECTIVE RECALL ]
┌──────────────────────────────────────────────┐
│ 3. SELECTIVE SEMANTIC RECALL │
│ memory.recall(new_task) │ Pre-computed vector BLOBs.
│ Returns only relevant lessons & rules │ Prevents prompt dilution.
│ filtered by project scope & relevance. │
└──────────────────────────────────────────────┘主要特性(v0.1.2-alpha)
预计算向量 BLOB:仅对查询进行一次嵌入,然后与预计算的存储向量进行比较,从而消除召回过程中的重复文本嵌入。
认知记忆生命周期:跟踪记忆在各阶段(
RAW→OBSERVED→REPEATED→VERIFIED→ACTIVE)的演进,自动隔离相互矛盾或高失败率的记忆。可验证的因果归因与效用反馈:通过结构化证据记录(
retrieval→action change→outcome attribution)评估检索到的记忆是否真正帮助了未来的执行。证据多样性因果假设:利用跨独立来源和环境的证据多样性缩放,将反复出现的失败提炼为因果机制。
贝叶斯自胜任力模型:估计跨复合领域的领域胜任力和贝叶斯 Beta 分布不确定性,为主机智能体提供自适应决策支持(验证强度、重试预算)。
一流的规则特异性引擎:通过层级优先级(
specific verified>general verified>specific candidate>general candidate)和动态异常抑制来解决规则冲突。作用域与项目隔离:多层级命名空间(
scope="repo_a"、scope="global")。项目特定知识被严格隔离,而通用惯用法和工具故障模式可以通过global选择性地共享。零强制重型依赖:使用标准 SQLite 和确定性哈希词袋回退方案即可开箱即用。安装
sentence-transformers(all-MiniLM-L6-v2)后无缝升级。
基准测试与评估
1. 受控迁移模拟(benchmarks/run.py)
评估在 12 个具有重复架构陷阱的顺序软件任务中的记忆整合、向量检索和知识迁移:
指标 | 记忆关闭 | 记忆开启 | 改进 |
通过率(Pass@12) | 67% | 92% | +25 个百分点 |
平均每次任务 LLM 调用次数 | 14.7 | 8.5 | -42%(调用更少) |
重复错误 | 8 | 2 | -75%(错误更少) |
注:受控迁移模拟评估的是记忆检索和陷阱规避的确定性认知控制动态。
2. 标准 6 路消融基准测试(benchmarks/agent_eval/runner.py)
在 8 个标准化软件工程任务上,对记忆驱动的智能体控制动态进行受控沙箱评估:
实验条件 | 通过率(零样本) | 平均每次任务 LLM 调用次数 | 重复陷阱 | 记忆有用率 |
| 12.5% | 3.6 | 4 | 0.0% |
| 12.5% | 3.6 | 4 | 0.0% |
| 12.5% | 3.6 | 4 | 0.0% |
| 25.0% | 2.9 | 2 | 12.5% |
| 37.5% | 2.5 | 1 | 25.0% |
| 75.0% | 1.4 | 0 | 75.0% |
python benchmarks/agent_eval/runner.py[!NOTE] 科学与后端披露:
沙箱基准测试在受控测试套件下评估智能体控制动态、token 效率和错误规避。
嵌入后端:高精度向量相似度依赖
sentence-transformers(all-MiniLM-L6-v2)。当依赖缺失时,库会自动回退到确定性哈希词袋嵌入。完整的可复现性协议和指标日志记录在
benchmarks/agent_eval/results.json中。
Python 库用法
如果你更愿意从自己的智能体代码中驱动记忆系统,而不是通过 MCP,那么 Python API 完全受支持。
from agent_sleep import AgentMemory, SleepConsolidator
# 1. Initialize memory scoped to your project/repo
memory = AgentMemory(session_id="session_01", scope="payment_service")
# 2. Record actions and outcomes during your agent's loop
memory.record_episode(
goal="Refactor payment processor to async",
action="edit_file('processor.py', ...)",
outcome="failure",
failure_reason="SyntaxError: 'await' outside async function",
)
# 3. Trigger sleep consolidation when idle or at session end
consolidator = SleepConsolidator(scope="payment_service")
report = consolidator.run(session_id="session_01")
# -> {'episodes_processed': 1, 'memories_written': 1, 'rules_promoted': 0, ...}
# 4. Next session: recall relevant context before executing
context = memory.recall("Add Stripe webhook handler")
print(context)
# [MEMORY CONTEXT]
# Relevant past experience:
# ⚠ [LESSON] Caution on task: Refactor payment processor to async:
# A previous attempt failed: SyntaxError: 'await' outside async function.
# [END MEMORY CONTEXT]安装
快速安装(含 MCP 支持):
pip install "agent-sleep[mcp]"完整语义嵌入(推荐):
pip install "agent-sleep[all]"从 GitHub 安装(最新 alpha 版):
pip install git+https://github.com/thevisionhub/agent-sleep.git可编辑安装(用于开发):
git clone https://github.com/thevisionhub/agent-sleep.git
cd agent-sleep
pip install -e ".[all]"MCP 工具参考
工具 | 调用时机 |
| 在规划或执行任何非平凡任务之前 — 检索经验教训、规则、因果陷阱和自胜任力指令 |
| 在执行期间 — 每次工具失败或达到里程碑之后 |
| 在会话结束或智能体空闲时 |
| 随时 — 检查记忆健康状态、认知分解和待处理情节 |
| 在应用检索到的知识之后 — 记录因果结果归因并更新效用分数 |
| 当发现现有规则的例外或边界条件时 |
所有工具默认将 scope 设为当前工作目录名称,将 db_path 设为项目根目录下的 .agent_sleep/memory.db。常见情况下无需任何配置。
运行测试
pytest tests/ -v被发现 — 注册表收录
将 agent-sleep 提交到 MCP 注册表每个大约需要 5 分钟,是触达寻找记忆工具的开发者最快的方式:
Smithery — 粘贴 GitHub URL,添加简短描述,完成。
modelcontextprotocol/servers — 提交一个 PR,在 README 的“Community Servers”下添加条目。
Cursor — 也会展示 MCP 服务器;查看其当前文档了解最新提交流程。
许可证
MIT 许可证 — 可免费用于个人、商业和研究用途。
This server cannot be deployed
Maintenance
Related MCP Connectors
Persistent memory for AI agents to retain, retrieve, and recall conversation context through MCP.
Keeps AI agents from repeating costly mistakes: past decisions, rules and incidents, shared by all.
Persistent memory for AI agents: keyed facts, a wake bundle each session, one memory in every model.
Private, portable memory and reusable skills for AI agents.
Related MCP Servers
- AlicenseNot gradedqualityAmaintenancePersistent memory for AI agents with semantic memory, belief tracking, and dream consolidation, enabling cross-session knowledge retention.135 npm50MIT
- AlicenseNot gradedqualityBmaintenanceProvides persistent, cross-session memory for AI agents, allowing them to store and automatically retrieve information across different conversations and sessions without repeating context.9 npm174MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to store, retrieve, and self-improve procedural memories (lessons learned) based on relevance to the current task, pruning unused memories to reduce context load and prevent repetition of past mistakes.MIT
- AlicenseAqualityAmaintenanceEnables AI agents to persistently recall, apply, and reinforce solutions to previously solved problems across different models and tools, so mistakes are not repeated.1414 npm1MIT