AgentDB Advanced Features skill
Master advanced AgentDB features including QUIC synchronization, multi-database management, custom distance metrics, hybrid search, and distributed systems integration.
by ruvnet·MIT license·★ 94,702 Stars on the repo·GitHub ↗
npx degit ruvnet/RuView/.claude/skills/agentdb-advanced#main ~/.claude/skills/agentdb-advancedChecked ·commit main
Files of AgentDB Advanced Features
Show the full text551 lines
AgentDB Advanced Features
What This Skill Does
Covers advanced AgentDB capabilities for distributed systems, multi-database coordination, custom distance metrics, hybrid search (vector + metadata), QUIC synchronization, and production deployment patterns. Enables building sophisticated AI systems with sub-millisecond cross-node communication and advanced search capabilities.
Performance: <1ms QUIC sync, hybrid search with filters, custom distance metrics.
Prerequisites
- Node.js 18+
- AgentDB v1.0.7+ (via agentic-flow)
- Understanding of distributed systems (for QUIC sync)
- Vector search fundamentals
QUIC Synchronization
What is QUIC Sync?
QUIC (Quick UDP Internet Connections) enables sub-millisecond latency synchronization between AgentDB instances across network boundaries with automatic retry, multiplexing, and encryption.
Benefits:
- <1ms latency between nodes
- Multiplexed streams (multiple operations simultaneously)
- Built-in encryption (TLS 1.3)
- Automatic retry and recovery
- Event-based broadcasting
Enable QUIC Sync
import { createAgentDBAdapter } from 'agentic-flow/reasoningbank';
// Initialize with QUIC synchronization
const adapter = await createAgentDBAdapter({
dbPath: '.agentdb/distributed.db',
enableQUICSync: true,
syncPort: 4433,
syncPeers: [
'192.168.1.10:4433',
'192.168.1.11:4433',
'192.168.1.12:4433',
],
});
// Patterns automatically sync across all peers
await adapter.insertPattern({
// ... pattern data
});
// Available on all peers within ~1ms
QUIC Configuration
const adapter = await createAgentDBAdapter({
enableQUICSync: true,
syncPort: 4433, // QUIC server port
syncPeers: ['host1:4433'], // Peer addresses
syncInterval: 1000, // Sync interval (ms)
syncBatchSize: 100, // Patterns per batch
maxRetries: 3, // Retry failed syncs
compression: true, // Enable compression
});
Multi-Node Deployment
# Node 1 (192.168.1.10)
AGENTDB_QUIC_SYNC=true \
AGENTDB_QUIC_PORT=4433 \
AGENTDB_QUIC_PEERS=192.168.1.11:4433,192.168.1.12:4433 \
node server.js
# Node 2 (192.168.1.11)
AGENTDB_QUIC_SYNC=true \
AGENTDB_QUIC_PORT=4433 \
AGENTDB_QUIC_PEERS=192.168.1.10:4433,192.168.1.12:4433 \
node server.js
# Node 3 (192.168.1.12)
AGENTDB_QUIC_SYNC=true \
AGENTDB_QUIC_PORT=4433 \
AGENTDB_QUIC_PEERS=192.168.1.10:4433,192.168.1.11:4433 \
node server.js
Distance Metrics
Cosine Similarity (Default)
Best for normalized vectors, semantic similarity:
# CLI
npx agentdb@latest query ./vectors.db "[0.1,0.2,...]" -m cosine
# API
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
metric: 'cosine',
k: 10,
});
Use Cases:
- Text embeddings (BERT, GPT, etc.)
- Semantic search
- Document similarity
- Most general-purpose applications
Formula: cos(θ) = (A · B) / (||A|| × ||B||)
Range: [-1, 1] (1 = identical, -1 = opposite)
Euclidean Distance (L2)
Best for spatial data, geometric similarity:
# CLI
npx agentdb@latest query ./vectors.db "[0.1,0.2,...]" -m euclidean
# API
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
metric: 'euclidean',
k: 10,
});
Use Cases:
- Image embeddings
- Spatial data
- Computer vision
- When vector magnitude matters
Formula: d = √(Σ(ai - bi)²)
Range: [0, ∞] (0 = identical, ∞ = very different)
Dot Product
Best for pre-normalized vectors, fast computation:
# CLI
npx agentdb@latest query ./vectors.db "[0.1,0.2,...]" -m dot
# API
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
metric: 'dot',
k: 10,
});
Use Cases:
- Pre-normalized embeddings
- Fast similarity computation
- When vectors are already unit-length
Formula: dot = Σ(ai × bi)
Range: [-∞, ∞] (higher = more similar)
Custom Distance Metrics
// Implement custom distance function
function customDistance(vec1: number[], vec2: number[]): number {
// Weighted Euclidean distance
const weights = [1.0, 2.0, 1.5, ...];
let sum = 0;
for (let i = 0; i < vec1.length; i++) {
sum += weights[i] * Math.pow(vec1[i] - vec2[i], 2);
}
return Math.sqrt(sum);
}
// Use in search (requires custom implementation)
Hybrid Search (Vector + Metadata)
Basic Hybrid Search
Combine vector similarity with metadata filtering:
// Store documents with metadata
await adapter.insertPattern({
id: '',
type: 'document',
domain: 'research-papers',
pattern_data: JSON.stringify({
embedding: documentEmbedding,
text: documentText,
metadata: {
author: 'Jane Smith',
year: 2025,
category: 'machine-learning',
citations: 150,
}
}),
confidence: 1.0,
usage_count: 0,
success_count: 0,
created_at: Date.now(),
last_used: Date.now(),
});
// Hybrid search: vector similarity + metadata filters
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
domain: 'research-papers',
k: 20,
filters: {
year: { $gte: 2023 }, // Published 2023 or later
category: 'machine-learning', // ML papers only
citations: { $gte: 50 }, // Highly cited
},
});
Advanced Filtering
// Complex metadata queries
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
domain: 'products',
k: 50,
filters: {
price: { $gte: 10, $lte: 100 }, // Price range
category: { $in: ['electronics', 'gadgets'] }, // Multiple categories
rating: { $gte: 4.0 }, // High rated
inStock: true, // Available
tags: { $contains: 'wireless' }, // Has tag
},
});
Weighted Hybrid Search
Combine vector and metadata scores:
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
domain: 'content',
k: 20,
hybridWeights: {
vectorSimilarity: 0.7, // 70% weight on semantic similarity
metadataScore: 0.3, // 30% weight on metadata match
},
filters: {
category: 'technology',
recency: { $gte: Date.now() - 30 * 24 * 3600000 }, // Last 30 days
},
});
Multi-Database Management
Multiple Databases
// Separate databases for different domains
const knowledgeDB = await createAgentDBAdapter({
dbPath: '.agentdb/knowledge.db',
});
const conversationDB = await createAgentDBAdapter({
dbPath: '.agentdb/conversations.db',
});
const codeDB = await createAgentDBAdapter({
dbPath: '.agentdb/code.db',
});
// Use appropriate database for each task
await knowledgeDB.insertPattern({ /* knowledge */ });
await conversationDB.insertPattern({ /* conversation */ });
await codeDB.insertPattern({ /* code */ });
Database Sharding
// Shard by domain for horizontal scaling
const shards = {
'domain-a': await createAgentDBAdapter({ dbPath: '.agentdb/shard-a.db' }),
'domain-b': await createAgentDBAdapter({ dbPath: '.agentdb/shard-b.db' }),
'domain-c': await createAgentDBAdapter({ dbPath: '.agentdb/shard-c.db' }),
};
// Route queries to appropriate shard
function getDBForDomain(domain: string) {
const shardKey = domain.split('-')[0]; // Extract shard key
return shards[shardKey] || shards['domain-a'];
}
// Insert to correct shard
const db = getDBForDomain('domain-a-task');
await db.insertPattern({ /* ... */ });
MMR (Maximal Marginal Relevance)
Retrieve diverse results to avoid redundancy:
// Without MMR: Similar results may be redundant
const standardResults = await adapter.retrieveWithReasoning(queryEmbedding, {
k: 10,
useMMR: false,
});
// With MMR: Diverse, non-redundant results
const diverseResults = await adapter.retrieveWithReasoning(queryEmbedding, {
k: 10,
useMMR: true,
mmrLambda: 0.5, // Balance relevance (0) vs diversity (1)
});
MMR Parameters:
mmrLambda = 0: Maximum relevance (may be redundant)mmrLambda = 0.5: Balanced (default)mmrLambda = 1: Maximum diversity (may be less relevant)
Use Cases:
- Search result diversification
- Recommendation systems
- Avoiding echo chambers
- Exploratory search
Context Synthesis
Generate rich context from multiple memories:
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
domain: 'problem-solving',
k: 10,
synthesizeContext: true, // Enable context synthesis
});
// ContextSynthesizer creates coherent narrative
console.log('Synthesized Context:', result.context);
// "Based on 10 similar problem-solving attempts, the most effective
// approach involves: 1) analyzing root cause, 2) brainstorming solutions,
// 3) evaluating trade-offs, 4) implementing incrementally. Success rate: 85%"
console.log('Patterns:', result.patterns);
// Extracted common patterns across memories
Production Patterns
Connection Pooling
// Singleton pattern for shared adapter
class AgentDBPool {
private static instance: AgentDBAdapter;
static async getInstance() {
if (!this.instance) {
this.instance = await createAgentDBAdapter({
dbPath: '.agentdb/production.db',
quantizationType: 'scalar',
cacheSize: 2000,
});
}
return this.instance;
}
}
// Use in application
const db = await AgentDBPool.getInstance();
const results = await db.retrieveWithReasoning(queryEmbedding, { k: 10 });
Error Handling
async function safeRetrieve(queryEmbedding: number[], options: any) {
try {
const result = await adapter.retrieveWithReasoning(queryEmbedding, options);
return result;
} catch (error) {
if (error.code === 'DIMENSION_MISMATCH') {
console.error('Query embedding dimension mismatch');
// Handle dimension error
} else if (error.code === 'DATABASE_LOCKED') {
// Retry with exponential backoff
await new Promise(resolve => setTimeout(resolve, 100));
return safeRetrieve(queryEmbedding, options);
}
throw error;
}
}
Monitoring and Logging
// Performance monitoring
const startTime = Date.now();
const result = await adapter.retrieveWithReasoning(queryEmbedding, { k: 10 });
const latency = Date.now() - startTime;
if (latency > 100) {
console.warn('Slow query detected:', latency, 'ms');
}
// Log statistics
const stats = await adapter.getStats();
console.log('Database Stats:', {
totalPatterns: stats.totalPatterns,
dbSize: stats.dbSize,
cacheHitRate: stats.cacheHitRate,
avgSearchLatency: stats.avgSearchLatency,
});
CLI Advanced Operations
Database Import/Export
# Export with compression
npx agentdb@latest export ./vectors.db ./backup.json.gz --compress
# Import from backup
npx agentdb@latest import ./backup.json.gz --decompress
# Merge databases
npx agentdb@latest merge ./db1.sqlite ./db2.sqlite ./merged.sqlite
Database Optimization
# Vacuum database (reclaim space)
sqlite3 .agentdb/vectors.db "VACUUM;"
# Analyze for query optimization
sqlite3 .agentdb/vectors.db "ANALYZE;"
# Rebuild indices
npx agentdb@latest reindex ./vectors.db
Environment Variables
# AgentDB configuration
AGENTDB_PATH=.agentdb/reasoningbank.db
AGENTDB_ENABLED=true
# Performance tuning
AGENTDB_QUANTIZATION=binary # binary|scalar|product|none
AGENTDB_CACHE_SIZE=2000
AGENTDB_HNSW_M=16
AGENTDB_HNSW_EF=100
# Learning plugins
AGENTDB_LEARNING=true
# Reasoning agents
AGENTDB_REASONING=true
# QUIC synchronization
AGENTDB_QUIC_SYNC=true
AGENTDB_QUIC_PORT=4433
AGENTDB_QUIC_PEERS=host1:4433,host2:4433
Troubleshooting
Issue: QUIC sync not working
# Check firewall allows UDP port 4433
sudo ufw allow 4433/udp
# Verify peers are reachable
ping host1
# Check QUIC logs
DEBUG=agentdb:quic node server.js
Issue: Hybrid search returns no results
// Relax filters
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
k: 100, // Increase k
filters: {
// Remove or relax filters
},
});
Issue: Memory consolidation too aggressive
// Disable automatic optimization
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
optimizeMemory: false, // Disable auto-consolidation
k: 10,
});
Learn More
- QUIC Protocol: docs/quic-synchronization.pdf
- Hybrid Search: docs/hybrid-search-guide.md
- GitHub: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb
- Website: https://agentdb.ruv.io
Category: Advanced / Distributed Systems Difficulty: Advanced Estimated Time: 45-60 minutes
| 1 | |
| 2 | name "AgentDB Advanced Features" |
| 3 | description "Master advanced AgentDB features including QUIC synchronization, multi-database management, custom distance metrics, hybrid search, and distributed systems integration. Use when building distributed AI systems, multi-agent coordination, or advanced vector search applications." |
| 4 | |
| 5 | |
| 6 | # AgentDB Advanced Features |
| 7 | |
| 8 | ## What This Skill Does |
| 9 | |
| 10 | Covers advanced AgentDB capabilities for distributed systems, multi-database coordination, custom distance metrics, hybrid search (vector + metadata), QUIC synchronization, and production deployment patterns. Enables building sophisticated AI systems with sub-millisecond cross-node communication and advanced search capabilities. |
| 11 | |
| 12 | **Performance**: <1ms QUIC sync, hybrid search with filters, custom distance metrics. |
| 13 | |
| 14 | ## Prerequisites |
| 15 | |
| 16 | Node.js 18+ |
| 17 | AgentDB v1.0.7+ (via agentic-flow) |
| 18 | Understanding of distributed systems (for QUIC sync) |
| 19 | Vector search fundamentals |
| 20 | |
| 21 | |
| 22 | |
| 23 | ## QUIC Synchronization |
| 24 | |
| 25 | ### What is QUIC Sync? |
| 26 | |
| 27 | QUIC (Quick UDP Internet Connections) enables sub-millisecond latency synchronization between AgentDB instances across network boundaries with automatic retry, multiplexing, and encryption. |
| 28 | |
| 29 | **Benefits**: |
| 30 | <1ms latency between nodes |
| 31 | Multiplexed streams (multiple operations simultaneously) |
| 32 | Built-in encryption (TLS 1.3) |
| 33 | Automatic retry and recovery |
| 34 | Event-based broadcasting |
| 35 | |
| 36 | ### Enable QUIC Sync |
| 37 | |
| 38 | |
| 39 | import { createAgentDBAdapter } from 'agentic-flow/reasoningbank'; |
| 40 | |
| 41 | // Initialize with QUIC synchronization |
| 42 | const adapter = await createAgentDBAdapter({ |
| 43 | dbPath: '.agentdb/distributed.db', |
| 44 | enableQUICSync: true, |
| 45 | syncPort: 4433, |
| 46 | syncPeers: [ |
| 47 | '192.168.1.10:4433', |
| 48 | '192.168.1.11:4433', |
| 49 | '192.168.1.12:4433', |
| 50 | ], |
| 51 | }); |
| 52 | |
| 53 | // Patterns automatically sync across all peers |
| 54 | await adapter.insertPattern({ |
| 55 | // ... pattern data |
| 56 | }); |
| 57 | |
| 58 | // Available on all peers within ~1ms |
| 59 | |
| 60 | |
| 61 | ### QUIC Configuration |
| 62 | |
| 63 | |
| 64 | const adapter = await createAgentDBAdapter({ |
| 65 | enableQUICSync: true, |
| 66 | syncPort: 4433, // QUIC server port |
| 67 | syncPeers: ['host1:4433'], // Peer addresses |
| 68 | syncInterval: 1000, // Sync interval (ms) |
| 69 | syncBatchSize: 100, // Patterns per batch |
| 70 | maxRetries: 3, // Retry failed syncs |
| 71 | compression: true, // Enable compression |
| 72 | }); |
| 73 | |
| 74 | |
| 75 | ### Multi-Node Deployment |
| 76 | |
| 77 | |
| 78 | # Node 1 (192.168.1.10) |
| 79 | AGENTDB_QUIC_SYNC=true \ |
| 80 | AGENTDB_QUIC_PORT=4433 \ |
| 81 | AGENTDB_QUIC_PEERS=192.168.1.11:4433,192.168.1.12:4433 \ |
| 82 | node server.js |
| 83 | |
| 84 | # Node 2 (192.168.1.11) |
| 85 | AGENTDB_QUIC_SYNC=true \ |
| 86 | AGENTDB_QUIC_PORT=4433 \ |
| 87 | AGENTDB_QUIC_PEERS=192.168.1.10:4433,192.168.1.12:4433 \ |
| 88 | node server.js |
| 89 | |
| 90 | # Node 3 (192.168.1.12) |
| 91 | AGENTDB_QUIC_SYNC=true \ |
| 92 | AGENTDB_QUIC_PORT=4433 \ |
| 93 | AGENTDB_QUIC_PEERS=192.168.1.10:4433,192.168.1.11:4433 \ |
| 94 | node server.js |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | ## Distance Metrics |
| 100 | |
| 101 | ### Cosine Similarity (Default) |
| 102 | |
| 103 | Best for normalized vectors, semantic similarity: |
| 104 | |
| 105 | |
| 106 | # CLI |
| 107 | npx agentdb@latest query ./vectors.db "[0.1,0.2,...]" -m cosine |
| 108 | |
| 109 | # API |
| 110 | const result = await adapter.retrieveWithReasoning(queryEmbedding, { |
| 111 | metric: 'cosine', |
| 112 | k: 10, |
| 113 | }); |
| 114 | |
| 115 | |
| 116 | **Use Cases**: |
| 117 | Text embeddings (BERT, GPT, etc.) |
| 118 | Semantic search |
| 119 | Document similarity |
| 120 | Most general-purpose applications |
| 121 | |
| 122 | **Formula**: `cos(θ) = (A · B) / (||A|| × ||B||)` |
| 123 | **Range**: [-1, 1] (1 = identical, -1 = opposite) |
| 124 | |
| 125 | ### Euclidean Distance (L2) |
| 126 | |
| 127 | Best for spatial data, geometric similarity: |
| 128 | |
| 129 | |
| 130 | # CLI |
| 131 | npx agentdb@latest query ./vectors.db "[0.1,0.2,...]" -m euclidean |
| 132 | |
| 133 | # API |
| 134 | const result = await adapter.retrieveWithReasoning(queryEmbedding, { |
| 135 | metric: 'euclidean', |
| 136 | k: 10, |
| 137 | }); |
| 138 | |
| 139 | |
| 140 | **Use Cases**: |
| 141 | Image embeddings |
| 142 | Spatial data |
| 143 | Computer vision |
| 144 | When vector magnitude matters |
| 145 | |
| 146 | **Formula**: `d = √(Σ(ai - bi)²)` |
| 147 | **Range**: [0, ∞] (0 = identical, ∞ = very different) |
| 148 | |
| 149 | ### Dot Product |
| 150 | |
| 151 | Best for pre-normalized vectors, fast computation: |
| 152 | |
| 153 | |
| 154 | # CLI |
| 155 | npx agentdb@latest query ./vectors.db "[0.1,0.2,...]" -m dot |
| 156 | |
| 157 | # API |
| 158 | const result = await adapter.retrieveWithReasoning(queryEmbedding, { |
| 159 | metric: 'dot', |
| 160 | k: 10, |
| 161 | }); |
| 162 | |
| 163 | |
| 164 | **Use Cases**: |
| 165 | Pre-normalized embeddings |
| 166 | Fast similarity computation |
| 167 | When vectors are already unit-length |
| 168 | |
| 169 | **Formula**: `dot = Σ(ai × bi)` |
| 170 | **Range**: [-∞, ∞] (higher = more similar) |
| 171 | |
| 172 | ### Custom Distance Metrics |
| 173 | |
| 174 | |
| 175 | // Implement custom distance function |
| 176 | function customDistance(vec1: number[], vec2: number[]): number { |
| 177 | // Weighted Euclidean distance |
| 178 | const weights = [1.0, 2.0, 1.5, ...]; |
| 179 | let sum = 0; |
| 180 | for (let i = 0; i < vec1.length; i++) { |
| 181 | sum += weights[i] * Math.pow(vec1[i] - vec2[i], 2); |
| 182 | } |
| 183 | return Math.sqrt(sum); |
| 184 | } |
| 185 | |
| 186 | // Use in search (requires custom implementation) |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | ## Hybrid Search (Vector + Metadata) |
| 192 | |
| 193 | ### Basic Hybrid Search |
| 194 | |
| 195 | Combine vector similarity with metadata filtering: |
| 196 | |
| 197 | |
| 198 | // Store documents with metadata |
| 199 | await adapter.insertPattern({ |
| 200 | id: '', |
| 201 | type: 'document', |
| 202 | domain: 'research-papers', |
| 203 | pattern_data: JSON.stringify({ |
| 204 | embedding: documentEmbedding, |
| 205 | text: documentText, |
| 206 | metadata: { |
| 207 | author: 'Jane Smith', |
| 208 | year: 2025, |
| 209 | category: 'machine-learning', |
| 210 | citations: 150, |
| 211 | } |
| 212 | }), |
| 213 | confidence: 1.0, |
| 214 | usage_count: 0, |
| 215 | success_count: 0, |
| 216 | created_at: Date.now(), |
| 217 | last_used: Date.now(), |
| 218 | }); |
| 219 | |
| 220 | // Hybrid search: vector similarity + metadata filters |
| 221 | const result = await adapter.retrieveWithReasoning(queryEmbedding, { |
| 222 | domain: 'research-papers', |
| 223 | k: 20, |
| 224 | filters: { |
| 225 | year: { $gte: 2023 }, // Published 2023 or later |
| 226 | category: 'machine-learning', // ML papers only |
| 227 | citations: { $gte: 50 }, // Highly cited |
| 228 | }, |
| 229 | }); |
| 230 | |
| 231 | |
| 232 | ### Advanced Filtering |
| 233 | |
| 234 | |
| 235 | // Complex metadata queries |
| 236 | const result = await adapter.retrieveWithReasoning(queryEmbedding, { |
| 237 | domain: 'products', |
| 238 | k: 50, |
| 239 | filters: { |
| 240 | price: { $gte: 10, $lte: 100 }, // Price range |
| 241 | category: { $in: ['electronics', 'gadgets'] }, // Multiple categories |
| 242 | rating: { $gte: 4.0 }, // High rated |
| 243 | inStock: true, // Available |
| 244 | tags: { $contains: 'wireless' }, // Has tag |
| 245 | }, |
| 246 | }); |
| 247 | |
| 248 | |
| 249 | ### Weighted Hybrid Search |
| 250 | |
| 251 | Combine vector and metadata scores: |
| 252 | |
| 253 | |
| 254 | const result = await adapter.retrieveWithReasoning(queryEmbedding, { |
| 255 | domain: 'content', |
| 256 | k: 20, |
| 257 | hybridWeights: { |
| 258 | vectorSimilarity: 0.7, // 70% weight on semantic similarity |
| 259 | metadataScore: 0.3, // 30% weight on metadata match |
| 260 | }, |
| 261 | filters: { |
| 262 | category: 'technology', |
| 263 | recency: { $gte: Date.now() - 30 * 24 * 3600000 }, // Last 30 days |
| 264 | }, |
| 265 | }); |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | ## Multi-Database Management |
| 271 | |
| 272 | ### Multiple Databases |
| 273 | |
| 274 | |
| 275 | // Separate databases for different domains |
| 276 | const knowledgeDB = await createAgentDBAdapter({ |
| 277 | dbPath: '.agentdb/knowledge.db', |
| 278 | }); |
| 279 | |
| 280 | const conversationDB = await createAgentDBAdapter({ |
| 281 | dbPath: '.agentdb/conversations.db', |
| 282 | }); |
| 283 | |
| 284 | const codeDB = await createAgentDBAdapter({ |
| 285 | dbPath: '.agentdb/code.db', |
| 286 | }); |
| 287 | |
| 288 | // Use appropriate database for each task |
| 289 | await knowledgeDB.insertPattern({ /* knowledge */ }); |
| 290 | await conversationDB.insertPattern({ /* conversation */ }); |
| 291 | await codeDB.insertPattern({ /* code */ }); |
| 292 | |
| 293 | |
| 294 | ### Database Sharding |
| 295 | |
| 296 | |
| 297 | // Shard by domain for horizontal scaling |
| 298 | const shards = { |
| 299 | 'domain-a': await createAgentDBAdapter({ dbPath: '.agentdb/shard-a.db' }), |
| 300 | 'domain-b': await createAgentDBAdapter({ dbPath: '.agentdb/shard-b.db' }), |
| 301 | 'domain-c': await createAgentDBAdapter({ dbPath: '.agentdb/shard-c.db' }), |
| 302 | }; |
| 303 | |
| 304 | // Route queries to appropriate shard |
| 305 | function getDBForDomain(domain: string) { |
| 306 | const shardKey = domain.split('-')[0]; // Extract shard key |
| 307 | return shards[shardKey] || shards['domain-a']; |
| 308 | } |
| 309 | |
| 310 | // Insert to correct shard |
| 311 | const db = getDBForDomain('domain-a-task'); |
| 312 | await db.insertPattern({ /* ... */ }); |
| 313 | |
| 314 | |
| 315 | |
| 316 | |
| 317 | ## MMR (Maximal Marginal Relevance) |
| 318 | |
| 319 | Retrieve diverse results to avoid redundancy: |
| 320 | |
| 321 | |
| 322 | // Without MMR: Similar results may be redundant |
| 323 | const standardResults = await adapter.retrieveWithReasoning(queryEmbedding, { |
| 324 | k: 10, |
| 325 | useMMR: false, |
| 326 | }); |
| 327 | |
| 328 | // With MMR: Diverse, non-redundant results |
| 329 | const diverseResults = await adapter.retrieveWithReasoning(queryEmbedding, { |
| 330 | k: 10, |
| 331 | useMMR: true, |
| 332 | mmrLambda: 0.5, // Balance relevance (0) vs diversity (1) |
| 333 | }); |
| 334 | |
| 335 | |
| 336 | **MMR Parameters**: |
| 337 | `mmrLambda = 0`: Maximum relevance (may be redundant) |
| 338 | `mmrLambda = 0.5`: Balanced (default) |
| 339 | `mmrLambda = 1`: Maximum diversity (may be less relevant) |
| 340 | |
| 341 | **Use Cases**: |
| 342 | Search result diversification |
| 343 | Recommendation systems |
| 344 | Avoiding echo chambers |
| 345 | Exploratory search |
| 346 | |
| 347 | |
| 348 | |
| 349 | ## Context Synthesis |
| 350 | |
| 351 | Generate rich context from multiple memories: |
| 352 | |
| 353 | |
| 354 | const result = await adapter.retrieveWithReasoning(queryEmbedding, { |
| 355 | domain: 'problem-solving', |
| 356 | k: 10, |
| 357 | synthesizeContext: true, // Enable context synthesis |
| 358 | }); |
| 359 | |
| 360 | // ContextSynthesizer creates coherent narrative |
| 361 | console.log('Synthesized Context:', result.context); |
| 362 | // "Based on 10 similar problem-solving attempts, the most effective |
| 363 | // approach involves: 1) analyzing root cause, 2) brainstorming solutions, |
| 364 | // 3) evaluating trade-offs, 4) implementing incrementally. Success rate: 85%" |
| 365 | |
| 366 | console.log('Patterns:', result.patterns); |
| 367 | // Extracted common patterns across memories |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | ## Production Patterns |
| 373 | |
| 374 | ### Connection Pooling |
| 375 | |
| 376 | |
| 377 | // Singleton pattern for shared adapter |
| 378 | class AgentDBPool { |
| 379 | private static instance: AgentDBAdapter; |
| 380 | |
| 381 | static async getInstance() { |
| 382 | if (!this.instance) { |
| 383 | this.instance = await createAgentDBAdapter({ |
| 384 | dbPath: '.agentdb/production.db', |
| 385 | quantizationType: 'scalar', |
| 386 | cacheSize: 2000, |
| 387 | }); |
| 388 | } |
| 389 | return this.instance; |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | // Use in application |
| 394 | const db = await AgentDBPool.getInstance(); |
| 395 | const results = await db.retrieveWithReasoning(queryEmbedding, { k: 10 }); |
| 396 | |
| 397 | |
| 398 | ### Error Handling |
| 399 | |
| 400 | |
| 401 | async function safeRetrieve(queryEmbedding: number[], options: any) { |
| 402 | try { |
| 403 | const result = await adapter.retrieveWithReasoning(queryEmbedding, options); |
| 404 | return result; |
| 405 | } catch (error) { |
| 406 | if (error.code === 'DIMENSION_MISMATCH') { |
| 407 | console.error('Query embedding dimension mismatch'); |
| 408 | // Handle dimension error |
| 409 | } else if (error.code === 'DATABASE_LOCKED') { |
| 410 | // Retry with exponential backoff |
| 411 | await new Promise(resolve => setTimeout(resolve, 100)); |
| 412 | return safeRetrieve(queryEmbedding, options); |
| 413 | } |
| 414 | throw error; |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | |
| 419 | ### Monitoring and Logging |
| 420 | |
| 421 | |
| 422 | // Performance monitoring |
| 423 | const startTime = Date.now(); |
| 424 | const result = await adapter.retrieveWithReasoning(queryEmbedding, { k: 10 }); |
| 425 | const latency = Date.now() - startTime; |
| 426 | |
| 427 | if (latency > 100) { |
| 428 | console.warn('Slow query detected:', latency, 'ms'); |
| 429 | } |
| 430 | |
| 431 | // Log statistics |
| 432 | const stats = await adapter.getStats(); |
| 433 | console.log('Database Stats:', { |
| 434 | totalPatterns: stats.totalPatterns, |
| 435 | dbSize: stats.dbSize, |
| 436 | cacheHitRate: stats.cacheHitRate, |
| 437 | avgSearchLatency: stats.avgSearchLatency, |
| 438 | }); |
| 439 | |
| 440 | |
| 441 | |
| 442 | |
| 443 | ## CLI Advanced Operations |
| 444 | |
| 445 | ### Database Import/Export |
| 446 | |
| 447 | |
| 448 | # Export with compression |
| 449 | npx agentdb@latest export ./vectors.db ./backup.json.gz --compress |
| 450 | |
| 451 | # Import from backup |
| 452 | npx agentdb@latest import ./backup.json.gz --decompress |
| 453 | |
| 454 | # Merge databases |
| 455 | npx agentdb@latest merge ./db1.sqlite ./db2.sqlite ./merged.sqlite |
| 456 | |
| 457 | |
| 458 | ### Database Optimization |
| 459 | |
| 460 | |
| 461 | # Vacuum database (reclaim space) |
| 462 | sqlite3 .agentdb/vectors.db "VACUUM;" |
| 463 | |
| 464 | # Analyze for query optimization |
| 465 | sqlite3 .agentdb/vectors.db "ANALYZE;" |
| 466 | |
| 467 | # Rebuild indices |
| 468 | npx agentdb@latest reindex ./vectors.db |
| 469 | |
| 470 | |
| 471 | |
| 472 | |
| 473 | ## Environment Variables |
| 474 | |
| 475 | |
| 476 | # AgentDB configuration |
| 477 | AGENTDB_PATH=.agentdb/reasoningbank.db |
| 478 | AGENTDB_ENABLED=true |
| 479 | |
| 480 | # Performance tuning |
| 481 | AGENTDB_QUANTIZATION=binary # binary|scalar|product|none |
| 482 | AGENTDB_CACHE_SIZE=2000 |
| 483 | AGENTDB_HNSW_M=16 |
| 484 | AGENTDB_HNSW_EF=100 |
| 485 | |
| 486 | # Learning plugins |
| 487 | AGENTDB_LEARNING=true |
| 488 | |
| 489 | # Reasoning agents |
| 490 | AGENTDB_REASONING=true |
| 491 | |
| 492 | # QUIC synchronization |
| 493 | AGENTDB_QUIC_SYNC=true |
| 494 | AGENTDB_QUIC_PORT=4433 |
| 495 | AGENTDB_QUIC_PEERS=host1:4433,host2:4433 |
| 496 | |
| 497 | |
| 498 | |
| 499 | |
| 500 | ## Troubleshooting |
| 501 | |
| 502 | ### Issue: QUIC sync not working |
| 503 | |
| 504 | |
| 505 | # Check firewall allows UDP port 4433 |
| 506 | sudo ufw allow 4433/udp |
| 507 | |
| 508 | # Verify peers are reachable |
| 509 | ping host1 |
| 510 | |
| 511 | # Check QUIC logs |
| 512 | DEBUG=agentdb:quic node server.js |
| 513 | |
| 514 | |
| 515 | ### Issue: Hybrid search returns no results |
| 516 | |
| 517 | |
| 518 | // Relax filters |
| 519 | const result = await adapter.retrieveWithReasoning(queryEmbedding, { |
| 520 | k: 100, // Increase k |
| 521 | filters: { |
| 522 | // Remove or relax filters |
| 523 | }, |
| 524 | }); |
| 525 | |
| 526 | |
| 527 | ### Issue: Memory consolidation too aggressive |
| 528 | |
| 529 | |
| 530 | // Disable automatic optimization |
| 531 | const result = await adapter.retrieveWithReasoning(queryEmbedding, { |
| 532 | optimizeMemory: false, // Disable auto-consolidation |
| 533 | k: 10, |
| 534 | }); |
| 535 | |
| 536 | |
| 537 | |
| 538 | |
| 539 | ## Learn More |
| 540 | |
| 541 | **QUIC Protocol**: docs/quic-synchronization.pdf |
| 542 | **Hybrid Search**: docs/hybrid-search-guide.md |
| 543 | **GitHub**: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb |
| 544 | **Website**: https://agentdb.ruv.io |
| 545 | |
| 546 | |
| 547 | |
| 548 | **Category**: Advanced / Distributed Systems |
| 549 | **Difficulty**: Advanced |
| 550 | **Estimated Time**: 45-60 minutes |
| 551 |
Discussion
Browse more free Claude skills.