The fastest vector database for Node.js—built in Rust, runs everywhere
Ruvector is a next-generation vector database that brings enterprise-grade semantic search to Node.js applications. Unlike cloud-only solutions or Python-first databases, Ruvector is designed specifically for JavaScript/TypeScript developers who need blazing-fast vector similarity search without the complexity of external services.
Built by rUv with production-grade Rust performance and intelligent platform detection—automatically uses native bindings when available, falls back to WebAssembly when needed.
Ruvector is purpose-built for modern JavaScript/TypeScript applications that need vector search:
🎯 Native Node.js Integration
Drop-in npm package—no Docker, no Python, no external services
Full TypeScript support with complete type definitions
Automatic platform detection with native Rust bindings
Seamless WebAssembly fallback for universal compatibility
⚡ Production-Grade Performance
52,000+ inserts/second with native Rust (10x faster than Python alternatives)
<0.5ms query latency with HNSW indexing and SIMD optimizations
~50 bytes per vector with advanced memory optimization
Scales from edge devices to millions of vectors
🧠 Built for AI Applications
Optimized for LLM embeddings (OpenAI, Cohere, Hugging Face)
Perfect for RAG (Retrieval-Augmented Generation) systems
Agent memory and semantic caching
Real-time recommendation engines
🌍 Universal Deployment
Linux, macOS, Windows with native performance
Browser support via WebAssembly (experimental)
Edge computing and serverless environments
Alpine Linux and non-glibc systems supported
💰 Zero Operational Costs
No cloud API fees or usage limits
No infrastructure to manage
No separate database servers
Open source MIT license
Key Advantages
⚡ Blazing Fast: <0.5ms p50 latency with native Rust, 10-50ms with WASM fallback
🎯 Automatic Platform Detection: Uses native when available, falls back to WASM seamlessly
🧠 AI-Native: Built specifically for embeddings, RAG, semantic search, and agent memory
🔧 CLI Tools Included: Full command-line interface for database management
🌍 Universal Deployment: Works on all platforms—Linux, macOS, Windows, even browsers
💾 Memory Efficient: ~50 bytes per vector with advanced quantization
🚀 Production Ready: Battle-tested algorithms with comprehensive benchmarks
🔓 Open Source: MIT licensed, community-driven
🚀 Quick Start Tutorial
Step 1: Installation
Install Ruvector with a single npm command:
npm install ruvector
What happens during installation:
npm automatically detects your platform (Linux, macOS, Windows)
Downloads the correct native binary for maximum performance
Falls back to WebAssembly if native binaries aren't available
No additional setup, Docker, or external services required
Windows Installation (without build tools):
bash
1# Skip native compilation, use WASM fallback2npminstall ruvector --ignore-scripts
34# The ONNX WASM runtime (7.4MB) works without build tools5# Memory cache provides 40,000x speedup over inference
Verify installation:
npx ruvector info
You should see your platform and implementation type (native Rust or WASM fallback).
Step 2: Your First Vector Database
Let's create a simple vector database and perform basic operations. This example demonstrates the complete CRUD (Create, Read, Update, Delete) workflow:
javascript
1const{VectorDb}=require('ruvector');23asyncfunctiontutorial(){4// Step 2.1: Create a new vector database5// The 'dimensions' parameter must match your embedding model6// Common sizes: 128, 384 (sentence-transformers), 768 (BERT), 1536 (OpenAI)7const db =newVectorDb({8dimensions:128,// Vector size - MUST match your embeddings9maxElements:10000,// Maximum vectors (can grow automatically)10storagePath:'./my-vectors.db'// Persist to disk (omit for in-memory)11});1213console.log('✅ Database created successfully');1415// Step 2.2: Insert vectors16// In real applications, these would come from an embedding model17const documents =[18{id:'doc1',text:'Artificial intelligence and machine learning'},19{id:'doc2',text:'Deep learning neural networks'},20{id:'doc3',text:'Natural language processing'},21];2223for(const doc of documents){24// Generate random vector for demonstration25// In production: use OpenAI, Cohere, or sentence-transformers26const vector =newFloat32Array(128).map(()=>Math.random());2728await db.insert({29id: doc.id,30vector: vector,31metadata:{32text: doc.text,33timestamp:Date.now(),34category:'AI'35}36});3738console.log(`✅ Inserted: ${doc.id}`);39}4041// Step 2.3: Search for similar vectors42// Create a query vector (in production, this would be from your search query)43const queryVector =newFloat32Array(128).map(()=>Math.random());4445const results =await db.search({46vector: queryVector,47k:5,// Return top 5 most similar vectors48threshold:0.7// Only return results with similarity > 0.749});5051console.log('\n🔍 Search Results:');52 results.forEach((result, index)=>{53console.log(`${index +1}. ${result.id} - Score: ${result.score.toFixed(3)}`);54console.log(` Text: ${result.metadata.text}`);55});5657// Step 2.4: Retrieve a specific vector58const retrieved =await db.get('doc1');59if(retrieved){60console.log('\n📄 Retrieved document:', retrieved.metadata.text);61}6263// Step 2.5: Get database statistics64const count =await db.len();65console.log(`\n📊 Total vectors in database: ${count}`);6667// Step 2.6: Delete a vector68const deleted =await db.delete('doc1');69console.log(`\n🗑️ Deleted doc1: ${deleted ?'Success':'Not found'}`);7071// Final count72const finalCount =await db.len();73console.log(`📊 Final count: ${finalCount}`);74}7576// Run the tutorial77tutorial().catch(console.error);
Expected Output:
✅ Database created successfully
✅ Inserted: doc1
✅ Inserted: doc2
✅ Inserted: doc3
🔍 Search Results:
1. doc2 - Score: 0.892
Text: Deep learning neural networks
2. doc1 - Score: 0.856
Text: Artificial intelligence and machine learning
3. doc3 - Score: 0.801
Text: Natural language processing
📄 Retrieved document: Artificial intelligence and machine learning
📊 Total vectors in database: 3
🗑️ Deleted doc1: Success
📊 Final count: 2
Step 3: TypeScript Tutorial
Ruvector provides full TypeScript support with complete type safety. Here's how to use it:
1# Search for similar vectors2npx ruvector search mydb.vec --vector "[0.1,0.2,0.3,...]" --top-k 1034# Options:5# --vector, -v Query vector (JSON array)6# --top-k, -k Number of results (default: 10)7# --threshold Minimum similarity score
Database Statistics
bash
1# Show database statistics2npx ruvector stats mydb.vec
34# Output:5# Total vectors: 10,0006# Dimensions: 3847# Metric: cosine8# Memory usage: ~500 KB9# Index type: HNSW
Benchmarking
bash
1# Run performance benchmark2npx ruvector benchmark --num-vectors 10000 --num-queries 100034# Options:5# --num-vectors Number of vectors to insert6# --num-queries Number of search queries7# --dimensions Vector dimensionality (default: 128)
System Information
bash
1# Show platform and implementation info2npx ruvector info
34# Output:5# Platform: linux-x64-gnu6# Implementation: native (Rust)7# GNN Module: Available8# Node.js: v18.17.09# Performance: <0.5ms p50 latency
Install Optional Packages
Ruvector supports optional packages that extend functionality. Use the install command to add them:
bash
1# List available packages2npx ruvector install34# Output:5# Available Ruvector Packages:6#7# gnn not installed8# Graph Neural Network layers, tensor compression, differentiable search9# npm: @ruvector/gnn10#11# core ✓ installed12# Core vector database with native Rust bindings13# npm: @ruvector/core1415# Install specific package16npx ruvector install gnn
1718# Install all optional packages19npx ruvector install --all
2021# Interactive selection22npx ruvector install -i
The install command auto-detects your package manager (npm, yarn, pnpm, bun).
GNN Commands
Ruvector includes Graph Neural Network (GNN) capabilities for advanced tensor compression and differentiable search.
1# Calculate Poincaré distance between two points2npx ruvector attention hyperbolic -a distance -v "[0.1,0.2,0.3]" -b "[0.4,0.5,0.6]"34# Project vector to Poincaré ball5npx ruvector attention hyperbolic -a project -v "[1.5,2.0,0.8]"67# Möbius addition in hyperbolic space8npx ruvector attention hyperbolic -a mobius-add -v "[0.1,0.2]" -b "[0.3,0.4]"910# Exponential map (tangent space → Poincaré ball)11npx ruvector attention hyperbolic -a exp-map -v "[0.1,0.2,0.3]"1213# Options:14# -a, --action Action: distance|project|mobius-add|exp-map|log-map15# -v, --vector Input vector as JSON array (required)16# -b, --vector-b Second vector for binary operations17# -c, --curvature Poincaré ball curvature (default: 1.0)
When to Use Each Attention Type
Use Case
Recommended Attention
Reason
Standard NLP/Transformers
MultiHeadAttention
Industry standard, well-tested
Long Documents (>4K tokens)
FlashAttention or LinearAttention
Memory efficient
Hierarchical Classification
HyperbolicAttention
Captures tree-like structures
Knowledge Graphs
GraphRoPeAttention
Position-aware graph attention
Multi-Relational Graphs
EdgeFeaturedAttention
Leverages edge attributes
Taxonomy/Ontology Search
DualSpaceAttention
Best of both Euclidean + hyperbolic
Large-Scale Graphs
LocalGlobalAttention
Efficient local + global context
Model Routing/MoE
MoEAttention
Expert selection and routing
⚡ ONNX WASM Embeddings (v2.0)
RuVector includes a pure JavaScript ONNX runtime for local embeddings - no Python, no API calls, no build tools required.
bash
1# Embeddings work out of the box2npx ruvector hooks remember "important context" -t project
3npx ruvector hooks recall "context query"4npx ruvector hooks rag-context "how does auth work"
Model: all-MiniLM-L6-v2 (384 dimensions, 23MB)
Downloads automatically on first use
Cached in .ruvector/models/
SIMD-accelerated when available
Performance:
Operation
Time
Notes
Model load
~2s
First use only
Embedding
~50ms
Per text chunk
HNSW search
0.045ms
150x faster than brute force
Cache hit
0.01ms
40,000x faster than inference
Fallback Chain:
Native SQLite → best persistence
WASM SQLite → cross-platform
Memory Cache → fastest (no persistence)
🧠 Self-Learning Hooks v2.0
Ruvector includes self-learning intelligence hooks for Claude Code integration with ONNX embeddings, AST analysis, and coverage-aware routing.
Initialize Hooks
bash
1# Initialize hooks in your project2npx ruvector hooks init
34# Options:5# --force Overwrite existing configuration6# --minimal Minimal configuration (no optional hooks)7# --pretrain Initialize + pretrain from git history8# --build-agents quality Generate optimized agent configs
This creates .claude/settings.json with pre-configured hooks and CLAUDE.md with comprehensive documentation.
Session Management
bash
1# Start a session (load intelligence data)2npx ruvector hooks session-start
34# End a session (save learned patterns)5npx ruvector hooks session-end
Pre/Post Edit Hooks
bash
1# Before editing a file - get agent recommendations2npx ruvector hooks pre-edit src/index.ts
3# Output: 🤖 Recommended: typescript-developer (85% confidence)45# After editing - record success/failure for learning6npx ruvector hooks post-edit src/index.ts --success
7npx ruvector hooks post-edit src/index.ts --error "Type error on line 42"
Pre/Post Command Hooks
bash
1# Before running a command - risk analysis2npx ruvector hooks pre-command "npm test"3# Output: ✅ Risk: LOW, Category: test45# After running - record outcome6npx ruvector hooks post-command "npm test" --success
7npx ruvector hooks post-command "npm test" --error "3 tests failed"
Agent Routing
bash
1# Get agent recommendation for a task2npx ruvector hooks route "fix the authentication bug in login.ts"3# Output: 🤖 Recommended: security-specialist (92% confidence)45npx ruvector hooks route "add unit tests for the API"6# Output: 🤖 Recommended: tester (88% confidence)
1# Analyze commit with semantic embeddings and risk scoring2npx ruvector hooks diff-analyze HEAD
3# Output: risk score, category, affected files45# Classify change type (feature, bugfix, refactor, docs, test)6npx ruvector hooks diff-classify
78# Find similar past commits via embeddings9npx ruvector hooks diff-similar -k 51011# Git churn analysis (hot spots)12npx ruvector hooks git-churn --days 30
Coverage-Aware Routing (v2.0)
bash
1# Get coverage-aware routing for a file2npx ruvector hooks coverage-route src/api.ts
3# Output: agent weights based on test coverage45# Suggest tests for files based on coverage gaps6npx ruvector hooks coverage-suggest src/*.ts
Multi-tenancy requirements - Weaviate or Qdrant offer better isolation
Distributed systems - Milvus provides better horizontal scaling
Zero-ops cloud solution - Pinecone handles all infrastructure
Why Choose Ruvector Over...
vs Pinecone:
✅ No API costs (save $1000s/month)
✅ No network latency (10x faster queries)
✅ No vendor lock-in
✅ Works offline and in restricted environments
❌ No managed multi-region clusters
vs ChromaDB:
✅ 50x faster queries (native Rust vs Python)
✅ True Node.js support (not HTTP API)
✅ Better TypeScript integration
✅ Lower memory usage
❌ Smaller ecosystem and community
vs Qdrant:
✅ Zero infrastructure setup
✅ Embedded in your app (no Docker)
✅ Better for serverless environments
✅ Native Node.js bindings
❌ No built-in clustering or HA
vs Faiss:
✅ Full Node.js support (Faiss is Python-only)
✅ Easier API and better developer experience
✅ Built-in persistence and metadata
⚠️ Slightly lower recall at same performance
🎯 Real-World Tutorials
Tutorial 1: Building a RAG System with OpenAI
What you'll learn: Create a production-ready Retrieval-Augmented Generation system that enhances LLM responses with relevant context from your documents.
1const{VectorDb}=require('ruvector');2constOpenAI=require('openai');34classRAGSystem{5constructor(){6// Initialize OpenAI client7this.openai=newOpenAI({8apiKey: process.env.OPENAI_API_KEY9});1011// Create vector database for OpenAI embeddings12// text-embedding-ada-002 produces 1536-dimensional vectors13this.db=newVectorDb({14dimensions:1536,15maxElements:100000,16storagePath:'./rag-knowledge-base.db'17});1819console.log('✅ RAG System initialized');20}2122// Step 1: Index your knowledge base23asyncindexDocuments(documents){24console.log(`📚 Indexing ${documents.length} documents...`);2526for(let i =0; i < documents.length; i++){27const doc = documents[i];2829// Generate embedding for the document30const response =awaitthis.openai.embeddings.create({31model:'text-embedding-ada-002',32input: doc.content33});3435// Store in vector database36awaitthis.db.insert({37id: doc.id||`doc_${i}`,38vector:newFloat32Array(response.data[0].embedding),39metadata:{40title: doc.title,41content: doc.content,42source: doc.source,43date: doc.date||newDate().toISOString()44}45});4647console.log(` ✅ Indexed: ${doc.title}`);48}4950const count =awaitthis.db.len();51console.log(`\n✅ Indexed ${count} documents total`);52}5354// Step 2: Retrieve relevant context for a query55asyncretrieveContext(query, k =3){56console.log(`🔍 Searching for: "${query}"`);5758// Generate embedding for the query59const response =awaitthis.openai.embeddings.create({60model:'text-embedding-ada-002',61input: query
62});6364// Search for similar documents65const results =awaitthis.db.search({66vector:newFloat32Array(response.data[0].embedding),67k: k,68threshold:0.7// Only use highly relevant results69});7071console.log(`📄 Found ${results.length} relevant documents\n`);7273return results.map(r=>({74content: r.metadata.content,75title: r.metadata.title,76score: r.score77}));78}7980// Step 3: Generate answer with retrieved context81asyncanswer(question){82// Retrieve relevant context83const context =awaitthis.retrieveContext(question,3);8485if(context.length===0){86return"I don't have enough information to answer that question.";87}8889// Build prompt with context90const contextText = context
91.map((doc, i)=>`[${i +1}] ${doc.title}\n${doc.content}`)92.join('\n\n');9394const prompt =`Answer the question based on the following context. If the context doesn't contain the answer, say so.
9596Context:
97${contextText}9899Question: ${question}100101Answer:`;102103console.log('🤖 Generating answer...\n');104105// Generate completion106const completion =awaitthis.openai.chat.completions.create({107model:'gpt-4',108messages:[109{role:'system',content:'You are a helpful assistant that answers questions based on provided context.'},110{role:'user',content: prompt }111],112temperature:0.3// Lower temperature for more factual responses113});114115return{116answer: completion.choices[0].message.content,117sources: context.map(c=> c.title)118};119}120}121122// Example Usage123asyncfunctionmain(){124const rag =newRAGSystem();125126// Step 1: Index your knowledge base127const documents =[128{129id:'doc1',130title:'Ruvector Introduction',131content:'Ruvector is a high-performance vector database for Node.js built in Rust. It provides sub-millisecond query latency and supports over 52,000 inserts per second.',132source:'documentation'133},134{135id:'doc2',136title:'Vector Databases Explained',137content:'Vector databases store data as high-dimensional vectors, enabling semantic similarity search. They are essential for AI applications like RAG systems and recommendation engines.',138source:'blog'139},140{141id:'doc3',142title:'HNSW Algorithm',143content:'Hierarchical Navigable Small World (HNSW) is a graph-based algorithm for approximate nearest neighbor search. It provides excellent recall with low latency.',144source:'research'145}146];147148await rag.indexDocuments(documents);149150// Step 2: Ask questions151console.log('\n'+'='.repeat(60)+'\n');152153const result =await rag.answer('What is Ruvector and what are its performance characteristics?');154155console.log('📝 Answer:', result.answer);156console.log('\n📚 Sources:', result.sources.join(', '));157}158159main().catch(console.error);
Expected Output:
✅ RAG System initialized
📚 Indexing 3 documents...
✅ Indexed: Ruvector Introduction
✅ Indexed: Vector Databases Explained
✅ Indexed: HNSW Algorithm
✅ Indexed 3 documents total
============================================================
🔍 Searching for: "What is Ruvector and what are its performance characteristics?"
📄 Found 2 relevant documents
🤖 Generating answer...
📝 Answer: Ruvector is a high-performance vector database built in Rust for Node.js applications. Its key performance characteristics include:
- Sub-millisecond query latency
- Over 52,000 inserts per second
- Optimized for semantic similarity search
📚 Sources: Ruvector Introduction, Vector Databases Explained
Production Tips:
✅ Use batch embedding for better throughput (OpenAI supports up to 2048 texts)
✅ Implement caching for frequently asked questions
✅ Add error handling for API rate limits
✅ Monitor token usage and costs
✅ Regularly update your knowledge base
Tutorial 2: Semantic Search Engine
What you'll learn: Build a semantic search engine that understands meaning, not just keywords.
Prerequisites:
npm install ruvector @xenova/transformers
Complete Implementation:
javascript
1const{VectorDb}=require('ruvector');2const{ pipeline }=require('@xenova/transformers');34classSemanticSearchEngine{5constructor(){6this.db=null;7this.embedder=null;8}910// Step 1: Initialize the embedding model11asyncinitialize(){12console.log('🚀 Initializing semantic search engine...');1314// Load sentence-transformers model (runs locally, no API needed!)15console.log('📥 Loading embedding model...');16this.embedder=awaitpipeline(17'feature-extraction',18'Xenova/all-MiniLM-L6-v2'19);2021// Create vector database (384 dimensions for all-MiniLM-L6-v2)22this.db=newVectorDb({23dimensions:384,24maxElements:50000,25storagePath:'./semantic-search.db'26});2728console.log('✅ Search engine ready!\n');29}3031// Step 2: Generate embeddings32asyncembed(text){33const output =awaitthis.embedder(text,{34pooling:'mean',35normalize:true36});3738// Convert to Float32Array39returnnewFloat32Array(output.data);40}4142// Step 3: Index documents43asyncindexDocuments(documents){44console.log(`📚 Indexing ${documents.length} documents...`);4546for(const doc of documents){47const vector =awaitthis.embed(doc.content);4849awaitthis.db.insert({50id: doc.id,51vector: vector,52metadata:{53title: doc.title,54content: doc.content,55category: doc.category,56url: doc.url57}58});5960console.log(` ✅ ${doc.title}`);61}6263const count =awaitthis.db.len();64console.log(`\n✅ Indexed ${count} documents\n`);65}6667// Step 4: Semantic search68asyncsearch(query, options ={}){69const{70 k =5,71 category =null,72 threshold =0.373}= options;7475console.log(`🔍 Searching for: "${query}"`);7677// Generate query embedding78const queryVector =awaitthis.embed(query);7980// Search vector database81const results =awaitthis.db.search({82vector: queryVector,83k: k *2,// Get more results for filtering84threshold: threshold
85});8687// Filter by category if specified88let filtered = results;89if(category){90 filtered = results.filter(r=> r.metadata.category=== category);91}9293// Return top k after filtering94const final = filtered.slice(0, k);9596console.log(`📄 Found ${final.length} results\n`);9798return final.map(r=>({99id: r.id,100title: r.metadata.title,101content: r.metadata.content,102category: r.metadata.category,103score: r.score,104url: r.metadata.url105}));106}107108// Step 5: Find similar documents109asyncfindSimilar(documentId, k =5){110const doc =awaitthis.db.get(documentId);111112if(!doc){113thrownewError(`Document ${documentId} not found`);114}115116const results =awaitthis.db.search({117vector: doc.vector,118k: k +1// +1 because the document itself will be included119});120121// Remove the document itself from results122return results
123.filter(r=> r.id!== documentId)124.slice(0, k);125}126}127128// Example Usage129asyncfunctionmain(){130const engine =newSemanticSearchEngine();131await engine.initialize();132133// Sample documents (in production, load from your database)134const documents =[135{136id:'1',137title:'Understanding Neural Networks',138content:'Neural networks are computing systems inspired by biological neural networks. They learn to perform tasks by considering examples.',139category:'AI',140url:'/docs/neural-networks'141},142{143id:'2',144title:'Introduction to Machine Learning',145content:'Machine learning is a subset of artificial intelligence that provides systems the ability to learn and improve from experience.',146category:'AI',147url:'/docs/machine-learning'148},149{150id:'3',151title:'Web Development Best Practices',152content:'Modern web development involves responsive design, performance optimization, and accessibility considerations.',153category:'Web',154url:'/docs/web-dev'155},156{157id:'4',158title:'Deep Learning Applications',159content:'Deep learning has revolutionized computer vision, natural language processing, and speech recognition.',160category:'AI',161url:'/docs/deep-learning'162}163];164165// Index documents166await engine.indexDocuments(documents);167168// Example 1: Basic semantic search169console.log('Example 1: Basic Search\n'+'='.repeat(60));170const results1 =await engine.search('AI and neural nets');171 results1.forEach((result, i)=>{172console.log(`${i +1}. ${result.title} (Score: ${result.score.toFixed(3)})`);173console.log(`${result.content.slice(0,80)}...`);174console.log(` Category: ${result.category}\n`);175});176177// Example 2: Category-filtered search178console.log('\nExample 2: Category-Filtered Search\n'+'='.repeat(60));179const results2 =await engine.search('learning algorithms',{180category:'AI',181k:3182});183 results2.forEach((result, i)=>{184console.log(`${i +1}. ${result.title} (Score: ${result.score.toFixed(3)})`);185});186187// Example 3: Find similar documents188console.log('\n\nExample 3: Find Similar Documents\n'+'='.repeat(60));189const similar =await engine.findSimilar('1',2);190console.log('Documents similar to "Understanding Neural Networks":');191 similar.forEach((doc, i)=>{192console.log(`${i +1}. ${doc.metadata.title} (Score: ${doc.score.toFixed(3)})`);193});194}195196main().catch(console.error);
Key Features:
✅ Runs completely locally (no API keys needed)
✅ Understands semantic meaning, not just keywords
✅ Category filtering for better results
✅ "Find similar" functionality
✅ Fast: ~10ms query latency
Tutorial 3: AI Agent Memory System
What you'll learn: Implement a memory system for AI agents that remembers past experiences and learns from them.
Complete Implementation:
javascript
1const{VectorDb}=require('ruvector');23classAgentMemory{4constructor(agentId){5this.agentId= agentId;67// Create separate databases for different memory types8this.episodicMemory=newVectorDb({9dimensions:768,10storagePath:`./memory/${agentId}-episodic.db`11});1213this.semanticMemory=newVectorDb({14dimensions:768,15storagePath:`./memory/${agentId}-semantic.db`16});1718console.log(`🧠 Memory system initialized for agent: ${agentId}`);19}2021// Step 1: Store an experience (episodic memory)22asyncstoreExperience(experience){23const{24 state,25 action,26 result,27 reward,28 embedding
29}= experience;3031const experienceId =`exp_${Date.now()}_${Math.random()}`;3233awaitthis.episodicMemory.insert({34id: experienceId,35vector:newFloat32Array(embedding),36metadata:{37state: state,38action: action,39result: result,40reward: reward,41timestamp:Date.now(),42type:'episodic'43}44});4546console.log(`💾 Stored experience: ${action} -> ${result} (reward: ${reward})`);47return experienceId;48}4950// Step 2: Store learned knowledge (semantic memory)51asyncstoreKnowledge(knowledge){52const{53 concept,54 description,55 embedding,56 confidence =1.057}= knowledge;5859const knowledgeId =`know_${Date.now()}`;6061awaitthis.semanticMemory.insert({62id: knowledgeId,63vector:newFloat32Array(embedding),64metadata:{65concept: concept,66description: description,67confidence: confidence,68learned:Date.now(),69uses:0,70type:'semantic'71}72});7374console.log(`📚 Learned: ${concept}`);75return knowledgeId;76}7778// Step 3: Recall similar experiences79asyncrecallExperiences(currentState, k =5){80console.log(`🔍 Recalling similar experiences...`);8182const results =awaitthis.episodicMemory.search({83vector:newFloat32Array(currentState.embedding),84k: k,85threshold:0.6// Only recall reasonably similar experiences86});8788// Sort by reward to prioritize successful experiences89const sorted = results.sort((a, b)=> b.metadata.reward- a.metadata.reward);9091console.log(`📝 Recalled ${sorted.length} relevant experiences`);9293return sorted.map(r=>({94state: r.metadata.state,95action: r.metadata.action,96result: r.metadata.result,97reward: r.metadata.reward,98similarity: r.score99}));100}101102// Step 4: Query knowledge base103asyncqueryKnowledge(query, k =3){104const results =awaitthis.semanticMemory.search({105vector:newFloat32Array(query.embedding),106k: k
107});108109// Update usage statistics110for(const result of results){111const knowledge =awaitthis.semanticMemory.get(result.id);112if(knowledge){113 knowledge.metadata.uses+=1;114// In production, update the entry115}116}117118return results.map(r=>({119concept: r.metadata.concept,120description: r.metadata.description,121confidence: r.metadata.confidence,122relevance: r.score123}));124}125126// Step 5: Reflect and learn from experiences127asyncreflect(){128console.log('\n🤔 Reflecting on experiences...');129130// Get all experiences131const totalExperiences =awaitthis.episodicMemory.len();132console.log(`📊 Total experiences: ${totalExperiences}`);133134// Analyze success rate135// In production, you'd aggregate experiences and extract patterns136console.log('💡 Analysis complete');137138return{139totalExperiences: totalExperiences,140knowledgeItems:awaitthis.semanticMemory.len()141};142}143144// Step 6: Get memory statistics145asyncgetStats(){146return{147episodicMemorySize:awaitthis.episodicMemory.len(),148semanticMemorySize:awaitthis.semanticMemory.len(),149agentId:this.agentId150};151}152}153154// Example Usage: Simulated agent learning to navigate155asyncfunctionmain(){156const agent =newAgentMemory('agent-001');157158// Simulate embedding function (in production, use a real model)159functionembed(text){160returnArray(768).fill(0).map(()=>Math.random());161}162163console.log('\n'+'='.repeat(60));164console.log('PHASE 1: Learning from experiences');165console.log('='.repeat(60)+'\n');166167// Store some experiences168await agent.storeExperience({169state:{location:'room1',goal:'room3'},170action:'move_north',171result:'reached room2',172reward:0.5,173embedding:embed('navigating from room1 to room2')174});175176await agent.storeExperience({177state:{location:'room2',goal:'room3'},178action:'move_east',179result:'reached room3',180reward:1.0,181embedding:embed('navigating from room2 to room3')182});183184await agent.storeExperience({185state:{location:'room1',goal:'room3'},186action:'move_south',187result:'hit wall',188reward:-0.5,189embedding:embed('failed navigation attempt')190});191192// Store learned knowledge193await agent.storeKnowledge({194concept:'navigation_strategy',195description:'Moving north then east is efficient for reaching room3 from room1',196embedding:embed('navigation strategy knowledge'),197confidence:0.9198});199200console.log('\n'+'='.repeat(60));201console.log('PHASE 2: Applying memory');202console.log('='.repeat(60)+'\n');203204// Agent encounters a similar situation205const currentState ={206location:'room1',207goal:'room3',208embedding:embed('navigating from room1 to room3')209};210211// Recall relevant experiences212const experiences =await agent.recallExperiences(currentState,3);213214console.log('\n📖 Recalled experiences:');215 experiences.forEach((exp, i)=>{216console.log(`${i +1}. Action: ${exp.action} | Result: ${exp.result} | Reward: ${exp.reward} | Similarity: ${exp.similarity.toFixed(3)}`);217});218219// Query relevant knowledge220const knowledge =await agent.queryKnowledge({221embedding:embed('how to navigate efficiently')222},2);223224console.log('\n📚 Relevant knowledge:');225 knowledge.forEach((k, i)=>{226console.log(`${i +1}. ${k.concept}: ${k.description} (confidence: ${k.confidence})`);227});228229console.log('\n'+'='.repeat(60));230console.log('PHASE 3: Reflection');231console.log('='.repeat(60)+'\n');232233// Reflect on learning234const stats =await agent.reflect();235const memoryStats =await agent.getStats();236237console.log('\n📊 Memory Statistics:');238console.log(` Episodic memories: ${memoryStats.episodicMemorySize}`);239console.log(` Semantic knowledge: ${memoryStats.semanticMemorySize}`);240console.log(` Agent ID: ${memoryStats.agentId}`);241}242243main().catch(console.error);
1// Cosine similarity (default, best for normalized vectors)2const db1 =newVectorDb({3dimensions:128,4distanceMetric:'cosine'5});67// Euclidean distance (L2, best for spatial data)8const db2 =newVectorDb({9dimensions:128,10distanceMetric:'euclidean'11});1213// Dot product (best for pre-normalized vectors)14const db3 =newVectorDb({15dimensions:128,16distanceMetric:'dot'17});
Persistence
javascript
1// Auto-save to disk2const persistent =newVectorDb({3dimensions:128,4storagePath:'./persistent.db'5});67// In-memory only (faster, but data lost on exit)8const temporary =newVectorDb({9dimensions:12810// No storagePath = in-memory11});
📦 Platform Support
Automatically installs the correct implementation for:
Ruvector integrates with RVF (RuVector Format) — a universal binary substrate that stores vectors, models, graphs, compute kernels, and attestation in a single .rvf file.
Enable RVF Backend
bash
1# Install the optional RVF package2npminstall @ruvector/rvf
34# Set backend via environment variable5exportRUVECTOR_BACKEND=rvf
67# Or detect automatically (native -> rvf -> wasm fallback)8npx ruvector info
typescript
1import{ getImplementationType, isRvf }from'ruvector';23console.log(getImplementationType());// 'native' | 'rvf' | 'wasm'4console.log(isRvf());// true if RVF backend is active
RVF CLI Commands
8 RVF-specific subcommands are available through the ruvector CLI:
A single .rvf file that contains vectors AND a bootable Linux kernel:
bash
1# Build and run the self-booting example2cd crates/rvf && cargo run --example self_booting
3# Output:4# Ingested 50 vectors (128 dims)5# Pre-kernel query: top-5 results OK (nearest ID=25)6# Kernel: 4,640 bytes embedded (x86_64, Hermit)7# Witness chain: 5 entries, all verified8# File: bootable.rvf (31 KB) — data + runtime in one file
rust
1// The pattern: vectors + kernel + witness in one file2letmut store =RvfStore::create("bootable.rvf", options)?;3store.ingest_batch(&vectors,&ids,None)?;4store.embed_kernel(KernelArch::X86_64asu8,KernelType::Hermitasu8,50x0018,&kernel_image,8080,Some("console=ttyS0 quiet"))?;6// Result: drop on a VM and it boots as a query service
Linux Microkernel Distribution
20-package Linux distro with SSH keys and kernel in a single file:
bash
1cd crates/rvf && cargo run --example linux_microkernel
2# Output:3# Installed 20 packages as vector embeddings4# Kernel embedded: Linux x86_64 (4,640 bytes)5# SSH keys: Ed25519, signed and verified6# Witness chain: 22 entries (1 per package + kernel + SSH)7# File: microkernel.rvf (14 KB) — immutable bootable system
Features: package search by embedding similarity, Ed25519 signed SSH keys, witness-audited installs, COW-derived child images for atomic updates.
Claude Code AI Appliance
A sealed, bootable AI development environment:
bash
1cd crates/rvf && cargo run --example claude_code_appliance
2# Output:3# 20 dev packages (rust, node, python, docker, ...)4# Kernel: Linux x86_64 with SSH on port 22225# eBPF: XDP distance program for fast-path lookups6# Witness chain: 6 entries, all verified7# Crypto: Ed25519 signature8# File: claude_code_appliance.rvf (17 KB)