永不重复自己:使用 ContextMD 为你的 LLM 应用提供持久记忆
Source: Dev.to
TL;DR: ContextMD 是一个 Python 中间件,为 OpenAI、Anthropic 和 LiteLLM 的 API 调用添加持久记忆。将对话存储为人类可读的 Markdown 文件,自动提取事实,并在后续请求中重新引入这些信息。
问题:LLM 没有记忆
如果你使用 LLM API 构建过任何东西,你一定遇到过这样的墙:
# Conversation 1
response = openai.chat.completions.create(
model="gpt-4.1",
messages=[{"role": "user", "content": "I prefer TypeScript over JavaScript"}]
)
# Conversation 2 (hours later)
response = openai.chat.completions.create(
model="gpt-4.1",
messages=[{"role": "user", "content": "Help me build a React component"}]
)
# Assistant suggests JavaScript... again! 😤
LLM 是无状态的。每一次请求都是全新的。你必须手动传递对话历史,即使如此,它也只是暂时的。那如果你希望你的 AI 能记住:
- 跨会话的用户偏好?
- 几周前做出的决定?
- 几个月前建立的项目上下文?
进入 ContextMD:持久记忆用于 LLM
ContextMD 是一个轻量级的 Python 中间件,位于你的代码和 LLM 提供商之间。它:
- 自动将已存储的记忆 注入每个 API 请求
- 从响应中提取值得记住的事实 并保存它们
- 将所有内容存储为人类可读的 Markdown 文件(无需数据库!)
快速入门:只需 3 行代码即可添加记忆
from openai import OpenAI
from contextmd import ContextMD
# Wrap your existing client
client = ContextMD(OpenAI(), memory_dir=".contextmd/")
# Use exactly like normal – memory is automatic!
response = client.chat.completions.create(
model="gpt-4.1",
messages=[{"role": "user", "content": "I prefer TypeScript over JavaScript"}]
)
# The fact is now saved and will be injected into future requests
就这样!您的 OpenAI 客户端现在拥有持久记忆。无需数据库设置,也不需要额外的 API 密钥——只需本地 Markdown 文件。
工作原理(内部实现)
ContextMD 在你的项目中创建一个 .contextmd/ 目录:
.contextmd/
├── MEMORY.md # Semantic facts (200‑line cap)
├── config.md # Configuration
├── memory/
│ ├── 2024-03-01.md # Daily episodic logs
│ └── 2024-03-02.md
└── sessions/
└── 2024-03-01-auth.md # Session snapshots
三种记忆类型
语义记忆 – 关于用户/项目的永久性事实
## 用户偏好
- 更倾向于使用 TypeScript 而非 JavaScript
- 使用暗色模式主题
- 遵循原子式 Git 提交
```markdown
### Episodic Memory – Time‑stamped events
```markdown
2024-03-01 14:30
- 决定前端使用 Next.js
- 完成了身份验证功能
### 程序性记忆 – 学习的工作流程
```markdown
## 工作流程
- 在提交前始终运行测试
- 使用 pnpm 进行包管理
## 实际案例:AI 编码助手
```python
from openai import OpenAI
from contextmd import ContextMD
client = ContextMD(OpenAI())
# First conversation – establish context
response = client.chat.completions.create(
model="gpt-4.1",
messages=[{
"role": "user",
"content": "I'm building a React app with TypeScript, Tailwind CSS, and Next.js. I prefer functional components with hooks."
}]
)
# ContextMD automatically saves these facts
# Week later – new conversation
response = client.chat.completions.create(
model="gpt-4.1",
messages=[{
"role": "user",
"content": "Help me create a user profile component"
}]
)
# Response automatically uses TypeScript, Tailwind, functional components!
无需重复你的技术栈。无需指定偏好。ContextMD 记住一切。
手动内存控制
有时你想显式地记住某件事:
# Remember a decision
client.remember(
"Chose PostgreSQL over MongoDB for better ACID compliance",
memory_type="semantic"
)
# Remember a completed task
client.remember(
"Implemented OAuth2 authentication with refresh tokens",
memory_type="episodic"
)
# Remember a workflow rule
client.remember(
"Always write tests before refactoring",
memory_type="procedural"
)
内存管理的 CLI 工具
ContextMD 附带了一个方便的 CLI:
# Initialize in your project
contextmd init
# View what the AI remembers about you
contextmd show
# See recent activity
contextmd history --hours 24
# List all sessions
contextmd sessions
# Manually add a fact
contextmd add "User loves Vim keybindings" --memory_type semantic
# Get statistics
contextmd stats
支持所有主要提供商
ContextMD 与提供商无关:
# OpenAI
client = ContextMD(OpenAI())
# Anthropic
client = ContextMD(Anthropic())
# LiteLLM (100+ providers)
import litellm
client = ContextMD(litellm)
高级功能
会话管理
对相关对话进行分组:
with client.session("project‑setup"):
response = client.chat.completions.create(
model="gpt-4.1",
messages=[{"role": "user", "content": "Set up the initial repo structure"}]
)
((更多会话相关的 API 已在官方 README 中记录。))
t.new_session("feature-auth") as session:
# All conversations here are grouped
response = client.chat.completions.create(...)
# Session snapshot saved automatically
自定义配置
微调 ContextMD 的工作方式:
from contextmd import ContextMD, ContextMDConfig
config = ContextMDConfig(
memory_line_cap=200, # Max lines in MEMORY.md
bootstrap_window_hours=48, # Hours of episodic memory to load
compaction_threshold=0.8, # Token threshold for extraction
extraction_frequency="session_end", # When to extract facts
)
client = ContextMD(openai_client, config=config)
为什么使用 Markdown 文件?
- 人类可读 – 您实际上可以阅读和编辑记忆。
- Git 友好 – 对 AI 的记忆进行版本控制。
- 无供应商锁定 – 您的数据保持本地。
- 可调试 – 精确查看 AI 记住了什么。
接下来是什么?
- 内存搜索与 RAG
- 多用户/项目命名空间
- 内存衰减与重要性评分
- Git 集成与同步
- 用于内存可视化的 Web UI
- 以及更多!
入门
pip install contextmd
查看 GitHub 仓库 获取完整文档和示例。
构建惊人的作品
使用 ContextMD,您可以构建:
- 能够记住用户偏好的 AI 助手
- 了解您项目模式的代码生成器
- 在多天内保持上下文的聊天机器人
- 随时间跟踪进度的学习工具
当您的大语言模型终于拥有记忆时,可能性是无穷的。
您会用持久记忆构建什么? 在下面的评论中分享!
P.S. 在 GitHub 上给仓库加星——这有助于让更多人发现 ContextMD!
