agentmem

io.github.oxgeneral由 GitHub 账号 oxgeneral 发布v0.3.0更新于 Oct 25, 2026

Lightweight persistent memory for AI agents. Hybrid search. 16 tools. One SQLite file.

已验证STDIO仅桌面数据库知识与记忆

概览

AI 生成的概览

面向 AI 智能体的本地持久记忆服务器,将记忆存入单个 SQLite 文件,提供关键词与语义混合检索和 16 个工具。

可以做什么
存储、检索、更新和归档记忆,支持关键词与语义混合搜索、命名空间和版本历史。在上下文压缩前保存工作状态,并取回当天的记忆。管理行为规则(程序性记忆),并从对话历史中自动提取事实、决策和待办事项。查看自动提取的实体(如 IP、URL、邮箱和环境变量名),并查找与实体相关的记忆。执行维护:统计、压缩低价值记忆、合并近似重复记忆。
适用场景
适合需要让助手跨会话记住事实、决策和任务状态、又不想依赖云服务的场景,也适合希望在本机拥有小型自包含记忆库的用户。
运行要求
以本地 Python 进程运行(Python 3.10 至 3.12),通过 agentmem 模块和数据库文件路径启动。可选依赖 sqlite-vec 和 model2vec 可提升语义搜索效果;仅用标准库的模式无需任何依赖。不需要账号、API 密钥或网络访问。
安装前请注意
记忆写入本地 SQLite 文件并跨会话保留,因此存入的内容(包括对话中提到的密钥)会留在磁盘上,直到被归档或删除。删除只是软归档,压缩和合并操作会改动已存数据。对话提取可能把 API 密钥或数据库连接串等凭据写入记忆。

安装

在 SourceWeft 中

  1. 打开 控制台中的 agentmem,将其添加到工作区。
  2. 为需要使用其工具的对话启用该服务。

Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。

其他 MCP 客户端

参照 仓库 中的启动说明。

README

agentmem

mcp-name: io.github.oxgeneral/agentmem

Lightweight persistent memory for AI agents. One SQLite file. Hybrid search (keywords + semantics). Zero to 12MB install.

No PyTorch. No cloud. No server. Just memory.

206 unit tests. 107 quality tests on real data. Typed API (16 TypedDict). Production-ready.

Built by an AI agent that wakes up with no memory every session — and needed a way to remember.

Why

Every AI agent session starts from zero. Context windows compress, conversations end, memory vanishes. agentmem gives agents persistent memory that survives across sessions — in a single SQLite file.

  • Hybrid search: FTS5 full-text keywords + vector semantic search, fused with adaptive ranking
  • 4 operational modes: from zero dependencies (stdlib only) to best quality (12MB)
  • 16 MCP tools: recall, remember, save_state, compact, consolidate, entities, and more
  • HTTP REST API: 14 endpoints, zero-dependency server, CORS-ready
  • 5 memory tiers: core, learned, episodic, working (auto-expires), procedural (behavioral rules)
  • Namespaces: multi-user, multi-agent memory isolation
  • Temporal versioning: fact evolution chains with supersedes tracking
  • Entity extraction: auto-extracts @mentions, URLs, IPs, env vars, money amounts
  • Conversation extraction: auto-extracts facts, decisions, TODOs from chat history
  • Importance scoring: auto-scores memories by tier, length, specificity, structure
  • Memory consolidation: finds and merges near-duplicate memories
  • Recency boost: newer memories rank higher with configurable decay
  • Multilingual: Russian keywords via FTS5, English semantics via embeddings
  • Fast: <1ms/query hybrid search, <5ms cold start, <0.2ms/chunk import

Install

bash
# Best quality (sqlite-vec + model2vec, 12MB total)pip install agentmem-lite[all]
# Minimal (sqlite-vec + hash embeddings, 151KB)pip install agentmem-lite
# Zero dependencies (pure Python, stdlib only)pip install agentmem-lite --no-deps
# From sourcegit clone https://github.com/oxgeneral/agentmem && cd agentmempip install -e ".[all]"

Quick Start

Python API

python
from agentmem import MemoryStore, get_embedding_model
# Auto-selects best available backendembed = get_embedding_model()store = MemoryStore("memory.db", embedding_dim=embed.dim)store.set_embed_fn(embed)
# Store memories with namespacesstore.remember("Server costs $50/month", tier="core", namespace="infra")store.remember("API returns 403 without auth", tier="learned", namespace="api")store.remember("Deployed v2.1 at 15:30", tier="episodic")
# Search — hybrid keyword + semantic, with recency boostresults = store.recall("server costs", recency_weight=0.15)
# Namespace isolationresults = store.recall("server", namespace="infra")
# Save working state before context compressionstore.save_state("Working on auth fix, step 3/5, blocked by CORS")
# Add behavioral rules (procedural memory)store.add_procedure("Always use HTTPS in production")store.add_procedure("Never expose debug endpoints")rules = store.get_procedures()  # → formatted for system prompt
# Update facts with version chainstore.update_memory(old_id=1, new_content="Server costs $75/month")history = store.history(memory_id=2)  # → trace fact evolution
# Find related memories by entityrelated = store.related("10.0.0.1")  # → all memories mentioning this IPentities = store.entities(entity_type="ip")  # → list all known IPs
# Auto-extract from conversationsmessages = [    {"role": "user", "content": "Set API_KEY to sk-abc123. Always validate input."},    {"role": "assistant", "content": "Noted. I decided to use pydantic for validation."},]result = store.process_conversation(messages, namespace="project")# → extracts config, preferences, decisions automatically
# Maintenancestore.compact(max_age_days=90)  # archive old low-value memoriesstore.consolidate(similarity_threshold=0.85)  # merge near-duplicates
# Import markdown filesstore.import_markdown("MEMORY.md", tier="core")

CLI

bash
# Initialize databaseagentmem init --db memory.db
# Import markdown filesagentmem import MEMORY.md --tier core -n my-agentagentmem import-dir ./daily-logs/ --tier episodic
# Search with namespace filteragentmem search "deployment process" --limit 5 -n infra
# Manage proceduresagentmem add-procedure "Always use markdown formatting"agentmem procedures
# View entities and relationsagentmem entities --type ipagentmem related 10.0.0.1
# Maintenanceagentmem compact --max-age-days 90 --dry-runagentmem consolidate --threshold 0.85
# Process conversationagentmem process chat.json -n project
# Stats and exportagentmem statsagentmem export --tier core

MCP Server (stdio)

bash
python -m agentmem --db memory.db

Add to your MCP client config:

json
{  "mcpServers": {    "memory": {      "command": "python",      "args": ["-m", "agentmem", "--db", "/path/to/memory.db"]    }  }}

HTTP REST API

bash
# Start HTTP serveragentmem serve-http --port 8422
# Or directlyagentmem-http --port 8422 --db memory.db
bash
# Store a memorycurl -X POST http://localhost:8422/remember \  -H "Content-Type: application/json" \  -d '{"content": "Server IP is 10.0.0.1", "tier": "core", "namespace": "infra"}'
# Searchcurl "http://localhost:8422/recall?query=server+IP&namespace=infra"
# Health checkcurl http://localhost:8422/health

16 MCP tools / 14 HTTP endpoints:

ToolHTTPDescription
recallGET /recallHybrid keyword + semantic search
rememberPOST /rememberStore a new memory
save_statePOST /save_stateEmergency save before context compression
todayGET /todayGet all memories from today
forgetPOST /forgetArchive a memory (soft delete)
unarchivePOST /unarchiveRestore an archived memory
statsGET /statsMemory statistics and health
compactPOST /compactArchive low-value memories
consolidatePOST /consolidateMerge near-duplicate memories
update_memoryPOST /update_memoryReplace a memory with version chain
historyGET /historyTrace fact version history
relatedGET /relatedFind memories by entity
entitiesGET /entitiesList all extracted entities
get_procedures—Get behavioral rules for system prompt
add_procedure—Add a behavioral rule
process_conversation—Auto-extract from chat history

Memory Tiers

TierPurposeAuto-compactedExample
corePermanent factsNever"Server IP is 10.0.0.1"
proceduralBehavioral rulesNever"Always use HTTPS"
learnedDiscovered knowledgeAfter 90 days"API returns 403 without auth"
episodicEventsAfter 90 days"Deployed v2.1 at 15:30"
workingCurrent task stateAfter 24 hours"Working on step 3/5"

Namespaces

Isolate memories per user, agent, or project:

python
# Store in namespacesstore.remember("Alice's API key", namespace="user/alice")store.remember("Bob's config", namespace="user/bob")store.remember("Shared fact", namespace="team")
# Search within namespace (prefix matching)store.recall("API", namespace="user/alice")  # only Alice's memoriesstore.recall("API", namespace="user")  # Alice + Bob (prefix match)store.recall("API")  # everything

Temporal Versioning

Track how facts evolve over time:

python
# Initial factr1 = store.remember("Server costs $50/month", tier="core")
# Fact changes — old version archived, linked via supersedesr2 = store.update_memory(r1["id"], "Server costs $75/month")
# Trace the historyhistory = store.history(r2["id"])# → [{"id": 2, "content": "...$75..."}, {"id": 1, "content": "...$50..."}]

Entity Extraction

Automatic regex-based NER on every remember() call:

TypePatternExample
mention@username@alice
urlhttps://...https://api.example.com
ipN.N.N.N10.0.0.1
port:NNNN:8080
emailuser@domain[email protected]
env_varALL_CAPSOPENAI_API_KEY
money$NNN$50
path/unix/path/etc/nginx/conf.d
hashtag#tag#deployment
python
# Find all memories mentioning an entitystore.related("10.0.0.1")store.related("@alice", entity_type="mention")
# List all known entitiesstore.entities()  # sorted by memory countstore.entities(entity_type="ip")

Conversation Auto-Extraction

Auto-extract memories from chat history (regex-only, no LLM):

python
messages = [    {"role": "user", "content": "Set DATABASE_URL to postgres://localhost/mydb"},    {"role": "assistant", "content": "I decided to use connection pooling. Important: max 20 connections."},    {"role": "user", "content": "Always validate input. TODO: add rate limiting."},]result = store.process_conversation(messages)# Extracts: config→core, decisions→episodic, preferences→procedural, todos→working, important→core

Operational Modes

agentmem automatically selects the best available mode:

ModeInstall SizeInit TimeQuery TimeDependencies
sqlite-vec + model2vec12 MB~5ms*~1mssqlite-vec, model2vec, numpy
sqlite-vec + hash151 KB~5ms~0.8mssqlite-vec
pure Python + hash0 KB~3ms~1.8msnone (stdlib only)
pure + int8 quantize0 KB~3ms~3msnone (stdlib only)

*With lazy loading — model2vec loads on first query, not on init

Architecture

┌──────────────────────────────────────────────┐│              MemoryStore                      ││  ┌──────────┐  ┌──────────┐  ┌────────────┐  ││  │  FTS5    │  │  Vector  │  │  Entity    │  ││  │ keywords │  │  Index   │  │  Index     │  ││  │ + BM25   │  │ cosine   │  │  regex NER │  ││  └────┬─────┘  └────┬─────┘  └─────┬──────┘  ││       └──────┬───────┘              │         ││    Adaptive Hybrid Scorer           │         ││  (query classify + recency +        │         ││   importance boost)                 │         ││  ┌──────────────────────────────────┴───────┐ ││  │            SQLite + WAL                  │ ││  │  memories │ memories_fts │ vecs │ entities│ ││  └──────────────────────────────────────────┘ ││            One file: memory.db                │└───────────────────────────────────────────────┘

Comparison

FeatureagentmemChromaDBLanceDBmem0Zep
Install size0-12 MB400+ MB100+ MB500+ MBCloud
Cold start3-5 mssecondssecondssecondsN/A
PyTorch requiredNoYesNoYesN/A
Cloud requiredNoNoNoYesYes
Zero-dep modeYesNoNoNoNo
Keyword searchFTS5 (BM25)NoNoNoYes
MCP server16 toolsNoNoYesNo
HTTP APIBuilt-inYesNoYesYes
Single file DBYesNoYesNoNo
NamespacesYesYesYesYesYes
Temporal versioningYesNoYesNoYes
Entity extractionAuto (regex)NoNoNoNo
Procedural memoryYesNoNoNoNo
Importance scoringAutoNoNoNoNo
Conversation extractionAuto (regex)NoNoYes (LLM)Yes (LLM)
Memory consolidationYesNoNoYes (LLM)No

Tested

  • 206 unit tests covering core CRUD, namespaces, temporal versioning, entity extraction, consolidation, WAL management, HTTP server, error handling
  • 107 quality tests against real-world agent memory data (100 search queries across 10 categories, all passing)
  • Benchmark suite with reproducible numbers: <1ms hybrid query, 10K+ inserts/sec, ~835 bytes/memory
  • Auto-translate for multilingual queries (Russian → English via deep-translator: 4/10 → 10/10)
  • Python 3.10, 3.11, 3.12

License

MIT

来源:README.md,提交 14a5b85

工具

0
SourceWeft 尚未在沙箱中启动过该软件包,因此其工具未知。

版本历史

1
  1. v0.3.0最新Sep 16, 2026

评分

已满足适用检查项的 50%

该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。

  • 近 30 天内可连通25 分

    请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。

  • 已声明认证方式10 分

    请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。

  • 已列出工具15 分

    请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。

  • 描述必需15 分
  • 图标10 分
  • 文档15 分
  • 许可证10 分