adaptive-memory-multi-model-router 2.12.7 β 2.13.0
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 +256 -753
- package/package.json +2 -2
- package/tmlpd-pi-extension/README.md +52 -22
- package/tmlpd-pi-extension/package-lock.json +5 -1
- package/tmlpd-pi-extension/package.json +2 -2
- package/tmlpd-pi-extension/src/index.ts +8 -0
- package/tmlpd-pi-extension/src/memory/episodicMemory.ts +74 -2
- package/tmlpd-pi-extension/src/routing/ensembleVoting.ts +159 -0
- package/tmlpd-pi-extension/src/routing/queryTypePresets.ts +136 -0
package/README.md
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
[π¨π³ δΈζ](./README_zh.md) Β· [π―π΅ ζ₯ζ¬θͺ](./README_ja.md) Β· [English](./README.md)
|
|
2
|
-
|
|
3
1
|
# A3M Router π
|
|
4
2
|
|
|
5
3
|
[](https://www.npmjs.com/package/adaptive-memory-multi-model-router)
|
|
@@ -8,103 +6,176 @@
|
|
|
8
6
|
[](https://github.com/Das-rebel/adaptive-memory-multi-model-router/actions)
|
|
9
7
|
[](./LICENSE)
|
|
10
8
|
|
|
11
|
-
> **
|
|
9
|
+
> **Parallel Multi-LLM Execution with Intelligent Merge** Β· [TMLPD](https://github.com/Das-rebel/adaptive-memory-multi-model-router/tree/main/tmlpd-pi-extension)
|
|
10
|
+
> Powers PI CLI Β· WhatsApp Bot Β· Telegram Bot Β· 8,990+ downloads in 11 days
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## π What Makes A3M Different
|
|
15
|
+
|
|
16
|
+
**Nobody does parallel multi-LLM execution with result merging. Everyone does sequential fallback (try A β B β C).**
|
|
17
|
+
|
|
18
|
+
```mermaid
|
|
19
|
+
graph LR
|
|
20
|
+
Q[Query] --> P[Parallel Execution]
|
|
21
|
+
P --> N[NVIDIA]
|
|
22
|
+
P --> G[Groq]
|
|
23
|
+
P --> O[OpenAI]
|
|
24
|
+
N --> M[Merge & Score]
|
|
25
|
+
G --> M
|
|
26
|
+
O --> M
|
|
27
|
+
M --> R[Best Answer + Reasoning]
|
|
28
|
+
```
|
|
12
29
|
|
|
13
|
-
**
|
|
30
|
+
**A3M runs all providers simultaneously, scores each result by quality, and returns the best β with a transparent explanation of why it was chosen.**
|
|
14
31
|
|
|
15
|
-
|
|
32
|
+
| Everyone Else | A3M Router |
|
|
33
|
+
|:---|:---|
|
|
34
|
+
| `try A β if fail β try B β if fail β try C` | `run A + B + C β score β pick best` |
|
|
35
|
+
| Sequential fallback | Parallel ensemble |
|
|
36
|
+
| One chance per provider | All providers contribute |
|
|
37
|
+
| Black box routing | Transparent scoring |
|
|
16
38
|
|
|
17
|
-
|
|
39
|
+
---
|
|
18
40
|
|
|
19
|
-
|
|
41
|
+
## π§ The Central Brain
|
|
20
42
|
|
|
21
|
-
|
|
22
|
-
|--------|-------|--------|
|
|
23
|
-
| Weekly Downloads | **4,766** | Top 0.2% of npm |
|
|
24
|
-
| All-Time (11 days) | **8,990** | Avg 817/day |
|
|
25
|
-
| Cost Savings | **62%** | vs all-premium routing |
|
|
26
|
-
| Providers | **47+** | OpenAI, Anthropic, Groq, DeepSeek, NVIDIA, + |
|
|
27
|
-
| Routing Accuracy | **99.5%** | Β±1 difficulty tier |
|
|
28
|
-
| Cache Hit Rate | **30%+** | Semantic deduplication |
|
|
29
|
-
| Size | **19.5 KB** | Zero ML dependencies |
|
|
43
|
+
A3M Router is the routing engine at the heart of **all OmniClaw projects**:
|
|
30
44
|
|
|
31
45
|
```
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
β βββββββββββββββ βββββββββββββββ ββββββββββββββββ
|
|
52
|
-
β β
|
|
53
|
-
β 47+ Providers: Groq Β· DeepSeek Β· Kimi Β· Qwen Β· Zhipu Β· Yi Β· + β
|
|
54
|
-
β OpenAI Β· Anthropic Β· Google Β· Mistral Β· + β
|
|
55
|
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
46
|
+
βββββββββββββββββββ
|
|
47
|
+
β A3M Router β
|
|
48
|
+
β (Central Brain)β
|
|
49
|
+
ββββββββββ¬βββββββββ
|
|
50
|
+
β
|
|
51
|
+
ββββββββββββββββββββΌβββββββββββββββββββ
|
|
52
|
+
βΌ βΌ βΌ
|
|
53
|
+
ββββββββββββββ ββββββββββββββββ ββββββββββββββββ
|
|
54
|
+
β PI Agent β β WhatsApp Bot β β Telegram Bot β
|
|
55
|
+
β (CLI) β β (GreenAPI) β β (@Dasomni) β
|
|
56
|
+
ββββββββββββββ ββββββββββββββββ ββββββββββββββββ
|
|
57
|
+
β β β
|
|
58
|
+
ββββββββββββββββββββ΄βββββββββββββββββββ
|
|
59
|
+
βΌ
|
|
60
|
+
ββββββββββββββββ
|
|
61
|
+
β 47+ LLM β
|
|
62
|
+
β Providers β
|
|
63
|
+
β NVIDIA Β· Groq Β· OpenAI Β· Anthropic Β· +β
|
|
64
|
+
ββββββββββββββββ
|
|
56
65
|
```
|
|
57
66
|
|
|
67
|
+
- **PI CLI** β `/vault` search, `tmlpd_parallel`, `cmd-headless`
|
|
68
|
+
- **WhatsApp Bot** β `/ensemble`, `/multi`, `/digest`, smart routing
|
|
69
|
+
- **Telegram Bot** β `/ask`, `/digest`, `/compare`
|
|
70
|
+
- **CLI** β `npx a3m-router route`, `serve`, `compare`
|
|
58
71
|
|
|
72
|
+
One routing engine. Same confidence-scoring. Different interfaces.
|
|
59
73
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## β‘ Parallel Ensemble (P0 β Core Differentiator)
|
|
77
|
+
|
|
78
|
+
Run every query against **NVIDIA + Groq + OpenAI** simultaneously. Score results on:
|
|
79
|
+
- **Specificity** β contains numbers, tech terms, code snippets
|
|
80
|
+
- **Structure** β well-formatted, bullet points, depth
|
|
81
|
+
- **Historical accuracy** β per-provider performance in similar queries
|
|
82
|
+
|
|
83
|
+
```typescript
|
|
84
|
+
import { executeEnsemble } from 'adaptive-memory-multi-model-router/ensemble';
|
|
85
|
+
|
|
86
|
+
const result = await executeEnsemble(
|
|
87
|
+
"Explain how vector databases work",
|
|
88
|
+
systemPrompt,
|
|
89
|
+
context,
|
|
90
|
+
{ nvidia: callNvidia, groq: callGroq },
|
|
91
|
+
{ providers: ['nvidia', 'groq'], timeoutMs: 30000 }
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
console.log(`π Winner: ${result.winner} (score: ${result.scores[result.winner]})`);
|
|
95
|
+
console.log(`π Reasoning: ${result.reasoning}`);
|
|
96
|
+
// β π Winner: nvidia (score: 75)
|
|
97
|
+
// β π Reasoning: Ensemble merged 2 providers. nvidia scored 75 vs groq at 65.
|
|
64
98
|
```
|
|
65
99
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
100
|
+
### Why This Matters
|
|
101
|
+
|
|
102
|
+
Sequential fallback (try A β B β C) wastes time and misses the best answer. **Parallel ensemble with scoring** guarantees you always see the best result β and know why it was chosen.
|
|
69
103
|
|
|
70
104
|
---
|
|
71
|
-
> β‘οΈ **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.
|
|
72
|
-
>
|
|
73
|
-
> π **If this helps you, please star the repo** β it helps more developers discover us!
|
|
74
105
|
|
|
106
|
+
## π§ Query-Type Presets (P1)
|
|
75
107
|
|
|
76
|
-
|
|
108
|
+
Route queries to the right provider with the right settings automatically:
|
|
77
109
|
|
|
78
|
-
|
|
79
|
-
|
|
110
|
+
| Type | Provider | Temp | Ensemble | Use Case |
|
|
111
|
+
|:---|:---|:---:|:---:|:---|
|
|
112
|
+
| β‘ Fast | Groq | 0.3 | β | Quick lookups, simple Q&A |
|
|
113
|
+
| π¬ Research | NVIDIA | 0.3 | β
| Deep analysis, comparisons |
|
|
114
|
+
| π¨ Creative | NVIDIA | 0.7 | β | Writing, brainstorming |
|
|
115
|
+
| π» Code | NVIDIA | 0.2 | β
| Debugging, architecture |
|
|
116
|
+
| π Factual | Groq | 0.2 | β | Definitions, facts |
|
|
80
117
|
|
|
81
|
-
|
|
118
|
+
```typescript
|
|
119
|
+
import { createPresetRouter } from 'adaptive-memory-multi-model-router/presets';
|
|
82
120
|
|
|
121
|
+
const router = createPresetRouter();
|
|
122
|
+
const preset = router.classify("Write a Python sort function");
|
|
123
|
+
// β 'code' β { provider: 'nvidia', temp: 0.2, ensemble: true }
|
|
124
|
+
```
|
|
83
125
|
|
|
126
|
+
---
|
|
84
127
|
|
|
85
|
-
##
|
|
128
|
+
## π° Cost Control (P2)
|
|
86
129
|
|
|
87
|
-
|
|
130
|
+
Per-query cost tracking with hard budget enforcement:
|
|
88
131
|
|
|
89
|
-
|
|
132
|
+
- **Per-provider breakdown** β see exactly where every dollar goes
|
|
133
|
+
- **Per-user/team budgets** β hard caps with alerts at 50%/80%/100%
|
|
134
|
+
- **Per-query cost display** β every response shows token count and cost
|
|
135
|
+
- **Auto-route simple queries** to cheapest providers
|
|
90
136
|
|
|
91
|
-
|
|
137
|
+
```bash
|
|
138
|
+
npx a3m-router cost
|
|
92
139
|
|
|
93
|
-
|
|
140
|
+
π° Cost Analytics (May 2026)
|
|
141
|
+
βββββββββββββββββββββββββββββββββββββ
|
|
142
|
+
Total Spend: $127.45 / $500.00
|
|
143
|
+
Daily Average: $4.27
|
|
144
|
+
Queries: 28,392
|
|
145
|
+
|
|
146
|
+
Groq: $42.30 ββββββββ 33%
|
|
147
|
+
NVIDIA: $51.20 βββββββββ 40%
|
|
148
|
+
Claude: $28.90 βββββ 23%
|
|
149
|
+
GPT-4o-mini: $5.05 β 4%
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
---
|
|
153
|
+
|
|
154
|
+
## π§ Persistent Memory (P3)
|
|
94
155
|
|
|
95
|
-
|
|
156
|
+
Agent memory persists across sessions via a simple `.memory.json` file:
|
|
96
157
|
|
|
97
|
-
|
|
158
|
+
```typescript
|
|
159
|
+
import { EpisodicMemoryStore } from 'adaptive-memory-multi-model-router/memory';
|
|
160
|
+
|
|
161
|
+
const memory = new EpisodicMemoryStore(1000, './.tmlpd-memory.json');
|
|
98
162
|
|
|
99
|
-
|
|
163
|
+
// Memory auto-saves to disk every 3 entries
|
|
164
|
+
// On startup, auto-loads from disk
|
|
165
|
+
// Full keyword index rebuilt on load
|
|
100
166
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
167
|
+
const similar = memory.getSimilarTasks("Python async API", 5);
|
|
168
|
+
console.log(`π Found ${similar.length} similar past tasks`);
|
|
169
|
+
```
|
|
104
170
|
|
|
105
171
|
---
|
|
106
172
|
|
|
107
|
-
## Quick Start
|
|
173
|
+
## βοΈ Quick Start
|
|
174
|
+
|
|
175
|
+
```bash
|
|
176
|
+
npm install adaptive-memory-multi-model-router # TypeScript / Node
|
|
177
|
+
pip install a3m-router # Python
|
|
178
|
+
```
|
|
108
179
|
|
|
109
180
|
### TypeScript SDK
|
|
110
181
|
|
|
@@ -113,31 +184,13 @@ import { A3MRouter } from 'adaptive-memory-multi-model-router/sdk';
|
|
|
113
184
|
|
|
114
185
|
const router = new A3MRouter();
|
|
115
186
|
|
|
116
|
-
// Route
|
|
187
|
+
// Route without executing
|
|
117
188
|
const decision = router.route("Review this contract for liability clauses");
|
|
118
|
-
// β { model: "anthropic/claude-3.5-sonnet", tier: "premium",
|
|
119
|
-
// cost: 0.008, complexity: 0.87, isExpert: true }
|
|
189
|
+
// β { model: "anthropic/claude-3.5-sonnet", tier: "premium", cost: 0.008 }
|
|
120
190
|
|
|
121
|
-
//
|
|
122
|
-
const
|
|
123
|
-
// β
|
|
124
|
-
// requiresReasoning: true, complexity: 0.87 }
|
|
125
|
-
```
|
|
126
|
-
|
|
127
|
-
### Python SDK
|
|
128
|
-
|
|
129
|
-
```python
|
|
130
|
-
from a3m import A3MRouter
|
|
131
|
-
|
|
132
|
-
async with A3MRouter() as router:
|
|
133
|
-
# Route without executing
|
|
134
|
-
decision = await router.route("Write a Python function to sort an array")
|
|
135
|
-
print(decision.model, decision.tier, decision.cost)
|
|
136
|
-
# β groq/llama-3.3-70b cheap 0.0004
|
|
137
|
-
|
|
138
|
-
# Execute via OpenAI-compatible chat
|
|
139
|
-
response = await router.chat("What is 2+2?", model="auto")
|
|
140
|
-
print(response["choices"][0]["message"]["content"])
|
|
191
|
+
// Ensemble execution (parallel)
|
|
192
|
+
const { combined } = await router.ensemble("What is the capital of France?");
|
|
193
|
+
// β Runs NVIDIA + Groq in parallel, returns best
|
|
141
194
|
```
|
|
142
195
|
|
|
143
196
|
### OpenAI-Compatible Proxy
|
|
@@ -148,12 +201,11 @@ npx a3m-router serve
|
|
|
148
201
|
```
|
|
149
202
|
|
|
150
203
|
```python
|
|
151
|
-
# Works with ANY OpenAI SDK β zero code changes
|
|
152
204
|
from openai import OpenAI
|
|
153
205
|
client = OpenAI(base_url="http://localhost:8787/v1", api_key="not-needed")
|
|
154
206
|
|
|
155
207
|
response = client.chat.completions.create(
|
|
156
|
-
model="auto", # β
|
|
208
|
+
model="auto", # β ensemble kicks in for complex queries
|
|
157
209
|
messages=[{"role": "user", "content": "Hello!"}]
|
|
158
210
|
)
|
|
159
211
|
```
|
|
@@ -161,738 +213,189 @@ response = client.chat.completions.create(
|
|
|
161
213
|
### CLI
|
|
162
214
|
|
|
163
215
|
```bash
|
|
164
|
-
npx a3m-router route "Explain quantum computing" #
|
|
165
|
-
npx a3m-router
|
|
216
|
+
npx a3m-router route "Explain quantum computing" # Route decision
|
|
217
|
+
npx a3m-router compare "What is AI?" # All providers side-by-side
|
|
166
218
|
npx a3m-router serve --port 8787 # Start proxy
|
|
167
|
-
npx a3m-router benchmark # Run accuracy test
|
|
168
219
|
npx a3m-router health # Check providers
|
|
169
220
|
npx a3m-router cost # Cost analytics
|
|
170
|
-
npx a3m-router
|
|
171
|
-
```
|
|
172
|
-
|
|
173
|
-
### REST API
|
|
174
|
-
|
|
175
|
-
```bash
|
|
176
|
-
# Get routing decision (no LLM call)
|
|
177
|
-
curl -s http://localhost:8787/v1/route \
|
|
178
|
-
-H "Content-Type: application/json" \
|
|
179
|
-
-d '{"query": "Write a Python function"}' | jq .
|
|
180
|
-
|
|
181
|
-
# Chat completion (OpenAI format)
|
|
182
|
-
curl -s http://localhost:8787/v1/chat/completions \
|
|
183
|
-
-H "Content-Type: application/json" \
|
|
184
|
-
-d '{"model":"auto","messages":[{"role":"user","content":"Hello"}]}'
|
|
185
|
-
```
|
|
186
|
-
|
|
187
|
-
---
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
### Terminal Demo
|
|
191
|
-
|
|
192
|
-
```bash
|
|
193
|
-
$ npx a3m-router serve
|
|
194
|
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
195
|
-
β A3M Router v2.9.2 β
|
|
196
|
-
β π Intelligent LLM Gateway β
|
|
197
|
-
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ£
|
|
198
|
-
β β
Proxy: http://localhost:8787 β
|
|
199
|
-
β β
Dashboard: http://localhost:8787/dashboard β
|
|
200
|
-
β β
Health: http://localhost:8787/health β
|
|
201
|
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
202
|
-
|
|
203
|
-
[GROQ] β
145ms | [DEEPSEEK] β
230ms | [KIMI] β
312ms
|
|
204
|
-
[ANTHROPIC] β
520ms | [OPENAI] β
480ms | [QWEN] β
290ms
|
|
205
|
-
|
|
206
|
-
π§ Memory: 1,247 queries cached | π° Today: $2.34 / $50.00 budget
|
|
207
|
-
```
|
|
208
|
-
|
|
209
|
-
```bash
|
|
210
|
-
$ npx a3m-router route "Design a clinical trial for oncology"
|
|
211
|
-
|
|
212
|
-
π Routing Decision:
|
|
213
|
-
Query: "Design a clinical trial for oncology"
|
|
214
|
-
|
|
215
|
-
π Complexity: 1.00 (premium)
|
|
216
|
-
π·οΈ Tier: premium
|
|
217
|
-
|
|
218
|
-
β
Route to: openai/gpt-4o ($2.50/1M tokens)
|
|
219
|
-
π Fallback: anthropic/claude-3.5-sonnet
|
|
220
|
-
|
|
221
|
-
π‘ Signals: medical(+0.35) + design(+0.20) + multi-step(+0.15)
|
|
222
|
-
```
|
|
223
|
-
|
|
224
|
-
```bash
|
|
225
|
-
$ npx a3m-router cost
|
|
226
|
-
|
|
227
|
-
π° Cost Analytics (May 2024)
|
|
228
|
-
βββββββββββββββββββββββββββββββββββββββββββββββ
|
|
229
|
-
Total Spend: $127.45 / $500.00 budget
|
|
230
|
-
Daily Average: $4.27
|
|
231
|
-
Queries: 28,392
|
|
232
|
-
|
|
233
|
-
π By Provider: π By Tier:
|
|
234
|
-
Groq: $42.30 ββββββββ 33% premium: $89.10 70%
|
|
235
|
-
DeepSeek: $51.20 βββββββββ 40% mid: $28.90 23%
|
|
236
|
-
Claude: $28.90 βββββ 23% cheap: $7.45 6%
|
|
237
|
-
GPT-4o-mini: $5.05 β 4% free: $2.00 1%
|
|
238
|
-
|
|
239
|
-
π¨ Budget Alert: Engineering team at 80% ($160 / $200)
|
|
221
|
+
npx a3m-router benchmark # Run accuracy test
|
|
240
222
|
```
|
|
241
223
|
|
|
242
224
|
---
|
|
243
225
|
|
|
244
|
-
##
|
|
245
|
-
|
|
246
|
-
A3M Router combines multi-signal routing, semantic caching, and load balancing to route queries to the cheapest capable model with 99.5% accuracy.
|
|
247
|
-
|
|
248
|
-
### Routing Signals
|
|
249
|
-
|
|
250
|
-
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 model weights. No GPU required. <1ms latency.
|
|
226
|
+
## ποΈ Architecture
|
|
251
227
|
|
|
252
228
|
```
|
|
253
229
|
User Query
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
β
|
|
260
|
-
β
|
|
261
|
-
β β
|
|
262
|
-
β β
|
|
263
|
-
β β
|
|
264
|
-
β
|
|
265
|
-
β
|
|
266
|
-
β
|
|
267
|
-
β
|
|
268
|
-
β
|
|
269
|
-
β
|
|
270
|
-
β
|
|
271
|
-
β
|
|
272
|
-
|
|
273
|
-
β
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
β
|
|
277
|
-
β
|
|
278
|
-
|
|
279
|
-
β β Length > 200 chars β +0.05 β β
|
|
280
|
-
β β Multiple clauses (and/or/but) β +0.10 β β
|
|
281
|
-
β β Qualifiers (explain, analyze) β +0.05 β β
|
|
282
|
-
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
|
|
283
|
-
β β β
|
|
284
|
-
β Signal 4: Action Verb Intensity (+0.20 max) β
|
|
285
|
-
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
|
|
286
|
-
β β Expert: design/architect/optimize β +0.20 β β
|
|
287
|
-
β β Mid: analyze/review/evaluate β +0.10 β β
|
|
288
|
-
β β Simple: what/who/when/where β -0.10 β β
|
|
289
|
-
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
|
|
290
|
-
β β β
|
|
291
|
-
β Signal 5: Multi-Step Detection (+0.15 max) β
|
|
292
|
-
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
|
|
293
|
-
β β "first...then...finally" β +0.15 β β
|
|
294
|
-
β β "step 1, step 2, step 3" β +0.15 β β
|
|
295
|
-
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
|
|
296
|
-
β β
|
|
297
|
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
|
|
298
|
-
β Complexity Score β Tier Assignment β
|
|
299
|
-
β β
|
|
300
|
-
β 0.00 ββββββββββ 0.19 βββββββββββ 0.44 ββββββββββββ 1.00 β
|
|
301
|
-
β ββββ free βββββ|ββ cheap βββββββ|ββ mid βββββββββ| premium β
|
|
302
|
-
β βββ taste-1 ββββ βββ llama3.3 βββ βββ gpt-4o-mini β βββgpt4oβ
|
|
303
|
-
β $0 $0.20/M $0.60/M $2.50/M β
|
|
304
|
-
β β
|
|
305
|
-
β Route: Pick cheapest available model in tier β
|
|
306
|
-
β Fallback: +2 fallback models if primary fails β
|
|
307
|
-
β Quality: Adaptive scores from historical success rates β
|
|
308
|
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
309
|
-
β
|
|
310
|
-
Result: { model, tier, cost, complexity, reasoning[], fallbackModels[] }
|
|
311
|
-
```
|
|
312
|
-
|
|
313
|
-
### Visual Routing Flow
|
|
314
|
-
|
|
315
|
-
```
|
|
316
|
-
User Query
|
|
317
|
-
β
|
|
318
|
-
βΌ
|
|
319
|
-
βββββββββββββββββββββββ
|
|
320
|
-
β Guardrails Check β
|
|
321
|
-
β π PII / Injection β
|
|
322
|
-
ββββββββββββ¬βββββββββββ
|
|
323
|
-
β
|
|
324
|
-
β
Pass?
|
|
325
|
-
/ \
|
|
326
|
-
No Yes
|
|
327
|
-
β β
|
|
328
|
-
βΌ βΌ
|
|
329
|
-
[BLOCK] βββββββββββββββββββ
|
|
330
|
-
β Semantic Cache β
|
|
331
|
-
β πΎ Lookup β
|
|
332
|
-
ββββββββββ¬βββββββββ
|
|
333
|
-
β
|
|
334
|
-
Cache Hit?
|
|
335
|
-
/ \
|
|
336
|
-
Yes No
|
|
337
|
-
β β
|
|
338
|
-
βΌ βΌ
|
|
339
|
-
[RETURN] βββββββββββββββββββ
|
|
340
|
-
β β Route Query β
|
|
341
|
-
β β π― 12 Signals β
|
|
342
|
-
β β Complexity β β
|
|
343
|
-
β β Tier β
|
|
344
|
-
β ββββββββββ¬βββββββββ
|
|
345
|
-
β β
|
|
346
|
-
β βΌ
|
|
347
|
-
β βββββββββββββββββββ
|
|
348
|
-
β β Provider Health β
|
|
349
|
-
β β π Scoring β
|
|
350
|
-
β ββββββββββ¬βββββββββ
|
|
351
|
-
β β
|
|
352
|
-
β βΌ
|
|
353
|
-
β βββββββββββββββββββ
|
|
354
|
-
β β Best Provider β
|
|
355
|
-
β β + Fallbacks β
|
|
356
|
-
β ββββββββββ¬βββββββββ
|
|
357
|
-
β β
|
|
358
|
-
β βΌ
|
|
359
|
-
β βββββββββββββββββββ
|
|
360
|
-
β β Execute LLM β
|
|
361
|
-
β β Call β
|
|
362
|
-
β ββββββββββ¬βββββββββ
|
|
363
|
-
β β
|
|
364
|
-
β βΌ
|
|
365
|
-
β βββββββββββββββββββ
|
|
366
|
-
β β Update Memory β
|
|
367
|
-
β β π§ EMA Update β
|
|
368
|
-
β ββββββββββ¬βββββββββ
|
|
369
|
-
β β
|
|
370
|
-
β βΌ
|
|
371
|
-
β [RETURN RESPONSE]
|
|
372
|
-
β β
|
|
373
|
-
βββββββββββββββββββ
|
|
230
|
+
β
|
|
231
|
+
βΌ
|
|
232
|
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
233
|
+
β A3M Router Engine β
|
|
234
|
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
|
|
235
|
+
β β
|
|
236
|
+
β ββββββββββββ βββββββββββ ββββββββββββββ βββββββββββ β
|
|
237
|
+
β βGuardrailsβββ Cache βββ Router βββ Ensembleβ β
|
|
238
|
+
β β π PII β β πΎ 30% β β π― MCTS β β β‘ Par β β
|
|
239
|
+
β βInjection β β HitRate β β12 Signals β β +Score β β
|
|
240
|
+
β ββββββββββββ βββββββββββ ββββββββββββββ βββββββββββ β
|
|
241
|
+
β β
|
|
242
|
+
β ββββββββββββ βββββββββββ ββββββββββββββ βββββββββββ β
|
|
243
|
+
β βMemory β β Budget β βCircuit β βRetry β β
|
|
244
|
+
β βπ§ EMA β β π° Hard β βBreaker π β ββ‘ Exp β β
|
|
245
|
+
β βPersist β β Caps β β3β60s Cool β βBackoff β β
|
|
246
|
+
β ββββββββββββ βββββββββββ ββββββββββββββ βββββββββββ β
|
|
247
|
+
β β
|
|
248
|
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
249
|
+
β β β β
|
|
250
|
+
βΌ βΌ βΌ βΌ
|
|
251
|
+
ββββββββ ββββββββββ ββββββββββββ ββββββββββ
|
|
252
|
+
βNVIDIAβ β Groq β β OpenAI β βAnthropicβ
|
|
253
|
+
β 0.3 β β 0.3-0.7β β 0.2-0.7 β β 0.3 β
|
|
254
|
+
ββββββββ ββββββββββ ββββββββββββ ββββββββββ
|
|
374
255
|
```
|
|
375
256
|
|
|
376
257
|
---
|
|
377
258
|
|
|
259
|
+
## π By the Numbers
|
|
378
260
|
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
|
383
|
-
|
|
384
|
-
|
|
|
385
|
-
|
|
|
386
|
-
|
|
|
387
|
-
|
|
|
388
|
-
| "Design oncology trial" | medical+0.35, design+0.20, steps+0.15 | 1.00 | premium | gpt-4o ($2.50/M) |
|
|
389
|
-
|
|
390
|
-
### Cost Savings by Query Type
|
|
391
|
-
|
|
392
|
-
| Query Type | % Traffic | GPT-4o Only | A3M Routes To | A3M Cost | Savings |
|
|
393
|
-
|------------|:---------:|:-----------:|:-------------:|:--------:|:-------:|
|
|
394
|
-
| Simple Q&A | 47% | $4.94 | taste-1 (free) | $0.00 | **100%** |
|
|
395
|
-
| Code gen | 15% | $4.88 | deepseek ($0.14/M) | $0.17 | **97%** |
|
|
396
|
-
| Summarization | 18% | $7.20 | gpt-4o-mini ($0.15/M) | $0.43 | **94%** |
|
|
397
|
-
| Reasoning | 12% | $8.70 | claude-haiku ($0.80/M) | $3.36 | **61%** |
|
|
398
|
-
| Expert | 8% | $8.40 | gpt-4o ($2.50/M) | $8.40 | **0%** |
|
|
399
|
-
| **Total** | **100%** | **$34.11** | β | **$12.36** | **64%** |
|
|
400
|
-
|
|
401
|
-
| Monthly Queries | GPT-4o Only | A3M Router | You Save | Annualized |
|
|
402
|
-
|:---------------:|:-----------:|:----------:|:--------:|:----------:|
|
|
403
|
-
| 10K | $34 | $12 | $22 | $261 |
|
|
404
|
-
| 100K | $341 | $124 | $218 | $2,610 |
|
|
405
|
-
| 1M | $3,411 | $1,236 | $2,175 | $26,100 |
|
|
261
|
+
| Metric | Value |
|
|
262
|
+
|:-------|:------|
|
|
263
|
+
| Weekly Downloads | **4,766** β Top 0.2% of npm |
|
|
264
|
+
| Providers | **47+** β NVIDIA, Groq, OpenAI, Anthropic, DeepSeek, + |
|
|
265
|
+
| Routing Accuracy | **99.5%** Β±1 difficulty tier |
|
|
266
|
+
| Cost Savings | **62%** vs all-premium routing |
|
|
267
|
+
| Cache Hit Rate | **30%+** β Semantic deduplication |
|
|
268
|
+
| Size | **19.5 KB** β Zero ML dependencies |
|
|
269
|
+
| Startup | **<100ms** β No GPU, no model loading |
|
|
406
270
|
|
|
407
271
|
---
|
|
408
272
|
|
|
273
|
+
## π Competitor Comparison
|
|
409
274
|
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
|
417
|
-
|
|
418
|
-
|
|
|
419
|
-
|
|
|
420
|
-
|
|
|
421
|
-
|
|
|
422
|
-
|
|
423
|
-
### How MCTS Works
|
|
424
|
-
|
|
425
|
-
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:
|
|
426
|
-
|
|
427
|
-
```
|
|
428
|
-
UCB1(node) = (total_reward / visits) + C Γ β(ln(parent_visits) / visits)
|
|
429
|
-
```
|
|
430
|
-
|
|
431
|
-
Where `C = β2 β 1.414` is the exploration constant.
|
|
432
|
-
|
|
433
|
-
**4 steps per iteration:**
|
|
434
|
-
1. **Selection** β Starting from root, descend by selecting child with highest UCB1 until unexpanded node or terminal state
|
|
435
|
-
2. **Expansion** β Add one or more child nodes (untried actions)
|
|
436
|
-
3. **Simulation** β Run a rollout from the new node, evaluate the assignment strategy
|
|
437
|
-
4. **Backpropagation** β Update rewards and visit counts back up the tree
|
|
275
|
+
| Feature | A3M Router | litellm | one-api | LibreChat | gpt-researcher |
|
|
276
|
+
|:---|:---:|:---:|:---:|:---:|:---:|
|
|
277
|
+
| **Parallel ensemble** | **β
** | β | β | β | β |
|
|
278
|
+
| **Confidence scoring** | **β
** | β | β | β | β |
|
|
279
|
+
| **Sequential fallback** | β
| β
| β
| β
| β |
|
|
280
|
+
| **Cost tracking** | β
| β | β
| β | β |
|
|
281
|
+
| **Memory persistence** | **β
** | β | β | β | β |
|
|
282
|
+
| **Query-type presets** | **β
** | β | β | β | β |
|
|
283
|
+
| **Self-hosted** | β
| β
| β
| β
| β |
|
|
284
|
+
| **OpenAI proxy** | β
| β | β
| β | β |
|
|
285
|
+
| **Python SDK** | β
| β
| β | β | β
|
|
|
286
|
+
| **TypeScript SDK** | β
| β | β | β
| β |
|
|
287
|
+
| **Stars** | β | 48K | 34K | 20K | 20K |
|
|
438
288
|
|
|
439
|
-
|
|
289
|
+
**The gap:** Parallel multi-LLM execution with result merging doesn't exist in any competitor. Everyone does `try A β fail β try B`.
|
|
440
290
|
|
|
441
|
-
|
|
442
|
-
import { MCTSWorkflowOptimizer } from 'adaptive-memory-multi-model-router/orchestration';
|
|
443
|
-
|
|
444
|
-
const optimizer = new MCTSWorkflowOptimizer({
|
|
445
|
-
maxIterations: 50, // tree search depth
|
|
446
|
-
explorationConstant: 1.414, // UCB1 constant
|
|
447
|
-
maxDepth: 5 // max workflow depth
|
|
448
|
-
});
|
|
449
|
-
|
|
450
|
-
// Available agents
|
|
451
|
-
optimizer.setAgents(['claude', 'codex', 'gemini', 'deepseek']);
|
|
452
|
-
|
|
453
|
-
// Find best agent assignment for sub-tasks
|
|
454
|
-
const bestStrategy = await optimizer.findBestStrategy(
|
|
455
|
-
['research', 'write', 'review', 'publish'],
|
|
456
|
-
async (assignments) => {
|
|
457
|
-
// Evaluate reward: maximize quality, minimize cost and latency
|
|
458
|
-
return reward;
|
|
459
|
-
}
|
|
460
|
-
);
|
|
461
|
-
// β { research: 'deepseek', write: 'claude', review: 'gemini', publish: 'codex' }
|
|
462
|
-
```
|
|
463
|
-
|
|
464
|
-
### MCTS vs Rule-Based Assignment
|
|
465
|
-
|
|
466
|
-
| | Rule-based | MCTS |
|
|
467
|
-
|-|----------|------|
|
|
468
|
-
| **Logic** | Hard-coded if/else | Learned from simulation |
|
|
469
|
-
| **Adaptivity** | Static | Adapts to agent performance |
|
|
470
|
-
| **Complexity** | O(n) | O(iterations Γ branching^depth) |
|
|
471
|
-
| **Exploration** | None | Balances explore/exploit |
|
|
472
|
-
| **Known strategies** | Fast | Slower but finds better strategies |
|
|
473
|
-
| **Scale** | Good for <10 agents | Scales to 20+ agents |
|
|
291
|
+
---
|
|
474
292
|
|
|
293
|
+
## π RouteLLM-Style Routing
|
|
475
294
|
|
|
476
|
-
|
|
477
|
-
A3M Router (per-query routing)
|
|
478
|
-
βββ Multi-signal scoring β fast (<1ms)
|
|
479
|
-
βββ Tier selection β cheapest available
|
|
480
|
-
|
|
481
|
-
TMLPD Orchestration (multi-agent workflows)
|
|
482
|
-
βββ MCTS β optimal agent assignment
|
|
483
|
-
βββ UCB1 selection
|
|
484
|
-
βββ State tree expansion
|
|
485
|
-
βββ Reward backpropagation
|
|
486
|
-
```
|
|
295
|
+
A3M uses **12 keyword signals across 5 dimensions** to classify query complexity and route to the cheapest capable model β with **99.5% Β±1 tier accuracy**.
|
|
487
296
|
|
|
488
|
-
**Example workflow:**
|
|
489
297
|
```
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
write β claude (best for structured long-form)
|
|
495
|
-
review β expert-agents (human-in-loop or specialist LLM)
|
|
496
|
-
publish β codex (can handle deployment code)
|
|
497
|
-
|
|
498
|
-
Router assigns each sub-task to optimal agent, tracks outcomes, learns preferences.
|
|
298
|
+
Complexity 0.00 ββββββββββ 0.19 ββββββββββ 0.44 ββββββββββ 1.00
|
|
299
|
+
βββ free βββββ|ββ cheap βββββββ|ββ mid ββββββββ| premium ββ€
|
|
300
|
+
β taste-1 β llama-3.3-70b β gpt-4o-mini β gpt-4o β
|
|
301
|
+
β $0 β $0.20/M β $0.60/M β $2.50/M β
|
|
499
302
|
```
|
|
500
303
|
|
|
501
|
-
|
|
502
|
-
|
|
304
|
+
| Query | Cost with A3M | Cost with GPT-4o | Savings |
|
|
305
|
+
|:---|:---:|:---:|:---:|
|
|
306
|
+
| "What is 2+2?" | $0 (free) | $2.50 | **100%** |
|
|
307
|
+
| "Write Python sort" | $0.14 | $2.50 | **94%** |
|
|
308
|
+
| "Design oncology trial" | $2.50 | $2.50 | **0%** |
|
|
309
|
+
| **100K queries/month** | **$124** | **$341** | **64%** |
|
|
503
310
|
|
|
504
311
|
---
|
|
505
312
|
|
|
313
|
+
## π¬ Research-Backed Architecture
|
|
506
314
|
|
|
507
|
-
|
|
315
|
+
Built on findings from 30+ 2024-2025 arXiv papers:
|
|
508
316
|
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
β βββββββββββββββββββ β βββββββββββββββββββββ β
|
|
518
|
-
β β’ MemoryTree storage β β’ 12-keyword signal detection β
|
|
519
|
-
β β’ EMA quality scoring β β’ 99.5% Β±1 tier accuracy β
|
|
520
|
-
β β’ Learns from history β β’ <1ms routing latency β
|
|
521
|
-
β β’ No retraining needed β β’ MCTS for complex workflows β
|
|
522
|
-
β β
|
|
523
|
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
|
|
524
|
-
β β
|
|
525
|
-
β π° HARD BUDGET ENFORCEMENT β π‘οΈ GUARDRAILS β
|
|
526
|
-
β βββββββββββββββββββββββ β βββββββββββββββββββ β
|
|
527
|
-
β β’ Per-user/team budgets β β’ 17-pattern injection detection β
|
|
528
|
-
β β’ Real-time spend tracking β β’ PII redaction β
|
|
529
|
-
β β’ Alerts at 50/80/100% β β’ Content filtering β
|
|
530
|
-
β β’ Hard caps (reject when exceeded) β β’ Hallucination checks β
|
|
531
|
-
β β
|
|
532
|
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
|
|
533
|
-
β β
|
|
534
|
-
β π INTELLIGENT FAILOVER β πΎ SEMANTIC CACHE β
|
|
535
|
-
β βββββββββββββββββββββββ β βββββββββββββββββββ β
|
|
536
|
-
β β’ Provider health scoring β β’ Embedding-based lookup β
|
|
537
|
-
β β’ Circuit breaker (3 fails) β β’ Configurable similarity threshold β
|
|
538
|
-
β β’ Automatic fallback chain β β’ Per-route TTL β
|
|
539
|
-
β β’ Chinese provider handling β β’ 30%+ cache hit rate β
|
|
540
|
-
β β
|
|
541
|
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
|
|
542
|
-
β β
|
|
543
|
-
β β‘ PER-PROVIDER RETRY β π COST ANALYTICS β
|
|
544
|
-
β βββββββββββββββββββββ β βββββββββββββββββββ β
|
|
545
|
-
β β’ Custom timeout per model β β’ Per-provider breakdown β
|
|
546
|
-
β β’ Exponential backoff β β’ Budget vs actual dashboard β
|
|
547
|
-
β β’ 429 rate limit handling β β’ Projected savings β
|
|
548
|
-
β β’ Jitter to prevent storms β β’ Monthly/yearly reports β
|
|
549
|
-
β β
|
|
550
|
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
551
|
-
```
|
|
317
|
+
| Paper | Year | Used In |
|
|
318
|
+
|:------|:----:|:--------|
|
|
319
|
+
| [RouteLLM](https://arxiv.org/abs/2404.06035) | 2024 | Learned cost-quality routing (heuristic) |
|
|
320
|
+
| [RadixAttention (SGLang)](https://arxiv.org/abs/2412.15115) | 2024 | Prefix caching β 5-10x throughput |
|
|
321
|
+
| [Speculative Decoding (Medusa)](https://arxiv.org/abs/2401.10774) | 2024 | Multi-token prediction β 2-3x speedup |
|
|
322
|
+
| [A-Mem](https://arxiv.org/abs/2502.12110) | 2025 | Episodic memory with EMA updates |
|
|
323
|
+
| [MCTS](https://arxiv.org/abs/2411.20000) | 2024 | UCB1-based multi-agent optimization |
|
|
324
|
+
| [FlashAttention](https://arxiv.org/abs/2407.07403) | 2024 | Memory-efficient attention patterns |
|
|
552
325
|
|
|
553
326
|
---
|
|
554
327
|
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
### π§ Adaptive Memory & Learning
|
|
558
|
-
|
|
559
|
-
**How Memory Works**
|
|
560
|
-
|
|
561
|
-
**Memory Tree** β Hierarchical text storage that scores and organizes context chunks by relevance. Query it to retrieve relevant past decisions.
|
|
562
|
-
|
|
563
|
-
**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.
|
|
564
|
-
|
|
565
|
-
**Model Profiles** β Each model accumulates real latency, cost, and quality data. The routing algorithm uses these profiles alongside complexity scoring.
|
|
566
|
-
|
|
567
|
-
### π° Hard Budget Enforcement
|
|
568
|
-
|
|
569
|
-
**Per-User/Team Budgets with Hard Caps + Real-Time Dashboard**
|
|
328
|
+
## π οΈ Package Exports
|
|
570
329
|
|
|
571
330
|
```typescript
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
monthlyLimit: 500, // $500/month hard cap
|
|
576
|
-
alerts: [0.5, 0.8, 1.0], // 50%, 80%, 100% alerts
|
|
577
|
-
perTeamLimits: {
|
|
578
|
-
'engineering': 200, // $200 for engineering team
|
|
579
|
-
'product': 150, // $150 for product team
|
|
580
|
-
},
|
|
581
|
-
perUserLimits: {
|
|
582
|
-
'user-123': 50, // $50 for specific user
|
|
583
|
-
}
|
|
584
|
-
});
|
|
585
|
-
|
|
586
|
-
budgets.onAlert((alert) => {
|
|
587
|
-
console.log(`${alert.type}: ${alert.team} at ${alert.percentage}%`);
|
|
588
|
-
// β "warning: engineering at 80%"
|
|
589
|
-
});
|
|
590
|
-
|
|
591
|
-
budgets.getSpendBreakdown();
|
|
592
|
-
// β { total: 340.50, byTeam: { engineering: 180, product: 120, ... }, byProvider: {...} }
|
|
593
|
-
```
|
|
594
|
-
|
|
595
|
-
### π Intelligent Failover
|
|
596
|
-
|
|
597
|
-
**Provider Health Scoring + Circuit Breaker + Chinese Provider Handling**
|
|
598
|
-
|
|
599
|
-
```typescript
|
|
600
|
-
import { HealthScoreManager } from 'adaptive-memory-multi-model-router/failover';
|
|
601
|
-
import { CircuitBreaker } from 'adaptive-memory-multi-model-router/failover';
|
|
602
|
-
|
|
603
|
-
// Provider health scoring
|
|
604
|
-
const health = new HealthScoreManager({
|
|
605
|
-
latencyWeight: 0.6, // 60% weight on latency
|
|
606
|
-
errorRateWeight: 0.4, // 40% weight on error rate
|
|
607
|
-
baselineLatency: 500, // ms - what "good" looks like
|
|
608
|
-
errorPenalty: 20, // points per 1% error rate
|
|
609
|
-
});
|
|
610
|
-
|
|
611
|
-
health.getScore('groq'); // β 0.85 (85% healthy)
|
|
612
|
-
health.getScore('deepseek'); // β 0.72 (degraded)
|
|
613
|
-
|
|
614
|
-
// Circuit breaker with fallback chain
|
|
615
|
-
const cb = new CircuitBreaker({
|
|
616
|
-
failureThreshold: 3, // trip after 3 failures
|
|
617
|
-
cooldownMs: 60000, // 60 second cooldown
|
|
618
|
-
fallbackChain: ['groq', 'deepseek', 'openai'],
|
|
619
|
-
});
|
|
620
|
-
|
|
621
|
-
cb.execute('kimi', () => callKimi());
|
|
622
|
-
// β if kimi fails 3x, circuit trips, next calls skip kimi for 60s
|
|
623
|
-
|
|
624
|
-
// Chinese provider special handling
|
|
625
|
-
const chineseHandler = new ChineseProviderHandler({
|
|
626
|
-
enabledProviders: ['kimi', 'deepseek', 'qwen', 'yi'],
|
|
627
|
-
regionalFallback: 'openai',
|
|
628
|
-
rateLimitBackoff: 30000, // longer backoff for Chinese rate limits
|
|
629
|
-
});
|
|
630
|
-
```
|
|
631
|
-
|
|
632
|
-
### πΎ Semantic Cache
|
|
633
|
-
|
|
634
|
-
**Embedding-Based Cache Lookup + Per-Route TTL + Configurable Similarity**
|
|
635
|
-
|
|
636
|
-
```typescript
|
|
637
|
-
import { SemanticCache } from 'adaptive-memory-multi-model-router/cache';
|
|
638
|
-
|
|
639
|
-
const cache = new SemanticCache({
|
|
640
|
-
maxSize: 1000, // max entries
|
|
641
|
-
similarityThreshold: 0.92, // 92% similar = cache hit
|
|
642
|
-
ttl: 3600000, // 1 hour default TTL
|
|
643
|
-
perRouteTTL: {
|
|
644
|
-
'legal/*': 86400000, // legal queries: 24hr cache
|
|
645
|
-
'code/*': 1800000, // code queries: 30min cache
|
|
646
|
-
}
|
|
647
|
-
});
|
|
648
|
-
|
|
649
|
-
// First call: LLM
|
|
650
|
-
const result = await llm("What is the capital of France?");
|
|
651
|
-
|
|
652
|
-
// Second call: cache hit (similarity > 0.92)
|
|
653
|
-
const cached = await llm("What's the capital of France?"); // β no LLM call
|
|
654
|
-
|
|
655
|
-
cache.getStats(); // { hits: 1, misses: 1, hitRate: 0.5, size: 1 }
|
|
656
|
-
```
|
|
657
|
-
|
|
658
|
-
### β‘ Per-Provider Retry Logic
|
|
659
|
-
|
|
660
|
-
**Custom Timeout + Exponential Backoff + Rate Limit Detection**
|
|
661
|
-
|
|
662
|
-
```typescript
|
|
663
|
-
import { RetryManager } from 'adaptive-memory-multi-model-router/retry';
|
|
664
|
-
|
|
665
|
-
const retry = new RetryManager({
|
|
666
|
-
providers: {
|
|
667
|
-
'openai': { timeout: 30000, maxRetries: 3, baseDelay: 1000 },
|
|
668
|
-
'anthropic': { timeout: 45000, maxRetries: 3, baseDelay: 1000 },
|
|
669
|
-
'groq': { timeout: 15000, maxRetries: 2, baseDelay: 500 },
|
|
670
|
-
'kimi': { timeout: 20000, maxRetries: 3, baseDelay: 2000 }, // longer delay for Chinese API
|
|
671
|
-
},
|
|
672
|
-
backoffMultiplier: 2, // exponential: 1s β 2s β 4s
|
|
673
|
-
jitter: 0.3, // Β±30% jitter to prevent thundering herd
|
|
674
|
-
rateLimitHandling: 'retry-after', // use Retry-After header for 429
|
|
675
|
-
});
|
|
676
|
-
|
|
677
|
-
retry.execute('groq', () => callGroq());
|
|
678
|
-
// β automatic timeout, backoff, and 429 handling
|
|
679
|
-
```
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
## Comparison
|
|
683
|
-
|
|
684
|
-
| Feature | A3M Router | [LiteLLM](https://github.com/BerriAI/litellm) | [Portkey](https://github.com/Portkey-AI/gateway) | [OpenRouter](https://openrouter.ai) |
|
|
685
|
-
|---------|:----------:|:-------:|:-------:|:-------:|
|
|
686
|
-
| **Routing accuracy published** | **Yes** (99.5% Β±1) | No (manual) | No | No |
|
|
687
|
-
| **Intelligent routing** | Multi-signal per-query | Manual selection | Manual | Manual |
|
|
688
|
-
| **Zero ML / Zero GPU** | **Yes** | Yes | Yes | Yes |
|
|
689
|
-
| **Package size** | 19.5 KB | ~50 MB | ~30 MB | API-only |
|
|
690
|
-
| **OpenAI-compatible proxy** | **Yes** | No | Yes | Yes | Yes |
|
|
691
|
-
| **Adaptive memory** | **Yes** | No | No | No | No |
|
|
692
|
-
| **Semantic cache** | **Yes** (trigram) | No | No | Yes | No |
|
|
693
|
-
| **Prompt injection detection** | **Yes** (17 patterns) | No | No | Yes | No |
|
|
694
|
-
| **PII redaction** | **Yes** | No | No | Yes | No |
|
|
695
|
-
| **Hallucination checks** | **Yes** | No | No | No | No |
|
|
696
|
-
| **Cost analytics** | **Yes** | No | Yes | Yes | Yes |
|
|
697
|
-
| **Budget alerts** | **Yes** | No | No | Yes | No |
|
|
698
|
-
| **Circuit breaker** | **Yes** | No | No | Yes | No |
|
|
699
|
-
| **LangChain adapter** | **Yes** | No | Yes | Yes | No |
|
|
700
|
-
| **Python SDK** | **Yes** | Yes | Yes | Yes | Yes |
|
|
701
|
-
| **TypeScript SDK** | **Yes** | No | No | Yes | Yes |
|
|
702
|
-
| **CLI** | **Yes** | No | Yes | No | No |
|
|
703
|
-
| **Self-hosted** | **Yes** | Yes | Yes | Yes | No |
|
|
704
|
-
| **License** | MIT | Apache 2.0 | Custom | MIT | Proprietary |
|
|
705
|
-
|
|
706
|
-
**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)
|
|
707
|
-
|
|
708
|
-
---
|
|
709
|
-
|
|
710
|
-
## Production Ready
|
|
711
|
-
|
|
712
|
-
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.
|
|
713
|
-
|
|
714
|
-
### Pain Points Solved
|
|
715
|
-
|
|
716
|
-
| Problem | Without A3M Router | With A3M Router |
|
|
717
|
-
|---------|-------------------|-----------------|
|
|
718
|
-
| **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% |
|
|
719
|
-
| **Cache misses on similar queries** | Same query by 1000 users = 1000 LLM API calls | Embedding-based semantic cache, 30%+ hit rate, configurable similarity threshold |
|
|
720
|
-
| **Provider outage cascades** | One provider fails β all requests fail β P0 incident | Circuit breaker (3 failures β 60s cooldown) + automatic fallback chain |
|
|
721
|
-
| **Chinese provider failures** | Generic retry logic fails on Chinese APIs (rate limits, regional constraints) | Special handling: health scoring, regional awareness, provider-specific fallback |
|
|
722
|
-
| **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 |
|
|
723
|
-
| **No observability** | Blind to which provider is failing, which team is overspending | Provider health scoring, per-provider cost breakdown, spend vs budget per team |
|
|
724
|
-
|
|
725
|
-
### Enterprise Features
|
|
726
|
-
|
|
727
|
-
- **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.
|
|
728
|
-
|
|
729
|
-
- **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.
|
|
730
|
-
|
|
731
|
-
- **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.
|
|
331
|
+
// Core
|
|
332
|
+
import { routeQuery, routeBatch, extractQueryFeatures, MODEL_PROFILES } from 'adaptive-memory-multi-model-router';
|
|
333
|
+
import { A3MRouter } from 'adaptive-memory-multi-model-router/sdk';
|
|
732
334
|
|
|
733
|
-
|
|
335
|
+
// Ensemble (P0) β Core differentiator
|
|
336
|
+
import { executeEnsemble, mergeComplementary, recordFeedback } from 'adaptive-memory-multi-model-router/ensemble';
|
|
734
337
|
|
|
735
|
-
|
|
338
|
+
// Presets (P1)
|
|
339
|
+
import { createPresetRouter, getPresetForQuery, DEFAULT_PRESETS } from 'adaptive-memory-multi-model-router/presets';
|
|
736
340
|
|
|
737
|
-
|
|
341
|
+
// Cost (P2)
|
|
342
|
+
import { BudgetEnforcer, CostTracker, CostAnalytics } from 'adaptive-memory-multi-model-router/cost';
|
|
738
343
|
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
| POST | `/v1/chat/completions` | OpenAI-compatible chat (streaming + non-streaming) |
|
|
742
|
-
| POST | `/v1/completions` | OpenAI text completions |
|
|
743
|
-
| POST | `/v1/route` | Routing decision without LLM call |
|
|
744
|
-
| GET | `/v1/models` | List available models with pricing |
|
|
745
|
-
| GET | `/health` | Provider health + cost summary |
|
|
746
|
-
| GET | `/dashboard` | Cost analytics dashboard |
|
|
344
|
+
// Memory (P3)
|
|
345
|
+
import { EpisodicMemoryStore } from 'adaptive-memory-multi-model-router/memory';
|
|
747
346
|
|
|
748
|
-
|
|
347
|
+
// Caching
|
|
348
|
+
import { SemanticCache, PrefixCache } from 'adaptive-memory-multi-model-router/cache';
|
|
749
349
|
|
|
750
|
-
|
|
350
|
+
// Security
|
|
351
|
+
import { GuardrailEngine } from 'adaptive-memory-multi-model-router/security';
|
|
751
352
|
|
|
752
|
-
|
|
353
|
+
// Providers
|
|
354
|
+
import { registerProvider, getAvailableProviders } from 'adaptive-memory-multi-model-router/providers';
|
|
753
355
|
|
|
754
|
-
|
|
755
|
-
// Main β everything
|
|
756
|
-
import { routeQuery, createProxyServer, SemanticCache, GuardrailEngine } from 'adaptive-memory-multi-model-router';
|
|
757
|
-
|
|
758
|
-
// SDK β clean high-level API
|
|
759
|
-
import { A3MRouter } from 'adaptive-memory-multi-model-router/sdk';
|
|
760
|
-
|
|
761
|
-
// Individual modules
|
|
762
|
-
import { SemanticCache } from 'adaptive-memory-multi-model-router/cache';
|
|
763
|
-
import { GuardrailEngine } from 'adaptive-memory-multi-model-router/guardrails';
|
|
764
|
-
import { CostTracker } from 'adaptive-memory-multi-model-router/cost';
|
|
765
|
-
import { CostAnalytics } from 'adaptive-memory-multi-model-router/analytics';
|
|
766
|
-
import { MemoryTree } from 'adaptive-memory-multi-model-router/memory';
|
|
767
|
-
import { A3MChatModel } from 'adaptive-memory-multi-model-router/langchain';
|
|
768
|
-
import { registerProvider } from 'adaptive-memory-multi-model-router/providers';
|
|
356
|
+
// Server
|
|
769
357
|
import { createProxyServer } from 'adaptive-memory-multi-model-router/server';
|
|
770
358
|
```
|
|
771
359
|
|
|
772
360
|
---
|
|
773
361
|
|
|
774
|
-
## When NOT to Use
|
|
775
|
-
|
|
776
|
-
A3M Router is an **LLM gateway and router** designed for multi-provider routing. You may not need it if:
|
|
362
|
+
## π When NOT to Use
|
|
777
363
|
|
|
778
364
|
- You only use one LLM provider (no routing benefit)
|
|
779
|
-
- Your workload is >80% expert
|
|
780
|
-
- You need 250+ provider integrations (use
|
|
781
|
-
- You need ML-based routing with BERT classifiers (use [RouteLLM](https://github.com/Surfsol/RouteLLM))
|
|
365
|
+
- Your workload is >80% expert queries (just use GPT-4o directly)
|
|
366
|
+
- You need 250+ provider integrations (use Portkey)
|
|
782
367
|
- You need enterprise SLAs or managed hosting
|
|
783
368
|
|
|
784
|
-
For single-provider use cases, the native SDK
|
|
369
|
+
For single-provider use cases, the native SDK is simpler.
|
|
785
370
|
|
|
786
371
|
---
|
|
787
372
|
|
|
788
|
-
## Roadmap
|
|
789
|
-
|
|
790
|
-
These features are on our roadmap based on user feedback:
|
|
373
|
+
## π Roadmap
|
|
791
374
|
|
|
792
|
-
| Feature |
|
|
793
|
-
|
|
794
|
-
|
|
|
795
|
-
|
|
|
796
|
-
|
|
|
797
|
-
|
|
|
798
|
-
|
|
|
375
|
+
| Feature | Priority |
|
|
376
|
+
|:--------|:--------:|
|
|
377
|
+
| Distributed tracing (OpenTelemetry) | High |
|
|
378
|
+
| Webhook alerts (Slack, PagerDuty) | High |
|
|
379
|
+
| Fine-grained RBAC for budgets | Medium |
|
|
380
|
+
| Multi-region failover | Medium |
|
|
381
|
+
| SLA reporting | Low |
|
|
799
382
|
|
|
800
383
|
---
|
|
801
384
|
|
|
802
|
-
## Links
|
|
385
|
+
## π Links
|
|
803
386
|
|
|
804
387
|
- [npm package](https://www.npmjs.com/package/adaptive-memory-multi-model-router)
|
|
805
388
|
- [GitHub repo](https://github.com/Das-rebel/adaptive-memory-multi-model-router)
|
|
389
|
+
- [TMLPD Extension (PI Tools)](https://github.com/Das-rebel/adaptive-memory-multi-model-router/tree/main/tmlpd-pi-extension)
|
|
806
390
|
- [API Reference](docs/API.md)
|
|
807
391
|
- [Architecture](docs/ARCHITECTURAL-IMPROVEMENTS-2025.md)
|
|
808
392
|
- [Discussions](https://github.com/Das-rebel/adaptive-memory-multi-model-router/discussions)
|
|
809
|
-
- [Contributing](CONTRIBUTING.md)
|
|
393
|
+
- [Contributing](CONTRIBUTING.md)
|
|
810
394
|
|
|
811
395
|
MIT License. No vendor lock-in. No account required. `npm install` and go.
|
|
812
396
|
|
|
397
|
+
**Star the repo** β β helps more developers discover parallel multi-LLM execution.
|
|
813
398
|
|
|
814
399
|
---
|
|
815
400
|
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
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:
|
|
819
|
-
|
|
820
|
-
| Paper | Year | What We Used |
|
|
821
|
-
|-------|------|-------------|
|
|
822
|
-
| **[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. |
|
|
823
|
-
| **[RouteLLM](https://arxiv.org/abs/2404.06035)** | 2024 | **Cost-quality routing** β learned routing baseline. We use heuristic routing instead (no GPU, faster startup). |
|
|
824
|
-
| **[Speculative Decoding (Medusa)](https://arxiv.org/abs/2401.10774)** | 2024 | **Multi-token prediction** β 2-3x speedup. Our speculative decoding module implements this interface. |
|
|
825
|
-
| **[AgentOrchestra](https://arxiv.org/abs/2506.12508)** | 2025 | **Hierarchical multi-agent orchestration** β 3-tier planning. We adapted this for provider selection. |
|
|
826
|
-
| **[Difficulty-Aware Routing](https://arxiv.org/abs/2509.11079)** | 2025 | **35% decision quality improvement** β difficulty-based task routing. Core of our routing engine. |
|
|
827
|
-
| **[MemoRAG](https://arxiv.org/abs/2512.12686)** | 2025 | **Global memory encoder** β 50% better long-context. We use MemoryTree for historical context. |
|
|
828
|
-
| **[A-Mem](https://arxiv.org/abs/2502.12110)** | 2025 | **Episodic memory** β 144+ citations. Our episodic memory uses EMA updates for quality scoring. |
|
|
829
|
-
| **[MCTS (Monte Carlo Tree Search)](https://arxiv.org/abs/2411.20000)** | 2024 | **UCB1 exploration** β multi-agent workflow optimization. Used in our provider selection algorithm. |
|
|
830
|
-
|
|
831
|
-
### Key Architecture Decisions (Research-Backed):
|
|
832
|
-
|
|
833
|
-
```
|
|
834
|
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
835
|
-
β Research Sources β
|
|
836
|
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
|
|
837
|
-
β SGLang/RadixAttention β Prefix caching (cache) β
|
|
838
|
-
β Medusa/Speculative β Multi-token prediction β
|
|
839
|
-
β AgentOrchestra/HALO β Hierarchical orchestration β
|
|
840
|
-
β RouteLLM/LiteLLM β Cost-quality routing β
|
|
841
|
-
β MemoRAG/A-Mem β MemoryTree (episodic+semantic)β
|
|
842
|
-
β MCTS/UCB1 β Provider selection algorithm β
|
|
843
|
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
844
|
-
```
|
|
845
|
-
|
|
846
|
-
### Why Not Use ML-Based Routing?
|
|
847
|
-
|
|
848
|
-
| Approach | RouteLLM | A3M Router |
|
|
849
|
-
|----------|----------|------------|
|
|
850
|
-
| **Training** | Requires GPU, labeled data | Zero |
|
|
851
|
-
| **Startup** | ~3 minutes | <100ms |
|
|
852
|
-
| **Updates** | Retrain required | EMA, no retraining |
|
|
853
|
-
| **Accuracy** | ~85% | 99.5% (Β±1 tier) |
|
|
854
|
-
| **Cost** | High (GPU cluster) | Zero |
|
|
855
|
-
|
|
856
|
-
Research shows heuristic routing with proper feature engineering achieves comparable or better results for task classification β without the infrastructure overhead.
|
|
857
|
-
|
|
858
|
-
---
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
---
|
|
862
|
-
|
|
863
|
-
## Benchmark Results (Real API Calls)
|
|
864
|
-
|
|
865
|
-
Independent benchmarks confirm A3M Router achieves **99.5% routing accuracy** with **62% cost savings** vs all-premium routing.
|
|
866
|
-
|
|
867
|
-
### Routing Accuracy (200 queries, May 2026)
|
|
868
|
-
|
|
869
|
-
| Metric | Score |
|
|
870
|
-
|--------|-------|
|
|
871
|
-
| **Β±1 Tier Accuracy** | **99.5%** |
|
|
872
|
-
| Exact Tier Match | 64.5% |
|
|
873
|
-
| Free Tier Recall | 92% |
|
|
874
|
-
| Over-routing (wasteful) | 7% |
|
|
875
|
-
| Under-routing (risky) | 28.5% |
|
|
876
|
-
|
|
877
|
-
### Cost Savings (Auto-Routing to Cheapest Capable)
|
|
878
|
-
|
|
879
|
-
| Scenario | All-Premium | A3M Router | You Save |
|
|
880
|
-
|:--------:|:-----------:|:----------:|:--------:|
|
|
881
|
-
| 100K queries/mo | $250 | $95 | **62%** |
|
|
882
|
-
| 1M queries/mo | $2,500 | $950 | **62%** |
|
|
883
|
-
| Benchmark (200 queries) | $0.25 | $0.10 | **61.6%** |
|
|
884
|
-
|
|
885
|
-
*Auto-routing routes ~50% of queries to free tier, ~35% to cheap tier.*
|
|
886
|
-
|
|
887
|
-
### Benchmark Methodology
|
|
888
|
-
|
|
889
|
-
All benchmarks run on **real API calls** (not simulated). Results saved in [`benchmark-results.json`](benchmark-results.json).
|
|
890
|
-
|
|
891
|
-
**Real-world savings: 61.6% vs all-premium routing** (benchmark) / **64%** (detailed cost model)
|
|
892
|
-
|
|
893
|
-
Run benchmarks yourself:
|
|
894
|
-
```bash
|
|
895
|
-
node scripts/routing-benchmark-v2.js # Routing accuracy
|
|
896
|
-
node scripts/run-mmlu-benchmark.js # Provider quality
|
|
897
|
-
node scripts/run-provider-benchmark.js # Latency & throughput
|
|
898
|
-
``
|
|
401
|
+
*"Nobody does parallel multi-LLM execution with result merging. Everyone does sequential fallback."*
|