AI代理记忆系统

基于SQLite和FTS5的持久化记忆系统,为AI代理提供隔离命名空间、全文搜索和Obsidian同步功能。

  • by khaled1174
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 khaled1174/agent-memory

使用说明

代理存储系统

使用SQLite+FTS5的AI代理的持久内存。
单文件核心·零依赖·可选MCP服务器和黑曜石同步。


✨ 特性

特性 描述
🗄️ 持久 SQLite数据库在进程重启后幸存下来
🔍 全文搜索 FTS5发动机排名结果
🔒 代理隔离 每个代理都会自动获得自己的命名空间
🛠️ MCP服务器 12工具克劳德代码/克劳德桌面
📝 黑曜石同步 可选双向Markdown桥
🤖 CLAUDE.md生成器 自动将上下文注入到每个会话中
🌍 跨平台 macOS、Linux、WSL、Windows
⚡ 零依赖 Core只使用Python标准库

🏗️ 建筑

graph TB
    subgraph Clients["🖥️ Clients"]
        CLI["💻 CLI\n(memory.py)"]
        MCP["🔌 MCP Server\n(memory_mcp.py)"]
        HERMES["🌉 Hermes Bridge\n(hermes/bridge.py)"]
    end

    subgraph Core["⚙️ Core Engine"]
        STORE["📥 Store\nmemory_store()"]
        SEARCH["🔍 Search\nFTS5 Engine"]
        ISO["🔒 Isolation\nNamespace Handler"]
        CTX["📋 Context\nCLAUDE.md Gen"]
    end

    subgraph Storage["💾 Storage"]
        DB[("🗄️ SQLite DB\nmemory.db")]
        FTS[("📑 FTS5 Index")]
    end

    subgraph External["🔗 Integrations"]
        OBS["📓 Obsidian Vault\n(Markdown)"]
        N8N["⚙️ n8n Workflow"]
        TG["📱 Telegram Bot"]
    end

    CLI --> STORE
    CLI --> SEARCH
    MCP --> STORE
    MCP --> SEARCH
    HERMES --> STORE
    HERMES --> SEARCH
    STORE --> ISO
    SEARCH --> ISO
    ISO --> DB
    DB --> FTS
    FTS --> SEARCH
    STORE --> OBS
    OBS --> STORE
    N8N --> HERMES
    TG --> HERMES
    CTX --> DB

    style Clients fill:#1f3558,stroke:#58a6ff,color:#cdd9e5
    style Core fill:#2d1f58,stroke:#bc8cff,color:#cdd9e5
    style Storage fill:#1f3a2d,stroke:#3fb950,color:#cdd9e5
    style External fill:#3a2d1f,stroke:#d29922,color:#cdd9e5

🔄 内存生命周期

sequenceDiagram
    actor Agent as 🤖 AI Agent
    participant CLI as 💻 CLI / MCP
    participant ISO as 🔒 Namespace
    participant DB as 🗄️ SQLite
    participant FTS as 🔍 FTS5 Index
    participant OBS as 📓 Obsidian

    Agent->>CLI: memory store --type semantic --content "..."
    CLI->>ISO: Resolve agent namespace (AGENT_NAME)
    ISO-->>CLI: agent_id = "health" (or global)
    CLI->>DB: INSERT INTO memories (agent_id, type, content, ...)
    DB->>FTS: Auto-index content
    DB-->>CLI: memory_id = 42
    CLI-->>Agent: ✅ Stored (id=42)

    Agent->>CLI: memory search --query "rate limit"
    CLI->>ISO: Resolve agent namespace
    ISO-->>CLI: agent_id
    CLI->>FTS: SELECT * FROM memories_fts WHERE content MATCH "rate limit"
    FTS-->>CLI: Ranked results
    CLI-->>Agent: 📋 Results (ranked by relevance)

    Note over DB,OBS: Optional Obsidian Sync
    DB->>OBS: Sync to Markdown vault
    OBS->>DB: Sync from Markdown vault

🧠 内存类型

mindmap
  root((🧠 Memory Types))
    📅 episodic
      Events and decisions
      Switched to Postgres
      Deployed v2 on Monday
    📚 semantic
      Facts and knowledge
      Rate limit 1000 req/min
      Max upload 50 MB
    ⚙️ procedural
      Workflows and how-tos
      Steps build test deploy
      Auth flow OAuth2 JWT

🚀 快速开始

选项1:CLI(零依赖)

cp memory.py /usr/local/bin/memory
chmod +x /usr/local/bin/memory

# Store a memory
memory store --type semantic --content "Max upload: 50 MB" --project api --importance 5

# Search memories
memory search --query "upload"

# List recent
memory list --project api --recent 10

# View stats
memory stats

选项2:MCP服务器(克劳德代码/克劳德桌面)

pip install mcp

添加 ~/.claude/settings.json (克劳德代码):

{
  "mcpServers": {
    "agent-memory": {
      "command": "python",
      "args": ["/path/to/memory_mcp.py"]
    }
  }
}

Claude桌面路径:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • 窗户: %APPDATA%\Claude\claude_desktop_config.json

重新启动,您将看到 12工具 可用。


🛠️ MCP工具

graph LR
    subgraph Session["📋 Session"]
        T1["memory_brief\nLoad context"]
        T2["memory_who\nAgent identity"]
        T3["memory_stats\nDB statistics"]
    end

    subgraph CRUD["✏️ CRUD"]
        T4["memory_store\nSave memory"]
        T5["memory_update\nPatch memory"]
        T6["memory_delete\nRemove by ID"]
    end

    subgraph Query["🔍 Query & Export"]
        T7["memory_search\nFTS5 full-text"]
        T8["memory_list\nFilter and sort"]
        T9["memory_export\nExport to JSON"]
        T10["memory_generate_context\nBuild CLAUDE.md"]
    end

    subgraph Sync["🔄 Sync"]
        T11["memory_sync_to_vault\nSQLite to Obsidian"]
        T12["memory_sync_from_vault\nObsidian to SQLite"]
    end

    style Session fill:#1f3558,stroke:#58a6ff,color:#cdd9e5
    style CRUD fill:#2d1f58,stroke:#bc8cff,color:#cdd9e5
    style Query fill:#1f3a2d,stroke:#3fb950,color:#cdd9e5
    style Sync fill:#3a2d1f,stroke:#d29922,color:#cdd9e5

🔒 代理隔离

graph TD
    ENV["🌍 AGENT_NAME env var"]

    ENV -->|"= 'health'"| HEALTH["🏥 health namespace\nWrite: own only\nRead: own + global"]
    ENV -->|"= 'orchestrator'"| ORCH["🎯 orchestrator\nWrite: anywhere\nRead: everything"]
    ENV -->|"not set"| GLOBAL["🌐 global\nWrite: anywhere\nRead: everything"]

    HEALTH --> DB1[("health::memories")]
    HEALTH -.->|read only| DB2[("global::memories")]
    ORCH --> DB1
    ORCH --> DB2
    ORCH --> DB3[("other::memories")]
    GLOBAL --> DB2

    style ENV fill:#21262d,stroke:#58a6ff,color:#cdd9e5
    style HEALTH fill:#1f3558,stroke:#58a6ff,color:#cdd9e5
    style ORCH fill:#2d1f58,stroke:#bc8cff,color:#cdd9e5
    style GLOBAL fill:#1f3a2d,stroke:#3fb950,color:#cdd9e5
export AGENT_NAME=health   # Linux / macOS / WSL
$env:AGENT_NAME = "health" # Windows PowerShell
角色 写访问权限 读访问权限
常规代理 仅限自有命名空间 自有+全局
orchestrator 任何地方 一切
未设置 任何地方 一切

🌉 Hermes——跨平台存储器

两个代理在Slack上合作。你在Telegram上问。记忆携带。

flowchart LR
    SLACK["💬 Slack Agent"] -->|POST| N8N["⚙️ n8n"]
    N8N -->|HTTP| BRIDGE["🌉 Hermes Bridge\nbridge.py :8765"]
    BRIDGE <-->|SQLite| DB[("🗄️ memory.db")]
    TG["📱 Telegram Bot"] <-->|HTTP| BRIDGE
    MCP["🔌 MCP Server"] <-->|SQLite| DB
    CLI["💻 CLI"] <-->|SQLite| DB

    style SLACK fill:#1f3a2d,stroke:#3fb950,color:#cdd9e5
    style N8N fill:#3a2d1f,stroke:#d29922,color:#cdd9e5
    style BRIDGE fill:#2d1f58,stroke:#bc8cff,color:#cdd9e5
    style DB fill:#1f3558,stroke:#58a6ff,color:#cdd9e5
    style TG fill:#1f3558,stroke:#58a6ff,color:#cdd9e5
    style MCP fill:#2d1f58,stroke:#bc8cff,color:#cdd9e5
    style CLI fill:#1f3a2d,stroke:#3fb950,color:#cdd9e5
# 1. Start the bridge
python hermes/bridge.py

# 2. Import hermes/n8n_workflow.json into your n8n instance

# 3. Start the Telegram bot
TELEGRAM_TOKEN=xxx HERMES_URL=http://your-server:8765 python hermes/telegram_bot.py

看 赫尔墨斯/README.md 用于完整设置、API参考和VPS部署。


📦 黑曜石集成(可选)

export OBSIDIAN_VAULT=/path/to/your/vault

# Auto-mirrors every store/update/delete to Markdown
memory store --type semantic --content "API uses JWT" --project api

# Bulk sync
memory sync-to-vault    # SQLite → Markdown
memory sync-from-vault  # Markdown → SQLite

📋 CLAUDE.md生成器

memory generate-context --output CLAUDE.md

从你最重要的记忆中创建一个Markdown文件。将其放置在项目根目录中,Claude Code会在每个会话中自动读取它。


📁 文件结构

agent-memory/
├── memory.py              # Core: CLI + library (1282 lines)
├── memory_mcp.py          # MCP server (645 lines, requires: pip install mcp)
├── assets/
│   └── banner.svg         # Repository banner image
├── hermes/                # Cross-platform memory layer
│   ├── bridge.py          # HTTP gateway (zero new deps)
│   ├── telegram_bot.py    # Telegram recall bot (requires: requests)
│   ├── n8n_workflow.json  # Ready-to-import Slack → memory workflow
│   └── README.md          # Hermes setup guide
├── README.md
├── LICENSE
├── .gitignore
├── requirements.txt       # Runtime: empty (stdlib only)
├── requirements-dev.txt   # Dev: pytest, black, mypy, ruff
└── tests/
    ├── __init__.py
    └── test_memory.py     # 58 tests across 8 classes

🗃️ 数据库位置

平台 默认路径
macOS/Linux ~/.claude/memory/memory.db
窗户 %APPDATA%\\claude\\memory\\memory.db

以(权力)否决 export AGENT_MEMORY_DIR=/custom/path


🧪 测试

pip install -r requirements-dev.txt
python -m pytest tests/test_memory.py -v          # 58 tests
python -m pytest tests/test_memory.py -v --cov=memory

📄 许可证

麻省理工学院 ©khaled1174


Built with ❤️ for AI agents that need to remember.