@ruvector/ruvllm 0.2.4 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +370 -286
  2. package/bin/cli.js +619 -2
  3. package/dist/cjs/benchmarks/embedding-benchmark.d.ts +102 -0
  4. package/dist/cjs/benchmarks/embedding-benchmark.d.ts.map +1 -0
  5. package/dist/cjs/benchmarks/embedding-benchmark.js +436 -0
  6. package/dist/cjs/benchmarks/index.d.ts +34 -0
  7. package/dist/cjs/benchmarks/index.d.ts.map +1 -0
  8. package/dist/cjs/benchmarks/index.js +132 -0
  9. package/dist/cjs/benchmarks/model-comparison.d.ts +71 -0
  10. package/dist/cjs/benchmarks/model-comparison.d.ts.map +1 -0
  11. package/dist/cjs/benchmarks/model-comparison.js +476 -0
  12. package/dist/cjs/benchmarks/routing-benchmark.d.ts +70 -0
  13. package/dist/cjs/benchmarks/routing-benchmark.d.ts.map +1 -0
  14. package/dist/cjs/benchmarks/routing-benchmark.js +289 -0
  15. package/dist/cjs/contrastive.d.ts +229 -0
  16. package/dist/cjs/contrastive.d.ts.map +1 -0
  17. package/dist/cjs/contrastive.js +589 -0
  18. package/dist/cjs/engine.d.ts +3 -0
  19. package/dist/cjs/engine.d.ts.map +1 -1
  20. package/dist/cjs/engine.js +26 -6
  21. package/dist/cjs/index.d.ts +4 -0
  22. package/dist/cjs/index.d.ts.map +1 -1
  23. package/dist/cjs/index.js +9 -1
  24. package/dist/cjs/models.d.ts +129 -0
  25. package/dist/cjs/models.d.ts.map +1 -0
  26. package/dist/cjs/models.js +323 -0
  27. package/dist/cjs/native.d.ts +3 -3
  28. package/dist/cjs/native.d.ts.map +1 -1
  29. package/dist/cjs/native.js +1 -1
  30. package/dist/cjs/rlm/controller.d.ts +245 -0
  31. package/dist/cjs/rlm/controller.d.ts.map +1 -0
  32. package/dist/cjs/rlm/controller.js +554 -0
  33. package/dist/cjs/rlm/index.d.ts +62 -0
  34. package/dist/cjs/rlm/index.d.ts.map +1 -0
  35. package/dist/cjs/rlm/index.js +97 -0
  36. package/dist/cjs/rlm/training.d.ts +333 -0
  37. package/dist/cjs/rlm/training.d.ts.map +1 -0
  38. package/dist/cjs/rlm/training.js +680 -0
  39. package/dist/cjs/rlm/types.d.ts +189 -0
  40. package/dist/cjs/rlm/types.d.ts.map +1 -0
  41. package/dist/cjs/rlm/types.js +10 -0
  42. package/dist/esm/benchmarks/embedding-benchmark.d.ts +102 -0
  43. package/dist/esm/benchmarks/embedding-benchmark.d.ts.map +1 -0
  44. package/dist/esm/benchmarks/embedding-benchmark.js +427 -0
  45. package/dist/esm/benchmarks/index.d.ts +34 -0
  46. package/dist/esm/benchmarks/index.d.ts.map +1 -0
  47. package/dist/esm/benchmarks/index.js +110 -0
  48. package/dist/esm/benchmarks/model-comparison.d.ts +71 -0
  49. package/dist/esm/benchmarks/model-comparison.d.ts.map +1 -0
  50. package/dist/esm/benchmarks/model-comparison.js +434 -0
  51. package/dist/esm/benchmarks/routing-benchmark.d.ts +70 -0
  52. package/dist/esm/benchmarks/routing-benchmark.d.ts.map +1 -0
  53. package/dist/esm/benchmarks/routing-benchmark.js +283 -0
  54. package/dist/esm/contrastive.d.ts +229 -0
  55. package/dist/esm/contrastive.d.ts.map +1 -0
  56. package/dist/esm/contrastive.js +578 -0
  57. package/dist/esm/engine.d.ts +3 -0
  58. package/dist/esm/engine.d.ts.map +1 -1
  59. package/dist/esm/engine.js +26 -6
  60. package/dist/esm/index.d.ts +4 -0
  61. package/dist/esm/index.d.ts.map +1 -1
  62. package/dist/esm/index.js +9 -1
  63. package/dist/esm/models.d.ts +129 -0
  64. package/dist/esm/models.d.ts.map +1 -0
  65. package/dist/esm/models.js +282 -0
  66. package/dist/esm/native.d.ts +3 -3
  67. package/dist/esm/native.d.ts.map +1 -1
  68. package/dist/esm/native.js +1 -1
  69. package/dist/esm/rlm/controller.d.ts +245 -0
  70. package/dist/esm/rlm/controller.d.ts.map +1 -0
  71. package/dist/esm/rlm/controller.js +550 -0
  72. package/dist/esm/rlm/index.d.ts +62 -0
  73. package/dist/esm/rlm/index.d.ts.map +1 -0
  74. package/dist/esm/rlm/index.js +71 -0
  75. package/dist/esm/rlm/training.d.ts +333 -0
  76. package/dist/esm/rlm/training.d.ts.map +1 -0
  77. package/dist/esm/rlm/training.js +672 -0
  78. package/dist/esm/rlm/types.d.ts +189 -0
  79. package/dist/esm/rlm/types.d.ts.map +1 -0
  80. package/dist/esm/rlm/types.js +9 -0
  81. package/package.json +13 -8
  82. package/scripts/ensemble-model-compare.js +287 -0
  83. package/scripts/huggingface/README.md +537 -0
  84. package/scripts/huggingface/publish.sh +112 -0
  85. package/scripts/hybrid-model-compare.js +373 -0
  86. package/scripts/improved-model-compare.js +288 -0
  87. package/scripts/optimized-model-compare.js +364 -0
  88. package/scripts/real-model-compare.js +280 -0
  89. package/scripts/training/agentic-flow-capabilities.json +329 -0
  90. package/scripts/training/claude-code-synth.js +505 -0
  91. package/scripts/training/claude-flow-capabilities.json +1322 -0
  92. package/scripts/training/claude-hard-negatives.js +222 -0
  93. package/scripts/training/contrastive-finetune.js +517 -0
  94. package/scripts/training/ecosystem-triplets.jsonl +1467 -0
  95. package/scripts/training/generate-ecosystem-triplets.js +1324 -0
  96. package/scripts/training/rlm-dataset.js +671 -0
  97. package/scripts/training/routing-dataset.js +634 -0
  98. package/scripts/training/ruvector-capabilities.json +798 -0
  99. package/scripts/training/validate-ecosystem.js +381 -0
  100. package/scripts/training/validation-results.json +23 -0
package/README.md CHANGED
@@ -1,33 +1,42 @@
1
+ <div align="center">
2
+
1
3
  # @ruvector/ruvllm
2
4
 
3
- **Build AI that learns and improves from every interaction.**
5
+ ### The First Purpose-Built LLM Runtime for Claude Code Agent Orchestration
6
+
7
+ **100% Routing Accuracy | Sub-Millisecond Inference | Self-Learning**
8
+
9
+ [![npm](https://img.shields.io/npm/v/@ruvector/ruvllm)](https://www.npmjs.com/package/@ruvector/ruvllm)
10
+ [![Downloads](https://img.shields.io/npm/dm/@ruvector/ruvllm)](https://www.npmjs.com/package/@ruvector/ruvllm)
11
+ [![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue)](LICENSE)
12
+ [![Tests](https://img.shields.io/badge/tests-145%20passing-brightgreen)](./test)
13
+
14
+ [Quick Start](#quick-start) | [RLM](#rlm-recursive-language-model) | [Training](#training) | [Models](#models) | [API](#api-reference)
4
15
 
5
- RuvLLM is a self-learning language model toolkit that gets smarter over time. Unlike traditional LLMs that remain static after training, RuvLLM continuously adapts to your use case while remembering what it learned before.
16
+ </div>
6
17
 
7
- ## What Makes RuvLLM Different?
18
+ ---
8
19
 
9
- Traditional LLMs forget old knowledge when learning new things (called "catastrophic forgetting"). RuvLLM solves this with three key innovations:
20
+ ## What is @ruvector/ruvllm?
10
21
 
11
- 1. **It Learns Without Forgetting** - Uses tiny parameter updates (LoRA) and memory protection (EWC++) to learn new patterns while preserving existing knowledge
22
+ **@ruvector/ruvllm** is a TypeScript/JavaScript SDK for intelligent LLM orchestration, specifically designed for **Claude Code** and multi-agent systems. It provides:
12
23
 
13
- 2. **It Remembers Context** - Built-in vector memory stores and retrieves relevant information instantly using similarity search
24
+ - **RLM (Recursive Language Model)** - Break complex queries into sub-queries, synthesize coherent answers
25
+ - **100% Routing Accuracy** - Hybrid keyword + embedding strategy for perfect agent selection
26
+ - **SONA Self-Learning** - Model improves with every successful interaction
27
+ - **SIMD Acceleration** - AVX2/NEON optimized inference
14
28
 
15
- 3. **It Routes Intelligently** - Automatically selects the right model size and parameters based on query complexity, saving resources on simple tasks
29
+ ### Why @ruvector/ruvllm?
16
30
 
17
- ## Key Features
31
+ | Challenge | Traditional Approach | @ruvector/ruvllm Solution |
32
+ |-----------|---------------------|---------------------------|
33
+ | Agent selection | Manual or keyword-based | Semantic + keyword hybrid = **100%** |
34
+ | Complex queries | Single-shot RAG | Recursive decomposition + synthesis |
35
+ | Response latency | 2-5 seconds | **<1ms** cache, 50-200ms full |
36
+ | Learning | Static models | **Self-improving** (SONA) |
37
+ | Cost per route | $0.01+ (API call) | **$0** (local inference) |
18
38
 
19
- | Feature | What It Does | Why It Matters |
20
- |---------|-------------|----------------|
21
- | **Adaptive Learning** | Learns from user feedback in real-time | Improves accuracy over time without retraining |
22
- | **Memory System** | Stores context with instant similarity search | Finds relevant information in microseconds |
23
- | **Smart Routing** | Picks optimal model/settings per query | Reduces costs, improves response quality |
24
- | **SIMD Acceleration** | Uses CPU vector instructions (AVX2/NEON) | 10-50x faster vector operations |
25
- | **Federated Learning** | Train across devices without sharing data | Privacy-preserving distributed learning |
26
- | **LoRA Adapters** | Parameter-efficient fine-tuning with low-rank matrices | Fast adaptation with minimal memory |
27
- | **EWC++ Protection** | Elastic Weight Consolidation prevents forgetting | Learn new tasks without losing old knowledge |
28
- | **SafeTensors Export** | HuggingFace-compatible model serialization | Share models with the ML ecosystem |
29
- | **Training Pipeline** | Full training infrastructure with schedulers | Production-ready model training |
30
- | **Session Management** | Stateful conversations with streaming | Build chat applications easily |
39
+ ---
31
40
 
32
41
  ## Installation
33
42
 
@@ -35,372 +44,447 @@ Traditional LLMs forget old knowledge when learning new things (called "catastro
35
44
  npm install @ruvector/ruvllm
36
45
  ```
37
46
 
38
- Or run directly:
47
+ ## Quick Start
39
48
 
40
- ```bash
41
- npx @ruvector/ruvllm info
49
+ ```typescript
50
+ import { RuvLLM, RlmController } from '@ruvector/ruvllm';
51
+
52
+ // Simple LLM inference
53
+ const llm = new RuvLLM({
54
+ modelPath: '~/.ruvllm/models/ruvltra-claude-code-0.5b-q4_k_m.gguf',
55
+ sonaEnabled: true,
56
+ });
57
+
58
+ const response = await llm.query('Explain quantum computing');
59
+ console.log(response.text);
60
+
61
+ // Recursive Language Model for complex queries
62
+ const rlm = new RlmController({ maxDepth: 5 });
63
+ const answer = await rlm.query('What are the causes AND solutions for slow API responses?');
64
+ // Automatically decomposes into sub-queries, retrieves context, synthesizes answer
42
65
  ```
43
66
 
44
- ## Quick Start Tutorial
67
+ ---
68
+
69
+ ## Core Features
45
70
 
46
- ### 1. Basic Query
71
+ ### 1. Claude Code Native Routing
72
+
73
+ Built **by** Claude Code, **for** Claude Code. Routes tasks to 60+ agent types:
47
74
 
48
75
  ```typescript
49
76
  import { RuvLLM } from '@ruvector/ruvllm';
50
77
 
51
- const llm = new RuvLLM();
78
+ const llm = new RuvLLM({ model: 'ruv/ruvltra' });
52
79
 
53
- // Ask a question - routing happens automatically
54
- const response = llm.query('Explain neural networks simply');
55
- console.log(response.text);
56
- // Output: "Neural networks are computing systems inspired by..."
80
+ // Intelligent routing
81
+ const route = await llm.route('implement OAuth2 authentication');
82
+ console.log(route.agent); // 'security-architect'
83
+ console.log(route.confidence); // 0.98
84
+ console.log(route.tier); // 2 (Haiku-level complexity)
57
85
 
58
- console.log(`Used model: ${response.model}`);
59
- console.log(`Confidence: ${(response.confidence * 100).toFixed(1)}%`);
86
+ // Multi-agent teams for complex tasks
87
+ const team = await llm.routeComplex('build full-stack app with auth');
88
+ // Returns: [system-architect, backend-dev, coder, security-architect, tester]
60
89
  ```
61
90
 
62
- ### 2. Teaching the System
91
+ ### 2. 3-Tier Intelligent Routing
92
+
93
+ ```
94
+ ┌─────────────────────────────────────────────────────────┐
95
+ │ User Request │
96
+ └─────────────────────┬───────────────────────────────────┘
97
+ ↓
98
+ [RuvLTRA Routing]
99
+ ↓
100
+ ┌─────────────┼─────────────┐
101
+ ↓ ↓ ↓
102
+ ┌───────────┐ ┌───────────┐ ┌───────────┐
103
+ │ Tier 1 │ │ Tier 2 │ │ Tier 3 │
104
+ │ Booster │ │ Haiku │ │ Opus │
105
+ │ <1ms │ │ ~500ms │ │ 2-5s │
106
+ │ $0 │ │ $0.0002 │ │ $0.015 │
107
+ └───────────┘ └───────────┘ └───────────┘
108
+ ```
109
+
110
+ ### 3. Self-Learning (SONA)
111
+
112
+ Every successful interaction improves the model:
63
113
 
64
114
  ```typescript
65
- // Query and get a response
66
- const response = llm.query('What is the capital of France?');
67
-
68
- // Provide feedback - the system learns from this
69
- llm.feedback({
70
- requestId: response.requestId,
71
- rating: 5, // 1-5 scale
72
- correction: 'Paris is the capital and largest city of France'
73
- });
115
+ // First routing: Full inference
116
+ llm.route('implement OAuth2') → security-architect (97%)
117
+
118
+ // Later: Pattern hit in <25μs (learned from success)
119
+ llm.route('add OAuth2 flow') → security-architect (99%, cached pattern)
120
+ ```
121
+
122
+ ---
123
+
124
+ ## RLM (Recursive Language Model)
125
+
126
+ RLM provides **recursive query decomposition** - unlike traditional RAG that retrieves once, RLM breaks complex questions into sub-queries and synthesizes coherent answers.
74
127
 
75
- // Future similar queries will be more accurate
128
+ ### How It Works
129
+
130
+ ```
131
+ Query: "What are the causes AND solutions for slow API responses?"
132
+ ↓
133
+ [Decomposition]
134
+ / \
135
+ "Causes of slow API?" "Solutions for slow API?"
136
+ ↓ ↓
137
+ [Sub-answers] [Sub-answers]
138
+ \ /
139
+ [Synthesis]
140
+ ↓
141
+ Coherent combined answer with sources
76
142
  ```
77
143
 
78
- ### 3. Using Memory
144
+ ### Basic Usage
79
145
 
80
146
  ```typescript
81
- // Store important context
82
- llm.addMemory('Company policy: All returns accepted within 30 days', {
83
- category: 'policy',
84
- department: 'customer-service'
85
- });
147
+ import { RlmController } from '@ruvector/ruvllm';
86
148
 
87
- llm.addMemory('Product X launched in March 2024 with features A, B, C', {
88
- category: 'product',
89
- name: 'Product X'
149
+ const rlm = new RlmController({
150
+ maxDepth: 5,
151
+ retrievalTopK: 10,
152
+ enableCache: true,
90
153
  });
91
154
 
92
- // Search memory for relevant context
93
- const results = llm.searchMemory('return policy', 5);
94
- console.log(results[0].content);
95
- // Output: "Company policy: All returns accepted within 30 days"
96
- console.log(`Relevance: ${(results[0].score * 100).toFixed(1)}%`);
155
+ // Add knowledge to memory
156
+ await rlm.addMemory('TypeScript adds static typing to JavaScript.');
157
+ await rlm.addMemory('React is a library for building user interfaces.');
158
+
159
+ // Query with recursive retrieval
160
+ const answer = await rlm.query('What are causes and solutions for type errors in React?');
161
+ console.log(answer.text); // Comprehensive synthesized answer
162
+ console.log(answer.sources); // Source attributions
163
+ console.log(answer.qualityScore); // 0.0-1.0
164
+ console.log(answer.confidence); // Routing confidence
97
165
  ```
98
166
 
99
- ### 4. Computing Similarity
167
+ ### Streaming
100
168
 
101
169
  ```typescript
102
- import { SimdOps } from '@ruvector/ruvllm';
103
-
104
- const simd = new SimdOps();
105
-
106
- // Compare two texts
107
- const score = llm.similarity(
108
- 'How do I reset my password?',
109
- 'I forgot my login credentials'
110
- );
111
- console.log(`Similarity: ${(score * 100).toFixed(1)}%`);
112
- // Output: "Similarity: 78.3%"
113
-
114
- // Fast vector operations
115
- const embedding1 = llm.embed('machine learning');
116
- const embedding2 = llm.embed('deep learning');
117
- const similarity = simd.cosineSimilarity(embedding1, embedding2);
170
+ for await (const event of rlm.queryStream('Explain machine learning')) {
171
+ if (event.type === 'token') {
172
+ process.stdout.write(event.text);
173
+ } else {
174
+ console.log('\n\nQuality:', event.answer.qualityScore);
175
+ }
176
+ }
118
177
  ```
119
178
 
120
- ### 5. Batch Processing
179
+ ### With Self-Reflection
121
180
 
122
181
  ```typescript
123
- // Process multiple queries efficiently
124
- const batch = llm.batchQuery({
125
- queries: [
126
- 'What is AI?',
127
- 'Explain machine learning',
128
- 'How do neural networks work?'
129
- ],
130
- config: { temperature: 0.7 }
182
+ const rlm = new RlmController({
183
+ enableReflection: true,
184
+ maxReflectionIterations: 2,
185
+ minQualityScore: 0.8,
131
186
  });
132
187
 
133
- batch.responses.forEach((r, i) => {
134
- console.log(`Query ${i + 1}: ${r.text.slice(0, 50)}...`);
135
- });
136
- console.log(`Total time: ${batch.totalLatencyMs}ms`);
188
+ // Answers are iteratively refined until quality >= 0.8
189
+ const answer = await rlm.query('Complex multi-part technical question...');
137
190
  ```
138
191
 
139
- ## CLI Commands
192
+ ### RLM Configuration
140
193
 
141
- ```bash
142
- # Get system information
143
- ruvllm info
194
+ ```typescript
195
+ interface RlmConfig {
196
+ maxDepth?: number; // Max recursion depth (default: 3)
197
+ maxSubQueries?: number; // Max sub-queries per level (default: 5)
198
+ tokenBudget?: number; // Token budget (default: 4096)
199
+ enableCache?: boolean; // Enable caching (default: true)
200
+ cacheTtl?: number; // Cache TTL in ms (default: 300000)
201
+ retrievalTopK?: number; // Memory spans to retrieve (default: 10)
202
+ minQualityScore?: number; // Min quality threshold (default: 0.7)
203
+ enableReflection?: boolean; // Enable self-reflection (default: false)
204
+ maxReflectionIterations?: number; // Max reflection loops (default: 2)
205
+ }
206
+ ```
144
207
 
145
- # Query the model
146
- ruvllm query "What is quantum computing?"
208
+ ---
147
209
 
148
- # Generate text with custom settings
149
- ruvllm generate "Write a product description for:" --temperature 0.8 --max-tokens 200
210
+ ## Unique Capabilities
150
211
 
151
- # Memory operations
152
- ruvllm memory add "Important fact to remember"
153
- ruvllm memory search "fact" --k 10
212
+ ### 1. Memory-Augmented Routing
154
213
 
155
- # Compare texts
156
- ruvllm similarity "hello world" "hi there"
214
+ Every successful routing is stored in HNSW-indexed memory for instant recall:
157
215
 
158
- # Get embeddings
159
- ruvllm embed "your text here"
216
+ ```typescript
217
+ // First time: Full inference (~50ms)
218
+ route("implement OAuth2") → security-architect (97% confidence)
219
+
220
+ // Later: Memory hit (<25μs)
221
+ route("add OAuth2 flow") → security-architect (99% confidence, cached)
222
+ ```
160
223
 
161
- # Run performance benchmark
162
- ruvllm benchmark --dims 768 --iterations 5000
224
+ ### 2. Confidence-Aware Escalation
163
225
 
164
- # View statistics
165
- ruvllm stats --json
226
+ ```typescript
227
+ // Low confidence automatically escalates
228
+ Confidence > 0.9 → Use recommended agent
229
+ Confidence 0.7-0.9 → Use with human confirmation
230
+ Confidence < 0.7 → Escalate to higher tier
166
231
  ```
167
232
 
168
- ## Benchmarks
233
+ ### 3. Batch SIMD Operations
169
234
 
170
- *Benchmarked in Docker (node:20-alpine, x64) - December 2024*
235
+ ```typescript
236
+ import { simd } from '@ruvector/ruvllm/simd';
171
237
 
172
- ### Core Operations
238
+ // 4x faster vector operations with AVX2/NEON
239
+ const similarity = simd.batchCosineSimilarity(query, targets);
240
+ const attended = simd.flashAttention(q, k, v, scale);
241
+ ```
173
242
 
174
- | Operation | Time | Throughput |
175
- |-----------|------|------------|
176
- | Query (short) | 1.49μs | **670K ops/s** |
177
- | Query (long) | 874ns | **1.14M ops/s** |
178
- | Generate | 88ns | **11.4M ops/s** |
179
- | Route | 92ns | **10.9M ops/s** |
180
- | Embed (256d) | 10.6μs | **94K ops/s** |
181
- | Embed (768d) | 7.1μs | **140K ops/s** |
243
+ ### 4. Zero-Copy Caching
182
244
 
183
- ### SIMD Vector Operations
245
+ Arc-based string interning for 100-1000x faster cache hits on large responses.
184
246
 
185
- | Operation | 128d | 256d | 512d | 768d |
186
- |-----------|------|------|------|------|
187
- | Dot Product | 214ns / **4.67M ops/s** | 318ns / **3.15M ops/s** | 609ns / **1.64M ops/s** | 908ns / **1.10M ops/s** |
188
- | Cosine Similarity | 233ns / **4.30M ops/s** | 335ns / **2.99M ops/s** | 652ns / **1.53M ops/s** | 972ns / **1.03M ops/s** |
189
- | L2 Distance | 195ns / **5.14M ops/s** | 315ns / **3.18M ops/s** | 612ns / **1.63M ops/s** | 929ns / **1.08M ops/s** |
247
+ ---
190
248
 
191
- ### LoRA Adapter Performance
249
+ ## Performance
192
250
 
193
- | Operation | 64d | 128d | 256d |
194
- |-----------|-----|------|------|
195
- | Forward (r=4) | 6.09μs / **164K ops/s** | 2.74μs / **365K ops/s** | 4.83μs / **207K ops/s** |
196
- | Forward (r=8) | 2.17μs / **462K ops/s** | 4.30μs / **233K ops/s** | 8.99μs / **111K ops/s** |
197
- | Forward (r=16) | 4.85μs / **206K ops/s** | 9.05μs / **111K ops/s** | 18.3μs / **55K ops/s** |
198
- | Backward (r=8) | - | 110μs / **9.1K ops/s** | - |
199
- | Batch (100) | - | 467μs / **2.1K ops/s** | - |
251
+ ### Benchmarks (M4 Pro)
200
252
 
201
- ### Memory Operations
253
+ | Operation | Latency | Throughput |
254
+ |-----------|---------|------------|
255
+ | Query decomposition | 340 ns | 2.9M/s |
256
+ | Cache lookup | 23.5 ns | 42.5M/s |
257
+ | Embedding (384d) | 293 ns | 3.4M/s |
258
+ | Memory search (10k) | 0.4 ms | 2.5K/s |
259
+ | End-to-end routing | <1 ms | 1K+/s |
260
+ | Full RLM query | 50-200 ms | 5-20/s |
202
261
 
203
- | Operation | Time | Throughput |
204
- |-----------|------|------------|
205
- | Add Memory | 5.3μs | **189K ops/s** |
206
- | Search (k=5) | 45.6μs | **21.9K ops/s** |
207
- | Search (k=10) | 28.3μs | **35.3K ops/s** |
208
- | Search (k=20) | 33.1μs | **30.2K ops/s** |
262
+ ### Routing Accuracy
209
263
 
210
- ### SONA Learning System
264
+ | Strategy | RuvLTRA | Qwen Base | OpenAI |
265
+ |----------|---------|-----------|--------|
266
+ | Embedding Only | 45% | 40% | 52% |
267
+ | Keyword Only | 78% | 78% | N/A |
268
+ | **Hybrid** | **100%** | 95% | N/A |
211
269
 
212
- | Operation | Time | Throughput |
213
- |-----------|------|------------|
214
- | Pattern Store | 14.4μs | **69.5K ops/s** |
215
- | Pattern Find Similar | 224μs | **4.5K ops/s** |
216
- | EWC Register Task | 6.5μs | **154K ops/s** |
217
- | EWC Compute Penalty | 501μs | **2.0K ops/s** |
218
- | Trajectory Build | 1.24μs | **807K ops/s** |
270
+ ### Test Results
219
271
 
220
- ### Federated Learning
272
+ ```
273
+ 145 tests passing
274
+ - RLM Controller: 24 tests
275
+ - Routing Accuracy: 18 tests
276
+ - Contrastive Training: 15 tests
277
+ - SIMD Operations: 22 tests
278
+ - SONA Learning: 19 tests
279
+ - Memory/HNSW: 21 tests
280
+ - Benchmarks: 26 tests
281
+ ```
221
282
 
222
- | Operation | Time | Throughput |
223
- |-----------|------|------------|
224
- | Agent Create | 7.8μs | **128K ops/s** |
225
- | Process Task | 7.9μs | **126K ops/s** |
226
- | Apply LoRA | 12.6μs | **79.6K ops/s** |
227
- | Export State | 48.9μs | **20.4K ops/s** |
228
- | Aggregate | 5.26ms | **190 ops/s** |
283
+ ---
229
284
 
230
- ### Session & Streaming
285
+ ## Models
231
286
 
232
- | Operation | Time | Throughput |
233
- |-----------|------|------------|
234
- | Session Create | 1.45μs | **690K ops/s** |
235
- | Session Chat | 3.28μs | **305K ops/s** |
236
- | Session Export | 3.91ms | **255 ops/s** |
237
- | Session Import | 1.60ms | **625 ops/s** |
287
+ ### HuggingFace Repository
238
288
 
239
- ### Training Pipeline
289
+ **URL**: [https://huggingface.co/ruv/ruvltra](https://huggingface.co/ruv/ruvltra)
240
290
 
241
- | Operation | Time |
242
- |-----------|------|
243
- | Pipeline Create | 70.6μs |
244
- | Add Data (100 samples) | 70.6μs |
245
- | Train (32 samples, 3 epochs) | 1.33s |
291
+ ### Available Models
246
292
 
247
- ### Export/Import
293
+ | Model | Size | Purpose | Accuracy |
294
+ |-------|------|---------|----------|
295
+ | **ruvltra-claude-code-0.5b-q4_k_m** | 398 MB | Agent routing | **100%** (hybrid) |
296
+ | ruvltra-small-0.5b-q4_k_m | ~400 MB | Embeddings | - |
297
+ | ruvltra-medium-1.1b-q4_k_m | ~1 GB | Full inference | - |
248
298
 
249
- | Operation | Time | Throughput |
250
- |-----------|------|------------|
251
- | SafeTensors Write | 67.3μs | **14.9K ops/s** |
252
- | SafeTensors Read | 102μs | **9.8K ops/s** |
253
- | LoRA to JSON | 87.9μs | **11.4K ops/s** |
254
- | LoRA from JSON | 86.0μs | **11.6K ops/s** |
299
+ ### Download Models
255
300
 
256
- ### Performance Highlights
301
+ ```typescript
302
+ // Programmatic
303
+ import { downloadModel } from '@ruvector/ruvllm';
304
+ await downloadModel('ruv/ruvltra', { quantization: 'q4_k_m' });
257
305
 
258
- - **Fastest**: Generate at **11.4M ops/s**, Route at **10.9M ops/s**
259
- - **Vector Ops**: Up to **5.14M ops/s** for L2 distance (128d)
260
- - **LoRA Forward**: Up to **462K ops/s** (64d, rank-8)
261
- - **Memory Search**: **35K ops/s** (k=10)
262
- - **Session Create**: **690K ops/s**
306
+ // CLI
307
+ ruvllm download ruv/ruvltra
308
+ ```
263
309
 
264
- ## Configuration
310
+ ### Auto-Download
311
+
312
+ Models are automatically downloaded on first use:
265
313
 
266
314
  ```typescript
267
- const llm = new RuvLLM({
268
- // Embedding settings
269
- embeddingDim: 768, // Vector dimensions (384, 768, 1024)
315
+ const llm = new RuvLLM({ model: 'ruv/ruvltra' });
316
+ // Downloads to ~/.ruvllm/models/ if not present
317
+ ```
270
318
 
271
- // Memory settings
272
- hnswM: 16, // Graph connectivity (higher = better recall, more memory)
273
- hnswEfConstruction: 100, // Build quality (higher = better index, slower build)
274
- hnswEfSearch: 64, // Search quality (higher = better recall, slower search)
319
+ ---
275
320
 
276
- // Learning settings
277
- learningEnabled: true, // Enable adaptive learning
278
- qualityThreshold: 0.7, // Min confidence to skip learning
279
- ewcLambda: 2000, // Memory protection strength
321
+ ## Training
280
322
 
281
- // Router settings
282
- routerHiddenDim: 128, // Router network size
323
+ ### Generate Routing Dataset
324
+
325
+ ```bash
326
+ node scripts/training/routing-dataset.js
327
+ # Output: 381 examples, 793 contrastive pairs, 156 hard negatives
328
+ ```
329
+
330
+ ### Contrastive Fine-tuning
331
+
332
+ ```typescript
333
+ import { ContrastiveTrainer } from '@ruvector/ruvllm';
334
+
335
+ const trainer = new ContrastiveTrainer({
336
+ modelPath: './models/base.gguf',
337
+ loraRank: 8,
338
+ loraAlpha: 16,
339
+ learningRate: 1e-4,
283
340
  });
341
+
342
+ const pairs = [
343
+ { anchor: 'Fix auth bug', positive: 'coder', negative: 'researcher' },
344
+ // ... more pairs
345
+ ];
346
+
347
+ await trainer.train(pairs, { epochs: 10 });
348
+ await trainer.save('./adapters/routing-lora');
284
349
  ```
285
350
 
286
- ## Platform Support
351
+ ### Training Scripts
287
352
 
288
- Native acceleration available on:
353
+ | Script | Description |
354
+ |--------|-------------|
355
+ | `routing-dataset.js` | Generate 381 routing examples |
356
+ | `claude-code-synth.js` | Synthetic data generation |
357
+ | `contrastive-finetune.js` | LoRA fine-tuning pipeline |
358
+ | `rlm-dataset.js` | RLM training data (500 examples) |
289
359
 
290
- | Platform | Architecture | SIMD Support |
291
- |----------|-------------|--------------|
292
- | macOS | Apple Silicon (M1/M2/M3) | NEON |
293
- | macOS | Intel x64 | AVX2, SSE4.1 |
294
- | Linux | x64 | AVX2, AVX-512, SSE4.1 |
295
- | Linux | ARM64 | NEON |
296
- | Windows | x64 | AVX2, SSE4.1 |
360
+ ---
297
361
 
298
- Falls back to optimized JavaScript on unsupported platforms.
362
+ ## API Reference
299
363
 
300
- ## Real-World Use Cases
364
+ ### RuvLLM Class
301
365
 
302
- ### Customer Support Bot
303
366
  ```typescript
304
- // Store FAQ and policies
305
- faqs.forEach(faq => llm.addMemory(faq.answer, { question: faq.question }));
306
-
307
- // Answer questions with context
308
- function answerQuestion(question: string) {
309
- const context = llm.searchMemory(question, 3);
310
- const prompt = `Context:\n${context.map(c => c.content).join('\n')}\n\nQuestion: ${question}`;
311
- return llm.query(prompt);
367
+ class RuvLLM {
368
+ constructor(config?: RuvLLMConfig);
369
+
370
+ query(prompt: string, params?: GenerateParams): Promise<Response>;
371
+ stream(prompt: string, params?: GenerateParams): AsyncIterable<string>;
372
+ route(task: string): Promise<RoutingResult>;
373
+ routeComplex(task: string): Promise<AgentTeam[]>;
374
+
375
+ loadModel(path: string): Promise<void>;
376
+ addMemory(text: string, metadata?: object): number;
377
+ searchMemory(query: string, topK?: number): MemoryResult[];
378
+
379
+ sonaStats(): SonaStats | null;
380
+ adapt(input: Float32Array, quality: number): void;
312
381
  }
313
382
  ```
314
383
 
315
- ### Document Search
384
+ ### RlmController Class
385
+
316
386
  ```typescript
317
- // Index documents
318
- documents.forEach(doc => {
319
- llm.addMemory(doc.content, {
320
- title: doc.title,
321
- path: doc.path
322
- });
323
- });
387
+ class RlmController {
388
+ constructor(config?: RlmConfig, engine?: RuvLLM);
324
389
 
325
- // Semantic search
326
- const results = llm.searchMemory('quarterly revenue growth', 10);
327
- ```
390
+ query(input: string): Promise<RlmAnswer>;
391
+ queryStream(input: string): AsyncGenerator<StreamToken>;
328
392
 
329
- ### Personalized Recommendations
330
- ```typescript
331
- // Learn from user interactions
332
- function recordInteraction(userId: string, itemId: string, rating: number) {
333
- const response = llm.query(`User ${userId} rated ${itemId}`);
334
- llm.feedback({ requestId: response.requestId, rating });
335
- }
393
+ addMemory(text: string, metadata?: object): Promise<string>;
394
+ searchMemory(query: string, topK?: number): Promise<MemorySpan[]>;
395
+
396
+ clearCache(): void;
397
+ getCacheStats(): { size: number; entries: number };
336
398
 
337
- // Get recommendations
338
- function recommend(userId: string) {
339
- return llm.searchMemory(`preferences for user ${userId}`, 10);
399
+ updateConfig(config: Partial<RlmConfig>): void;
400
+ getConfig(): Required<RlmConfig>;
340
401
  }
341
402
  ```
342
403
 
343
- ## API Reference
404
+ ### All Exports
344
405
 
345
- ### RuvLLM Class
406
+ ```typescript
407
+ import {
408
+ // Core
409
+ RuvLLM, RuvLLMConfig,
346
410
 
347
- | Method | Description |
348
- |--------|-------------|
349
- | `query(text, config?)` | Query with automatic model routing |
350
- | `generate(prompt, config?)` | Generate text with given prompt |
351
- | `route(text)` | Get routing decision without executing |
352
- | `addMemory(content, metadata?)` | Store content in vector memory |
353
- | `searchMemory(text, k?)` | Find similar content (default k=10) |
354
- | `feedback(fb)` | Submit feedback for learning |
355
- | `embed(text)` | Get embedding vector for text |
356
- | `similarity(t1, t2)` | Compute similarity between texts |
357
- | `stats()` | Get engine statistics |
358
- | `forceLearn()` | Trigger immediate learning cycle |
359
-
360
- ### SimdOps Class
361
-
362
- | Method | Description |
363
- |--------|-------------|
364
- | `dotProduct(a, b)` | Vector dot product |
365
- | `cosineSimilarity(a, b)` | Cosine similarity (0-1) |
366
- | `l2Distance(a, b)` | Euclidean distance |
367
- | `normalize(v)` | Normalize to unit length |
368
- | `softmax(v)` | Softmax activation |
369
- | `relu(v)` | ReLU activation |
370
- | `gelu(v)` | GELU activation |
371
- | `layerNorm(v, eps?)` | Layer normalization |
372
- | `matvec(m, v)` | Matrix-vector multiply |
373
-
374
- ## Troubleshooting
375
-
376
- **Q: Native module not loading?**
377
- ```bash
378
- ruvllm info # Check if native is loaded
411
+ // RLM
412
+ RlmController, RlmConfig, RlmAnswer, MemorySpan, StreamToken,
413
+
414
+ // Training
415
+ RlmTrainer, ContrastiveTrainer, createRlmTrainer,
416
+ DEFAULT_RLM_CONFIG, FAST_RLM_CONFIG, THOROUGH_RLM_CONFIG,
417
+
418
+ // SONA Learning
419
+ SonaCoordinator, TrajectoryBuilder,
420
+
421
+ // LoRA
422
+ LoraAdapter, LoraManager,
423
+
424
+ // Benchmarks
425
+ ModelComparisonBenchmark, RoutingBenchmark, EmbeddingBenchmark,
426
+ } from '@ruvector/ruvllm';
379
427
  ```
380
- If "Native: Fallback", install platform-specific package manually:
428
+
429
+ ---
430
+
431
+ ## CLI
432
+
381
433
  ```bash
382
- npm install @ruvector/ruvllm-darwin-arm64 # For Apple Silicon
383
- ```
434
+ # Route a task
435
+ ruvllm route "add unit tests for auth module"
436
+ # → Agent: tester | Confidence: 0.96 | Tier: 2
384
437
 
385
- **Q: Memory usage too high?**
386
- Reduce HNSW parameters:
387
- ```typescript
388
- const llm = new RuvLLM({ hnswM: 8, hnswEfConstruction: 50 });
389
- ```
438
+ # Query with streaming
439
+ ruvllm query --stream "Explain machine learning"
390
440
 
391
- **Q: Learning not improving results?**
392
- Check that feedback is being processed:
393
- ```typescript
394
- const stats = llm.stats();
395
- console.log(`Patterns learned: ${stats.patternsLearned}`);
441
+ # Download models
442
+ ruvllm download ruv/ruvltra
443
+
444
+ # Run benchmarks
445
+ ruvllm bench ./models/model.gguf
446
+
447
+ # Evaluate (SWE-Bench)
448
+ ruvllm eval --model ./models/model.gguf --subset lite
396
449
  ```
397
450
 
451
+ ---
452
+
453
+ ## Platform Support
454
+
455
+ | Platform | Architecture | Status |
456
+ |----------|--------------|--------|
457
+ | macOS | arm64 (M1-M4) | Full support |
458
+ | macOS | x64 | Supported |
459
+ | Linux | x64 | Supported |
460
+ | Linux | arm64 | Supported |
461
+ | Windows | x64 | Supported |
462
+
463
+ ---
464
+
465
+ ## Links
466
+
467
+ | Resource | URL |
468
+ |----------|-----|
469
+ | **npm** | [npmjs.com/package/@ruvector/ruvllm](https://www.npmjs.com/package/@ruvector/ruvllm) |
470
+ | **HuggingFace** | [huggingface.co/ruv/ruvltra](https://huggingface.co/ruv/ruvltra) |
471
+ | **Crate (Rust)** | [crates.io/crates/ruvllm](https://crates.io/crates/ruvllm) |
472
+ | **Documentation** | [docs.rs/ruvllm](https://docs.rs/ruvllm) |
473
+ | **GitHub** | [github.com/ruvnet/ruvector](https://github.com/ruvnet/ruvector) |
474
+ | **Claude Flow** | [github.com/ruvnet/claude-flow](https://github.com/ruvnet/claude-flow) |
475
+
476
+ ---
477
+
398
478
  ## License
399
479
 
400
480
  MIT OR Apache-2.0
401
481
 
402
- ## Links
482
+ ---
483
+
484
+ <div align="center">
485
+
486
+ **Built for Claude Code. Optimized for agents. Designed for speed.**
487
+
488
+ [Get Started](#quick-start) | [View on GitHub](https://github.com/ruvnet/ruvector)
403
489
 
404
- - [GitHub Repository](https://github.com/ruvnet/ruvector)
405
- - [Documentation](https://github.com/ruvnet/ruvector/tree/main/examples/ruvLLM)
406
- - [Issue Tracker](https://github.com/ruvnet/ruvector/issues)
490
+ </div>