持久化记忆管理_agentdb-memory-patterns
以下为本文档的中文说明
agentdb-memory-patterns 是为 AI 智能体提供持久化内存管理的技能,基于 AgentDB 的持久化存储和 ReasoningBank 集成能力。该技能使 AI 智能体能够跨会话记住对话内容、从交互中学习并维护上下文,实现真正有状态的智能体行为。其性能优势显著,相比传统方案快 150 倍到 12500 倍,同时保持 100% 向后兼容。核心功能包括:会话内存,在单次会话内维护对话上下文;长期存储,将重要信息持久化到数据库中供未来会话使用;模式学习,从历史交互中提取行为模式并加以利用;以及上下文管理,在多个会话之间维护和切换上下文。使用场景广泛:构建有状态的 AI 聊天系统时,需要智能体记住用户偏好和历史对话;开发智能助手时,需要智能体从过去的交互中学习和改进;实现复杂的多轮对话系统时,需要维护跨会话的用户上下文。先决条件包括 Node.js 18+ 环境、AgentDB v1.0.7+(可通过 agentic-flow 或独立安装)以及对智能体架构的基本理解。快速启动方式包括使用 CLI 初始化向量数据库,支持自定义向量维度和预设配置,也支持内存数据库模式。核心原则是智能体内存应当像人类记忆一样分层管理,短期记忆用于当前会话,长期记忆用于持久化知识,模式学习用于提炼经验。
AgentDB Memory Patterns
What This Skill Does
Provides memory management patterns for AI agents using AgentDB’s persistent storage and ReasoningBank integration. Enables agents to remember conversations, learn from interactions, and maintain context across sessions.
Performance: 150x-12,500x faster than traditional solutions with 100% backward compatibility.
Prerequisites
- Node.js 18+
- AgentDB v1.0.7+ (via agentic-flow or standalone)
- Understanding of agent architectures
Quick Start with CLI
Initialize AgentDB
# Initialize vector database
npx agentdb@latest init ./agents.db
# Or with custom dimensions
npx agentdb@latest init ./agents.db --dimension 768
# Use preset configurations
npx agentdb@latest init ./agents.db --preset large
# In-memory database for testing
npx agentdb@latest init ./memory.db --in-memory
Start MCP Server for Claude Code
# Start MCP server (integrates with Claude Code)
npx agentdb@latest mcp
# Add to Claude Code (one-time setup)
claude mcp add agentdb npx agentdb@latest mcp
Create Learning Plugin
# Interactive plugin wizard
npx agentdb@latest create-plugin
# Use template directly
npx agentdb@latest create-plugin -t decision-transformer -n my-agent
# Available templates:
# - decision-transformer (sequence modeling RL)
# - q-learning (value-based learning)
# - sarsa (on-policy TD learning)
# - actor-critic (policy gradient)
# - curiosity-driven (exploration-based)
Quick Start with API
import { createAgentDBAdapter } from 'agentic-flow/reasoningbank';
// Initialize with default configuration
const adapter = await createAgentDBAdapter({
dbPath: '.agentdb/reasoningbank.db',
enableLearning: true, // Enable learning plugins
enableReasoning: true, // Enable reasoning agents
quantizationType: 'scalar', // binary | scalar | product | none
cacheSize: 1000, // In-memory cache
});
// Store interaction memory
const patternId = await adapter.insertPattern({
id: '',
type: 'pattern',
domain: 'conversation',
pattern_data: JSON.stringify({
embedding: await computeEmbedding('What is the capital of France?'),
pattern: {
user: 'What is the capital of France?',
assistant: 'The capital of France is Paris.',
timestamp: Date.now()
}
}),
confidence: 0.95,
usage_count: 1,
success_count: 1,
created_at: Date.now(),
last_used: Date.now(),
});
// Retrieve context with reasoning
const context = await adapter.retrieveWithReasoning(queryEmbedding, {
domain: 'conversation',
k: 10,
useMMR: true, // Maximal Marginal Relevance
synthesizeContext: true, // Generate rich context
});
Memory Patterns
1. Session Memory
class SessionMemory {
async storeMessage(role: string, content: string) {
return await db.storeMemory({
sessionId: this.sessionId,
role,
content,
timestamp: Date.now()
});
}
async getSessionHistory(limit = 20) {
return await db.query({
filters: { sessionId: this.sessionId },
orderBy: 'timestamp',
limit
});
}
}
2. Long-Term Memory
// Store important facts
await db.storeFact({
category: 'user_preference',
key: 'language',
value: 'English',
confidence: 1.0,
source: 'explicit'
});
// Retrieve facts
const prefs = await db.getFacts({
category: 'user_preference'
});
3. Pattern Learning
// Learn from successful interactions
await db.storePattern({
trigger: 'user_asks_time',
response: 'provide_formatted_time',
success: true,
context: { timezone: 'UTC' }
});
// Apply learned patterns
const pattern = await db.matchPattern(currentContext);
Advanced Patterns
Hierarchical Memory
// Organize memory in hierarchy
await memory.organize({
immediate: recentMessages, // Last 10 messages
shortTerm: sessionContext, // Current session
longTerm: importantFacts, // Persistent facts
semantic: embeddedKnowledge // Vector search
});
Memo
ry Consolidation
// Periodically consolidate memories
await memory.consolidate({
strategy: 'importance', // Keep important memories
maxSize: 10000, // Size limit
minScore: 0.5 // Relevance threshold
});
CLI Operations
Query Database
# Query with vector embedding
npx agentdb@latest query ./agents.db "[0.1,0.2,0.3,...]"
# Top-k results
npx agentdb@latest query ./agents.db "[0.1,0.2,0.3]" -k 10
# With similarity threshold
npx agentdb@latest query ./agents.db "0.1 0.2 0.3" -t 0.75
# JSON output
npx agentdb@latest query ./agents.db "[...]" -f json
Import/Export Data
# Export vectors to file
npx agentdb@latest export ./agents.db ./backup.json
# Import vectors from file
npx agentdb@latest import ./backup.json
# Get database statistics
npx agentdb@latest stats ./agents.db
Performance Benchmarks
# Run performance benchmarks
npx agentdb@latest benchmark
# Results show:
# - Pattern Search: 150x faster (100µs vs 15ms)
# - Batch Insert: 500x faster (2ms vs 1s)
# - Large-scale Query: 12,500x faster (8ms vs 100s)
Integration with ReasoningBank
import { createAgentDBAdapter, migrateToAgentDB } from 'agentic-flow/reasoningbank';
// Migrate from legacy ReasoningBank
const result = await migrateToAgentDB(
'.swarm/memory.db', // Source (legacy)
'.agentdb/reasoningbank.db' // Destination (AgentDB)
);
console.log(`✅ Migrated ${result.patternsMigrated} patterns`);
// Train learning model
const adapter = await createAgentDBAdapter({
enableLearning: true,
});
await adapter.train({
epochs: 50,
batchSize: 32,
});
// Get optimal strategy with reasoning
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
domain: 'task-planning',
synthesizeContext: true,
optimizeMemory: true,
});
Learning Plugins
Available Algorithms (9 Total)
- Decision Transformer - Sequence modeling RL (recommended)
- Q-Learning - Value-based learning
- SARSA - On-policy TD learning
- Actor-Critic - Policy gradient with baseline
- Active Learning - Query selection
- Adversarial Training - Robustness
- Curriculum Learning - Progressive difficulty
- Federated Learning - Distributed learning
- Multi-task Learning - Transfer learning
List and Manage Plugins
# List available plugins
npx agentdb@latest list-plugins
# List plugin templates
npx agentdb@latest list-templates
# Get plugin info
npx agentdb@latest plugin-info <name>
Reasoning Agents (4 Modules)
- PatternMatcher - Find similar patterns with HNSW indexing
- ContextSynthesizer - Generate rich context from multiple sources
- MemoryOptimizer - Consolidate similar patterns, prune low-quality
- ExperienceCurator - Quality-based experience filtering
Best Practices
- Enable quantization: Use scalar/binary for 4-32x memory reduction
- Use caching: 1000 pattern cache for <1ms retrieval
- Batch operations: 500x faster than individual inserts
- Train regularly: Update learning models with new experiences
- Enable reasoning: Automatic context synthesis and optimization
- Monitor metrics: Use
statscommand to track performance
Troubleshooting
Issue: Memory growing too large
# Check database size
npx agentdb@latest stats ./agents.db
# Enable quantization
# Use 'binary' (32x smaller) or 'scalar' (4x smaller)
Issue: Slow search performance
# Enable HNSW indexing and caching
# Results: <100µs search time
Issue: Migration from legacy ReasoningBank
# Automatic migration with validation
npx agentdb@latest migrate --source .swarm/memory.db
Performance Characteristics
- Vector Search: <100µs (HNSW indexing)
- Pattern Retrieval: <1ms (with cache)
- Batch Insert: 2ms for 100 patterns
- Memory Efficiency: 4-32x reduction with quantization
- Backward Compatibility: 100% compatible with ReasoningBank API
Learn More
- GitHub: https://github
.com/ruvnet/agentic-flow/tree/main/packages/agentdb - Documentation: node_modules/agentic-flow/docs/AGENTDB_INTEGRATION.md
- MCP Integration:
npx agentdb@latest mcpfor Claude Code - Website: https://agentdb.ruv.io
3d:[“","","","L40”,null,{“content”:“$41”,“frontMatter”:{“name”:“AgentDB Memory Patterns”,“description”:“Implement persistent memory patterns for AI agents using AgentDB. Includes session memory, long-term storage, pattern learning, and context management. Use when building stateful agents, chat systems, or intelligent assistants.”}}]
3e:[“KaTeX parse error: Expected '}', got 'EOF' at end of input: …,"children":[["”,“div”,null,{“className”:“flex items-center justify-between border-b border-border bg-muted/30 px-4 py-2.5”,“children”:[[“KaTeX parse error: Expected '}', got 'EOF' at end of input: …","children":["”,“span”,null,{“className”:“truncate text-xs font-medium text-muted-foreground”,“children”:“同仓库更多 Skills”}]}],[“KaTeX parse error: Expected 'EOF', got '}' at position 88: …ldren":"同仓库"}]]}̲],["”,“div”,null,{“className”:“p-4 sm:p-5”,“children”:[[“","h2",null,"id":"related−skills−heading","className":"text−2xlfont−semiboldtracking−normaltext−foreground","children":"同仓库更多Skills"],["","h2",null,{"id":"related-skills-heading","className":"text-2xl font-semibold tracking-normal text-foreground","children":"同仓库更多 Skills"}],["","h2",null,"id":"related−skills−heading","className":"text−2xlfont−semiboldtracking−normaltext−foreground","children":"同仓库更多Skills"],["”,“div”,null,{“className”:“mt-4 grid gap-3 sm:grid-cols-2”,“children”:[“L42","L42","L42","L43”,“L44","L44","L44","L45”,“L46","L46","L46","L47”]}]]}]]}]
48:I[206516,[“/_next/static/chunks/051aanbhrv4br.js”,“/_next/static/chunks/0mizr60h7ayzt.js”,“/_next/static/chunks/0v9lm1dmbdoo-.js”,“/_next/static/chunks/0rxr1j1j3j-.r.js”,“/_next/static/chunks/02ftybezfvqjd.js”,“/_next/static/chunks/0.v9ksvnnj8ia.js”,“/_next/static/chunks/0bn6id96nx3k.js",“/_next/static/chunks/13ybnhn37c.tc.js”,“/_next/static/chunks/0_fnrdtruz8uf.js”,“/_next/static/chunks/0r6l15utt1mwb.js”,“/_next/static/chunks/0dm9a5into854.js”,"/_next/static/chunks/07k6hqoibtcn.js”,“/next/static/chunks/0b4cao.4y…j.js”,“/_next/static/chunks/02i-n28z7kjd0.js”],“default”]
更多推荐


所有评论(0)