adaptive-memory-multi-model-router 2.2.5 → 2.2.7

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 (52) hide show
  1. package/README.md +149 -116
  2. package/README.md.bak +836 -0
  3. package/assets/benchmark-results.png +0 -0
  4. package/assets/complexity-scoring-v2.png +0 -0
  5. package/assets/complexity-scoring.png +0 -0
  6. package/assets/cost-comparison-chart.png +0 -0
  7. package/assets/cost-comparison-v2.png +0 -0
  8. package/assets/feature-comparison-v2.png +0 -0
  9. package/assets/feature-comparison-v3.png +0 -0
  10. package/assets/provider-health-chart.png +0 -0
  11. package/assets/provider-health-v2.png +0 -0
  12. package/assets/routing-flow-v2.png +0 -0
  13. package/assets/routing-flow-v3.png +0 -0
  14. package/assets/routing-flow.png +0 -0
  15. package/assets/tier-distribution.png +0 -0
  16. package/benchmark-results.json +620 -46
  17. package/dist/cache/cacheKeyGenerator.d.ts +67 -0
  18. package/dist/cache/cacheKeyGenerator.d.ts.map +1 -0
  19. package/dist/cache/cacheKeyGenerator.js +211 -0
  20. package/dist/cache/cacheKeyGenerator.js.map +1 -0
  21. package/dist/cli.js +0 -0
  22. package/dist/cost/preCallCostEstimator.d.ts +114 -0
  23. package/dist/cost/preCallCostEstimator.d.ts.map +1 -0
  24. package/dist/cost/preCallCostEstimator.js +256 -0
  25. package/dist/cost/preCallCostEstimator.js.map +1 -0
  26. package/dist/inference/speculativeDecoding.d.ts +133 -0
  27. package/dist/inference/speculativeDecoding.d.ts.map +1 -0
  28. package/dist/inference/speculativeDecoding.js +276 -0
  29. package/dist/inference/speculativeDecoding.js.map +1 -0
  30. package/dist/providers/providerHealth.d.ts +117 -0
  31. package/dist/providers/providerHealth.d.ts.map +1 -0
  32. package/dist/providers/providerHealth.js +309 -0
  33. package/dist/providers/providerHealth.js.map +1 -0
  34. package/dist/routing/difficultyClassifier.d.ts +79 -0
  35. package/dist/routing/difficultyClassifier.d.ts.map +1 -0
  36. package/dist/routing/difficultyClassifier.js +329 -0
  37. package/dist/routing/difficultyClassifier.js.map +1 -0
  38. package/dist/sdk.d.ts +125 -0
  39. package/dist/sdk.d.ts.map +1 -0
  40. package/dist/sdk.js.map +1 -0
  41. package/package.json +2 -322
  42. package/scripts/run-mmlu-benchmark.js +176 -0
  43. package/scripts/run-provider-benchmark.js +244 -0
  44. package/src/cache/cacheKeyGenerator.ts +242 -0
  45. package/src/cost/preCallCostEstimator.ts +345 -0
  46. package/src/inference/speculativeDecoding.ts +373 -0
  47. package/src/providers/providerHealth.ts +397 -0
  48. package/src/routing/difficultyClassifier.ts +420 -0
  49. package/test/provider-test.js +69 -90
  50. package/test.js +43 -69
  51. package/test.js.bak +376 -0
  52. package/src/skills/__tests__/skill_manager.test.ts +0 -328
package/README.md CHANGED
@@ -54,7 +54,7 @@ npx a3m-router serve # OpenAI proxy at localhost:87
54
54
 
55
55
  ## Why A3M Router
56
56
 
57
- Every LLM router either uses ML (RouteLLM 1.5 GB, GPU required) or doesn't route at all (LiteLLM you pick the model). A3M Router is the only one that achieves near-ML accuracy with zero ML overhead, then adds memory, caching, guardrails, and cost tracking on top.
57
+ A3M Router uses multi-signal heuristic routing -- 12 keyword signals across 5 dimensions -- to classify query complexity and route to cost-effective providers. No ML model weights. No GPU required. Starts in <100ms.
58
58
 
59
59
  For **generative engine optimization** — synthesizing multiple AI models into a single coherent output — A3M Router pairs [MCTS workflow optimization](#mcts-workflow-optimization) for multi-agent orchestration with heuristic scoring for per-query routing. The result is a [generative AI pipeline](#generative-engine-optimization) that learns which models work best for each task type and dynamically assembles them without manual intervention.
60
60
 
@@ -62,6 +62,42 @@ For **generative engine optimization** — synthesizing multiple AI models into
62
62
  |:---|:---|:---|
63
63
  | Learns from your usage over time. Remembers which models work for your query types. Updates model quality scores with every real request using exponential moving average. No retraining. | 5-signal complexity scoring: **domain detection** (legal, medical, finance, security, architecture, ML research), **task indicators** (code, math, creative, multilingual), **query structure** (length, clauses, qualifiers), **action verb intensity**, **multi-step detection**. All regex + keyword. Zero ML weights. | **Semantic cache** — trigram Jaccard similarity skips duplicate LLM calls. **Guardrails** — 17-pattern prompt injection detection, PII detection & redaction, content filtering, hallucination checks. **Cost analytics** — per-provider spend, budget alerts, savings vs GPT-4o baseline. **Circuit breaker** — 3 failures → 60s cooldown, automatic provider failover. |
64
64
 
65
+ ## 📊 Visual Overview
66
+
67
+ ### Complete Routing Pipeline
68
+ ![Routing Flow](assets/routing-flow-v3.png)
69
+
70
+ ### Tier Distribution
71
+ ![Tier Distribution](assets/tier-distribution.png)
72
+
73
+ ### Benchmark Results
74
+ ![Benchmark Results](assets/benchmark-results.png)
75
+
76
+ ### Cost Comparison (10K queries/month)
77
+ ![Cost Comparison](assets/cost-comparison-v2.png)
78
+
79
+ ### Feature Comparison
80
+ ![Feature Comparison](assets/feature-comparison-v3.png)
81
+
82
+ ### Provider Health
83
+ ![Provider Health](assets/provider-health-v2.png)
84
+
85
+ ### Complexity Scoring
86
+ ![Complexity Scoring](assets/complexity-scoring-v2.png)
87
+
88
+ ### Key Metrics
89
+
90
+ | Metric | Value | Notes |
91
+ |--------|-------|-------|
92
+ | Routing latency | <4ms | Guardrails + Cache + Classifier + Selection |
93
+ | Cache hit rate | ~30% | Trigram Jaccard similarity |
94
+ | ±1 tier accuracy | 99.5% | 200-query internal benchmark |
95
+ | Cost savings | 74% vs GPT-4o | 10K queries/month |
96
+ | Package size | 19.5 KB | gzipped |
97
+ | Startup time | <100ms | No ML weights loading |
98
+
99
+
100
+
65
101
  ---
66
102
 
67
103
  ## Quick Start
@@ -204,49 +240,134 @@ User Query
204
240
  Routing Accuracy Comparison (200 queries)
205
241
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
206
242
  A3M Router ████████████████████████████████████████████████████ 99.5%
207
- RouteLLM ███████████████████████████████████████████ ~85%
208
243
 
209
244
  Package Size Comparison
210
245
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
211
246
  A3M Router █ 19.5 KB
212
247
  LiteLLM ████████████████████████████████ ~50 MB
213
- RouteLLM ████████████████████████████████████████████████████ ~1.5 GB
214
248
 
215
249
  Startup Time
216
250
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
217
251
  A3M Router ████ <100ms
218
252
  LiteLLM ████████████████ ~500ms
219
- RouteLLM ████████████████████████████████████████████████████ ~2s
220
253
  ```
221
254
 
222
255
  See full benchmark methodology at [`scripts/routing-benchmark-v2.js`](scripts/routing-benchmark-v2.js) or run it with `node scripts/routing-benchmark-v2.js`.
223
256
 
224
- , same methodology as [RouteLLM (arXiv:2404.06035)](https://arxiv.org/abs/2404.06035).
225
-
226
- | Metric | A3M Router | RouteLLM (BERT) |
257
+ | Metric | A3M Router | LiteLLM |
227
258
  |--------|:----------:|:---------------:|
228
- | **±1 tier accuracy** | **99.5%** | ~85% |
229
- | Exact tier match | 64.5% | Not published |
230
- | Cost savings vs all-premium | 61.6% | ~60-70% |
231
- | GPU required | No | Yes |
232
- | Model weights | 0 KB | 500 MB+ |
233
- | Package size | 19.5 KB gzipped | 1.5 GB+ |
234
- | Startup time | <100 ms | ~2 s |
259
+ | **±1 tier accuracy** | **99.5%** | N/A (manual) |
260
+ | Exact tier match | 64.5% | N/A |
261
+ | Cost savings vs all-premium | 61.6% | 0% (you pick) |
262
+ | GPU required | No | No |
263
+ | Model weights | 0 KB | 0 KB |
264
+ | Package size | 19.5 KB gzipped | ~50 MB |
265
+ | Startup time | <100 ms | ~500ms |
235
266
 
236
- RouteLLM scores from arXiv:2404.06035 on MT-Bench. Our scores on 200-query self-benchmark. Same methodology, different test set. Not directly comparable.
267
+ Internal benchmark on 200-query test set. LiteLLM requires manual model selection.
237
268
 
238
269
  ```
239
- routed → free cheap mid premium
240
- actual free (50) 46 4 0 0
241
- actual medium (60) 11 47 2 0
242
- actual complex (50) 0 24 18 8
243
- actual expert (40) 0 1 21 18
270
+ Routing Confusion Matrix (200 queries)
271
+
272
+ Tier Assignment | free | cheap | mid | premium | recall
273
+ --------------------|------|-------|------|---------|-------
274
+ actual: free | 46 | 4 | 0 | 0 | 92%
275
+ actual: medium | 11 | 47 | 2 | 0 | 78%
276
+ actual: complex | 0 | 24 | 18 | 8 | 60%
277
+ actual: expert | 0 | 1 | 21 | 18 | 45%
278
+
279
+ Only 1 in 200 queries misses by more than one tier.
244
280
  ```
245
281
 
246
- Free recall: 92%. Cheap recall: 78%. Expert domain recall: 45%. Only 1 in 200 queries misses by more than one tier.
282
+ | | Score |
283
+ |--|--:|
284
+ | Exact tier match | 64.5% |
285
+ | ±1 tier match | **99.5%** |
286
+ | Free tier recall | 92% |
287
+ | Expert recall | 45% |
288
+
289
+ > Expert recall is lower because complex queries sometimes route to mid-tier when DeepSeek Coder or similar can handle them at 60% the cost of GPT-4o.
247
290
 
248
291
  Run it yourself: `node scripts/routing-benchmark-v2.js`
249
292
 
293
+ ---
294
+
295
+ ## Provider Benchmarks
296
+
297
+ Benchmarks from public model evaluations. Costs from provider pricing pages. **Cost/Quality = input cost ÷ MT-Bench score** (lower = better value).
298
+
299
+ ### Real Benchmark Results (May 2026)
300
+
301
+ We ran **MMLU-style questions** and **quality tests** against each provider via real API calls. All providers are **100% free tier**:
302
+
303
+ | Provider | MMLU Accuracy | Quality Score | Notes |
304
+ |----------|:-------------:|:-------------:|-------|
305
+ | **Groq Allam 2 7B** | **87%** | 9.4/10 | Best overall — fast + accurate |
306
+ | **Groq Llama 3.1 8B** | 80% | 9.4/10 | Fastest at 211ms, great value |
307
+ | **Groq Llama 3.3 70B** | 80% | 9.4/10 | Best for complex reasoning |
308
+ | Cerebras Llama 3.1 8B | 33% | 1.3/10 | Lower capability, short outputs |
309
+ | Cerebras Qwen 3 235B | 33% | 1.3/10 | Large model, lower free-tier limits |
310
+
311
+ > **May 2026** — 15 MMLU questions + 8 quality questions per provider via real API. Run `node scripts/run-mmlu-benchmark.js` to replicate. Results in [`benchmark-results.json`](benchmark-results.json).
312
+
313
+ | Metric | A3M Router | LiteLLM |
314
+ |--------|:----------:|:--------:|
315
+ | ±1 tier accuracy | **99.5%** | N/A |
316
+ | Package size | **19.5 KB** | ~50 MB |
317
+ | GPU required | **No** | No |
318
+ | MMLU accuracy (free tier) | 80-87% | N/A |
319
+
320
+ > Full benchmark data including per-question responses available in [`benchmark-results.json`](benchmark-results.json).
321
+
322
+ ### Why This Matters for Routing
323
+
324
+ ```
325
+ A3M Router routing decision for "debug my Python code":
326
+
327
+ Query: "debug my Python code" (code domain detected)
328
+
329
+ Without routing (GPT-4o): $2.50/1M tokens
330
+ With A3M Router (DeepSeek Coder): $0.55/1M tokens
331
+
332
+ Quality difference: MT-Bench 92% vs 90% (negligible)
333
+ Cost savings: 78% cheaper
334
+
335
+ Result: Same quality, 78% less spend.
336
+ ```
337
+
338
+ ### Provider Latency (p50 / p95)
339
+
340
+ | Tier | Provider | p50 (ms) | p95 (ms) |
341
+ |------|----------|:---------:|:---------:|
342
+ | Free | Ollama (local) | 0 | 0 |
343
+ | Free | Groq | 800 | 2,000 |
344
+ | Cheap | DeepSeek | 1,200 | 3,000 |
345
+ | Cheap | Kimi (Moonshot) | 1,500 | 4,000 |
346
+ | Cheap | Qwen (via OpenRouter) | 1,800 | 4,500 |
347
+ | Mid | Mistral | 2,000 | 5,000 |
348
+ | Premium | OpenAI | 2,000 | 5,000 |
349
+ | Premium | Anthropic | 2,500 | 6,000 |
350
+
351
+ Latency measured from US West coast, May 2026. Local Ollama = 0ms (no network).
352
+
353
+ ### Run Your Own Benchmark
354
+
355
+ ```bash
356
+ # Install
357
+ npm install adaptive-memory-multi-model-router
358
+ npx a3m-router benchmark
359
+
360
+ # Benchmark specific query distributions
361
+ npx a3m-router benchmark --tiers free,cheap --queries 100
362
+
363
+ # Compare costs
364
+ npx a3m-router benchmark --cost --queries 10000
365
+ ```
366
+
367
+ Benchmarks use 200 real queries across 4 tiers. Run on your own query distribution for accurate numbers.
368
+
369
+
370
+
250
371
  ---
251
372
 
252
373
 
@@ -270,7 +391,7 @@ Premium █ ~5% of queries
270
391
 
271
392
  Based on real provider pricing. Simple queries → free models. Expert → premium only when needed.
272
393
 
273
- Real provider pricing. 10,000 queries/month. [RouteLLM paper](https://arxiv.org/abs/2404.06035) shows ~47% of queries are simple.
394
+ Real provider pricing. 10,000 queries/month. Industry data shows ~47% of queries are simple (routable to free/cheap tiers).
274
395
 
275
396
  | Query Type | % Traffic | GPT-4o Only | A3M Routes To | A3M Cost | Savings |
276
397
  |-----------|:---------:|:-----------:|:-------------:|:--------:|:-------:|
@@ -487,94 +608,6 @@ Router assigns each sub-task to optimal agent, tracks outcomes, learns preferenc
487
608
 
488
609
  ---
489
610
 
490
- ## Generative Engine Optimization
491
-
492
- A3M Router is also a **[generative engine](https://en.wikipedia.org/wiki/Generative_artificial_intelligence)** — not just a router, but a system that synthesizes multiple AI models into optimized output pipelines. The difference:
493
-
494
- | | Router | Generative Engine |
495
- |---|---|---|
496
- | **Focus** | Route to cheapest capable model | Orchestrate multi-model pipelines for quality + cost |
497
- | **Routing** | Per-query (heuristic or MCTS) | Per-task (MCTS workflow) |
498
- | **Learning** | Model quality scores (EMA) | Strategy learning from execution outcomes |
499
- | **Output** | Single model response | Synthesized multi-model synthesis |
500
- | **Use case** | "Which model for this query?" | "How do I decompose and assign this task across models?" |
501
-
502
- ### Generative Engine vs Traditional RAG
503
-
504
- | Feature | [RAG](https://arxiv.org/abs/2402.19457) | A3M Generative Engine |
505
- |---------|:------------------:|:--------------------:|
506
- | **Data retrieval** | Vector similarity search | Trigram semantic cache |
507
- | **Model selection** | Static or rule-based | Adaptive via MCTS |
508
- | **Query routing** | Embedding-based | Multi-signal scoring |
509
- | **Memory** | Flat vector store | Hierarchical MemoryTree |
510
- | **Update latency** | Index rebuild required | Real-time (EMA) |
511
- | **Multi-agent** | Not supported | [MCTS orchestration](#mcts-workflow-optimization) |
512
- | **Cost control** | Basic | [Budget alerts + per-provider tracking](#cost-analytics) |
513
-
514
- ### Generative Engine Architecture
515
-
516
- ```
517
- User Query
518
-
519
- ┌──────────────────────────────────────────────────────┐
520
- │ A3M Router — Per-Query Layer (fast, <1ms) │
521
- │ │
522
- │ 1. Guardrails check (injection, PII, content) │
523
- │ 2. Semantic cache (trigram similarity) │
524
- │ 3. Complexity scoring (5 signals → tier) │
525
- │ 4. Route to cheapest available model │
526
- │ ↓ pass? → return cached/llm response │
527
- │ ↓ fail? → circuit breaker → fallback │
528
- └──────────────────────────────────────────────────────┘
529
- ↓ (complex query)
530
- ┌──────────────────────────────────────────────────────┐
531
- │ TMLPD Orchestration — Workflow Layer (MCTS) │
532
- │ │
533
- │ 1. Task decomposition (sub-task graph) │
534
- │ 2. MCTS agent assignment (UCB1 selection) │
535
- │ 3. Parallel execution (multi-agent) │
536
- │ 4. Result synthesis + quality scoring │
537
- │ 5. Memory update (learn outcomes) │
538
- └──────────────────────────────────────────────────────┘
539
-
540
- Synthesized Output
541
- ```
542
-
543
- ### Key Components
544
-
545
- | Component | Description | Doc |
546
- |-----------|-------------|-----|
547
- | [Guardrails Engine](#guardrails-engine) | Input/output safety checks | [17 patterns](https://github.com/Das-rebel/adaptive-memory-multi-model-router/blob/main/src/guardrails/injectionPatterns.ts) |
548
- | [Semantic Cache](#semantic-cache) | Trigram Jaccard similarity | [algorithm](https://github.com/Das-rebel/adaptive-memory-multi-model-router/blob/main/src/cache/semanticCache.ts) |
549
- | [MemoryTree](#adaptive-memory--learning) | Hierarchical context storage | [implementation](https://github.com/Das-rebel/adaptive-memory-multi-model-router/blob/main/src/memory/memoryTree.ts) |
550
- | [MCTS Orchestration](#mcts-workflow-optimization) | Monte Carlo agent assignment | [UCB1 formula](#mcts-workflow-optimization) |
551
- | [Cost Analytics](#cost-analytics) | Per-provider budget tracking | [tracker](https://github.com/Das-rebel/adaptive-memory-multi-model-router/blob/main/src/analytics/costTracker.ts) |
552
- | [Circuit Breaker](#comparison) | Provider failover | [3-failure rule](#comparison) |
553
-
554
- ### Routing Flow Diagram
555
-
556
- ```
557
- Query → Guardrails → Cache? → Complexity → Tier → Cheapest Available
558
- ↓ ↓
559
- HIT Score → Route
560
- ↓ ↓
561
- Return Fallback models
562
- cached (2 configured)
563
-
564
- Cache miss → LLM call → Memory update → Response
565
- ```
566
-
567
- ### Optimization Levers
568
-
569
- | Lever | How It Works | Impact |
570
- |-------|-------------|--------|
571
- | **Cache hit rate** | Higher similarity threshold → fewer misses, more savings | ~30% of queries cached |
572
- | **Tier boundaries** | Adjust complexity thresholds | Moves queries up/down tiers |
573
- | **Model profiles** | EMA updates quality scores per model | Better model selection over time |
574
- | **Provider health** | Circuit breaker excludes failed providers | 99.9% uptime SLA |
575
- | **MCTS iterations** | More iterations → better strategy, slower | 50 default, increase for critical tasks |
576
-
577
- For production tuning, see [`docs/GENERATIVE_ENGINE_TUNING.md`](docs/GENERATIVE_ENGINE_TUNING.md).
578
611
 
579
612
  ## Features in Detail
580
613
 
@@ -751,12 +784,12 @@ const modelWithTools = model.bindTools([searchTool, calculatorTool]);
751
784
 
752
785
  ## Comparison
753
786
 
754
- | Feature | A3M Router | [RouteLLM](https://github.com/lm-sys/RouteLLM) | [LiteLLM](https://github.com/BerriAI/litellm) | [Portkey](https://github.com/Portkey-AI/gateway) | [OpenRouter](https://openrouter.ai) |
755
- |---------|:----------:|:-------:|:-------:|:-------:|:-------:|
756
- | **Routing accuracy published** | **Yes** (99.5% ±1) | Yes (~85%) | No | No | No |
757
- | **Intelligent routing** | Multi-signal per-query | BERT classifier | Manual selection | Manual | Manual |
758
- | **Zero ML / Zero GPU** | **Yes** | No (BERT) | Yes | Yes | Yes |
759
- | **Package size** | 19.5 KB | ~1.5 GB | ~50 MB | ~30 MB | API-only |
787
+ | Feature | A3M Router | [LiteLLM](https://github.com/BerriAI/litellm) | [Portkey](https://github.com/Portkey-AI/gateway) | [OpenRouter](https://openrouter.ai) |
788
+ |---------|:----------:|:-------:|:-------:|:-------:|
789
+ | **Routing accuracy published** | **Yes** (99.5% ±1) | No (manual) | No | No |
790
+ | **Intelligent routing** | Multi-signal per-query | Manual selection | Manual | Manual |
791
+ | **Zero ML / Zero GPU** | **Yes** | Yes | Yes | Yes |
792
+ | **Package size** | 19.5 KB | ~50 MB | ~30 MB | API-only |
760
793
  | **OpenAI-compatible proxy** | **Yes** | No | Yes | Yes | Yes |
761
794
  | **Adaptive memory** | **Yes** | No | No | No | No |
762
795
  | **Semantic cache** | **Yes** (trigram) | No | No | Yes | No |