adaptive-memory-multi-model-router 2.14.60 → 2.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/.github/ISSUE_TEMPLATE/checklist.md +35 -0
  2. package/.github/workflows/ci.yml +9 -6
  3. package/POPULARITY_BOOSTERS.md +18 -0
  4. package/README.md +130 -1067
  5. package/assets/chart-accuracy-by-tier.svg +63 -0
  6. package/assets/chart-confusion-matrix.svg +98 -0
  7. package/assets/chart-cost-comparison.svg +66 -0
  8. package/assets/chart-latency-overhead.svg +102 -0
  9. package/assets/chart-routerena-leaderboard.svg +76 -0
  10. package/dist/analytics/costAnalytics.d.ts +1 -0
  11. package/dist/benchmark/comprehensive.d.ts +4 -53
  12. package/dist/benchmark/comprehensive.d.ts.map +1 -0
  13. package/dist/benchmark/comprehensive.js +112 -214
  14. package/dist/benchmark/comprehensive.js.map +1 -1
  15. package/dist/benchmark/reproducible.d.ts +1 -0
  16. package/dist/cache/semanticCache.d.ts +1 -0
  17. package/dist/cli/setupWizard.d.ts +6 -1
  18. package/dist/cli/setupWizard.d.ts.map +1 -1
  19. package/dist/cli/setupWizard.js +6 -9
  20. package/dist/cli/setupWizard.js.map +1 -1
  21. package/dist/cli.js +15 -14
  22. package/dist/cost/budgetEnforcer.d.ts +1 -0
  23. package/dist/cost/costTracker.d.ts +1 -0
  24. package/dist/ensemble/multiRoundDialog.d.ts +1 -0
  25. package/dist/ensemble/multiRoundDialog.d.ts.map +1 -0
  26. package/dist/ensemble/shapleyValue.d.ts +1 -0
  27. package/dist/ensemble/shapleyValue.d.ts.map +1 -0
  28. package/dist/ensemble.d.ts +1 -0
  29. package/dist/index.d.ts +1 -0
  30. package/dist/integrations/langchainAdapter.d.ts +1 -0
  31. package/dist/integrations/oauth.d.ts +1 -0
  32. package/dist/integrations/scienceAdapter.d.ts +1 -0
  33. package/dist/integrations/scienceAdapter.d.ts.map +1 -0
  34. package/dist/memory/autoFetch.d.ts +1 -0
  35. package/dist/memory/hybridMemory.d.ts +1 -0
  36. package/dist/memory/hybridMemory.d.ts.map +1 -0
  37. package/dist/memory/memoryTree.d.ts +1 -0
  38. package/dist/memory/memoryTree.d.ts.map +1 -1
  39. package/dist/memory/obsidianVault.d.ts +1 -0
  40. package/dist/memory/obsidianVault.d.ts.map +1 -1
  41. package/dist/memory/reasoningBank.d.ts +1 -0
  42. package/dist/memory/reasoningBank.d.ts.map +1 -0
  43. package/dist/observability/changeWatch.d.ts +1 -0
  44. package/dist/observability/fatigueDetector.d.ts +1 -0
  45. package/dist/observability/index.d.ts +1 -0
  46. package/dist/observability/metrics.d.ts +1 -0
  47. package/dist/observability/metrics.d.ts.map +1 -1
  48. package/dist/observability/middleware.d.ts +1 -0
  49. package/dist/observability/tracer.d.ts +1 -0
  50. package/dist/observability/tracer.d.ts.map +1 -1
  51. package/dist/observability/types.d.ts +1 -0
  52. package/dist/providers/providerConfig.d.ts +1 -0
  53. package/dist/providers/providerConfig.d.ts.map +1 -1
  54. package/dist/routing/advancedRouter.d.ts +2 -1
  55. package/dist/routing/advancedRouter.d.ts.map +1 -1
  56. package/dist/routing/crossModelValidation.d.ts +1 -0
  57. package/dist/routing/providerHealth.d.ts +1 -0
  58. package/dist/routing/providerHealth.d.ts.map +1 -1
  59. package/dist/routing/providerRetry.d.ts +1 -0
  60. package/dist/sdk.d.ts +1 -0
  61. package/dist/security/guardrails.d.ts +1 -0
  62. package/dist/security/guardrails.d.ts.map +1 -1
  63. package/dist/server/dashboard.d.ts +1 -0
  64. package/dist/server/handlers/chatHandler.d.ts +11 -0
  65. package/dist/server/handlers/chatHandler.d.ts.map +1 -0
  66. package/dist/server/handlers/chatHandler.js +159 -0
  67. package/dist/server/handlers/chatHandler.js.map +1 -0
  68. package/dist/server/handlers/completionsHandler.d.ts +10 -0
  69. package/dist/server/handlers/completionsHandler.d.ts.map +1 -0
  70. package/dist/server/handlers/completionsHandler.js +124 -0
  71. package/dist/server/handlers/completionsHandler.js.map +1 -0
  72. package/dist/server/handlers/embeddingsHandler.d.ts +17 -0
  73. package/dist/server/handlers/embeddingsHandler.d.ts.map +1 -0
  74. package/dist/server/handlers/embeddingsHandler.js +235 -0
  75. package/dist/server/handlers/embeddingsHandler.js.map +1 -0
  76. package/dist/server/handlers/healthHandler.d.ts +10 -0
  77. package/dist/server/handlers/healthHandler.d.ts.map +1 -0
  78. package/dist/server/handlers/healthHandler.js +49 -0
  79. package/dist/server/handlers/healthHandler.js.map +1 -0
  80. package/dist/server/handlers/metricsHandler.d.ts +11 -0
  81. package/dist/server/handlers/metricsHandler.d.ts.map +1 -0
  82. package/dist/server/handlers/metricsHandler.js +24 -0
  83. package/dist/server/handlers/metricsHandler.js.map +1 -0
  84. package/dist/server/handlers/modelsHandler.d.ts +10 -0
  85. package/dist/server/handlers/modelsHandler.d.ts.map +1 -0
  86. package/dist/server/handlers/modelsHandler.js +19 -0
  87. package/dist/server/handlers/modelsHandler.js.map +1 -0
  88. package/dist/server/metrics.d.ts +96 -0
  89. package/dist/server/metrics.d.ts.map +1 -0
  90. package/dist/server/metrics.js +267 -0
  91. package/dist/server/metrics.js.map +1 -0
  92. package/dist/server/modelMapper.d.ts +1 -0
  93. package/dist/server/proxyServer.d.ts +53 -17
  94. package/dist/server/proxyServer.d.ts.map +1 -1
  95. package/dist/server/proxyServer.js +66 -303
  96. package/dist/server/proxyServer.js.map +1 -1
  97. package/dist/server/router.d.ts +49 -0
  98. package/dist/server/router.d.ts.map +1 -0
  99. package/dist/server/router.js +120 -0
  100. package/dist/server/router.js.map +1 -0
  101. package/dist/server/state.d.ts +30 -0
  102. package/dist/server/state.d.ts.map +1 -0
  103. package/dist/server/state.js +18 -0
  104. package/dist/server/state.js.map +1 -0
  105. package/dist/skills/__tests__/skill_manager.test.d.ts +3 -0
  106. package/dist/skills/__tests__/skill_manager.test.d.ts.map +1 -1
  107. package/dist/skills/__tests__/skill_manager.test.js +3 -6
  108. package/dist/skills/__tests__/skill_manager.test.js.map +1 -1
  109. package/dist/tui/dashboard.d.ts +1 -0
  110. package/dist/tui/index.d.ts +1 -0
  111. package/dist/utils/costUtils.d.ts +1 -0
  112. package/dist/utils/reliability.js +4 -18
  113. package/dist/utils/sorting.d.ts +1 -0
  114. package/dist/utils/tokenUtils.d.ts +1 -0
  115. package/docs/assets/chart-accuracy-by-tier.svg +63 -0
  116. package/docs/assets/chart-confusion-matrix.svg +98 -0
  117. package/docs/assets/chart-cost-comparison.svg +66 -0
  118. package/docs/assets/chart-latency-overhead.svg +102 -0
  119. package/docs/assets/chart-routerena-leaderboard.svg +76 -0
  120. package/docs/index.html +72 -80
  121. package/docs/llms-full.txt +156 -184
  122. package/docs/llms.txt +77 -42
  123. package/hf-space/app.py +3 -3
  124. package/llms-full.txt +156 -184
  125. package/llms.txt +77 -42
  126. package/mcp-server/package.json +6 -0
  127. package/mcp-server/tsconfig.json +3 -2
  128. package/package.json +5 -5
  129. package/src/server/handlers/chatHandler.ts +173 -0
  130. package/src/server/handlers/completionsHandler.ts +120 -0
  131. package/src/server/handlers/embeddingsHandler.ts +271 -0
  132. package/src/server/handlers/healthHandler.ts +57 -0
  133. package/src/server/handlers/metricsHandler.ts +30 -0
  134. package/src/server/handlers/modelsHandler.ts +25 -0
  135. package/src/server/metrics.ts +303 -0
  136. package/src/server/proxyServer.ts +71 -394
  137. package/src/server/router.ts +157 -0
  138. package/src/server/state.ts +34 -0
  139. package/src/skills/__tests__/skill_manager.test.ts +3 -3
  140. package/NEW_OPPORTUNITIES.md +0 -163
  141. package/NEW_SUBMISSIONS.md +0 -80
  142. package/PRIORITY_REDDIT_TARGETS.md +0 -53
  143. package/VISIBILITY_PLAN.md +0 -146
  144. package/articles/TWITTER_THREAD_IMPLICATIONS.md +0 -182
  145. package/articles/TWITTER_THREAD_VAULT.md +0 -164
  146. package/index.html +0 -667
package/README.md CHANGED
@@ -1,1179 +1,242 @@
1
- ## ⚡ 30-second install
2
-
3
- A3M Router is an OpenAI-compatible LLM gateway. Install it, start the proxy, and point your existing OpenAI SDK to `http://localhost:8787/v1`.
4
-
5
- ```bash
6
- npm install adaptive-memory-multi-model-router
7
- npx a3m-router serve
8
- ```
9
-
10
- ```python
11
- from openai import OpenAI
12
-
13
- client = OpenAI(base_url="http://localhost:8787/v1", api_key="not-needed")
14
-
15
- response = client.chat.completions.create(
16
- model="auto", # A3M routes to the cheapest capable provider
17
- messages=[{"role": "user", "content": "Explain quantum computing in 3 bullets"}]
18
- )
19
-
20
- print(response.choices[0].message.content)
21
- ```
22
-
23
- In 30 seconds you get:
24
-
25
- - OpenAI-compatible proxy at `http://localhost:8787/v1`
26
- - Auto-routing across **47+ providers**
27
- - Semantic cache, provider health, budget controls, and circuit breakers
28
- - RouterArena PR #144 proof: **0.9404 score**, **96.77% accuracy**, **$0.0768/1K**, **1.0000 robustness**, **0 abnormal entries** across **8,400 queries**
29
-
30
- No ML training. No GPU. Drop-in for existing LLM apps.
31
-
32
- [🇨🇳 中文](./README_zh.md) · [🇯🇵 日本語](./README_ja.md) · [English](./README.md)
33
-
34
- ## 🆕 What's New (v2.14 — June 2026)
35
-
36
- **🔥 MMR-Bench MERGED** (Jun 28) — A3M Router is now an official baseline in the [MMR-Bench multimodal routing benchmark](https://github.com/Hunter-Wrynn/MMR-Bench/pull/4). This ArXiv 2026 benchmark evaluates LLM routers on multimodal tasks across diverse domains. The merge confirms A3M's position as a production-ready routing solution for real-world enterprise deployments.
37
-
38
- **ReasoningBank Integration** — A3M now learns from its routing history. The `MemoryTree` module uses Google's ReasoningBank approach: it selects relevant past sessions via embeddings, evaluates trajectory quality, and induces memory from both successes and failures. **Why it matters:** A3M avoids repeating costly provider mistakes — if Groq failed for a certain query type last week, A3M can route the next similar request to Anthropic instead. Reduces repeated-query routing mistakes in internal tests by ~15%.
39
-
40
- **Auto-Publish CI removed** — Rapid npm republishing caused package-manager abuse detection, so the auto-publish workflow was removed. **Why it matters:** A3M now uses deliberate, stable releases instead of high-frequency version churn, reducing risk for users installing from npm.
41
-
42
- **MCTS routing research** — A prototype MCTS router was added in `a3m-router-research/experiments/mcts-routing` with quality, cost-quality, and robust strategies. Early Run 001 showed the `cost_quality` strategy at **0.9370 accuracy-cost** vs the A3M heuristic baseline at **0.9300**, confirming MCTS/RL-style routing as the next research path for improving cost-quality tradeoffs beyond the current RouterArena-confirmed result.
43
-
44
- **OpenAI-compatible proxy endpoint** — `npx a3m-router serve` now exposes an OpenAI-compatible `/v1/chat/completions` endpoint at `localhost:8787`. **Why it matters:** Existing code using `openai.Chat.create()` can point to A3M with a one-line endpoint change, gaining parallel routing + validation without code refactoring.
45
-
46
- ---
47
-
48
1
  # A3M Router
49
2
 
50
- [![npm](https://img.shields.io/npm/dt/adaptive-memory-multi-model-router?label=npm+downloads)](https://www.npmjs.com/package/adaptive-memory-multi-model-router)
51
- [![GitHub stars](https://img.shields.io/github/stars/Das-rebel/a3m-router)](https://github.com/Das-rebel/a3m-router)
52
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
53
- [![RouterEval](https://img.shields.io/badge/RouterEval-MERGED-brightgreen)](https://github.com/MilkThink-Lab/RouterEval/pull/4)
54
- [![MMR-Bench](https://img.shields.io/badge/MMR--Bench-MERGED-brightgreen)](https://github.com/Hunter-Wrynn/MMR-Bench/pull/4)
55
- [![RouterArena](https://img.shields.io/badge/RouterArena-PR%20%23152-blue)](https://github.com/RouteWorks/RouterArena/pull/152)
56
- [![LLMRouterBench](https://img.shields.io/badge/LLMRouterBench-PR%20%233-blue)](https://github.com/ynulihao/LLMRouterBench/pull/3)
57
- [![Benchmarks](https://img.shields.io/badge/Benchmarks-6_total-9627ff)]
58
- [![HuggingFace](https://img.shields.io/badge/HuggingFace-Space-blue)](https://huggingface.co/spaces/Hayasuki/a3m-router)(https://github.com/Das-rebel/a3m-router#-benchmarks--evaluations)
59
-
60
- 🔀 — Enterprise AI Gateway for Cost Optimization & Reliability
61
-
62
- **Stop overpaying for LLM APIs.** A3M Router is an OpenAI-compatible LLM routing gateway that reduces API spend by choosing the cheapest capable provider while preserving reliability through parallel routing, semantic cache, provider health checks, and budget enforcement.
63
-
64
- A3M doesn't just route—it orchestrates. By calling multiple providers in parallel, it ensures the highest quality answer is delivered with the lowest possible cost and latency.
65
-
66
- **🥇 RouterArena #1 in Accuracy, Cost & Robustness among known public baselines** — **96.77% accuracy**, **$0.0768/1K**, **1.0000 robustness**, **0 abnormal entries** across **8,400 queries**. No training required, <1ms routing decision.
67
-
68
- **Try it in 1 second (no install needed):**
69
-
70
- ```bash
71
- npx a3m-router route "Explain quantum computing"
72
- ```
73
-
74
- | Business Value | A3M Impact | The Result |
75
- |:---|:---|:---|
76
- | **Cost Reduction** | No. 1 RouterArena cost: $0.0768/1K | Lowest published cost among known public baselines |
77
- | **Accuracy** | No. 1 RouterArena accuracy: 96.77% | Highest published accuracy among known public baselines |
78
- | **Robustness** | No. 1 robustness: 1.0000 | Perfect robustness score with 0 abnormal entries |
79
- | **Control** | Hard Budget Enforcement | No more end-of-month API bill surprises |
80
-
81
- > **🛡️ Hallucination Shield:** A3M identifies and removes errors by verifying answers across 47+ providers simultaneously. [See the Research →](research/HALLUCINATION_RESEARCH.md)
82
-
83
-
84
- [![npm](https://img.shields.io/npm/dt/adaptive-memory-multi-model-router?color=blue&label=weekly%20downloads)](https://www.npmjs.com/package/adaptive-memory-multi-model-router)
85
- [![npm](https://img.shields.io/npm/v/adaptive-memory-multi-model-router)](https://www.npmjs.com/package/adaptive-memory-multi-model-router)
86
- [![RouterArena Score](https://img.shields.io/badge/RouterArena-96.77-2ea44f)](https://github.com/Das-rebel/RouterArena)
87
- [![GitHub stars](https://img.shields.io/github/stars/Das-rebel/a3m-router)](https://github.com/Das-rebel/a3m-router)
88
- [![MIT](https://img.shields.io/badge/license-MIT-green)](./LICENSE)
3
+ **OpenAI-compatible LLM routing gateway — routes requests to the cheapest capable provider per query.**
89
4
 
90
- ### Why this instead of sequential fallback?
5
+ A3M Router is a stateless proxy that sits between your application and 47+ LLM providers. It inspects each request, estimates how complex it is, and routes it to the cheapest provider that can handle it — without retraining a model or managing GPU infrastructure.
91
6
 
92
- | | Sequential (everyone else) | Parallel (A3M) |
93
- |---|---|---|
94
- | **How** | Try A → fail → try B → fail → try C | Call all at once, pick best |
95
- | **Cost** | Pay for every attempt | Pay for best response only |
96
- | **Latency** | 3+ round-trips | 1 round-trip |
97
- | **Example** | GPT-4o fails ($0.03) → try Groq ($0.0006) | Groq wins ($0.0006) |
98
-
99
- ### 📖 AI-Friendly: [`llms.txt`](./llms.txt) · [`llms-full.txt`](./llms-full.txt) · [`docs/QUICK_START.md`](./docs/QUICK_START.md)
100
-
101
- ### 💅 Terminal UI
102
-
103
- ```bash
104
- node dist/tui/dashboard.js
105
- ```
106
-
107
- Terminal overlay box with `/route`, `/cost`, `/health`, `/models`, `/model <provider>`. Type anything to auto-route through the cheapest model.
108
-
109
- ### 📊 By the Numbers
110
-
111
- | Metric | Value | Context |
112
- |--------|-------|--------|
113
- | | Weekly Downloads | **2,079** | Last reported week (Jun 21–27) | npm search #1 for key terms |
114
- | Last Month | **13,842** | Last 30 days (May 29–Jun 27) | Strong organic traffic |
115
- | Total Downloads | **26,393** | All-time since Dec 2024 | Sustained growth |
116
- RouterArena Score | **0.9404** | #1 among known public baselines |
117
- | Accuracy | **96.77%** | #1 among known public baselines |
118
- | Cost | **$0.0768/1K** | #1 among known public baselines with published cost |
119
- | Robustness | **1.0000** | #1 / perfect robustness score |
120
- | Providers | **47+** | OpenAI, Anthropic, Groq, DeepSeek, NVIDIA, OpenRouter, + |
121
-
122
- ```
123
- ╔══════════════════════════════════════════════════════════════════╗
124
- ║ A3M Router — LLM Gateway ║
125
- ╠══════════════════════════════════════════════════════════════════╣
126
- ║ ║
127
- ║ ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ ║
128
- ║ │ Guardrails │ ──▶ │ Cache │ ──▶ │ Router │ ║
129
- ║ │ 🔒 Prompt │ │ 💾 30%+ │ │ 🏆 No. 1 │ ║
130
- ║ │ Injection │ │ Hit │ │ Accuracy/Cost │ ║
131
- ║ │ PII Detect │ │ Semantic │ │ 12 Signals │ ║
132
- ║ └─────────────┘ └─────────────┘ └────────┬────────┘ ║
133
- ║ │ ║
134
- ║ ┌─────────────────┬──────────────────────────┴──────┐ ║
135
- ║ │ │ │ ║
136
- ║ ▼ ▼ ▼ ║
137
- ║ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐║
138
- ║ │ MemoryTree │ │ CostTrack │ │ Robustness │║
139
- ║ │ 🧠 │ │ 💰 │ │ 1.0000 ✅ │║
140
- ║ │ EMA │ │ Budget │ │ 0 Abnormal │║
141
- ║ │ Learning │ │ Alerts │ │ 8,400 Query │║
142
- ║ └─────────────┘ └─────────────┘ └─────────────┘║
143
- ║ ║
144
- ║ 47+ Providers: Groq · DeepSeek · Kimi · Qwen · Zhipu · Yi · + ║
145
- ║ OpenAI · Anthropic · Google · Mistral · + ║
146
- ╚══════════════════════════════════════════════════════════════════╝
147
- ```
148
-
149
-
150
-
151
- ```bash
152
- npm install adaptive-memory-multi-model-router # TypeScript / Node
153
- pip install a3m-router # Python
154
- npx a3m-router serve # OpenAI proxy at localhost:8787
155
- ```
156
-
157
- [![npm version](https://badge.fury.io/js/adaptive-memory-multi-model-router.svg)](https://www.npmjs.com/package/adaptive-memory-multi-model-router)
158
- [![npm downloads](https://img.shields.io/npm/dw/adaptive-memory-multi-model-router)](https://www.npmjs.com/package/adaptive-memory-multi-model-router)
159
- [![GitHub license](https://img.shields.io/github/license/Das-rebel/a3m-router)](https://github.com/Das-rebel/a3m-router/blob/main/LICENSE)
160
-
161
- ---
162
- > ⚡️ **A3M Router** — OpenAI-compatible LLM router and AI gateway. RouterArena-evaluated at **96.77% accuracy**, **$0.0768/1K**, and **1.0000 robustness**. Cost-aware routing across 47+ providers, semantic cache, guardrails, and budget controls. 19.5KB core, no ML training required.
163
- >
164
- > ⭐ Star us on [GitHub](https://github.com/Das-rebel/a3m-router) if you find this useful
165
-
166
-
167
- ### Used By
168
-
169
- ![Used by](https://img.shields.io/badge/Used%20by-Developers%20building%20LLM%20apps-brightgreen)
170
- [![Star this repo](https://img.shields.io/github/stars/Das-rebel/a3m-router?style=social)](https://github.com/Das-rebel/a3m-router)
171
-
172
- *We track usage but don't collect personal data. If you're using A3M Router, [let us know](https://github.com/Das-rebel/a3m-router/discussions)!*
173
-
174
-
175
-
176
- ---
177
-
178
- ## 🔥 What Makes A3M Different
179
-
180
- **Everybody does sequential fallback (try A → B → C). A3M does parallel multi-LLM execution with transparent scoring — and RouterArena PR #144 confirms this approach at No. 1 accuracy, No. 1 cost, and No. 1 robustness among known public baselines.**
181
-
182
- ```mermaid
183
- graph LR
184
- Q[Query] --> P[Parallel Execution]
185
- P --> N[NVIDIA]
186
- P --> G[Groq]
187
- P --> O[OpenAI]
188
- N --> M[Merge & Score]
189
- G --> M
190
- O --> M
191
- M --> R[Best Answer]
192
- ```
193
-
194
- | Everyone Else | A3M Router |
195
- |:---|:---|
196
- | `try A → fail → try B → fail → try C` | `run A + B + C → score → pick best` |
197
- | Sequential fallback (slow, fragile) | **Parallel ensemble** (fast, robust) |
198
- | One chance per provider | All providers contribute simultaneously |
199
- | Black-box routing | Transparent scoring with winner reasoning |
200
-
201
- ---
202
-
203
-
204
- ## 🏆 Benchmarks & Evaluations
205
-
206
-
207
- ## 🏆 Benchmarks & Evaluations
208
-
209
- ### ✅ Submitted & Accepted
210
-
211
- | Benchmark | Venue | Status | Performance |
212
- |----------|-------|--------|-------------|
213
- | **RouterEval** | EMNLP 2025 | ✅ **MERGED** | Custom baseline router added |
214
- | **LLMRouterBench** | ACL 2026 | ✅ PR Open | Baseline implementation submitted |
215
- | **routerbench** | ICML Workshop 2024 | ✅ PR Open | Router implementation submitted |
216
- | **MMR-Bench** | ArXiv 2026 | ✅ **MERGED** | Multimodal routing baseline merged Jun 28 |
217
- | **RouterArena** | ICLR 2025 | ✅ PR #152 Open | 50.59% accuracy (free-tier) |
218
-
219
- ### RouterArena Performance
220
-
221
- | Metric | Free-Tier Mode (PR #152) | Premium Mode (PR #144) |
222
- |--------|---------------------------|------------------------|
223
- | Score | 0.5234 | **0.9404** |
224
- | Accuracy | 50.59% | **96.77%** |
225
- | Robustness | 0.0000 | **1.0000** |
226
- | Cost | **$0.038/1K** | $0.0768/1K |
227
-
228
- > **Note:** Free-tier mode uses Gemma-31b, Llama-3.3-70B, GPT-OSS-120B. Premium mode uses DeepSeek-V4-Pro.
229
-
230
- ### Local Benchmark Results
231
-
232
- | Metric | Value |
233
- |--------|-------|
234
- | Exact Tier Match | **67%** |
235
- | ±1 Tier Accuracy | **96%** |
236
- | Cost Savings | **62.9%** vs all-premium |
237
- | Robustness Score | **0.8524** |
238
- | Free Tier Accuracy | **96%** |
239
-
240
- ### Key Differentiators
241
-
242
- - **RouterEval:** First router to be included as baseline in EMNLP 2025 benchmark
243
- - **RouterArena:** Only router achieving #1 in Accuracy, Cost, AND Robustness simultaneously
244
- - **Local:** 96% accuracy on free-tier routing with 62.9% cost savings
245
-
246
- ---
247
-
248
-
249
- ## Why A3M Router
250
-
251
- Enterprise AI deployments face a common set of costly problems. The new finding is that cost-aware routing can be both cheaper and more accurate: RouterArena PR #144 confirms A3M at **No. 1 accuracy**, **No. 1 cost**, and **No. 1 robustness among known public baselines**. These problems include 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.
252
-
253
- **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.
254
-
255
- **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.
256
-
257
- **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.
258
-
259
- **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.
260
-
261
- Beyond these operational concerns, A3M Router uses **multi-signal heuristic routing** — domain detection, task classification, query structure analysis, provider health, cost, and confidence signals — to route to the most cost-effective provider. Features **load balancing**, **circuit breakers**, **semantic caching**, and **automatic failover** for production reliability. No ML training. No GPU required for routing. Starts in <100ms.
262
-
263
- 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.
264
-
265
- | 🧠 Adaptive Memory | 🎯 Intelligent Routing | 🛡️ Hard Budget Enforcement | 🔄 Intelligent Failover | 💾 Semantic Cache | ⚡ Per-Provider Retry |
266
- |:---|:---|:---|:---|:---|:---|
267
- | 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). |
7
+ Drop-in replacement for OpenAI API calls. Switch providers or add new ones without changing application code.
268
8
 
269
9
  ---
270
10
 
271
11
  ## Quick Start
272
12
 
273
- ### TypeScript SDK
274
-
275
- ```typescript
276
- adaptive-memory-multi-model-router/sdk';
277
-
278
- const router = new A3MRouter();
279
-
280
- // Route a query — returns model + tier + cost + complexity
281
- const decision = router.route("Review this contract for liability clauses");
282
- // → { model: "anthropic/claude-3.5-sonnet", tier: "premium",
283
- // cost: 0.008, complexity: 0.87, isExpert: true }
284
-
285
- // Analyze why it chose that model
286
- const features = router.analyze("Review this contract for liability clauses");
287
- // → { detectedDomain: "legal", domainScore: 0.35, hasCode: false,
288
- // requiresReasoning: true, complexity: 0.87 }
289
- ```
290
-
291
- ### Python SDK
292
-
293
- ```python
294
- from a3m import A3MRouter
295
-
296
- async with A3MRouter() as router:
297
- # Route without executing
298
- decision = await router.route("Write a Python function to sort an array")
299
- print(decision.model, decision.tier, decision.cost)
300
- # → groq/llama-3.3-70b cheap 0.0004
301
-
302
- # Execute via OpenAI-compatible chat
303
- response = await router.chat("What is 2+2?", model="auto")
304
- print(response["choices"][0]["message"]["content"])
305
- ```
306
-
307
- ### OpenAI-Compatible Proxy
308
-
309
13
  ```bash
14
+ npm install adaptive-memory-multi-model-router
310
15
  npx a3m-router serve
311
- # → Proxy running at http://localhost:8787
312
16
  ```
313
17
 
314
18
  ```python
315
- # Works with ANY OpenAI SDK — zero code changes
316
19
  from openai import OpenAI
20
+
317
21
  client = OpenAI(base_url="http://localhost:8787/v1", api_key="not-needed")
318
22
 
319
23
  response = client.chat.completions.create(
320
- model="auto", # intelligent routing kicks in
321
- messages=[{"role": "user", "content": "Hello!"}]
24
+ model="auto", # "auto" = heuristic routing
25
+ messages=[{"role": "user", "content": "Explain quantum computing in 3 bullets"}]
322
26
  )
323
27
  ```
324
28
 
325
- ### CLI
326
-
327
- ```bash
328
- npx a3m-router route "Explain quantum computing" # → groq/llama-3.3-70b
329
- npx a3m-router route "Design a clinical trial" # → openai/gpt-4o
330
- npx a3m-router serve --port 8787 # Start proxy
331
- npx a3m-router benchmark # Run accuracy test
332
- npx a3m-router health # Check providers
333
- npx a3m-router cost # Cost analytics
334
- npx a3m-router compare "What is AI?" # All providers side-by-side
335
- ```
336
-
337
- ### REST API
338
-
339
- ```bash
340
- # Get routing decision (no LLM call)
341
- curl -s http://localhost:8787/v1/route \
342
- -H "Content-Type: application/json" \
343
- -d '{"query": "Write a Python function"}' | jq .
344
-
345
- # Chat completion (OpenAI format)
346
- curl -s http://localhost:8787/v1/chat/completions \
347
- -H "Content-Type: application/json" \
348
- -d '{"model":"auto","messages":[{"role":"user","content":"Hello"}]}'
349
- ```
350
-
351
- ---
352
-
353
-
354
- ### Terminal Demo
355
-
356
- ```bash
357
- $ npx a3m-router serve
358
- ╔════════════════════════════════════════════════════════════╗
359
- ║ A3M Router v2.9.2 ║
360
- ║ 🔀 Intelligent LLM Gateway ║
361
- ╠════════════════════════════════════════════════════════════╣
362
- ║ ✅ Proxy: http://localhost:8787 ║
363
- ║ ✅ Dashboard: http://localhost:8787/dashboard ║
364
- ║ ✅ Health: http://localhost:8787/health ║
365
- ╚════════════════════════════════════════════════════════════╝
366
-
367
- [GROQ] ✅ 145ms | [DEEPSEEK] ✅ 230ms | [KIMI] ✅ 312ms
368
- [ANTHROPIC] ✅ 520ms | [OPENAI] ✅ 480ms | [QWEN] ✅ 290ms
369
-
370
- 🧠 Memory: 1,247 queries cached | 💰 Today: $2.34 / $50.00 budget
371
- ```
372
-
373
- ```bash
374
- $ npx a3m-router route "Design a clinical trial for oncology"
375
-
376
- 🔀 Routing Decision:
377
- Query: "Design a clinical trial for oncology"
378
-
379
- 📊 Complexity: 1.00 (premium)
380
- 🏷️ Tier: premium
381
-
382
- ✅ Route to: openai/gpt-4o ($2.50/1M tokens)
383
- 🔄 Fallback: anthropic/claude-3.5-sonnet
384
-
385
- 💡 Signals: medical(+0.35) + design(+0.20) + multi-step(+0.15)
386
- ```
387
-
388
- ```bash
389
- $ npx a3m-router cost
390
-
391
- 💰 Cost Analytics (May 2024)
392
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
393
- Total Spend: $127.45 / $500.00 budget
394
- Daily Average: $4.27
395
- Queries: 28,392
396
-
397
- 📈 By Provider: 📊 By Tier:
398
- Groq: $42.30 ████████ 33% premium: $89.10 70%
399
- DeepSeek: $51.20 █████████ 40% mid: $28.90 23%
400
- Claude: $28.90 █████ 23% cheap: $7.45 6%
401
- GPT-4o-mini: $5.05 █ 4% free: $2.00 1%
402
-
403
- 🚨 Budget Alert: Engineering team at 80% ($160 / $200)
404
- ```
29
+ That's it. `model="auto"` triggers routing. All other OpenAI SDK calls work unchanged.
405
30
 
406
31
  ---
407
32
 
408
- ## How It Works — Routing Engine
409
-
410
- A3M Router combines multi-signal routing, semantic caching, and load balancing to route queries to the cheapest capable model with 96.77% official RouterArena accuracy.
411
-
412
- ### Routing Signals
413
-
414
- 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.
415
-
416
- #### 1. Domain Detection (+0.35 max)
33
+ ## How Routing Works
417
34
 
418
- | Keywords | Score |
419
- |:---------|:----:|
420
- | `legal`, `contract`, `liability`, `clause` | +0.35 |
421
- | `medical`, `clinical`, `patient`, `diagnosis` | +0.35 |
422
- | `security`, `vulnerability`, `exploit` | +0.35 |
423
- | `finance`, `investment`, `risk`, `portfolio` | +0.30 |
424
- | `architecture`, `system design` | +0.25 |
425
- | `ML`, `model`, `training`, `gradient` | +0.25 |
35
+ For every request, A3M Router scores complexity across five signals:
426
36
 
427
- #### 2. Task Indicators (+0.25 max)
37
+ | Signal | What it detects |
38
+ |--------|----------------|
39
+ | **Domain** | Legal, medical, code, finance, ML keywords |
40
+ | **Task type** | Code generation, translation, analysis, creative |
41
+ | **Query structure** | Clause count, length, qualifier words |
42
+ | **Verb intensity** | "design/architect" → complex, "what/who" → simple |
43
+ | **Multi-step** | Explicit step markers (first...then, step 1/2/3) |
428
44
 
429
- | Keywords | Score |
430
- |:---------|:----:|
431
- | `code`, `function`, `algorithm`, `debug` | +0.25 |
432
- | `math`, `calculate`, `equation`, `formula` | +0.20 |
433
- | `translate`, `multilingual`, `language` | +0.15 |
434
- | `creative`, `story`, `poem` | +0.10 |
45
+ The combined score maps to a tier (free → cheap → mid → premium). Within that tier, A3M picks the cheapest available provider with a passing health score.
435
46
 
436
- #### 3. Query Structure (+0.20 max)
47
+ This is the same approach other routing systems use — the key differences between implementations are:
437
48
 
438
- | Feature | Score |
439
- |:--------|:----:|
440
- | Multiple clauses (`and`/`or`/`but`) | +0.10 |
441
- | Length > 200 characters | +0.05 |
442
- | Qualifiers (`explain`, `analyze`) | +0.05 |
49
+ - **Signal weights** how much each dimension contributes
50
+ - **Provider tiers** — which models live in which tier
51
+ - **Health scoring** — how failures and latency affect provider selection
52
+ - **Fallback behavior** what happens when the preferred provider is down
443
53
 
444
- #### 4. Action Verb Intensity (+0.20 max)
445
-
446
- | Intensity | Verbs | Score |
447
- |:----------|:------|:----:|
448
- | Expert | `design`, `architect`, `optimize` | +0.20 |
449
- | Mid | `analyze`, `review`, `evaluate` | +0.10 |
450
- | Simple | `what`, `who`, `when`, `where` | −0.10 |
451
-
452
- #### 5. Multi-Step Detection (+0.15 max)
453
-
454
- | Pattern | Score |
455
- |:--------|:----:|
456
- | `first...then...finally` | +0.15 |
457
- | `step 1, step 2, step 3` | +0.15 |
54
+ A3M stores no training data, requires no GPU, and routes in ~140ms overhead.
458
55
 
459
56
  ---
460
57
 
461
- **→ Complexity Score gets summed, then mapped to a tier:**
462
-
463
- ```
464
- 0.00 ───────── 0.19 ────────── 0.44 ─────────── 1.00
465
- ├── free ─────|── cheap ───────|── mid ────────| premium ─┤
466
- │ taste-1 │ llama-3.3-70b │ gpt-4o-mini │ gpt-4o │
467
- │ $0 │ $0.20/M │ $0.60/M │ $2.50/M │
468
- ```
58
+ ## Why Not Just Use LiteLLM?
469
59
 
470
- Route: pick cheapest available model in the assigned tier, with +2 fallback models.
60
+ LiteLLM is the dominant open-source AI gateway (54K stars). It handles unified API access well. A3M Router adds two capabilities LiteLLM doesn't have built-in:
471
61
 
472
- #### Real-World Classification Examples
62
+ ### 1. Heuristic Routing
63
+ LiteLLM routes by model name or requires you to specify which model to call. A3M's `model="auto"` mode analyzes the query content and picks the cheapest capable provider automatically. This is useful when you want cost efficiency without writing routing logic.
473
64
 
474
- | Query | Signals Detected | Score | Tier | Route To |
475
- |:------|:-----------------|:----:|:----:|:---------|
476
- | `"What is 2+2?"` | Simple structure | 0.10 | free | taste-1 ($0) |
477
- | `"Write a Python sort"` | code +0.25, simple −0.10 | 0.33 | cheap | llama-3.3-70b ($0.20/M) |
478
- | `"Analyze AI implications"` | analyze +0.10 | 0.41 | cheap | llama-3.3-70b ($0.20/M) |
479
- | `"Review contract liability"` | legal +0.35, review +0.10, long +0.05 | 0.87 | premium | claude-3.5-sonnet ($1.50/M) |
480
- | `"Design oncology trial"` | medical +0.35, design +0.20, steps +0.15 | 1.00 | premium | gpt-4o ($2.50/M) |
65
+ ### 2. Parallel Ensemble Execution
66
+ Sometimes you want the best answer regardless of cost. A3M can call multiple providers in parallel, score each response, and return the best one — with full provenance of which provider won and why.
481
67
 
482
68
  ```typescript
483
- adaptive-memory-multi-model-router';
484
-
485
- // See exactly what signals a query triggers
486
- const features = extractQueryFeatures("Review this contract for liability clauses");
487
- // → { complexity: 0.87, has_code: false, requires_reasoning: true,
488
- // detected_domain: 'legal', domain_score: 0.35 }
489
-
490
- // Route to the cheapest capable model
491
- const decision = routeQuery("Write a Python function to sort an array");
492
- // → { model: 'groq/llama-3.3-70b', tier: 'cheap', cost: 0.0004,
493
- // complexity: 0.33, reasoning: ['code signal +0.25', 'simple verb -0.10'] }
494
- ```
495
-
496
- ### Visual Routing Flow
69
+ import { executeEnsemble } from 'adaptive-memory-multi-model-router/ensemble';
497
70
 
71
+ const result = await executeEnsemble(
72
+ "Explain how vector databases work",
73
+ systemPrompt,
74
+ context,
75
+ { groq: callGroq, openai: callOpenAI, nvidia: callNvidia },
76
+ { providers: ['groq', 'openai', 'nvidia'], timeoutMs: 30000 }
77
+ );
78
+ // result.winner — which provider gave the best response
79
+ // result.scores — per-provider quality scores
80
+ // result.allResults — all responses preserved
498
81
  ```
499
- User Query
500
-
501
-
502
- ┌─────────────────────┐
503
- │ Guardrails Check │
504
- │ 🔒 PII / Injection │
505
- └──────────┬──────────┘
506
-
507
- ✅ Pass?
508
- / \
509
- No Yes
510
- │ │
511
- ▼ ▼
512
- [BLOCK] ┌─────────────────┐
513
- │ Semantic Cache │
514
- │ 💾 Lookup │
515
- └────────┬────────┘
516
-
517
- Cache Hit?
518
- / \
519
- Yes No
520
- │ │
521
- ▼ ▼
522
- [RETURN] ┌─────────────────┐
523
- │ │ Route Query │
524
- │ │ 🎯 12 Signals │
525
- │ │ Complexity → │
526
- │ │ Tier │
527
- │ └────────┬────────┘
528
- │ │
529
- │ ▼
530
- │ ┌─────────────────┐
531
- │ │ Provider Health │
532
- │ │ 📊 Scoring │
533
- │ └────────┬────────┘
534
- │ │
535
- │ ▼
536
- │ ┌─────────────────┐
537
- │ │ Best Provider │
538
- │ │ + Fallbacks │
539
- │ └────────┬────────┘
540
- │ │
541
- │ ▼
542
- │ ┌─────────────────┐
543
- │ │ Execute LLM │
544
- │ │ Call │
545
- │ └────────┬────────┘
546
- │ │
547
- │ ▼
548
- │ ┌─────────────────┐
549
- │ │ Update Memory │
550
- │ │ 🧠 EMA Update │
551
- │ └────────┬────────┘
552
- │ │
553
- │ ▼
554
- │ [RETURN RESPONSE]
555
- │ │
556
- └─────────────────┘
557
- ```
558
-
559
- ---
560
-
561
-
562
82
 
563
- ### Cost Efficiency by Query Type
83
+ ### What A3M doesn't do (LiteLLM does)
84
+ - Virtual keys, spend limits per team/user
85
+ - Admin dashboard, UI
86
+ - OAuth/SSO integration
87
+ - LangChain/LlamaIndex first-class integrations
88
+ - Enterprise SLA and support contracts
564
89
 
565
- | Query Type | % Traffic | GPT-4o Only | A3M Routes To | A3M Cost | Savings |
566
- |------------|:---------:|:-----------:|:-------------:|:--------:|:-------:|
567
- | Simple Q&A | 47% | $4.94 | taste-1 (free) | $0.00 | **100%** |
568
- | Code gen | 15% | $4.88 | deepseek ($0.14/M) | $0.17 | **97%** |
569
- | Summarization | 18% | $7.20 | gpt-4o-mini ($0.15/M) | $0.43 | **94%** |
570
- | Reasoning | 12% | $8.70 | claude-haiku ($0.80/M) | $3.36 | **61%** |
571
- | Expert | 8% | $8.40 | gpt-4o ($2.50/M) | $8.40 | **0%** |
572
- | **Total** | **100%** | **$34.11** | — | **$12.36** | **64%** |
573
-
574
- | Monthly Queries | GPT-4o Only | A3M Router | You Save | Annualized |
575
- |:---------------:|:-----------:|:----------:|:--------:|:----------:|
576
- | 10K | $34 | $12 | $22 | $261 |
577
- | 100K | $341 | $124 | $218 | $2,610 |
578
- | 1M | $3,411 | $1,236 | $2,175 | $26,100 |
90
+ A3M is a routing engine. LiteLLM is an enterprise platform. Use the right tool for your stage.
579
91
 
580
92
  ---
581
93
 
582
-
583
- 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 achieved **RouterArena PR #144: 96.77% accuracy, $0.0768/1K, and 1.0000 robustness** without ML training.
584
-
585
- 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)**. Early MCTS research showed a `cost_quality` strategy at **0.9370 accuracy-cost** vs the heuristic baseline at **0.9300**, making MCTS/RL the next path for further cost-quality gains.
586
-
587
- ### When to Use MCTS vs Heuristic Scoring
588
-
589
- | Scenario | Approach |
590
- |----------|----------|
591
- | Single query, route to cheapest capable model | Multi-signal scoring (default, <1ms) |
592
- | Decompose task into sub-tasks, assign each to optimal agent | MCTS (finds optimal assignment) |
593
- | Batch queries with different complexity levels | Heuristic scoring |
594
- | Multi-turn workflow with branching decisions | MCTS |
595
-
596
- ### How MCTS Works
597
-
598
- 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:
94
+ ## Architecture
599
95
 
600
96
  ```
601
- UCB1(node) = (total_reward / visits) + C × √(ln(parent_visits) / visits)
97
+ Request Guardrails Cache Router Provider Response
98
+
99
+ Cost tracking
100
+ Metrics
602
101
  ```
603
102
 
604
- Where `C = √2 1.414` is the exploration constant.
605
-
606
- **4 steps per iteration:**
607
- 1. **Selection** — Starting from root, descend by selecting child with highest UCB1 until unexpanded node or terminal state
608
- 2. **Expansion** — Add one or more child nodes (untried actions)
609
- 3. **Simulation** — Run a rollout from the new node, evaluate the assignment strategy
610
- 4. **Backpropagation** — Update rewards and visit counts back up the tree
611
-
612
- After N iterations, the node with the highest average reward is the best strategy.
613
-
614
- ```typescript
615
- adaptive-memory-multi-model-router/orchestration';
616
-
617
- const optimizer = new MCTSWorkflowOptimizer({
618
- maxIterations: 50, // tree search depth
619
- explorationConstant: 1.414, // UCB1 constant
620
- maxDepth: 5 // max workflow depth
621
- });
622
-
623
- // Available agents
624
- optimizer.setAgents(['claude', 'codex', 'gemini', 'deepseek']);
625
-
626
- // Find best agent assignment for sub-tasks
627
- const bestStrategy = await optimizer.findBestStrategy(
628
- ['research', 'write', 'review', 'publish'],
629
- async (assignments) => {
630
- // Evaluate reward: maximize quality, minimize cost and latency
631
- return reward;
632
- }
633
- );
634
- // → { research: 'deepseek', write: 'claude', review: 'gemini', publish: 'codex' }
635
- ```
636
-
637
- ### MCTS vs Rule-Based Assignment
638
-
639
- | | Rule-based | MCTS |
640
- |-|----------|------|
641
- | **Logic** | Hard-coded if/else | Learned from simulation |
642
- | **Adaptivity** | Static | Adapts to agent performance |
643
- | **Complexity** | O(n) | O(iterations × branching^depth) |
644
- | **Exploration** | None | Balances explore/exploit |
645
- | **Known strategies** | Fast | Slower but finds better strategies |
646
- | **Scale** | Good for <10 agents | Scales to 20+ agents |
647
-
648
-
649
- ```
650
- A3M Router (per-query routing)
651
- └── Multi-signal scoring → fast (<1ms)
652
- └── Tier selection → cheapest available
653
-
654
- TMLPD Orchestration (multi-agent workflows)
655
- └── MCTS → optimal agent assignment
656
- ├── UCB1 selection
657
- ├── State tree expansion
658
- └── Reward backpropagation
659
- ```
660
-
661
- **Example workflow:**
662
- ```
663
- User: "Research AI safety, write a report, have experts review it, then publish"
664
-
665
- MCTS decomposes into:
666
- research → deepseek (cost-effective for research)
667
- write → claude (best for structured long-form)
668
- review → expert-agents (human-in-loop or specialist LLM)
669
- publish → codex (can handle deployment code)
670
-
671
- Router assigns each sub-task to optimal agent, tracks outcomes, learns preferences.
672
- ```
103
+ **Guardrails** Runs before any provider call: prompt injection detection, PII detection, content filtering. Rejects or sanitizes dangerous input.
673
104
 
105
+ **Semantic Cache** — Optional. Uses embedding similarity to return cached responses for repeated queries. Cache hit = instant response, zero provider cost.
674
106
 
107
+ **Router** — Scores the query, selects tier, picks the cheapest healthy provider in that tier. Model quality scores update online via exponential moving average after each real call — no retraining.
675
108
 
109
+ **Ensemble** — Optional. Calls multiple providers in parallel, scores responses on specificity and structure, returns the winner.
676
110
 
677
111
  ---
678
112
 
113
+ ## API Reference
679
114
 
680
- ## Features in Detail
115
+ | Method | Endpoint | Description |
116
+ |--------|----------|-------------|
117
+ | POST | `/v1/chat/completions` | OpenAI-compatible chat (streaming + non-streaming) |
118
+ | POST | `/v1/completions` | OpenAI completions |
119
+ | POST | `/v1/embeddings` | Text embeddings |
120
+ | POST | `/v1/route` | Get routing decision without calling an LLM |
121
+ | GET | `/v1/models` | Available models and pricing |
122
+ | GET | `/health` | Provider health, recent requests, cost totals |
123
+ | GET | `/metrics` | Prometheus-compatible metrics |
681
124
 
682
- ### Feature Overview
125
+ ### CLI
683
126
 
127
+ ```bash
128
+ npx a3m-router serve # start proxy on port 8787
129
+ npx a3m-router route "query" # see routing decision for a query
130
+ npx a3m-router health # provider latency and availability
131
+ npx a3m-router benchmark # run local accuracy test (n=200)
684
132
  ```
685
- ┌────────────────────────────────────────────────────────────────────────────┐
686
- │ A3M Router Features │
687
- ├────────────────────────────────────────────────────────────────────────────┤
688
- │ │
689
- │ ⚡ PARALLEL ENSEMBLE │ 🧠 ADAPTIVE MEMORY │
690
- │ ──────────────────── │ ─────────────────── │
691
- │ • Run N providers at once │ • MemoryTree storage │
692
- │ • Confidence scoring │ • EMA quality scoring │
693
- │ • Transparent winner logic │ • Learns from history │
694
- │ • Historical feedback │ • No retraining needed │
695
- │ │
696
- ├────────────────────────────────────────────────────────────────────────────┤
697
- │ │
698
- │ 🎯 INTELLIGENT ROUTING │ 💰 HARD BUDGET ENFORCEMENT │
699
- │ ───────────────────── │ ─────────────────────── │
700
- │ ─────────────────────── │ ─────────────────── │
701
- │ • Per-user/team budgets │ • 17-pattern injection detection │
702
- │ • Real-time spend tracking │ • PII redaction │
703
- │ • Alerts at 50/80/100% │ • Content filtering │
704
- │ • Hard caps (reject when exceeded) │ • Hallucination checks │
705
- │ │
706
- ├────────────────────────────────────────────────────────────────────────────┤
707
- │ │
708
- │ 🔄 INTELLIGENT FAILOVER │ 💾 SEMANTIC CACHE │
709
- │ ─────────────────────── │ ─────────────────── │
710
- │ • Provider health scoring │ • Embedding-based lookup │
711
- │ • Circuit breaker (3 fails) │ • Configurable similarity threshold │
712
- │ • Automatic fallback chain │ • Per-route TTL │
713
- │ • Chinese provider handling │ • 30%+ cache hit rate │
714
- │ │
715
- ├────────────────────────────────────────────────────────────────────────────┤
716
- │ │
717
- │ ⚡ PER-PROVIDER RETRY │ 📊 COST ANALYTICS │
718
- │ ───────────────────── │ ─────────────────── │
719
- │ • Custom timeout per model │ • Per-provider breakdown │
720
- │ • Exponential backoff │ • Budget vs actual dashboard │
721
- │ • 429 rate limit handling │ • Projected savings │
722
- │ • Jitter to prevent storms │ • Monthly/yearly reports │
723
- │ │
724
- └────────────────────────────────────────────────────────────────────────────┘
725
- ```
726
-
727
- ---
728
-
729
-
730
-
731
- ### 🧠 Adaptive Memory & Learning
732
-
733
- **How Memory Works**
734
133
 
735
- **Memory Tree** — Hierarchical text storage that scores and organizes context chunks by relevance. Query it to retrieve relevant past decisions.
134
+ ### Configuration
736
135
 
737
- **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.
136
+ **Environment variables** — API keys for each provider:
738
137
 
739
- **Model Profiles** — Each model accumulates real latency, cost, and quality data. The routing algorithm uses these profiles alongside complexity scoring.
740
-
741
- ### 💰 Hard Budget Enforcement
742
-
743
- **Per-User/Team Budgets with Hard Caps + Real-Time Dashboard**
744
-
745
- ```typescript
746
- adaptive-memory-multi-model-router/billing';
747
-
748
- const budgets = new BudgetManager({
749
- monthlyLimit: 500, // $500/month hard cap
750
- alerts: [0.5, 0.8, 1.0], // 50%, 80%, 100% alerts
751
- perTeamLimits: {
752
- 'engineering': 200, // $200 for engineering team
753
- 'product': 150, // $150 for product team
754
- },
755
- perUserLimits: {
756
- 'user-123': 50, // $50 for specific user
757
- }
758
- });
759
-
760
- budgets.onAlert((alert) => {
761
- console.log(`${alert.type}: ${alert.team} at ${alert.percentage}%`);
762
- // → "warning: engineering at 80%"
763
- });
764
-
765
- budgets.getSpendBreakdown();
766
- // → { total: 340.50, byTeam: { engineering: 180, product: 120, ... }, byProvider: {...} }
138
+ ```bash
139
+ export OPENAI_API_KEY=sk-...
140
+ export ANTHROPIC_API_KEY=sk-ant-...
141
+ export GROQ_API_KEY=gsk_...
142
+ # No key needed for free tier providers
767
143
  ```
768
144
 
769
- ### 🔄 Intelligent Failover
770
-
771
- **Provider Health Scoring + Circuit Breaker + Chinese Provider Handling**
145
+ **Budget enforcement:**
772
146
 
773
147
  ```typescript
774
- adaptive-memory-multi-model-router/failover';
775
- adaptive-memory-multi-model-router/failover';
776
-
777
- // Provider health scoring
778
- const health = new HealthScoreManager({
779
- latencyWeight: 0.6, // 60% weight on latency
780
- errorRateWeight: 0.4, // 40% weight on error rate
781
- baselineLatency: 500, // ms - what "good" looks like
782
- errorPenalty: 20, // points per 1% error rate
783
- });
784
-
785
- health.getScore('groq'); // → 0.85 (85% healthy)
786
- health.getScore('deepseek'); // → 0.72 (degraded)
787
-
788
- // Circuit breaker with fallback chain
789
- const cb = new CircuitBreaker({
790
- failureThreshold: 3, // trip after 3 failures
791
- cooldownMs: 60000, // 60 second cooldown
792
- fallbackChain: ['groq', 'deepseek', 'openai'],
793
- });
794
-
795
- cb.execute('kimi', () => callKimi());
796
- // → if kimi fails 3x, circuit trips, next calls skip kimi for 60s
148
+ import { BudgetManager } from 'adaptive-memory-multi-model-router/billing';
797
149
 
798
- // Chinese provider special handling
799
- const chineseHandler = new ChineseProviderHandler({
800
- enabledProviders: ['kimi', 'deepseek', 'qwen', 'yi'],
801
- regionalFallback: 'openai',
802
- rateLimitBackoff: 30000, // longer backoff for Chinese rate limits
803
- });
804
- ```
805
-
806
- ### 💾 Semantic Cache
807
-
808
- **Embedding-Based Cache Lookup + Per-Route TTL + Configurable Similarity**
809
-
810
- ```typescript
811
- adaptive-memory-multi-model-router/cache';
812
-
813
- const cache = new SemanticCache({
814
- maxSize: 1000, // max entries
815
- similarityThreshold: 0.92, // 92% similar = cache hit
816
- ttl: 3600000, // 1 hour default TTL
817
- perRouteTTL: {
818
- 'legal/*': 86400000, // legal queries: 24hr cache
819
- 'code/*': 1800000, // code queries: 30min cache
820
- }
150
+ const budgets = new BudgetManager({
151
+ monthlyLimit: 500,
152
+ alerts: [0.5, 0.8, 1.0],
821
153
  });
822
-
823
- // First call: LLM
824
- const result = await llm("What is the capital of France?");
825
-
826
- // Second call: cache hit (similarity > 0.92)
827
- const cached = await llm("What's the capital of France?"); // ← no LLM call
828
-
829
- cache.getStats(); // { hits: 1, misses: 1, hitRate: 0.5, size: 1 }
830
154
  ```
831
155
 
832
- ### Per-Provider Retry Logic
833
-
834
- **Custom Timeout + Exponential Backoff + Rate Limit Detection**
156
+ **Provider retry with backoff:**
835
157
 
836
158
  ```typescript
837
- adaptive-memory-multi-model-router/retry';
159
+ import { RetryManager } from 'adaptive-memory-multi-model-router/retry';
838
160
 
839
161
  const retry = new RetryManager({
840
162
  providers: {
841
163
  'openai': { timeout: 30000, maxRetries: 3, baseDelay: 1000 },
842
- 'anthropic': { timeout: 45000, maxRetries: 3, baseDelay: 1000 },
843
164
  'groq': { timeout: 15000, maxRetries: 2, baseDelay: 500 },
844
- 'kimi': { timeout: 20000, maxRetries: 3, baseDelay: 2000 }, // longer delay for Chinese API
845
165
  },
846
- backoffMultiplier: 2, // exponential: 1s → 2s → 4s
847
- jitter: 0.3, // ±30% jitter to prevent thundering herd
848
- rateLimitHandling: 'retry-after', // use Retry-After header for 429
849
166
  });
850
-
851
- retry.execute('groq', () => callGroq());
852
- // → automatic timeout, backoff, and 429 handling
853
167
  ```
854
168
 
855
- ---
856
-
857
- ## ⚡ Parallel Ensemble (P0 — Core Differentiator)
858
-
859
- 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.
169
+ **Circuit breaker:**
860
170
 
861
171
  ```typescript
862
- adaptive-memory-multi-model-router/ensemble';
172
+ import { CircuitBreaker } from 'adaptive-memory-multi-model-router/failover';
863
173
 
864
- const result = await executeEnsemble(
865
- "Explain how vector databases work",
866
- systemPrompt,
867
- context,
868
- { nvidia: callNvidia, groq: callGroq, openai: callOpenAI },
869
- { providers: ['nvidia', 'groq', 'openai'], timeoutMs: 30000 }
870
- );
871
-
872
- console.log(`🏆 Winner: ${result.winner}`); // → nvidia
873
- console.log(`📊 Score: ${result.scores.nvidia}`); // → 75
874
- console.log(`💡 Reasoning: ${result.reasoning}`); // → scored higher on specificity
875
-
876
- // All results preserved, even from losers
877
- console.log(result.allResults.groq); // → groq's answer (available if needed)
174
+ const cb = new CircuitBreaker({
175
+ failureThreshold: 3,
176
+ cooldownMs: 60000,
177
+ fallbackChain: ['groq', 'deepseek', 'openai'],
178
+ });
878
179
  ```
879
180
 
880
- **When to use ensemble:** When answer quality matters more than latency. Ensemble always returns the best result across all providers, with full provenance.
181
+ ---
881
182
 
882
- **When to skip:** For simple lookups or latency-critical paths, use single-provider routing (heuristic <1ms).
183
+ ## Provider Coverage
883
184
 
884
- ```typescript
885
- // Track historical accuracy per provider
886
- adaptive-memory-multi-model-router/ensemble';
185
+ | Provider | Tiers | Notes |
186
+ |----------|-------|-------|
187
+ | OpenAI | premium, mid | gpt-4o, gpt-4o-mini |
188
+ | Anthropic | premium, mid | claude-3.5-sonnet, claude-3-haiku |
189
+ | Google | premium, mid | gemini-1.5-pro, gemini-1.5-flash |
190
+ | Groq | cheap | llama-3.3-70b, llama-3.1-8b |
191
+ | DeepSeek | cheap, mid | deepseek-chat, deepseek-coder |
192
+ | Mistral | cheap, mid | mistral-large, mistral-small |
193
+ | NVIDIA | premium | nvidia/llama-3.1-nemotron |
194
+ | OpenRouter | all | aggregated access |
195
+ | Ollama | all | self-hosted models |
196
+ | vLLM | all | self-hosted OpenAI-compatible servers |
197
+ | Azure OpenAI | premium, mid | enterprise |
198
+ | AWS Bedrock | premium, mid | enterprise |
887
199
 
888
- let history = {};
889
- history = recordFeedback('nvidia', true, history); // good answer
890
- history = recordFeedback('groq', false, history); // bad answer
891
- // → { nvidia: { good: 1, bad: 0 }, groq: { good: 0, bad: 1 } }
892
- ```
200
+ 47+ providers total. Availability is checked at runtime.
893
201
 
894
202
  ---
895
203
 
896
- ## 🧭 Query-Type Presets (P1)
204
+ ## Adding a New Endpoint
897
205
 
898
- Route queries to the optimal provider and temperature based on task type no manual configuration needed.
206
+ The server uses a route-based architecture. To add a new endpoint:
899
207
 
900
- | Type | Provider | Temp | Ensemble | Use Case |
901
- |:---|:---|:---:|:---:|:---|
902
- | ⚡ Fast | Groq | 0.3 | ❌ | Quick lookups, simple Q&A |
903
- | 🔬 Research | NVIDIA | 0.3 | ✅ | Deep analysis, comparisons |
904
- | 🎨 Creative | NVIDIA | 0.7 | ❌ | Writing, brainstorming |
905
- | 💻 Code | Any | 0.2 | ✅ | Debugging, architecture |
906
- | 📖 Factual | Groq | 0.2 | ❌ | Definitions, facts |
208
+ **1. Create the handler** `src/server/handlers/myHandler.ts`:
907
209
 
908
210
  ```typescript
909
- adaptive-memory-multi-model-router/presets';
910
-
911
- const router = createPresetRouter();
912
-
913
- // Classify any query automatically
914
- const preset = router.classify("Write a Python function to sort an array");
915
- // → 'code'
211
+ import { RouteContext } from '../router';
916
212
 
917
- preset.provider; // 'nvidia' (or whichever code provider is configured)
918
- preset.temperature; // 0.2
919
- preset.ensemble; // → true
920
- preset.maxTokens; // → 3000
921
- preset.timeoutMs; // → 45000
922
-
923
- // Customize presets for your workload
924
- adaptive-memory-multi-model-router/presets';
925
-
926
- const customRouter = createPresetRouter({
927
- ...DEFAULT_PRESETS,
928
- research: { ...DEFAULT_PRESETS.research, provider: 'openai' },
929
- });
213
+ export async function handleMyEndpoint(ctx: RouteContext): Promise<void> {
214
+ ctx.json(200, { hello: 'world' });
215
+ }
930
216
  ```
931
217
 
932
- ---
933
-
934
- ## 🧠 Persistent Memory (P3)
935
-
936
- 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.
218
+ **2. Register the route** in `proxyServer.ts`:
937
219
 
938
220
  ```typescript
939
- adaptive-memory-multi-model-router/memory';
940
-
941
- // Pass a file path to enable persistence
942
- const memory = new EpisodicMemoryStore(1000, './.a3m-memory.json');
943
-
944
- // Auto-saves to disk every 3 entries
945
- memory.storeEntry({
946
- task: { description: "Build a REST API in Python", type: "code", complexity: 0.7 },
947
- result: { success: true, output: "...", duration_ms: 45000 },
948
- agent: { id: "codex", model: "gpt-4o", provider: "openai" },
949
- });
950
-
951
- // On next startup, memory auto-loads from disk
952
- const similar = memory.getSimilarTasks("Python async API", 5);
953
- console.log(`🔍 Found ${similar.length} similar past executions`);
954
-
955
- memory.getStats();
956
- // → { total_entries: 142, success_rate: 0.94, avg_duration_ms: 12000 }
957
- ```
958
-
959
- **Not just in-memory:** Unlike most agent frameworks that lose context on restart, A3M's memory survives process restarts, container redeploys, and machine reboots.
960
-
961
- ---
962
-
963
- ## Comparison
964
-
965
- | Feature | A3M Router | [LiteLLM](https://github.com/BerriAI/litellm) | [Portkey](https://github.com/Portkey-AI/gateway) | [OpenRouter](https://openrouter.ai) |
966
- |---------|:----------:|:-------:|:-------:|:-------:|
967
- | **Parallel ensemble** | **✅** | ❌ | ❌ | ❌ |
968
- | **Confidence scoring** | **✅** | ❌ | ❌ | ❌ |
969
- | **Routing accuracy published** | **Yes** (96.77% official) | No (manual) | No | No |
970
- | **Intelligent routing** | Multi-signal per-query | Manual selection | Manual | Manual |
971
- | **Zero ML / Zero GPU** | **Yes** | Yes | Yes | Yes |
972
- | **Package size** | 19.5 KB | ~50 MB | ~30 MB | API-only |
973
- | **OpenAI-compatible proxy** | **Yes** | No | Yes | Yes | Yes |
974
- | **Adaptive memory** | **Yes** | No | No | No | No |
975
- | **Semantic cache** | **Yes** (trigram) | No | No | Yes | No |
976
- | **Prompt injection detection** | **Yes** (17 patterns) | No | No | Yes | No |
977
- | **PII redaction** | **Yes** | No | No | Yes | No |
978
- | **Hallucination checks** | **Yes** | No | No | No | No |
979
- | **Cost analytics** | **Yes** | No | Yes | Yes | Yes |
980
- | **Budget alerts** | **Yes** | No | No | Yes | No |
981
- | **Circuit breaker** | **Yes** | No | No | Yes | No |
982
- | **LangChain adapter** | **Yes** | No | Yes | Yes | No |
983
- | **Python SDK** | **Yes** | Yes | Yes | Yes | Yes |
984
- | **TypeScript SDK** | **Yes** | No | No | Yes | Yes |
985
- | **CLI** | **Yes** | No | Yes | No | No |
986
- | **Self-hosted** | **Yes** | Yes | Yes | Yes | No |
987
- | **License** | MIT | Apache 2.0 | Custom | MIT | Proprietary |
988
-
989
- **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)
990
-
991
- ---
992
-
993
- ## Production-Oriented
994
-
995
- 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.
996
-
997
- ### Pain Points Solved
998
-
999
- | Problem | Without A3M Router | With A3M Router |
1000
- |---------|-------------------|-----------------|
1001
- | **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% |
1002
- | **Cache misses on similar queries** | Same query by 1000 users = 1000 LLM API calls | Embedding-based semantic cache, 30%+ hit rate, configurable similarity threshold |
1003
- | **Provider outage cascades** | One provider fails → all requests fail → P0 incident | Circuit breaker (3 failures → 60s cooldown) + automatic fallback chain |
1004
- | **Chinese provider failures** | Generic retry logic fails on Chinese APIs (rate limits, regional constraints) | Special handling: health scoring, regional awareness, provider-specific fallback |
1005
- | **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 |
1006
- | **No observability** | Blind to which provider is failing, which team is overspending | Provider health scoring, per-provider cost breakdown, spend vs budget per team |
1007
-
1008
- ### Enterprise Features
1009
-
1010
- - **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.
1011
-
1012
- - **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.
1013
-
1014
- - **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.
1015
-
1016
- - **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.
1017
-
1018
- ---
1019
-
1020
- ## API Reference
1021
-
1022
- | Method | Endpoint | Description |
1023
- |--------|----------|-------------|
1024
- | POST | `/v1/chat/completions` | OpenAI-compatible chat (streaming + non-streaming) |
1025
- | POST | `/v1/completions` | OpenAI text completions |
1026
- | POST | `/v1/route` | Routing decision without LLM call |
1027
- | GET | `/v1/models` | List available models with pricing |
1028
- | GET | `/health` | Provider health + cost summary |
1029
- | GET | `/dashboard` | Cost analytics dashboard |
221
+ import { handleMyEndpoint } from './handlers/myHandler';
1030
222
 
1031
- Full API docs: [`docs/API.md`](docs/API.md)
1032
-
1033
- ---
1034
-
1035
- ## Package Exports
1036
-
1037
- ```typescript
1038
- // Main — everything
1039
- adaptive-memory-multi-model-router';
1040
-
1041
- // SDK — clean high-level API
1042
- adaptive-memory-multi-model-router/sdk';
1043
-
1044
- // Individual modules
1045
- adaptive-memory-multi-model-router/cache';
1046
- adaptive-memory-multi-model-router/guardrails';
1047
- adaptive-memory-multi-model-router/cost';
1048
- adaptive-memory-multi-model-router/analytics';
1049
- adaptive-memory-multi-model-router/memory';
1050
- adaptive-memory-multi-model-router/langchain';
1051
- adaptive-memory-multi-model-router/providers';
1052
- adaptive-memory-multi-model-router/server';
1053
-
1054
- // Ensemble (P0) — core differentiator
1055
- adaptive-memory-multi-model-router/ensemble';
1056
-
1057
- // Query-type presets (P1)
1058
- adaptive-memory-multi-model-router/presets';
1059
-
1060
- // Persistent memory (P3)
1061
- adaptive-memory-multi-model-router/memory';
223
+ // In createProxyServer():
224
+ registerRoute('GET', /^\/v1\/my-endpoint$/, handleMyEndpoint, 'GET /v1/my-endpoint');
1062
225
  ```
1063
226
 
1064
- ---
1065
-
1066
- ## When NOT to Use This
1067
-
1068
- A3M Router is an **LLM gateway and router** designed for multi-provider routing. You may not need it if:
1069
-
1070
- - You only use one LLM provider (no routing benefit)
1071
- - You intentionally want every query sent to the strongest model regardless of cost
1072
- - You need 250+ provider integrations (use [Portkey](https://github.com/Portkey-AI/gateway))
1073
- - You specifically need ML-based routing and are willing to train, deploy, and maintain a classifier
1074
- - You need enterprise SLAs or managed hosting
1075
-
1076
- For single-provider use cases, the native SDK (OpenAI, Anthropic, etc.) is simpler.
1077
-
1078
- ---
1079
-
1080
- ## Roadmap (Coming Soon)
1081
-
1082
- These features are on our roadmap based on user feedback:
1083
-
1084
- | Feature | Status | Priority |
1085
- |---------|--------|----------|
1086
- | **Distributed tracing** — OpenTelemetry integration for production observability | Planned | High |
1087
- | **Webhook alerts** — Push budget alerts to Slack, PagerDuty, Teams | Planned | High |
1088
- | **Fine-grained RBAC** — Role-based access control for team budgets | Planned | Medium |
1089
- | **Multi-region failover** — Geographic load balancing across regions | Researching | Medium |
1090
- | **SLA reporting** — Uptime and latency SLAs for enterprise contracts | Researching | Low |
227
+ Two lines total.
1091
228
 
1092
229
  ---
1093
230
 
1094
- ## Supporters
231
+ ## Project Stats
1095
232
 
1096
- If A3M Router helps you, consider:
1097
- - Starring on [GitHub](https://github.com/Das-rebel/a3m-router)
1098
- - 📦 Sharing on [npm](https://www.npmjs.com/package/adaptive-memory-multi-model-router)
1099
- - 🐛 Reporting issues
1100
- - 🔀 Submitting PRs
233
+ - **Stars**: 10
234
+ - **npm downloads/month**: ~5,000
235
+ - **Providers**: 47+
236
+ - **License**: MIT
1101
237
 
1102
238
  ---
1103
239
 
1104
- ## Links
1105
-
1106
- - [npm package](https://www.npmjs.com/package/adaptive-memory-multi-model-router)
1107
- - [GitHub repo](https://github.com/Das-rebel/a3m-router)
1108
- - [API Reference](docs/API.md)
1109
- - [Architecture](docs/ARCHITECTURAL-IMPROVEMENTS-2025.md)
1110
- - [Discussions](https://github.com/Das-rebel/a3m-router/discussions)
1111
- - [Contributing](CONTRIBUTING.md) · [Good first issues](https://github.com/Das-rebel/a3m-router/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)
1112
-
1113
- ### Community & Support
1114
-
1115
- - [🐛 Report a Bug](https://github.com/Das-rebel/a3m-router/issues/new?template=bug_report.md) — File a detailed bug report
1116
- - [✨ Request a Feature](https://github.com/Das-rebel/a3m-router/issues/new?template=feature_request.md) — Suggest an enhancement
1117
- - [📥 Pull Request Template](https://github.com/Das-rebel/a3m-router/blob/main/.github/PULL_REQUEST_TEMPLATE.md) — Use this format for all PRs
1118
- - [📋 All Issue Templates](https://github.com/Das-rebel/a3m-router/issues/new/choose) — Choose the right template for your submission
1119
-
1120
- MIT License. No vendor lock-in. No account required. `npm install` and go.
1121
-
1122
-
1123
- ---
1124
-
1125
- ## Research-Backed Architecture
1126
-
1127
- 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-oriented features. The current validation anchor is **RouterArena PR #144: 0.9404 score, 96.77% accuracy, $0.0768/1K, 1.0000 robustness, 0 abnormal entries, 8,400 queries**.
1128
-
1129
- | Paper | Year | What We Used |
1130
- |-------|------|-------------|
1131
- | **[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. |
1132
- | **[RouteLLM](https://arxiv.org/abs/2404.06035)** | 2024 | **Cost-quality routing** — learned routing baseline. We use heuristic routing instead (no GPU, faster startup). |
1133
- | **[Speculative Decoding (Medusa)](https://arxiv.org/abs/2401.10774)** | 2024 | **Multi-token prediction** — 2-3x speedup. Our speculative decoding module implements this interface. |
1134
- | **[AgentOrchestra](https://arxiv.org/abs/2506.12508)** | 2025 | **Hierarchical multi-agent orchestration** — 3-tier planning. We adapted this for provider selection. |
1135
- | **[Difficulty-Aware Routing](https://arxiv.org/abs/2509.11079)** | 2025 | **35% decision quality improvement** — difficulty-based task routing. Core of our routing engine. |
1136
- | **[MemoRAG](https://arxiv.org/abs/2512.12686)** | 2025 | **Global memory encoder** — 50% better long-context. We use MemoryTree for historical context. |
1137
- | **[A-Mem](https://arxiv.org/abs/2502.12110)** | 2025 | **Episodic memory** — 144+ citations. Our episodic memory uses EMA updates for quality scoring. |
1138
- | **[MCTS (Monte Carlo Tree Search)](https://arxiv.org/abs/2411.20000)** | 2024 | **UCB1 exploration** — multi-agent workflow optimization. Early A3M MCTS research showed `cost_quality` at 0.9370 accuracy-cost vs 0.9300 heuristic baseline. |
1139
-
1140
- ### Key Architecture Decisions (Research-Backed):
1141
-
1142
- ```text
1143
- Research Inputs A3M Implementation Validation
1144
- ─────────────────────────────────────────────────────────────────────────────────────
1145
- SGLang / RadixAttention → Prefix-aware semantic cache → 30%+ observed hit rate
1146
- RouteLLM / Cost-quality → Heuristic cost-quality routing → RouterArena PR #144
1147
- Difficulty-aware routing → Multi-signal tier classifier → 96.77% accuracy
1148
- A-Mem / MemoRAG → MemoryTree + EMA quality updates → no retraining required
1149
- MCTS / UCB1 → Workflow optimizer prototype → 0.9370 vs 0.9300 baseline
1150
- ```
1151
-
1152
- ```text
1153
- Current RouterArena Anchor
1154
- ─────────────────────────────────────────────────────────────────────────────
1155
- RouterArena PR #144: 0.9404 score | 96.77% accuracy | $0.0768/1K
1156
- 1.0000 robustness | 0 abnormal entries | 8,400 queries
1157
-
1158
- Next Research Loop
1159
- ─────────────────────────────────────────────────────────────────────────────
1160
- MCTS/RL-style routing → test cost-quality strategies → submit improved predictions → compare against 0.9404 / 96.77% anchor
1161
- ```
1162
-
1163
- ### Why Not Use ML-Based Routing?
1164
-
1165
- | Approach | RouteLLM | A3M Router |
1166
- |----------|----------|------------|
1167
- | **Training** | Requires GPU, labeled data | Zero |
1168
- | **Startup** | ~3 minutes | <100ms |
1169
- | **Updates** | Retrain required | EMA, no retraining |
1170
- | **Accuracy** | Varies | 96.77% RouterArena PR #144 |
1171
- | **Cost** | High (GPU cluster) | Zero routing training; RouterArena cost $0.0768/1K |
1172
-
1173
- RouterArena PR #144 shows A3M’s zero-training routing achieves **96.77% accuracy** and **$0.0768/1K** without ML training, outperforming known public baselines on accuracy, cost, and robustness.
1174
-
1175
- ---
1176
-
1177
-
1178
- ---
240
+ ## License
1179
241
 
242
+ MIT. See [LICENSE](LICENSE).