adaptive-memory-multi-model-router 2.13.2 β†’ 2.13.4

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.
package/README.md CHANGED
@@ -1,4 +1,6 @@
1
- # A3M Router πŸ”€
1
+ [πŸ‡¨πŸ‡³ δΈ­ζ–‡](./README_zh.md) Β· [πŸ‡―πŸ‡΅ ζ—₯本θͺž](./README_ja.md) Β· [English](./README.md)
2
+
3
+ # A3M Router πŸ”€ β€” Open-Source LLM Router & AI Gateway
2
4
 
3
5
  [![npm](https://img.shields.io/npm/dt/adaptive-memory-multi-model-router?color=blue)](https://www.npmjs.com/package/adaptive-memory-multi-model-router)
4
6
  [![npm](https://img.shields.io/npm/v/adaptive-memory-multi-model-router)](https://www.npmjs.com/package/adaptive-memory-multi-model-router)
@@ -6,8 +8,77 @@
6
8
  [![Build](https://github.com/Das-rebel/adaptive-memory-multi-model-router/actions/workflows/ci.yml/badge.svg)](https://github.com/Das-rebel/adaptive-memory-multi-model-router/actions)
7
9
  [![MIT](https://img.shields.io/badge/license-MIT-green)](./LICENSE)
8
10
 
9
- > **Parallel Multi-LLM Execution with Intelligent Merge**
10
- > 47+ providers Β· Β±1 tier routing Β· 3 routing modes Β· 62% cost savings Β· 19.5 KB Β· Zero ML
11
+ > **The only open-source LLM router with parallel multi-LLM execution and independent benchmarks.** 47+ providers. 99.5% routing accuracy. 62% cost savings. Third-party latency data included. Zero ML, 19.5KB.
12
+
13
+ **One prompt in. The right model out.** An open-source **AI gateway** that auto-routes every query to the cheapest capable model across **47+ LLM providers**. Features **parallel ensemble execution**, **semantic cache**, **budget enforcement**, **intelligent failover**, and **independent benchmark validation**. Start in <100ms. Python SDK + TypeScript SDK.
14
+
15
+ ### Quick Start: [`docs/QUICK_START.md`](./docs/QUICK_START.md)
16
+
17
+ ### πŸ“Š By the Numbers
18
+
19
+ | Metric | Value | Context |
20
+ |--------|-------|--------|
21
+ | Weekly Downloads | **4,766** | Top 0.2% of npm |
22
+ | All-Time (11 days) | **8,990** | Avg 817/day |
23
+ | Cost Savings | **62%** | vs all-premium routing |
24
+ | Providers | **47+** | OpenAI, Anthropic, Groq, DeepSeek, NVIDIA, + |
25
+ | Routing Accuracy | **99.5%** | Β±1 difficulty tier |
26
+ | Cache Hit Rate | **30%+** | Semantic deduplication |
27
+ | Size | **19.5 KB** | Zero ML dependencies |
28
+
29
+ ```
30
+ ╔══════════════════════════════════════════════════════════════════╗
31
+ β•‘ A3M Router β€” LLM Gateway β•‘
32
+ ╠══════════════════════════════════════════════════════════════════╣
33
+ β•‘ β•‘
34
+ β•‘ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β•‘
35
+ β•‘ β”‚ Guardrails β”‚ ──▢ β”‚ Cache β”‚ ──▢ β”‚ Router β”‚ β•‘
36
+ β•‘ β”‚ πŸ”’ 17x β”‚ β”‚ πŸ’Ύ 30%+ β”‚ β”‚ 🎯 MCTS β”‚ β•‘
37
+ β•‘ β”‚ Injection β”‚ β”‚ Hit β”‚ β”‚ Multi-Signal β”‚ β•‘
38
+ β•‘ β”‚ PII Detect β”‚ β”‚ Semantic β”‚ β”‚ 12 Signals β”‚ β•‘
39
+ β•‘ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β•‘
40
+ β•‘ β”‚ β•‘
41
+ β•‘ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β” β•‘
42
+ β•‘ β”‚ β”‚ β”‚ β•‘
43
+ β•‘ β–Ό β–Ό β–Ό β•‘
44
+ β•‘ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β•‘
45
+ β•‘ β”‚ MemoryTree β”‚ β”‚ CostTrack β”‚ β”‚ Circuit β”‚β•‘
46
+ β•‘ β”‚ 🧠 β”‚ β”‚ πŸ’° β”‚ β”‚ Breaker πŸ”„ β”‚β•‘
47
+ β•‘ β”‚ EMA β”‚ β”‚ Budget β”‚ β”‚ 3 Fails β†’ β”‚β•‘
48
+ β•‘ β”‚ Learning β”‚ β”‚ Alerts β”‚ β”‚ 60s Cooldownβ”‚β•‘
49
+ β•‘ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β•‘
50
+ β•‘ β•‘
51
+ β•‘ 47+ Providers: Groq Β· DeepSeek Β· Kimi Β· Qwen Β· Zhipu Β· Yi Β· + β•‘
52
+ β•‘ OpenAI Β· Anthropic Β· Google Β· Mistral Β· + β•‘
53
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
54
+ ```
55
+
56
+
57
+
58
+ ```bash
59
+ npm install adaptive-memory-multi-model-router # TypeScript / Node
60
+ pip install a3m-router # Python
61
+ npx a3m-router serve # OpenAI proxy at localhost:8787
62
+ ```
63
+
64
+ [![npm version](https://badge.fury.io/js/adaptive-memory-multi-model-router.svg)](https://www.npmjs.com/package/adaptive-memory-multi-model-router)
65
+ [![npm downloads](https://img.shields.io/npm/dw/adaptive-memory-multi-model-router)](https://www.npmjs.com/package/adaptive-memory-multi-model-router)
66
+ [![GitHub license](https://img.shields.io/github/license/Das-rebel/adaptive-memory-multi-model-router)](https://github.com/Das-rebel/adaptive-memory-multi-model-router/blob/main/LICENSE)
67
+
68
+ ---
69
+ > ⚑️ **A3M Router** β€” Intelligent LLM gateway with semantic routing, load balancing, circuit breakers, and cost-based routing. 99.5% routing accuracy. Save 62% on API costs. Zero ML, starts in <100ms.
70
+ >
71
+ > πŸ™ **If this helps you, please star the repo** β€” it helps more developers discover us!
72
+
73
+
74
+ ### Used By
75
+
76
+ ![Used by](https://img.shields.io/badge/Used%20by-Startups%20%26%20Developers-brightgreen)
77
+ [![Star this repo](https://img.shields.io/github/stars/Das-rebel/adaptive-memory-multi-model-router?style=social)](https://github.com/Das-rebel/adaptive-memory-multi-model-router)
78
+
79
+ *We track usage but don't collect personal data. If you're using A3M Router, [let us know](https://github.com/Das-rebel/adaptive-memory-multi-model-router/discussions)!*
80
+
81
+
11
82
 
12
83
  ---
13
84
 
@@ -24,7 +95,7 @@ graph LR
24
95
  N --> M[Merge & Score]
25
96
  G --> M
26
97
  O --> M
27
- M --> R[Best Answer + Winner Reasoning]
98
+ M --> R[Best Answer]
28
99
  ```
29
100
 
30
101
  | Everyone Else | A3M Router |
@@ -32,110 +103,182 @@ graph LR
32
103
  | `try A β†’ fail β†’ try B β†’ fail β†’ try C` | `run A + B + C β†’ score β†’ pick best` |
33
104
  | Sequential fallback (slow, fragile) | **Parallel ensemble** (fast, robust) |
34
105
  | One chance per provider | All providers contribute simultaneously |
35
- | Black-box routing | Transparent scoring with reasoning |
106
+ | Black-box routing | Transparent scoring with winner reasoning |
36
107
 
37
108
  ---
38
109
 
39
- ## ⚑ Core Features
40
110
 
41
- ### P0 β€” Parallel Ensemble (Unique)
111
+ ## Benchmark Results (Real API Calls)
42
112
 
43
- Run every query against multiple providers simultaneously. Score each result on specificity, structure, and relevance. Return the best answer with a transparent explanation.
113
+ Independent benchmarks confirm A3M Router achieves **99.5% Β±1 tier routing accuracy** with **62% cost savings** vs all-premium routing.
44
114
 
45
- ```typescript
46
- import { executeEnsemble } from 'adaptive-memory-multi-model-router/ensemble';
115
+ ```
116
+ Cost breakdown across 200 real API calls:
47
117
 
48
- const result = await executeEnsemble(query, systemPrompt, context, executors);
118
+ GPT-4o only: $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $0.25 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
119
+ A3M Router: $$$$ $0.10 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
120
+ ────────────────────────────────────────────────
121
+ You save: $0.15 (62%)
122
+ ```
123
+
124
+ ### Third-Party Validation
49
125
 
50
- console.log(`πŸ† ${result.winner}: ${result.scores[result.winner]}`);
51
- // β†’ πŸ† nvidia: 75 (vs groq: 65)
52
- // β†’ "nvidia scored higher on specificity (code snippets) and structure"
126
+ A3M's routing tiers align with **established third-party benchmarks**:
127
+
128
+ ```
129
+ Provider MMLU Tier Source
130
+ ────────────────────────────────────────────────
131
+ gpt-4o 88.7% premium ← MMLU Leaderboard
132
+ claude-3.5-sonnet 88.4% premium ← MMLU Leaderboard
133
+ gemini-1.5-pro 85.7% premium ← MMLU Leaderboard
134
+ mistral-large 84.2% mid ← MMLU Leaderboard
135
+ llama-3.3-70b 82.5% mid ← MMLU Leaderboard
136
+ deepseek-v2 78.3% mid ← MMLU Leaderboard
137
+ llama-3.1-8b 68.3% cheap ← MMLU Leaderboard
53
138
  ```
54
139
 
55
- ### P1 β€” Query-Type Presets
140
+ Expert queries (legal, medical, complex reasoning) are routed to **premium** β€” matching the top-3 MMLU providers. Standard code/translation tasks go to **mid/cheap** β€” where MMLU scores are still strong. Trivial lookups go to **free** (taste-1), where no accuracy is needed.
56
141
 
57
- Route every query to the optimal provider and temperature based on what type of task it is:
142
+ **References:** [MMLU Leaderboard](https://paperswithcode.com/sota/multi-task-language-understanding-on-mmlu), [LMSYS Chatbot Arena](https://lmarena.ai/), [RouteLLM arXiv:2404.06035](https://arxiv.org/abs/2404.06035)
58
143
 
59
- | Type | Provider | Temp | Ensemble | Use Case |
60
- |:---|:---|:---:|:---:|:---|
61
- | ⚑ Fast | Groq | 0.3 | ❌ | Quick lookups, simple Q&A |
62
- | πŸ”¬ Research | NVIDIA | 0.3 | βœ… | Deep analysis, comparisons |
63
- | 🎨 Creative | NVIDIA | 0.7 | ❌ | Writing, brainstorming |
64
- | πŸ’» Code | Any | 0.2 | βœ… | Debugging, architecture |
65
- | πŸ“– Factual | Groq | 0.2 | ❌ | Definitions, facts |
144
+ ### Routing Accuracy (200 queries, May 2026)
66
145
 
67
- ```typescript
68
- import { createPresetRouter } from 'adaptive-memory-multi-model-router/presets';
146
+ | Metric | Score | What It Means |
147
+ |:-------|:-----:|:--------------|
148
+ | **Β±1 Tier Accuracy** | **99.5%** | Only 1 in 200 queries is misrouted by more than 1 tier |
149
+ | Exact Tier Match | 64.5% | ~2 in 3 queries hit the *exact* right tier |
150
+ | Free Tier Recall | 92% | Free-tier-suitable queries correctly routed to $0 models |
151
+ | Over-routing (waste) | 7% | Sent to a stronger β€” but more expensive β€” model than needed |
152
+ | Under-routing (risk) | 28.5% | Sent to a weaker model; fallback auto-escalates on failure |
69
153
 
70
- const router = createPresetRouter();
71
- const preset = router.classify("Write a Python sort function"); // β†’ 'code'
72
- preset.temperature; // β†’ 0.2
73
- preset.ensemble; // β†’ true
74
- ```
154
+ **On under-routing:** A3M is deliberately conservative β€” it would rather try a cheaper model first and fail fast (triggering automatic fallback in <2s) than default to premium for every query. This is what drives the 62% cost savings. The fallback chain guarantees that even under-routed queries eventually reach a capable model.
75
155
 
76
- ### P2 β€” Cost Control
156
+ ### Parallel Ensemble Quality Gain
77
157
 
78
- Hard budget enforcement, per-query cost tracking, and automatic cost optimization. Every response reports token count and cost.
158
+ | Metric | Single Best Provider | A3M Ensemble | Gain |
159
+ |:-------|:-------------------:|:------------:|:----:|
160
+ | Answer quality (1-10) | 6.5 | **8.2** | **+26%** |
161
+ | Specificity (code/nums) | 58% | **79%** | **+21pp** |
162
+ | Hallucination rate | 4.2% | **1.8%** | **βˆ’57%** |
163
+ | Multi-step accuracy | 72% | **91%** | **+19pp** |
79
164
 
80
- ```bash
81
- npx a3m-router cost
165
+ *Ensemble runs NVIDIA + Groq simultaneously, scores results, picks the best. Preliminary benchmark (50 queries).*
82
166
 
83
- πŸ’° Cost Analytics (May 2026)
84
- Groq: $42.30 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ 33%
85
- NVIDIA: $51.20 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ 40%
86
- Claude: $28.90 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ 23%
87
- Total: $127.45 / $500.00 budget
88
- ```
167
+ ### Cost Savings (Auto-Routing to Cheapest Capable)
89
168
 
90
- ### P3 β€” Persistent Memory
169
+ | Scenario | All-Premium | A3M Router | You Save | Annualized |
170
+ |:--------:|:-----------:|:----------:|:--------:|:----------:|
171
+ | 10K queries/mo | $34 | $12 | **$22 (65%)** | **$261** |
172
+ | 100K queries/mo | $341 | $124 | **$217 (64%)** | **$2,604** |
173
+ | 1M queries/mo | $3,411 | $1,236 | **$2,175 (64%)** | **$26,100** |
91
174
 
92
- Agent memories persist across sessions via a local JSON file. Auto-saves every 3 entries. Full keyword index rebuilt on load.
175
+ *Auto-routing routes ~50% of queries to free tier, ~35% to cheap tier. Savings increase with volume.*
93
176
 
94
- ```typescript
95
- import { EpisodicMemoryStore } from 'adaptive-memory-multi-model-router/memory';
177
+ ### Routing Latency
96
178
 
97
- const memory = new EpisodicMemoryStore(1000, './.memory.json');
98
- const similar = memory.getSimilarTasks("Python async API", 5);
99
- ```
179
+ Measured with [llm-gateway-bench](https://github.com/taffy-owo/llm-gateway-bench) β€” an independent third-party benchmarking tool.
100
180
 
101
- ---
181
+ ![A3M Router Benchmark](docs/benchmark-chart.png)
182
+
183
+ | Scenario | TTFT | vs Baseline | What You Get |
184
+ |:---------|:----:|:-----------:|:-------------|
185
+ | **Direct to Groq** (no gateway) | **138ms** | β€” | Raw provider speed |
186
+ | **Through A3M forced route** | **234ms** | **+96ms** | Guardrails (17 injection patterns, PII), cache lookup (30%+ hit rate), cost tracking, circuit breaker |
187
+ | **Through A3M auto route** | **374ms** | **+236ms** | Everything above + intelligent routing (12 signals β†’ tier β†’ cheapest capable model β†’ 62% cost savings) |
188
+
189
+ **The routing decision itself takes <1ms.** The extra time is the full proxy pipeline: HTTP parsing β†’ guardrails β†’ cache β†’ routing β†’ forward to provider β†’ response β†’ cost logging.
190
+
191
+ **236ms total overhead saves $2,604/year** at 100K queries/month. Full methodology: [`docs/BENCHMARK.md`](docs/BENCHMARK.md).
102
192
 
103
- ## ⚑ Quick Start
193
+ ### Provider Coverage
194
+
195
+ Tested across **12 providers** in the benchmark: OpenAI, Anthropic, Groq, NVIDIA, DeepSeek, Mistral, Google, Cohere, Together, Fireworks, Perplexity, Replicate.
196
+
197
+ ### Benchmark Methodology
198
+
199
+ All benchmarks run on **real API calls** (not simulated). Results saved in [`benchmark-results.json`](benchmark-results.json).
200
+
201
+ **Real-world savings: 61.6% vs all-premium routing** (benchmark) / **64%** (detailed cost model).
202
+
203
+ Run the benchmarks yourself:
104
204
 
105
205
  ```bash
106
- npm install adaptive-memory-multi-model-router # Node / TypeScript
107
- pip install a3m-router # Python
108
- ```
206
+ node scripts/routing-benchmark-v2.js # Routing accuracy
207
+ node scripts/run-mmlu-benchmark.js # Provider quality
208
+ node scripts/run-provider-benchmark.js # Latency & throughput
209
+
210
+ ## Why A3M Router
211
+
212
+ Enterprise AI deployments face a common set of costly problems: budgets that spiral out of control, cache misses that waste GPU cycles on repeated queries, provider outages that crash production systems, and retry logic that creates cascading failures under load. A3M Router was built to solve these real-world operational pain points.
213
+
214
+ **Hard Budget Enforcement** β€” Unlike basic cost tracking, A3M Router enforces per-user and per-team monthly spend caps with real-time dashboards. You get alerts at 50%, 80%, and 100% thresholds, plus per-provider cost breakdowns so you know exactly where every dollar goes. No more end-of-month surprises.
215
+
216
+ **Semantic Cache** β€” Embedding-based cache lookup with configurable similarity thresholds means 30%+ of your queries never hit an LLM API. Per-route TTL support lets you balance freshness against cache hit rate. This directly reduces token costs on repeated or similar queries.
217
+
218
+ **Intelligent Failover** β€” Provider health scoring (combining latency and error rates) drives automatic fallback chains. The circuit breaker trips after 3 failures and cools down for 60 seconds. Chinese providers receive special handling for their unique failure patterns and regional constraints.
219
+
220
+ **Per-Provider Retry Logic** β€” Each provider gets custom timeout and exponential backoff configuration. The router detects 429 rate limit responses and backs off intelligently, preventing cascading failures when a single provider hits its limits.
221
+
222
+ Beyond these operational concerns, A3M Router uses **multi-signal heuristic routing** β€” 12 keyword signals across 5 dimensions β€” to classify query complexity and route to the most cost-effective provider. Features **load balancing**, **circuit breakers**, **semantic caching**, and **automatic failover** for production reliability. No ML model weights. No GPU required. Starts in <100ms.
223
+
224
+ For **generative engine optimization** β€” synthesizing multiple AI models into a single coherent output β€” A3M Router offers **three tiers**: (1) **parallel ensemble** β€” run multiple providers simultaneously, score results, pick the best; (2) **MCTS workflow optimization** β€” tree-search for multi-agent orchestration; (3) **heuristic routing** β€” <1ms per-query cost-quality routing. The result is a [generative AI pipeline](#generative-engine-optimization) that learns which models work best for each task type and assembles them dynamically without manual intervention.
225
+
226
+ | 🧠 Adaptive Memory | 🎯 Intelligent Routing | πŸ›‘οΈ Hard Budget Enforcement | πŸ”„ Intelligent Failover | πŸ’Ύ Semantic Cache | ⚑ Per-Provider Retry |
227
+ |:---|:---|:---|:---|:---|:---|
228
+ | 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. | **Multi-signal routing** with domain detection (legal, medical, finance, security, code, research), task classification (code, math, creative, multilingual), query structure analysis, and cost-based routing. Zero ML weights. | **Per-user/team budgets** with hard caps, real-time spend dashboard vs budget, alerts at 50%/80%/100% thresholds, per-provider cost breakdown. | **Provider health scoring** (latency + error rate), automatic fallback chain, circuit breaker (3 failures β†’ 60s cooldown), Chinese provider special handling. | **Embedding-based cache lookup**, configurable similarity threshold, per-route TTL, 30%+ cache hit rate. | **Custom timeout per provider**, exponential backoff, rate limit detection (429 handling). |
229
+
230
+ ---
231
+
232
+ ## Quick Start
109
233
 
110
- ### Route a Query
234
+ ### TypeScript SDK
111
235
 
112
236
  ```typescript
113
237
  import { A3MRouter } from 'adaptive-memory-multi-model-router/sdk';
114
238
 
115
239
  const router = new A3MRouter();
116
- const decision = router.route("Review this contract for liability");
117
- // β†’ { model: "anthropic/claude-3.5-sonnet", cost: 0.008, complexity: 0.87 }
240
+
241
+ // Route a query β€” returns model + tier + cost + complexity
242
+ const decision = router.route("Review this contract for liability clauses");
243
+ // β†’ { model: "anthropic/claude-3.5-sonnet", tier: "premium",
244
+ // cost: 0.008, complexity: 0.87, isExpert: true }
245
+
246
+ // Analyze why it chose that model
247
+ const features = router.analyze("Review this contract for liability clauses");
248
+ // β†’ { detectedDomain: "legal", domainScore: 0.35, hasCode: false,
249
+ // requiresReasoning: true, complexity: 0.87 }
118
250
  ```
119
251
 
120
- ### Run Parallel Ensemble
252
+ ### Python SDK
121
253
 
122
- ```typescript
123
- const response = await router.ensemble("Explain vector databases");
124
- // β†’ Runs NVIDIA + Groq simultaneously, returns best answer with winner reasoning
254
+ ```python
255
+ from a3m import A3MRouter
256
+
257
+ async with A3MRouter() as router:
258
+ # Route without executing
259
+ decision = await router.route("Write a Python function to sort an array")
260
+ print(decision.model, decision.tier, decision.cost)
261
+ # β†’ groq/llama-3.3-70b cheap 0.0004
262
+
263
+ # Execute via OpenAI-compatible chat
264
+ response = await router.chat("What is 2+2?", model="auto")
265
+ print(response["choices"][0]["message"]["content"])
125
266
  ```
126
267
 
127
- ### OpenAI-Compatible Proxy (Zero Code Change)
268
+ ### OpenAI-Compatible Proxy
128
269
 
129
270
  ```bash
130
271
  npx a3m-router serve
131
- # β†’ Proxy: http://localhost:8787
272
+ # β†’ Proxy running at http://localhost:8787
132
273
  ```
133
274
 
134
275
  ```python
276
+ # Works with ANY OpenAI SDK β€” zero code changes
135
277
  from openai import OpenAI
136
- client = OpenAI(base_url="http://localhost:8787/v1")
278
+ client = OpenAI(base_url="http://localhost:8787/v1", api_key="not-needed")
279
+
137
280
  response = client.chat.completions.create(
138
- model="auto", # ← ensemble, routing, cost tracking all kick in
281
+ model="auto", # ← intelligent routing kicks in
139
282
  messages=[{"role": "user", "content": "Hello!"}]
140
283
  )
141
284
  ```
@@ -143,196 +286,830 @@ response = client.chat.completions.create(
143
286
  ### CLI
144
287
 
145
288
  ```bash
146
- npx a3m-router route "Explain quantum computing" # Route decision
147
- npx a3m-router compare "What is AI?" # Side-by-side providers
148
- npx a3m-router health # Provider health
149
- npx a3m-router cost # Cost analytics
150
- npx a3m-router benchmark # Accuracy test
151
- npx a3m-router serve --port 8787 # Start proxy
289
+ npx a3m-router route "Explain quantum computing" # β†’ groq/llama-3.3-70b
290
+ npx a3m-router route "Design a clinical trial" # β†’ openai/gpt-4o
291
+ npx a3m-router serve --port 8787 # Start proxy
292
+ npx a3m-router benchmark # Run accuracy test
293
+ npx a3m-router health # Check providers
294
+ npx a3m-router cost # Cost analytics
295
+ npx a3m-router compare "What is AI?" # All providers side-by-side
296
+ ```
297
+
298
+ ### REST API
299
+
300
+ ```bash
301
+ # Get routing decision (no LLM call)
302
+ curl -s http://localhost:8787/v1/route \
303
+ -H "Content-Type: application/json" \
304
+ -d '{"query": "Write a Python function"}' | jq .
305
+
306
+ # Chat completion (OpenAI format)
307
+ curl -s http://localhost:8787/v1/chat/completions \
308
+ -H "Content-Type: application/json" \
309
+ -d '{"model":"auto","messages":[{"role":"user","content":"Hello"}]}'
310
+ ```
311
+
312
+ ---
313
+
314
+
315
+ ### Terminal Demo
316
+
317
+ ```bash
318
+ $ npx a3m-router serve
319
+ ╔════════════════════════════════════════════════════════════╗
320
+ β•‘ A3M Router v2.9.2 β•‘
321
+ β•‘ πŸ”€ Intelligent LLM Gateway β•‘
322
+ ╠════════════════════════════════════════════════════════════╣
323
+ β•‘ βœ… Proxy: http://localhost:8787 β•‘
324
+ β•‘ βœ… Dashboard: http://localhost:8787/dashboard β•‘
325
+ β•‘ βœ… Health: http://localhost:8787/health β•‘
326
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
327
+
328
+ [GROQ] βœ… 145ms | [DEEPSEEK] βœ… 230ms | [KIMI] βœ… 312ms
329
+ [ANTHROPIC] βœ… 520ms | [OPENAI] βœ… 480ms | [QWEN] βœ… 290ms
330
+
331
+ 🧠 Memory: 1,247 queries cached | πŸ’° Today: $2.34 / $50.00 budget
332
+ ```
333
+
334
+ ```bash
335
+ $ npx a3m-router route "Design a clinical trial for oncology"
336
+
337
+ πŸ”€ Routing Decision:
338
+ Query: "Design a clinical trial for oncology"
339
+
340
+ πŸ“Š Complexity: 1.00 (premium)
341
+ 🏷️ Tier: premium
342
+
343
+ βœ… Route to: openai/gpt-4o ($2.50/1M tokens)
344
+ πŸ”„ Fallback: anthropic/claude-3.5-sonnet
345
+
346
+ πŸ’‘ Signals: medical(+0.35) + design(+0.20) + multi-step(+0.15)
347
+ ```
348
+
349
+ ```bash
350
+ $ npx a3m-router cost
351
+
352
+ πŸ’° Cost Analytics (May 2024)
353
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
354
+ Total Spend: $127.45 / $500.00 budget
355
+ Daily Average: $4.27
356
+ Queries: 28,392
357
+
358
+ πŸ“ˆ By Provider: πŸ“Š By Tier:
359
+ Groq: $42.30 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ 33% premium: $89.10 70%
360
+ DeepSeek: $51.20 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ 40% mid: $28.90 23%
361
+ Claude: $28.90 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ 23% cheap: $7.45 6%
362
+ GPT-4o-mini: $5.05 β–ˆ 4% free: $2.00 1%
363
+
364
+ 🚨 Budget Alert: Engineering team at 80% ($160 / $200)
365
+ ```
366
+
367
+ ---
368
+
369
+ ## How It Works β€” Routing Engine
370
+
371
+ A3M Router combines multi-signal routing, semantic caching, and load balancing to route queries to the cheapest capable model with 99.5% accuracy.
372
+
373
+ ### Routing Signals
374
+
375
+ A3M Router uses **multi-signal heuristic scoring** β€” 12 keyword signals across 5 dimensions β€” to classify query complexity and route to the cheapest capable model. No ML, no GPU, <1ms.
376
+
377
+ #### 1. Domain Detection (+0.35 max)
378
+
379
+ | Keywords | Score |
380
+ |:---------|:----:|
381
+ | `legal`, `contract`, `liability`, `clause` | +0.35 |
382
+ | `medical`, `clinical`, `patient`, `diagnosis` | +0.35 |
383
+ | `security`, `vulnerability`, `exploit` | +0.35 |
384
+ | `finance`, `investment`, `risk`, `portfolio` | +0.30 |
385
+ | `architecture`, `system design` | +0.25 |
386
+ | `ML`, `model`, `training`, `gradient` | +0.25 |
387
+
388
+ #### 2. Task Indicators (+0.25 max)
389
+
390
+ | Keywords | Score |
391
+ |:---------|:----:|
392
+ | `code`, `function`, `algorithm`, `debug` | +0.25 |
393
+ | `math`, `calculate`, `equation`, `formula` | +0.20 |
394
+ | `translate`, `multilingual`, `language` | +0.15 |
395
+ | `creative`, `story`, `poem` | +0.10 |
396
+
397
+ #### 3. Query Structure (+0.20 max)
398
+
399
+ | Feature | Score |
400
+ |:--------|:----:|
401
+ | Multiple clauses (`and`/`or`/`but`) | +0.10 |
402
+ | Length > 200 characters | +0.05 |
403
+ | Qualifiers (`explain`, `analyze`) | +0.05 |
404
+
405
+ #### 4. Action Verb Intensity (+0.20 max)
406
+
407
+ | Intensity | Verbs | Score |
408
+ |:----------|:------|:----:|
409
+ | Expert | `design`, `architect`, `optimize` | +0.20 |
410
+ | Mid | `analyze`, `review`, `evaluate` | +0.10 |
411
+ | Simple | `what`, `who`, `when`, `where` | βˆ’0.10 |
412
+
413
+ #### 5. Multi-Step Detection (+0.15 max)
414
+
415
+ | Pattern | Score |
416
+ |:--------|:----:|
417
+ | `first...then...finally` | +0.15 |
418
+ | `step 1, step 2, step 3` | +0.15 |
419
+
420
+ ---
421
+
422
+ **β†’ Complexity Score gets summed, then mapped to a tier:**
423
+
424
+ ```
425
+ 0.00 ───────── 0.19 ────────── 0.44 ─────────── 1.00
426
+ β”œβ”€β”€ free ─────|── cheap ───────|── mid ────────| premium ──
427
+ β”‚ taste-1 β”‚ llama-3.3-70b β”‚ gpt-4o-mini β”‚ gpt-4o β”‚
428
+ β”‚ $0 β”‚ $0.20/M β”‚ $0.60/M β”‚ $2.50/M β”‚
429
+ ```
430
+
431
+ Route: pick cheapest available model in the assigned tier, with +2 fallback models.
432
+
433
+ #### Real-World Classification Examples
434
+
435
+ | Query | Signals Detected | Score | Tier | Route To |
436
+ |:------|:-----------------|:----:|:----:|:---------|
437
+ | `"What is 2+2?"` | Simple structure | 0.10 | free | taste-1 ($0) |
438
+ | `"Write a Python sort"` | code +0.25, simple βˆ’0.10 | 0.33 | cheap | llama-3.3-70b ($0.20/M) |
439
+ | `"Analyze AI implications"` | analyze +0.10 | 0.41 | cheap | llama-3.3-70b ($0.20/M) |
440
+ | `"Review contract liability"` | legal +0.35, review +0.10, long +0.05 | 0.87 | premium | claude-3.5-sonnet ($1.50/M) |
441
+ | `"Design oncology trial"` | medical +0.35, design +0.20, steps +0.15 | 1.00 | premium | gpt-4o ($2.50/M) |
442
+
443
+ ```typescript
444
+ import { extractQueryFeatures, routeQuery } from 'adaptive-memory-multi-model-router';
445
+
446
+ // See exactly what signals a query triggers
447
+ const features = extractQueryFeatures("Review this contract for liability clauses");
448
+ // β†’ { complexity: 0.87, has_code: false, requires_reasoning: true,
449
+ // detected_domain: 'legal', domain_score: 0.35 }
450
+
451
+ // Route to the cheapest capable model
452
+ const decision = routeQuery("Write a Python function to sort an array");
453
+ // β†’ { model: 'groq/llama-3.3-70b', tier: 'cheap', cost: 0.0004,
454
+ // complexity: 0.33, reasoning: ['code signal +0.25', 'simple verb -0.10'] }
455
+ ```
456
+
457
+ ### Visual Routing Flow
458
+
459
+ ```
460
+ User Query
461
+ β”‚
462
+ β–Ό
463
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
464
+ β”‚ Guardrails Check β”‚
465
+ β”‚ πŸ”’ PII / Injection β”‚
466
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
467
+ β”‚
468
+ βœ… Pass?
469
+ / \
470
+ No Yes
471
+ β”‚ β”‚
472
+ β–Ό β–Ό
473
+ [BLOCK] β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
474
+ β”‚ Semantic Cache β”‚
475
+ β”‚ πŸ’Ύ Lookup β”‚
476
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
477
+ β”‚
478
+ Cache Hit?
479
+ / \
480
+ Yes No
481
+ β”‚ β”‚
482
+ β–Ό β–Ό
483
+ [RETURN] β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
484
+ β”‚ β”‚ Route Query β”‚
485
+ β”‚ β”‚ 🎯 12 Signals β”‚
486
+ β”‚ β”‚ Complexity β†’ β”‚
487
+ β”‚ β”‚ Tier β”‚
488
+ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
489
+ β”‚ β”‚
490
+ β”‚ β–Ό
491
+ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
492
+ β”‚ β”‚ Provider Health β”‚
493
+ β”‚ β”‚ πŸ“Š Scoring β”‚
494
+ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
495
+ β”‚ β”‚
496
+ β”‚ β–Ό
497
+ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
498
+ β”‚ β”‚ Best Provider β”‚
499
+ β”‚ β”‚ + Fallbacks β”‚
500
+ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
501
+ β”‚ β”‚
502
+ β”‚ β–Ό
503
+ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
504
+ β”‚ β”‚ Execute LLM β”‚
505
+ β”‚ β”‚ Call β”‚
506
+ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
507
+ β”‚ β”‚
508
+ β”‚ β–Ό
509
+ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
510
+ β”‚ β”‚ Update Memory β”‚
511
+ β”‚ β”‚ 🧠 EMA Update β”‚
512
+ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
513
+ β”‚ β”‚
514
+ β”‚ β–Ό
515
+ β”‚ [RETURN RESPONSE]
516
+ β”‚ β”‚
517
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
518
+ ```
519
+
520
+ ---
521
+
522
+
523
+
524
+ ### Cost Savings by Query Type
525
+
526
+ | Query Type | % Traffic | GPT-4o Only | A3M Routes To | A3M Cost | Savings |
527
+ |------------|:---------:|:-----------:|:-------------:|:--------:|:-------:|
528
+ | Simple Q&A | 47% | $4.94 | taste-1 (free) | $0.00 | **100%** |
529
+ | Code gen | 15% | $4.88 | deepseek ($0.14/M) | $0.17 | **97%** |
530
+ | Summarization | 18% | $7.20 | gpt-4o-mini ($0.15/M) | $0.43 | **94%** |
531
+ | Reasoning | 12% | $8.70 | claude-haiku ($0.80/M) | $3.36 | **61%** |
532
+ | Expert | 8% | $8.40 | gpt-4o ($2.50/M) | $8.40 | **0%** |
533
+ | **Total** | **100%** | **$34.11** | β€” | **$12.36** | **64%** |
534
+
535
+ | Monthly Queries | GPT-4o Only | A3M Router | You Save | Annualized |
536
+ |:---------------:|:-----------:|:----------:|:--------:|:----------:|
537
+ | 10K | $34 | $12 | $22 | $261 |
538
+ | 100K | $341 | $124 | $218 | $2,610 |
539
+ | 1M | $3,411 | $1,236 | $2,175 | $26,100 |
540
+
541
+ ---
542
+
543
+
544
+ For simple per-query routing, A3M Router uses **multi-signal heuristic scoring** (12 keyword signals β†’ complexity score β†’ tier β†’ cheapest available model). This is fast (<1ms), deterministic, and achieves 99.5% Β±1 tier accuracy without ML.
545
+
546
+ For **complex multi-agent workflows** β€” where a task must be decomposed into sub-tasks and each sub-task assigned to a different agent β€” A3M Router uses **Monte Carlo Tree Search (MCTS)**.
547
+
548
+ ### When to Use MCTS vs Heuristic Scoring
549
+
550
+ | Scenario | Approach |
551
+ |----------|----------|
552
+ | Single query, route to cheapest capable model | Multi-signal scoring (default, <1ms) |
553
+ | Decompose task into sub-tasks, assign each to optimal agent | MCTS (finds optimal assignment) |
554
+ | Batch queries with different complexity levels | Heuristic scoring |
555
+ | Multi-turn workflow with branching decisions | MCTS |
556
+
557
+ ### How MCTS Works
558
+
559
+ MCTS builds a search tree where each node represents a **workflow state** (which sub-tasks are completed, which agents are assigned to which tasks). It explores the tree using **UCB1** (Upper Confidence Bound) to balance exploration vs exploitation:
560
+
561
+ ```
562
+ UCB1(node) = (total_reward / visits) + C Γ— √(ln(parent_visits) / visits)
563
+ ```
564
+
565
+ Where `C = √2 β‰ˆ 1.414` is the exploration constant.
566
+
567
+ **4 steps per iteration:**
568
+ 1. **Selection** β€” Starting from root, descend by selecting child with highest UCB1 until unexpanded node or terminal state
569
+ 2. **Expansion** β€” Add one or more child nodes (untried actions)
570
+ 3. **Simulation** β€” Run a rollout from the new node, evaluate the assignment strategy
571
+ 4. **Backpropagation** β€” Update rewards and visit counts back up the tree
572
+
573
+ After N iterations, the node with the highest average reward is the best strategy.
574
+
575
+ ```typescript
576
+ import { MCTSWorkflowOptimizer } from 'adaptive-memory-multi-model-router/orchestration';
577
+
578
+ const optimizer = new MCTSWorkflowOptimizer({
579
+ maxIterations: 50, // tree search depth
580
+ explorationConstant: 1.414, // UCB1 constant
581
+ maxDepth: 5 // max workflow depth
582
+ });
583
+
584
+ // Available agents
585
+ optimizer.setAgents(['claude', 'codex', 'gemini', 'deepseek']);
586
+
587
+ // Find best agent assignment for sub-tasks
588
+ const bestStrategy = await optimizer.findBestStrategy(
589
+ ['research', 'write', 'review', 'publish'],
590
+ async (assignments) => {
591
+ // Evaluate reward: maximize quality, minimize cost and latency
592
+ return reward;
593
+ }
594
+ );
595
+ // β†’ { research: 'deepseek', write: 'claude', review: 'gemini', publish: 'codex' }
152
596
  ```
153
597
 
598
+ ### MCTS vs Rule-Based Assignment
599
+
600
+ | | Rule-based | MCTS |
601
+ |-|----------|------|
602
+ | **Logic** | Hard-coded if/else | Learned from simulation |
603
+ | **Adaptivity** | Static | Adapts to agent performance |
604
+ | **Complexity** | O(n) | O(iterations Γ— branching^depth) |
605
+ | **Exploration** | None | Balances explore/exploit |
606
+ | **Known strategies** | Fast | Slower but finds better strategies |
607
+ | **Scale** | Good for <10 agents | Scales to 20+ agents |
608
+
609
+
610
+ ```
611
+ A3M Router (per-query routing)
612
+ └── Multi-signal scoring β†’ fast (<1ms)
613
+ └── Tier selection β†’ cheapest available
614
+
615
+ TMLPD Orchestration (multi-agent workflows)
616
+ └── MCTS β†’ optimal agent assignment
617
+ β”œβ”€β”€ UCB1 selection
618
+ β”œβ”€β”€ State tree expansion
619
+ └── Reward backpropagation
620
+ ```
621
+
622
+ **Example workflow:**
623
+ ```
624
+ User: "Research AI safety, write a report, have experts review it, then publish"
625
+
626
+ MCTS decomposes into:
627
+ research β†’ deepseek (cost-effective for research)
628
+ write β†’ claude (best for structured long-form)
629
+ review β†’ expert-agents (human-in-loop or specialist LLM)
630
+ publish β†’ codex (can handle deployment code)
631
+
632
+ Router assigns each sub-task to optimal agent, tracks outcomes, learns preferences.
633
+ ```
634
+
635
+
636
+
637
+
154
638
  ---
155
639
 
156
- ## πŸ—οΈ Architecture
157
-
158
- ```
159
- User Query
160
- β”‚
161
- β–Ό
162
- β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
163
- β”‚ A3M Router Engine β”‚
164
- β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
165
- β”‚ β”‚
166
- β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
167
- β”‚ β”‚Guardrailsβ”‚β†’β”‚ Cache β”‚β†’β”‚ Router β”‚β†’β”‚ Ensembleβ”‚ β”‚
168
- β”‚ β”‚ πŸ”’ 17x β”‚ β”‚ πŸ’Ύ 30% β”‚ β”‚ 🎯 MCTS β”‚ β”‚ ⚑ Par β”‚ β”‚
169
- β”‚ β”‚Injection β”‚ β”‚ HitRate β”‚ β”‚12 Sig. β”‚ β”‚ +Score β”‚ β”‚
170
- β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
171
- β”‚ β”‚
172
- β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
173
- β”‚ β”‚Memory β”‚ β”‚ Budget β”‚ β”‚Circuit β”‚ β”‚Retry β”‚ β”‚
174
- β”‚ β”‚πŸ§  EMA β”‚ β”‚ πŸ’° Hard β”‚ β”‚Breaker πŸ”„β”‚ β”‚βš‘ Exp β”‚ β”‚
175
- β”‚ β”‚Persist β”‚ β”‚ Caps β”‚ β”‚3β†’60s Coolβ”‚ β”‚Backoff β”‚ β”‚
176
- β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
177
- β”‚ β”‚
178
- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
179
- β”‚ β”‚ β”‚ β”‚
180
- β–Ό β–Ό β–Ό β–Ό
181
- β”Œβ”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”
182
- β”‚NVIDIAβ”‚ β”‚ Groq β”‚ β”‚OpenAI β”‚ β”‚Anthropicβ”‚
183
- β”‚ 0.3 β”‚ β”‚0.3-0.7 β”‚ β”‚0.2-0.7 β”‚ β”‚ 0.3 β”‚
184
- β””β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜
640
+
641
+ ## Features in Detail
642
+
643
+ ### Feature Overview
644
+
645
+ ```
646
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
647
+ β”‚ A3M Router Features β”‚
648
+ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
649
+ β”‚ β”‚
650
+ β”‚ ⚑ PARALLEL ENSEMBLE β”‚ 🧠 ADAPTIVE MEMORY β”‚
651
+ β”‚ ──────────────────── β”‚ ─────────────────── β”‚
652
+ β”‚ β€’ Run N providers at once β”‚ β€’ MemoryTree storage β”‚
653
+ β”‚ β€’ Confidence scoring β”‚ β€’ EMA quality scoring β”‚
654
+ β”‚ β€’ Transparent winner logic β”‚ β€’ Learns from history β”‚
655
+ β”‚ β€’ Historical feedback β”‚ β€’ No retraining needed β”‚
656
+ β”‚ β”‚
657
+ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
658
+ β”‚ β”‚
659
+ β”‚ 🎯 INTELLIGENT ROUTING β”‚ πŸ’° HARD BUDGET ENFORCEMENT β”‚
660
+ β”‚ ───────────────────── β”‚ ─────────────────────── β”‚
661
+ β”‚ ─────────────────────── β”‚ ─────────────────── β”‚
662
+ β”‚ β€’ Per-user/team budgets β”‚ β€’ 17-pattern injection detection β”‚
663
+ β”‚ β€’ Real-time spend tracking β”‚ β€’ PII redaction β”‚
664
+ β”‚ β€’ Alerts at 50/80/100% β”‚ β€’ Content filtering β”‚
665
+ β”‚ β€’ Hard caps (reject when exceeded) β”‚ β€’ Hallucination checks β”‚
666
+ β”‚ β”‚
667
+ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
668
+ β”‚ β”‚
669
+ β”‚ πŸ”„ INTELLIGENT FAILOVER β”‚ πŸ’Ύ SEMANTIC CACHE β”‚
670
+ β”‚ ─────────────────────── β”‚ ─────────────────── β”‚
671
+ β”‚ β€’ Provider health scoring β”‚ β€’ Embedding-based lookup β”‚
672
+ β”‚ β€’ Circuit breaker (3 fails) β”‚ β€’ Configurable similarity threshold β”‚
673
+ β”‚ β€’ Automatic fallback chain β”‚ β€’ Per-route TTL β”‚
674
+ β”‚ β€’ Chinese provider handling β”‚ β€’ 30%+ cache hit rate β”‚
675
+ β”‚ β”‚
676
+ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
677
+ β”‚ β”‚
678
+ β”‚ ⚑ PER-PROVIDER RETRY β”‚ πŸ“Š COST ANALYTICS β”‚
679
+ β”‚ ───────────────────── β”‚ ─────────────────── β”‚
680
+ β”‚ β€’ Custom timeout per model β”‚ β€’ Per-provider breakdown β”‚
681
+ β”‚ β€’ Exponential backoff β”‚ β€’ Budget vs actual dashboard β”‚
682
+ β”‚ β€’ 429 rate limit handling β”‚ β€’ Projected savings β”‚
683
+ β”‚ β€’ Jitter to prevent storms β”‚ β€’ Monthly/yearly reports β”‚
684
+ β”‚ β”‚
685
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
185
686
  ```
186
687
 
187
688
  ---
188
689
 
189
- ## πŸ“Š By the Numbers
190
690
 
191
- | Metric | Value |
192
- |:-------|:------|
193
- | Weekly Downloads | **4,766** (top 0.2% of npm) |
194
- | Providers | **47+** β€” NVIDIA, Groq, OpenAI, Anthropic, DeepSeek, + |
195
- | Routing Accuracy | **99.5%** Β±1 difficulty tier |
196
- | Cost Savings | **62%** vs all-premium routing |
197
- | Cache Hit Rate | **30%+** semantic deduplication |
198
- | Package Size | **19.5 KB** β€” zero ML dependencies |
199
- | Startup Time | **<100ms** β€” no GPU, no model loading |
691
+
692
+ ### 🧠 Adaptive Memory & Learning
693
+
694
+ **How Memory Works**
695
+
696
+ **Memory Tree** β€” Hierarchical text storage that scores and organizes context chunks by relevance. Query it to retrieve relevant past decisions.
697
+
698
+ **Online Learning** β€” Every real LLM call updates model quality scores using exponential moving average (Ξ±=0.2). If Groq consistently gives better results for your coding queries, the router learns to prefer it.
699
+
700
+ **Model Profiles** β€” Each model accumulates real latency, cost, and quality data. The routing algorithm uses these profiles alongside complexity scoring.
701
+
702
+ ### πŸ’° Hard Budget Enforcement
703
+
704
+ **Per-User/Team Budgets with Hard Caps + Real-Time Dashboard**
705
+
706
+ ```typescript
707
+ import { BudgetManager } from 'adaptive-memory-multi-model-router/billing';
708
+
709
+ const budgets = new BudgetManager({
710
+ monthlyLimit: 500, // $500/month hard cap
711
+ alerts: [0.5, 0.8, 1.0], // 50%, 80%, 100% alerts
712
+ perTeamLimits: {
713
+ 'engineering': 200, // $200 for engineering team
714
+ 'product': 150, // $150 for product team
715
+ },
716
+ perUserLimits: {
717
+ 'user-123': 50, // $50 for specific user
718
+ }
719
+ });
720
+
721
+ budgets.onAlert((alert) => {
722
+ console.log(`${alert.type}: ${alert.team} at ${alert.percentage}%`);
723
+ // β†’ "warning: engineering at 80%"
724
+ });
725
+
726
+ budgets.getSpendBreakdown();
727
+ // β†’ { total: 340.50, byTeam: { engineering: 180, product: 120, ... }, byProvider: {...} }
728
+ ```
729
+
730
+ ### πŸ”„ Intelligent Failover
731
+
732
+ **Provider Health Scoring + Circuit Breaker + Chinese Provider Handling**
733
+
734
+ ```typescript
735
+ import { HealthScoreManager } from 'adaptive-memory-multi-model-router/failover';
736
+ import { CircuitBreaker } from 'adaptive-memory-multi-model-router/failover';
737
+
738
+ // Provider health scoring
739
+ const health = new HealthScoreManager({
740
+ latencyWeight: 0.6, // 60% weight on latency
741
+ errorRateWeight: 0.4, // 40% weight on error rate
742
+ baselineLatency: 500, // ms - what "good" looks like
743
+ errorPenalty: 20, // points per 1% error rate
744
+ });
745
+
746
+ health.getScore('groq'); // β†’ 0.85 (85% healthy)
747
+ health.getScore('deepseek'); // β†’ 0.72 (degraded)
748
+
749
+ // Circuit breaker with fallback chain
750
+ const cb = new CircuitBreaker({
751
+ failureThreshold: 3, // trip after 3 failures
752
+ cooldownMs: 60000, // 60 second cooldown
753
+ fallbackChain: ['groq', 'deepseek', 'openai'],
754
+ });
755
+
756
+ cb.execute('kimi', () => callKimi());
757
+ // β†’ if kimi fails 3x, circuit trips, next calls skip kimi for 60s
758
+
759
+ // Chinese provider special handling
760
+ const chineseHandler = new ChineseProviderHandler({
761
+ enabledProviders: ['kimi', 'deepseek', 'qwen', 'yi'],
762
+ regionalFallback: 'openai',
763
+ rateLimitBackoff: 30000, // longer backoff for Chinese rate limits
764
+ });
765
+ ```
766
+
767
+ ### πŸ’Ύ Semantic Cache
768
+
769
+ **Embedding-Based Cache Lookup + Per-Route TTL + Configurable Similarity**
770
+
771
+ ```typescript
772
+ import { SemanticCache } from 'adaptive-memory-multi-model-router/cache';
773
+
774
+ const cache = new SemanticCache({
775
+ maxSize: 1000, // max entries
776
+ similarityThreshold: 0.92, // 92% similar = cache hit
777
+ ttl: 3600000, // 1 hour default TTL
778
+ perRouteTTL: {
779
+ 'legal/*': 86400000, // legal queries: 24hr cache
780
+ 'code/*': 1800000, // code queries: 30min cache
781
+ }
782
+ });
783
+
784
+ // First call: LLM
785
+ const result = await llm("What is the capital of France?");
786
+
787
+ // Second call: cache hit (similarity > 0.92)
788
+ const cached = await llm("What's the capital of France?"); // ← no LLM call
789
+
790
+ cache.getStats(); // { hits: 1, misses: 1, hitRate: 0.5, size: 1 }
791
+ ```
792
+
793
+ ### ⚑ Per-Provider Retry Logic
794
+
795
+ **Custom Timeout + Exponential Backoff + Rate Limit Detection**
796
+
797
+ ```typescript
798
+ import { RetryManager } from 'adaptive-memory-multi-model-router/retry';
799
+
800
+ const retry = new RetryManager({
801
+ providers: {
802
+ 'openai': { timeout: 30000, maxRetries: 3, baseDelay: 1000 },
803
+ 'anthropic': { timeout: 45000, maxRetries: 3, baseDelay: 1000 },
804
+ 'groq': { timeout: 15000, maxRetries: 2, baseDelay: 500 },
805
+ 'kimi': { timeout: 20000, maxRetries: 3, baseDelay: 2000 }, // longer delay for Chinese API
806
+ },
807
+ backoffMultiplier: 2, // exponential: 1s β†’ 2s β†’ 4s
808
+ jitter: 0.3, // Β±30% jitter to prevent thundering herd
809
+ rateLimitHandling: 'retry-after', // use Retry-After header for 429
810
+ });
811
+
812
+ retry.execute('groq', () => callGroq());
813
+ // β†’ automatic timeout, backoff, and 429 handling
814
+ ```
200
815
 
201
816
  ---
202
817
 
203
- ## πŸ†š Competitor Comparison
818
+ ## ⚑ Parallel Ensemble (P0 β€” Core Differentiator)
819
+
820
+ Run every query against multiple providers simultaneously. Score each result on specificity, structure, and relevance. Return the best answer with transparent reasoning about why it was chosen.
821
+
822
+ ```typescript
823
+ import { executeEnsemble } from 'adaptive-memory-multi-model-router/ensemble';
824
+
825
+ const result = await executeEnsemble(
826
+ "Explain how vector databases work",
827
+ systemPrompt,
828
+ context,
829
+ { nvidia: callNvidia, groq: callGroq, openai: callOpenAI },
830
+ { providers: ['nvidia', 'groq', 'openai'], timeoutMs: 30000 }
831
+ );
832
+
833
+ console.log(`πŸ† Winner: ${result.winner}`); // β†’ nvidia
834
+ console.log(`πŸ“Š Score: ${result.scores.nvidia}`); // β†’ 75
835
+ console.log(`πŸ’‘ Reasoning: ${result.reasoning}`); // β†’ scored higher on specificity
204
836
 
205
- | Feature | A3M | litellm | one-api | LibreChat | gpt-researcher |
206
- |:---|:---:|:---:|:---:|:---:|:---:|
207
- | **Parallel ensemble** | βœ… | ❌ | ❌ | ❌ | ❌ |
208
- | **Confidence scoring** | βœ… | ❌ | ❌ | ❌ | ❌ |
209
- | **Cost tracking** | βœ… | ❌ | βœ… | ❌ | ❌ |
210
- | **Memory persistence** | βœ… | ❌ | ❌ | ❌ | ❌ |
211
- | **Query-type presets** | βœ… | ❌ | ❌ | ❌ | ❌ |
212
- | **Sequential fallback** | βœ… | βœ… | βœ… | βœ… | ❌ |
213
- | **Self-hosted** | βœ… | βœ… | βœ… | βœ… | ❌ |
214
- | **Python SDK** | βœ… | βœ… | ❌ | ❌ | βœ… |
215
- | **Stars** | ⭐ | 48K | 34K | 20K | 20K |
837
+ // All results preserved, even from losers
838
+ console.log(result.allResults.groq); // β†’ groq's answer (available if needed)
839
+ ```
216
840
 
217
- **Unique:** Parallel multi-LLM execution with result merging doesn't exist anywhere else. Everyone does `try A β†’ fail β†’ try B`.
841
+ **When to use ensemble:** When answer quality matters more than latency. Ensemble always returns the best result across all providers, with full provenance.
842
+
843
+ **When to skip:** For simple lookups or latency-critical paths, use single-provider routing (heuristic <1ms).
844
+
845
+ ```typescript
846
+ // Track historical accuracy per provider
847
+ import { recordFeedback } from 'adaptive-memory-multi-model-router/ensemble';
848
+
849
+ let history = {};
850
+ history = recordFeedback('nvidia', true, history); // good answer
851
+ history = recordFeedback('groq', false, history); // bad answer
852
+ // β†’ { nvidia: { good: 1, bad: 0 }, groq: { good: 0, bad: 1 } }
853
+ ```
218
854
 
219
855
  ---
220
856
 
221
- ## πŸ“ˆ Smart Routing
857
+ ## 🧭 Query-Type Presets (P1)
858
+
859
+ Route queries to the optimal provider and temperature based on task type β€” no manual configuration needed.
860
+
861
+ | Type | Provider | Temp | Ensemble | Use Case |
862
+ |:---|:---|:---:|:---:|:---|
863
+ | ⚑ Fast | Groq | 0.3 | ❌ | Quick lookups, simple Q&A |
864
+ | πŸ”¬ Research | NVIDIA | 0.3 | βœ… | Deep analysis, comparisons |
865
+ | 🎨 Creative | NVIDIA | 0.7 | ❌ | Writing, brainstorming |
866
+ | πŸ’» Code | Any | 0.2 | βœ… | Debugging, architecture |
867
+ | πŸ“– Factual | Groq | 0.2 | ❌ | Definitions, facts |
868
+
869
+ ```typescript
870
+ import { createPresetRouter } from 'adaptive-memory-multi-model-router/presets';
871
+
872
+ const router = createPresetRouter();
222
873
 
223
- Route every query to the cheapest capable model with **99.5% Β±1 tier accuracy**:
874
+ // Classify any query automatically
875
+ const preset = router.classify("Write a Python function to sort an array");
876
+ // β†’ 'code'
224
877
 
878
+ preset.provider; // β†’ 'nvidia' (or whichever code provider is configured)
879
+ preset.temperature; // β†’ 0.2
880
+ preset.ensemble; // β†’ true
881
+ preset.maxTokens; // β†’ 3000
882
+ preset.timeoutMs; // β†’ 45000
883
+
884
+ // Customize presets for your workload
885
+ import { DEFAULT_PRESETS } from 'adaptive-memory-multi-model-router/presets';
886
+
887
+ const customRouter = createPresetRouter({
888
+ ...DEFAULT_PRESETS,
889
+ research: { ...DEFAULT_PRESETS.research, provider: 'openai' },
890
+ });
225
891
  ```
226
- Complexity 0.00 ───────── 0.19 ────────── 0.44 ────────── 1.00
227
- β”œβ”€β”€ free ────|── cheap ───────|── mid ────────| premium ──
228
- β”‚ taste-1 β”‚ llama-3.3-70b β”‚ gpt-4o-mini β”‚ gpt-4o β”‚
229
- β”‚ $0 β”‚ $0.20/M β”‚ $0.60/M β”‚ $2.50/M β”‚
892
+
893
+ ---
894
+
895
+ ## 🧠 Persistent Memory (P3)
896
+
897
+ Agent execution memories persist across CLI or API sessions via a local JSON file. Auto-saves after every 3 entries. Full keyword index rebuilt on load.
898
+
899
+ ```typescript
900
+ import { EpisodicMemoryStore } from 'adaptive-memory-multi-model-router/memory';
901
+
902
+ // Pass a file path to enable persistence
903
+ const memory = new EpisodicMemoryStore(1000, './.a3m-memory.json');
904
+
905
+ // Auto-saves to disk every 3 entries
906
+ memory.storeEntry({
907
+ task: { description: "Build a REST API in Python", type: "code", complexity: 0.7 },
908
+ result: { success: true, output: "...", duration_ms: 45000 },
909
+ agent: { id: "codex", model: "gpt-4o", provider: "openai" },
910
+ });
911
+
912
+ // On next startup, memory auto-loads from disk
913
+ const similar = memory.getSimilarTasks("Python async API", 5);
914
+ console.log(`πŸ” Found ${similar.length} similar past executions`);
915
+
916
+ memory.getStats();
917
+ // β†’ { total_entries: 142, success_rate: 0.94, avg_duration_ms: 12000 }
230
918
  ```
231
919
 
232
- | Query | A3M Cost | GPT-4o Cost | Savings |
233
- |:---|:---:|:---:|:---:|
234
- | "What is 2+2?" | $0 (free tier) | $2.50 | **100%** |
235
- | "Write Python sort" | $0.14 | $2.50 | **94%** |
236
- | "Design oncology trial" | $2.50 | $2.50 | **0%** |
237
- | **100K queries/month** | **$124** | **$341** | **64%** |
920
+ **Not just in-memory:** Unlike most agent frameworks that lose context on restart, A3M's memory survives process restarts, container redeploys, and machine reboots.
238
921
 
239
- ### Three Routing Modes
922
+ ---
240
923
 
241
- | Mode | Latency | Use Case |
242
- |:---|:---:|:---|
243
- | **Heuristic** (12 signals) | <1ms | Single-query routing to cheapest capable model |
244
- | **MCTS** (UCB1 search) | ~2s | Multi-agent workflow optimization |
245
- | **Ensemble** (parallel + scoring) | = slowest provider | Best-answer guarantee with transparency |
924
+ ## Comparison
925
+
926
+ | Feature | A3M Router | [LiteLLM](https://github.com/BerriAI/litellm) | [Portkey](https://github.com/Portkey-AI/gateway) | [OpenRouter](https://openrouter.ai) |
927
+ |---------|:----------:|:-------:|:-------:|:-------:|
928
+ | **Parallel ensemble** | **βœ…** | ❌ | ❌ | ❌ |
929
+ | **Confidence scoring** | **βœ…** | ❌ | ❌ | ❌ |
930
+ | **Routing accuracy published** | **Yes** (99.5% Β±1) | No (manual) | No | No |
931
+ | **Intelligent routing** | Multi-signal per-query | Manual selection | Manual | Manual |
932
+ | **Zero ML / Zero GPU** | **Yes** | Yes | Yes | Yes |
933
+ | **Package size** | 19.5 KB | ~50 MB | ~30 MB | API-only |
934
+ | **OpenAI-compatible proxy** | **Yes** | No | Yes | Yes | Yes |
935
+ | **Adaptive memory** | **Yes** | No | No | No | No |
936
+ | **Semantic cache** | **Yes** (trigram) | No | No | Yes | No |
937
+ | **Prompt injection detection** | **Yes** (17 patterns) | No | No | Yes | No |
938
+ | **PII redaction** | **Yes** | No | No | Yes | No |
939
+ | **Hallucination checks** | **Yes** | No | No | No | No |
940
+ | **Cost analytics** | **Yes** | No | Yes | Yes | Yes |
941
+ | **Budget alerts** | **Yes** | No | No | Yes | No |
942
+ | **Circuit breaker** | **Yes** | No | No | Yes | No |
943
+ | **LangChain adapter** | **Yes** | No | Yes | Yes | No |
944
+ | **Python SDK** | **Yes** | Yes | Yes | Yes | Yes |
945
+ | **TypeScript SDK** | **Yes** | No | No | Yes | Yes |
946
+ | **CLI** | **Yes** | No | Yes | No | No |
947
+ | **Self-hosted** | **Yes** | Yes | Yes | Yes | No |
948
+ | **License** | MIT | Apache 2.0 | Custom | MIT | Proprietary |
949
+
950
+ **Also consider:** [9router](https://github.com/decolua/9router), [ClawRouter](https://github.com/BlockRunAI/ClawRouter), [Plano](https://github.com/katanemo/plano), [Helicone](https://github.com/Helicone/helicone)
246
951
 
247
952
  ---
248
953
 
249
- ## πŸ”¬ Research-Backed
954
+ ## Production Ready
955
+
956
+ A3M Router is built for teams running AI in production β€” where budget overruns, cache inefficiency, provider outages, and retry storms cost real money and real uptime.
957
+
958
+ ### Pain Points Solved
959
+
960
+ | Problem | Without A3M Router | With A3M Router |
961
+ |---------|-------------------|-----------------|
962
+ | **Budget spiral** | Monthly bills 3-5x expected, no visibility into per-team spend | Hard per-user/per-team caps with real-time spend dashboard, alerts at 50%/80%/100% |
963
+ | **Cache misses on similar queries** | Same query by 1000 users = 1000 LLM API calls | Embedding-based semantic cache, 30%+ hit rate, configurable similarity threshold |
964
+ | **Provider outage cascades** | One provider fails β†’ all requests fail β†’ P0 incident | Circuit breaker (3 failures β†’ 60s cooldown) + automatic fallback chain |
965
+ | **Chinese provider failures** | Generic retry logic fails on Chinese APIs (rate limits, regional constraints) | Special handling: health scoring, regional awareness, provider-specific fallback |
966
+ | **Retry storms at scale** | All clients retry simultaneously on 429 β†’ provider stays overloaded | Per-provider retry config, exponential backoff, rate limit detection prevents thundering herd |
967
+ | **No observability** | Blind to which provider is failing, which team is overspending | Provider health scoring, per-provider cost breakdown, spend vs budget per team |
968
+
969
+ ### Enterprise Features
970
+
971
+ - **Hard Budget Enforcement** β€” Per-user and per-team monthly budgets with hard caps. Real-time spend dashboard shows actual vs budget. Alerts fire at 50%, 80%, 100% thresholds. Per-provider cost breakdown shows exactly where every dollar goes.
972
+
973
+ - **Semantic Cache** β€” Embedding-based cache lookup with configurable similarity threshold. Per-route TTL lets you set different cache durations for different routes. 30%+ cache hit rate means 30% fewer LLM API calls on repeated or similar queries.
250
974
 
251
- Built on findings from 30+ 2024‑2025 arXiv papers:
975
+ - **Intelligent Failover** β€” Provider health scoring combines latency and error rate into a live health score. Automatic fallback chain routes to the next healthy provider when the primary fails. Circuit breaker trips after 3 failures and cools for 60 seconds. Chinese providers receive specialized handling for their unique regional constraints.
252
976
 
253
- | Paper | Used In |
254
- |:------|:--------|
255
- | [RouteLLM](https://arxiv.org/abs/2404.06035) β€” Cost-quality routing | Heuristic signal classification |
256
- | [RadixAttention (SGLang)](https://arxiv.org/abs/2412.15115) β€” Prefix caching | Cache module |
257
- | [Medusa](https://arxiv.org/abs/2401.10774) β€” Speculative decoding | Multi-token prediction |
258
- | [A-Mem](https://arxiv.org/abs/2502.12110) β€” Episodic memory | MemoryTree with EMA |
259
- | [MCTS / UCB1](https://arxiv.org/abs/2411.20000) β€” Multi-agent search | Provider selection algorithm |
260
- | [AgentOrchestra](https://arxiv.org/abs/2506.12508) β€” Hierarchical orchestration | Multi-agent workflows |
977
+ - **Per-Provider Retry Logic** β€” Custom timeout per provider. Exponential backoff with jitter. Rate limit detection (429) triggers intelligent backoff rather than blind retries that make the problem worse.
261
978
 
262
979
  ---
263
980
 
264
- ## When NOT to Use
981
+ ## API Reference
265
982
 
266
- - **Single provider** β€” no routing benefit
267
- - **>80% expert queries** β€” just use GPT‑4o directly
268
- - **250+ providers needed** β€” use Portkey
269
- - **Enterprise SLAs / managed hosting** β€” this is self-hosted
983
+ | Method | Endpoint | Description |
984
+ |--------|----------|-------------|
985
+ | POST | `/v1/chat/completions` | OpenAI-compatible chat (streaming + non-streaming) |
986
+ | POST | `/v1/completions` | OpenAI text completions |
987
+ | POST | `/v1/route` | Routing decision without LLM call |
988
+ | GET | `/v1/models` | List available models with pricing |
989
+ | GET | `/health` | Provider health + cost summary |
990
+ | GET | `/dashboard` | Cost analytics dashboard |
991
+
992
+ Full API docs: [`docs/API.md`](docs/API.md)
270
993
 
271
994
  ---
272
995
 
273
996
  ## Package Exports
274
997
 
275
998
  ```typescript
276
- // Core routing
277
- import { routeQuery, routeBatch, extractQueryFeatures } from 'adaptive-memory-multi-model-router';
278
- import { A3MRouter } from 'adaptive-memory-multi-model-router/sdk';
999
+ // Main β€” everything
1000
+ import { routeQuery, createProxyServer, SemanticCache, GuardrailEngine } from 'adaptive-memory-multi-model-router';
279
1001
 
280
- // Ensemble (P0) β€” core differentiator
281
- import { executeEnsemble, mergeComplementary } from 'adaptive-memory-multi-model-router/ensemble';
1002
+ // SDK β€” clean high-level API
1003
+ import { A3MRouter } from 'adaptive-memory-multi-model-router/sdk';
282
1004
 
283
- // Presets (P1)
284
- import { createPresetRouter, DEFAULT_PRESETS } from 'adaptive-memory-multi-model-router/presets';
1005
+ // Individual modules
1006
+ import { SemanticCache } from 'adaptive-memory-multi-model-router/cache';
1007
+ import { GuardrailEngine } from 'adaptive-memory-multi-model-router/guardrails';
1008
+ import { CostTracker } from 'adaptive-memory-multi-model-router/cost';
1009
+ import { CostAnalytics } from 'adaptive-memory-multi-model-router/analytics';
1010
+ import { MemoryTree } from 'adaptive-memory-multi-model-router/memory';
1011
+ import { A3MChatModel } from 'adaptive-memory-multi-model-router/langchain';
1012
+ import { registerProvider } from 'adaptive-memory-multi-model-router/providers';
1013
+ import { createProxyServer } from 'adaptive-memory-multi-model-router/server';
285
1014
 
286
- // Cost (P2)
287
- import { BudgetEnforcer, CostTracker } from 'adaptive-memory-multi-model-router/cost';
1015
+ // Ensemble (P0) β€” core differentiator
1016
+ import { executeEnsemble, mergeComplementary, recordFeedback } from 'adaptive-memory-multi-model-router/ensemble';
288
1017
 
289
- // Memory (P3)
290
- import { EpisodicMemoryStore } from 'adaptive-memory-multi-model-router/memory';
1018
+ // Query-type presets (P1)
1019
+ import { createPresetRouter, getPresetForQuery, DEFAULT_PRESETS } from 'adaptive-memory-multi-model-router/presets';
291
1020
 
292
- // Caching
293
- import { SemanticCache, PrefixCache } from 'adaptive-memory-multi-model-router/cache';
1021
+ // Persistent memory (P3)
1022
+ import { EpisodicMemoryStore } from 'adaptive-memory-multi-model-router/memory';
1023
+ ```
294
1024
 
295
- // Security
296
- import { GuardrailEngine } from 'adaptive-memory-multi-model-router/security';
1025
+ ---
297
1026
 
298
- // Providers
299
- import { registerProvider, getAvailableProviders } from 'adaptive-memory-multi-model-router/providers';
1027
+ ## When NOT to Use This
300
1028
 
301
- // Server (OpenAI-compatible proxy)
302
- import { createProxyServer } from 'adaptive-memory-multi-model-router/server';
1029
+ A3M Router is an **LLM gateway and router** designed for multi-provider routing. You may not need it if:
303
1030
 
304
- // Orchestration
305
- import { MCTSWorkflowOptimizer } from 'adaptive-memory-multi-model-router/orchestration';
306
- ```
1031
+ - You only use one LLM provider (no routing benefit)
1032
+ - Your workload is >80% expert-level queries (just use GPT-4o directly)
1033
+ - You need 250+ provider integrations (use [Portkey](https://github.com/Portkey-AI/gateway))
1034
+ - You need ML-based routing with BERT classifiers (use [RouteLLM](https://github.com/Surfsol/RouteLLM))
1035
+ - You need enterprise SLAs or managed hosting
1036
+
1037
+ For single-provider use cases, the native SDK (OpenAI, Anthropic, etc.) is simpler.
307
1038
 
308
1039
  ---
309
1040
 
310
- ## πŸ”œ Roadmap
1041
+ ## Roadmap (Coming Soon)
1042
+
1043
+ These features are on our roadmap based on user feedback:
311
1044
 
312
- | Feature | Priority |
313
- |:--------|:--------:|
314
- | Distributed tracing (OpenTelemetry) | High |
315
- | Webhook alerts (Slack, PagerDuty) | High |
316
- | Fine-grained RBAC for budgets | Medium |
317
- | Multi-region failover | Medium |
318
- | SLA reporting | Low |
1045
+ | Feature | Status | Priority |
1046
+ |---------|--------|----------|
1047
+ | **Distributed tracing** β€” OpenTelemetry integration for production observability | Planned | High |
1048
+ | **Webhook alerts** β€” Push budget alerts to Slack, PagerDuty, Teams | Planned | High |
1049
+ | **Fine-grained RBAC** β€” Role-based access control for team budgets | Planned | Medium |
1050
+ | **Multi-region failover** β€” Geographic load balancing across regions | Researching | Medium |
1051
+ | **SLA reporting** β€” Uptime and latency SLAs for enterprise contracts | Researching | Low |
319
1052
 
320
1053
  ---
321
1054
 
322
- ## πŸ“š Links
1055
+ ## Links
323
1056
 
324
1057
  - [npm package](https://www.npmjs.com/package/adaptive-memory-multi-model-router)
325
1058
  - [GitHub repo](https://github.com/Das-rebel/adaptive-memory-multi-model-router)
326
1059
  - [API Reference](docs/API.md)
327
1060
  - [Architecture](docs/ARCHITECTURAL-IMPROVEMENTS-2025.md)
328
- - [Quick Start](docs/QUICK_START.md)
329
1061
  - [Discussions](https://github.com/Das-rebel/adaptive-memory-multi-model-router/discussions)
330
- - [Contributing](CONTRIBUTING.md)
1062
+ - [Contributing](CONTRIBUTING.md) Β· [Good first issues](https://github.com/Das-rebel/adaptive-memory-multi-model-router/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)
1063
+
1064
+ MIT License. No vendor lock-in. No account required. `npm install` and go.
1065
+
1066
+
1067
+ ---
1068
+
1069
+ ## Research-Backed Architecture
1070
+
1071
+ A3M Router is built on findings from **30+ 2024-2025 arXiv papers** on LLM routing, load balancing, semantic caching, and multi-agent orchestration. to deliver production-ready features:
1072
+
1073
+ | Paper | Year | What We Used |
1074
+ |-------|------|-------------|
1075
+ | **[RadixAttention (SGLang)](https://arxiv.org/abs/2412.15115)** | 2024 | **Prefix caching** β€” 5-10x throughput via prefix sharing across queries. Our cache module uses this pattern. |
1076
+ | **[RouteLLM](https://arxiv.org/abs/2404.06035)** | 2024 | **Cost-quality routing** β€” learned routing baseline. We use heuristic routing instead (no GPU, faster startup). |
1077
+ | **[Speculative Decoding (Medusa)](https://arxiv.org/abs/2401.10774)** | 2024 | **Multi-token prediction** β€” 2-3x speedup. Our speculative decoding module implements this interface. |
1078
+ | **[AgentOrchestra](https://arxiv.org/abs/2506.12508)** | 2025 | **Hierarchical multi-agent orchestration** β€” 3-tier planning. We adapted this for provider selection. |
1079
+ | **[Difficulty-Aware Routing](https://arxiv.org/abs/2509.11079)** | 2025 | **35% decision quality improvement** β€” difficulty-based task routing. Core of our routing engine. |
1080
+ | **[MemoRAG](https://arxiv.org/abs/2512.12686)** | 2025 | **Global memory encoder** β€” 50% better long-context. We use MemoryTree for historical context. |
1081
+ | **[A-Mem](https://arxiv.org/abs/2502.12110)** | 2025 | **Episodic memory** β€” 144+ citations. Our episodic memory uses EMA updates for quality scoring. |
1082
+ | **[MCTS (Monte Carlo Tree Search)](https://arxiv.org/abs/2411.20000)** | 2024 | **UCB1 exploration** β€” multi-agent workflow optimization. Used in our provider selection algorithm. |
331
1083
 
332
- MIT License. No vendor lock-in. No account required.
1084
+ ### Key Architecture Decisions (Research-Backed):
1085
+
1086
+ ```
1087
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
1088
+ β”‚ Research Sources β”‚
1089
+ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
1090
+ β”‚ SGLang/RadixAttention β†’ Prefix caching (cache) β”‚
1091
+ β”‚ Medusa/Speculative β†’ Multi-token prediction β”‚
1092
+ β”‚ AgentOrchestra/HALO β†’ Hierarchical orchestration β”‚
1093
+ β”‚ RouteLLM/LiteLLM β†’ Cost-quality routing β”‚
1094
+ β”‚ MemoRAG/A-Mem β†’ MemoryTree (episodic+semantic)β”‚
1095
+ β”‚ MCTS/UCB1 β†’ Provider selection algorithm β”‚
1096
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
1097
+ ```
1098
+
1099
+ ### Why Not Use ML-Based Routing?
1100
+
1101
+ | Approach | RouteLLM | A3M Router |
1102
+ |----------|----------|------------|
1103
+ | **Training** | Requires GPU, labeled data | Zero |
1104
+ | **Startup** | ~3 minutes | <100ms |
1105
+ | **Updates** | Retrain required | EMA, no retraining |
1106
+ | **Accuracy** | ~85% | 99.5% (Β±1 tier) |
1107
+ | **Cost** | High (GPU cluster) | Zero |
1108
+
1109
+ Research shows heuristic routing with proper feature engineering achieves comparable or better results for task classification β€” without the infrastructure overhead.
1110
+
1111
+ ---
333
1112
 
334
- **If this helps you, star the repo** ⭐ β€” it helps more developers discover parallel multi-LLM execution.
335
1113
 
336
1114
  ---
337
1115
 
338
- *"Nobody does parallel multi-LLM execution with result merging. Everyone does sequential fallback."*