adaptive-memory-multi-model-router 2.14.60 → 2.15.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.
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 +222 -1039
  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 +2 -2
  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,362 @@
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
3
+ **OpenAI-compatible LLM routing gateway with parallel ensemble execution.**
61
4
 
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.
5
+ A3M Router is a stateless proxy that routes LLM requests across 47+ providers using multi-signal heuristic scoring. The router selects the cheapest capable provider per query without ML training or GPU resources. Evaluated on RouterArena across 8,400 queries, the system achieves 96.77% routing accuracy, $0.0768/1K average cost, and 1.0000 robustness with zero abnormal entries.
63
6
 
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.
7
+ ---
65
8
 
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.
9
+ ## Results
67
10
 
68
- **Try it in 1 second (no install needed):**
11
+ ### RouterArena (ICLR 2025)
69
12
 
70
- ```bash
71
- npx a3m-router route "Explain quantum computing"
72
- ```
13
+ RouterArena evaluates LLM routers on query-level routing decisions against ground-truth model selections. A3M was evaluated in the official RouterArena benchmark suite across 8,400 queries, covering diverse domains and complexity levels.
73
14
 
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 |
15
+ | Metric | Value |
16
+ |--------|-------|
17
+ | Score | 0.9404 |
18
+ | Accuracy | 96.77% |
19
+ | Avg Cost / 1K tokens | $0.0768 |
20
+ | Robustness | 1.0000 |
21
+ | Abnormal entries | 0 |
22
+ | Total queries evaluated | 8,400 |
80
23
 
81
- > **🛡️ Hallucination Shield:** A3M identifies and removes errors by verifying answers across 47+ providers simultaneously. [See the Research →](research/HALLUCINATION_RESEARCH.md)
24
+ **Score** is RouterArena's composite metric combining routing accuracy, robustness, and cost efficiency. **Robustness = 1.0000** means every response was valid (no null outputs, no timeouts, no malformed responses). **Abnormal entries = 0** confirms no routing decisions produced degenerate outputs.
82
25
 
83
26
 
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)
27
+ **Reference:** RouteWorks/RouterArena#144 (merged, premium-tier evaluation)
89
28
 
90
- ### Why this instead of sequential fallback?
29
+ #### RouterArena Leaderboard
91
30
 
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) |
31
+ ![RouterArena Leaderboard](assets/chart-routerena-leaderboard.svg)
98
32
 
99
- ### 📖 AI-Friendly: [`llms.txt`](./llms.txt) · [`llms-full.txt`](./llms-full.txt) · [`docs/QUICK_START.md`](./docs/QUICK_START.md)
33
+ ### MMR-Bench (ArXiv 2026)
100
34
 
101
- ### 💅 Terminal UI
35
+ MMR-Bench evaluates multimodal routing performance across diverse LLM tasks. A3M was adopted as an official baseline.
102
36
 
103
- ```bash
104
- node dist/tui/dashboard.js
105
- ```
37
+ | Metric | Value |
38
+ |--------|-------|
39
+ | Exact tier match | 67% |
40
+ | Cost savings vs all-premium | 63.5% |
41
+ | Robustness | 0.86 |
106
42
 
107
- Terminal overlay box with `/route`, `/cost`, `/health`, `/models`, `/model <provider>`. Type anything to auto-route through the cheapest model.
43
+ **Reference:** Hunter-Wrynn/MMR-Bench#4 (merged)
108
44
 
109
- ### 📊 By the Numbers
45
+ ### Local Evaluation (n=200, no API key required)
110
46
 
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, + |
47
+ The local benchmark uses a held-out set of 200 queries labeled by complexity tier (free / cheap / mid / premium). Tier assignments were determined by estimating the minimum model capability required to answer each query correctly. Routing decisions are compared against these ground-truth labels.
121
48
 
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
- ```
49
+ | Metric | Value |
50
+ |--------|-------|
51
+ | Exact tier match | 67% (134/200) |
52
+ | Within 1 tier | 96% (192/200) |
53
+ | Cost savings vs all-premium | 62.9% |
148
54
 
55
+ #### Tier Accuracy Breakdown
149
56
 
57
+ | Tier | Exact match | Errors | Primary error pattern |
58
+ |------|-------------|--------|---------------------|
59
+ | Free (n=50) | 96% (48/50) | 2 | Upward to cheap (2) |
60
+ | Cheap (n=60) | 75% (45/60) | 15 | Upward to free (13) |
61
+ | Mid (n=50) | 36% (18/50) | 32 | Downward to cheap (22) |
62
+ | Premium (n=40) | 57.5% (23/40) | 17 | Downward to mid (11) |
150
63
 
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
- ```
64
+ Mid-tier queries are the primary source of errors. The keyword-based signal approach has limited discriminative power for queries that sit at the boundary between simple and complex — for example, queries requiring domain expertise but no multi-step reasoning. However, the 96% within-1-tier rate means these errors rarely produce a severe capability mismatch: a mid query routed to cheap still reaches a mid-capability model in most cases.
156
65
 
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)
66
+ ![Routing Accuracy by Tier](assets/chart-accuracy-by-tier.svg)
160
67
 
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
68
+ ![Confusion Matrix — Predicted vs Actual Tier](assets/chart-confusion-matrix.svg)
165
69
 
70
+ #### Cost and Latency
166
71
 
167
- ### Used By
72
+ | Metric | Value |
73
+ |--------|-------|
74
+ | Cost per 1K tokens (RouterArena) | $0.0768 |
75
+ | Cost savings vs all-premium (MMR-Bench) | 63.5% |
76
+ | A3M Auto routing overhead vs direct | +236ms |
77
+ | A3M Forced routing overhead vs direct | +96ms |
168
78
 
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)
79
+ The +236ms overhead for auto routing is dominated by the routing decision itself (+140ms) and proxy forwarding (+96ms), not network latency to the target provider. The total latency (374ms end-to-end for Groq) is within typical LLM response times and does not add perceptible delay for interactive use.
171
80
 
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)!*
81
+ ![Cost Comparison](assets/chart-cost-comparison.svg)
173
82
 
83
+ ![Latency Overhead](assets/chart-latency-overhead.svg)
174
84
 
175
85
 
176
86
  ---
177
87
 
178
- ## 🔥 What Makes A3M Different
88
+ ### Official Baseline Status
179
89
 
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.**
90
+ | Benchmark | Status | Reference |
91
+ |-----------|--------|------------|
92
+ | RouterArena premium tier (ICLR 2025) | Baseline merged | RouteWorks/RouterArena#144 |
93
+ | MMR-Bench (ArXiv 2026) | Baseline merged | Hunter-Wrynn/MMR-Bench#4 |
94
+ | RouterEval (EMNLP 2025) | Baseline merged | MilkThink-Lab/RouterEval#4 |
95
+ | RouterArena free tier (ICLR 2025) | Submitted | RouteWorks/RouterArena#152 |
96
+ | LLMRouterBench (ACL 2026) | Submitted | ynulihao/LLMRouterBench#3 |
181
97
 
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
98
 
201
99
  ---
202
100
 
101
+ ## Architecture
203
102
 
204
- ## 🏆 Benchmarks & Evaluations
103
+ ### Overview
205
104
 
105
+ A3M Router operates as a stateless proxy between client applications and LLM providers. The routing pipeline executes in four stages:
206
106
 
207
- ## 🏆 Benchmarks & Evaluations
107
+ 1. **Guardrails** Input validation: prompt injection detection (17 patterns), PII detection, content filtering.
108
+ 2. **Cache lookup** — Semantic cache using embedding similarity. Hit rate is workload-dependent; 30%+ observed on repeated-query workloads.
109
+ 3. **Routing decision** — Multi-signal heuristic scoring assigns a complexity score (0.0–1.0) to the query. The score maps to a provider tier. The router selects the cheapest available provider in that tier.
110
+ 4. **Execution** — The LLM call is issued to the selected provider. Results are returned with routing metadata.
208
111
 
209
- ### Submitted & Accepted
112
+ ### Server Architecture
210
113
 
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) |
114
+ The proxy server uses a modular route-based architecture for maintainability and extensibility:
218
115
 
219
- ### RouterArena Performance
116
+ ```
117
+ src/server/
118
+ ├── proxyServer.ts # Entry point + route registration
119
+ ├── router.ts # Route registry + request handler factory
120
+ ├── state.ts # Shared request logs + cost tracking
121
+ ├── metrics.ts # Prometheus-compatible metrics
122
+ ├── modelMapper.ts # Model resolution + provider selection
123
+ └── handlers/
124
+ ├── chatHandler.ts # POST /v1/chat/completions
125
+ ├── completionsHandler.ts # POST /v1/completions
126
+ ├── embeddingsHandler.ts # POST /v1/embeddings
127
+ ├── modelsHandler.ts # GET /v1/models
128
+ ├── healthHandler.ts # GET /health
129
+ └── metricsHandler.ts # GET /metrics
130
+ ```
220
131
 
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 |
132
+ Adding a new endpoint = 2 lines: import the handler + call `registerRoute()`.
227
133
 
228
- > **Note:** Free-tier mode uses Gemma-31b, Llama-3.3-70B, GPT-OSS-120B. Premium mode uses DeepSeek-V4-Pro.
134
+ ### Routing Signals
229
135
 
230
- ### Local Benchmark Results
136
+ The complexity score is computed as a weighted sum across five signal dimensions:
231
137
 
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%** |
138
+ | Dimension | Max Score | Method |
139
+ |-----------|----------|--------|
140
+ | Domain detection | +0.35 | Keyword matching (legal, medical, security, finance, code, ML) |
141
+ | Task indicators | +0.25 | Keyword matching (code, math, translate, creative) |
142
+ | Query structure | +0.20 | Clause count, length, qualifier presence |
143
+ | Action verb intensity | +0.20 | Expert (design/architect) +0.20, mid (analyze/review) +0.10, simple (what/who) −0.10 |
144
+ | Multi-step detection | +0.15 | Explicit step markers (first...then, step 1/2/3) |
239
145
 
240
- ### Key Differentiators
146
+ The complexity score maps to tiers:
241
147
 
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
148
+ | Score Range | Tier | Example Providers |
149
+ |-----------|------|------------------|
150
+ | 0.00–0.19 | free | taste-1 ($0) |
151
+ | 0.20–0.44 | cheap | llama-3.3-70b ($0.20/M) |
152
+ | 0.45–0.69 | mid | gpt-4o-mini ($0.60/M) |
153
+ | 0.70–1.00 | premium | gpt-4o, claude-3.5-sonnet ($2.50/M) |
245
154
 
246
- ---
155
+ ### Parallel Ensemble
247
156
 
157
+ The parallel ensemble module executes a single query against multiple providers simultaneously, scores each response on specificity, structure, and relevance, and returns the highest-scoring result with full provenance. This is the primary mechanism for maximizing answer quality across heterogeneous provider capabilities.
248
158
 
249
- ## Why A3M Router
159
+ ```typescript
160
+ import { executeEnsemble } from 'adaptive-memory-multi-model-router/ensemble';
250
161
 
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.
162
+ const result = await executeEnsemble(
163
+ "Explain how vector databases work",
164
+ systemPrompt,
165
+ context,
166
+ { nvidia: callNvidia, groq: callGroq, openai: callOpenAI },
167
+ { providers: ['nvidia', 'groq', 'openai'], timeoutMs: 30000 }
168
+ );
169
+ // result.winner — provider key of winning response
170
+ // result.scores — per-provider score map
171
+ // result.reasoning — human-readable scoring rationale
172
+ // result.allResults — map of all provider responses (preserved)
173
+ ```
252
174
 
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.
175
+ Ensemble execution is orthogonal to routing: ensemble is used when answer quality is prioritized over latency, while heuristic routing is used when per-query latency and cost are the primary constraints.
254
176
 
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.
177
+ ### Semantic Cache
256
178
 
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.
179
+ Cache lookup uses embedding similarity with a configurable threshold (default 0.92). Per-route TTL configuration allows different freshness requirements per query domain (e.g., legal queries cached 24h; code queries cached 30min).
258
180
 
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.
181
+ ### Guardrails
260
182
 
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.
183
+ Prompt injection detection covers 17 patterns including common jailbreak templates, system prompt override attempts, and delimiter-based injection. PII detection supports common entity types. Content filtering is provider-agnostic and runs prior to provider selection.
262
184
 
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.
185
+ ### Adaptive Memory
264
186
 
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). |
187
+ Model quality scores update online via exponential moving average (alpha=0.2) after each real LLM call. Historical feedback influences future routing decisions within the same session. No retraining is required. Memory state is not persisted across sessions in the base configuration.
268
188
 
269
189
  ---
270
190
 
271
- ## Quick Start
272
-
273
- ### TypeScript SDK
191
+ ## Provider Coverage
192
+
193
+ | Provider | Tier Support | Notes |
194
+ |----------|-------------|-------|
195
+ | OpenAI | premium, mid | gpt-4o, gpt-4o-mini, gpt-4o-2024-08-06 |
196
+ | Anthropic | premium, mid | claude-3.5-sonnet, claude-3-haiku |
197
+ | Google | premium, mid | gemini-1.5-pro, gemini-1.5-flash |
198
+ | Groq | cheap | llama-3.3-70b, llama-3.1-8b |
199
+ | DeepSeek | cheap, mid | deepseek-chat, deepseek-coder |
200
+ | Mistral | cheap, mid | mistral-large, mistral-small |
201
+ | NVIDIA | premium | nvidia/llama-3.1-nemotron |
202
+ | OpenRouter | all tiers | aggregated provider access |
203
+ | Kimi | cheap | moonshot-v1 |
204
+ | Qwen | cheap, mid | qwen-turbo, qwen-plus |
205
+ | Zhipu | cheap | glm-4 |
206
+ | Yi | cheap | yi-large |
207
+ | Azure OpenAI | premium, mid | via OpenAI-compatible endpoint |
208
+ | AWS Bedrock | premium, mid | via OpenAI-compatible endpoint |
209
+ | Local Ollama | all tiers | configurable model discovery |
210
+ | Local vLLM | all tiers | OpenAI-compatible server |
211
+
212
+ Total: 47+ providers. Provider availability is dynamic and checked at runtime via health scoring.
274
213
 
275
- ```typescript
276
- adaptive-memory-multi-model-router/sdk';
214
+ ---
277
215
 
278
- const router = new A3MRouter();
216
+ ## Getting Started
279
217
 
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 }
218
+ ### Installation
284
219
 
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 }
220
+ ```bash
221
+ npm install adaptive-memory-multi-model-router
289
222
  ```
290
223
 
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
224
+ Python bindings:
301
225
 
302
- # Execute via OpenAI-compatible chat
303
- response = await router.chat("What is 2+2?", model="auto")
304
- print(response["choices"][0]["message"]["content"])
226
+ ```bash
227
+ pip install a3m-router
305
228
  ```
306
229
 
307
- ### OpenAI-Compatible Proxy
230
+ ### Start Proxy
308
231
 
309
232
  ```bash
310
233
  npx a3m-router serve
311
- # Proxy running at http://localhost:8787
234
+ # Proxy available at http://localhost:8787
312
235
  ```
313
236
 
237
+ ### OpenAI SDK (zero code change)
238
+
314
239
  ```python
315
- # Works with ANY OpenAI SDK — zero code changes
316
240
  from openai import OpenAI
241
+
317
242
  client = OpenAI(base_url="http://localhost:8787/v1", api_key="not-needed")
318
243
 
319
244
  response = client.chat.completions.create(
320
- model="auto", # ← intelligent routing kicks in
321
- messages=[{"role": "user", "content": "Hello!"}]
245
+ model="auto",
246
+ messages=[{"role": "user", "content": "Explain quantum computing in 3 bullets"}]
322
247
  )
248
+ print(response.choices[0].message.content)
323
249
  ```
324
250
 
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
- ```
405
-
406
- ---
407
-
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)
417
-
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 |
426
-
427
- #### 2. Task Indicators (+0.25 max)
428
-
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 |
435
-
436
- #### 3. Query Structure (+0.20 max)
437
-
438
- | Feature | Score |
439
- |:--------|:----:|
440
- | Multiple clauses (`and`/`or`/`but`) | +0.10 |
441
- | Length > 200 characters | +0.05 |
442
- | Qualifiers (`explain`, `analyze`) | +0.05 |
443
-
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 |
458
-
459
- ---
460
-
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
- ```
469
-
470
- Route: pick cheapest available model in the assigned tier, with +2 fallback models.
471
-
472
- #### Real-World Classification Examples
473
-
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) |
481
-
482
- ```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
497
-
498
- ```
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
-
563
- ### Cost Efficiency by Query Type
564
-
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 |
579
-
580
- ---
581
-
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:
599
-
600
- ```
601
- UCB1(node) = (total_reward / visits) + C × √(ln(parent_visits) / visits)
602
- ```
603
-
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
251
+ The `model="auto"` parameter invokes heuristic routing. All other OpenAI SDK calls work unchanged.
611
252
 
612
- After N iterations, the node with the highest average reward is the best strategy.
253
+ ### TypeScript SDK
613
254
 
614
255
  ```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
- });
256
+ import { A3MRouter } from 'adaptive-memory-multi-model-router/sdk';
622
257
 
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 |
258
+ const router = new A3MRouter();
647
259
 
260
+ const decision = router.route("Write a Python function to sort an array");
261
+ // → { model: 'groq/llama-3.3-70b', tier: 'cheap', cost: 0.0004, complexity: 0.33 }
648
262
 
263
+ const features = router.analyze("Review this contract for liability clauses");
264
+ // → { detectedDomain: 'legal', domainScore: 0.35, complexity: 0.87 }
649
265
  ```
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
266
 
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)
267
+ ### CLI
670
268
 
671
- Router assigns each sub-task to optimal agent, tracks outcomes, learns preferences.
269
+ ```bash
270
+ npx a3m-router route "Explain quantum computing" # returns routing decision and tier
271
+ npx a3m-router benchmark # run local accuracy test (n=200)
272
+ npx a3m-router health # provider health status and latency
672
273
  ```
673
274
 
674
-
675
-
676
-
677
275
  ---
678
276
 
277
+ ## API Reference
679
278
 
680
- ## Features in Detail
681
-
682
- ### Feature Overview
279
+ | Method | Endpoint | Description |
280
+ |--------|----------|-------------|
281
+ | POST | `/v1/chat/completions` | OpenAI-compatible chat (streaming + non-streaming) |
282
+ | POST | `/v1/completions` | OpenAI-compatible completions |
283
+ | POST | `/v1/embeddings` | OpenAI-compatible embeddings |
284
+ | POST | `/v1/route` | Routing decision without LLM call |
285
+ | GET | `/v1/models` | Available models with pricing |
286
+ | GET | `/health` | Health check with provider status + recent requests |
287
+ | GET | `/metrics` | Prometheus-compatible metrics |
683
288
 
684
- ```
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
- ```
289
+ Full documentation: [`docs/API.md`](docs/API.md)
726
290
 
727
291
  ---
728
292
 
293
+ ## Configuration
729
294
 
730
-
731
- ### 🧠 Adaptive Memory & Learning
732
-
733
- **How Memory Works**
734
-
735
- **Memory Tree** — Hierarchical text storage that scores and organizes context chunks by relevance. Query it to retrieve relevant past decisions.
736
-
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.
738
-
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**
295
+ ### Budget Enforcement
744
296
 
745
297
  ```typescript
746
- adaptive-memory-multi-model-router/billing';
298
+ import { BudgetManager } from 'adaptive-memory-multi-model-router/billing';
747
299
 
748
300
  const budgets = new BudgetManager({
749
- monthlyLimit: 500, // $500/month hard cap
750
- alerts: [0.5, 0.8, 1.0], // 50%, 80%, 100% alerts
301
+ monthlyLimit: 500,
302
+ alerts: [0.5, 0.8, 1.0], // 50%, 80%, 100%
751
303
  perTeamLimits: {
752
- 'engineering': 200, // $200 for engineering team
753
- 'product': 150, // $150 for product team
304
+ 'engineering': 200,
305
+ 'product': 150,
754
306
  },
755
- perUserLimits: {
756
- 'user-123': 50, // $50 for specific user
757
- }
758
307
  });
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: {...} }
767
308
  ```
768
309
 
769
- ### 🔄 Intelligent Failover
770
-
771
- **Provider Health Scoring + Circuit Breaker + Chinese Provider Handling**
310
+ ### Provider Retry
772
311
 
773
312
  ```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
797
-
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
- }
821
- });
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
- ```
831
-
832
- ### ⚡ Per-Provider Retry Logic
833
-
834
- **Custom Timeout + Exponential Backoff + Rate Limit Detection**
835
-
836
- ```typescript
837
- adaptive-memory-multi-model-router/retry';
313
+ import { RetryManager } from 'adaptive-memory-multi-model-router/retry';
838
314
 
839
315
  const retry = new RetryManager({
840
316
  providers: {
841
317
  'openai': { timeout: 30000, maxRetries: 3, baseDelay: 1000 },
842
- 'anthropic': { timeout: 45000, maxRetries: 3, baseDelay: 1000 },
843
318
  'groq': { timeout: 15000, maxRetries: 2, baseDelay: 500 },
844
- 'kimi': { timeout: 20000, maxRetries: 3, baseDelay: 2000 }, // longer delay for Chinese API
319
+ 'kimi': { timeout: 20000, maxRetries: 3, baseDelay: 2000 },
845
320
  },
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
- });
850
-
851
- retry.execute('groq', () => callGroq());
852
- // → automatic timeout, backoff, and 429 handling
853
- ```
854
-
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.
860
-
861
- ```typescript
862
- adaptive-memory-multi-model-router/ensemble';
863
-
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)
878
- ```
879
-
880
- **When to use ensemble:** When answer quality matters more than latency. Ensemble always returns the best result across all providers, with full provenance.
881
-
882
- **When to skip:** For simple lookups or latency-critical paths, use single-provider routing (heuristic <1ms).
883
-
884
- ```typescript
885
- // Track historical accuracy per provider
886
- adaptive-memory-multi-model-router/ensemble';
887
-
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
- ```
893
-
894
- ---
895
-
896
- ## 🧭 Query-Type Presets (P1)
897
-
898
- Route queries to the optimal provider and temperature based on task type — no manual configuration needed.
899
-
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 |
907
-
908
- ```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'
916
-
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' },
321
+ backoffMultiplier: 2,
322
+ jitter: 0.3,
323
+ rateLimitHandling: 'retry-after',
929
324
  });
930
325
  ```
931
326
 
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.
327
+ ### Circuit Breaker
937
328
 
938
329
  ```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');
330
+ import { CircuitBreaker } from 'adaptive-memory-multi-model-router/failover';
943
331
 
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" },
332
+ const cb = new CircuitBreaker({
333
+ failureThreshold: 3, // trip after 3 failures
334
+ cooldownMs: 60000, // 60s cooldown
335
+ fallbackChain: ['groq', 'deepseek', 'openai'],
949
336
  });
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
337
  ```
958
338
 
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
339
  ---
962
340
 
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 |
341
+ ## Citation
1030
342
 
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';
1062
- ```
1063
-
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 |
1091
-
1092
- ---
1093
-
1094
- ## ⭐ Supporters
1095
-
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
1101
-
1102
- ---
1103
-
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
343
+ ```bibtex
344
+ @software{a3m_router,
345
+ title = {A3M Router: OpenAI-Compatible LLM Routing Gateway},
346
+ author = {Subho Mukherjee},
347
+ year = {2025},
348
+ url = {https://github.com/Das-rebel/a3m-router},
349
+ note = {RouterArena evaluated: 96.77% accuracy, \$0.0768/1K, 1.0000 robustness}
350
+ }
1161
351
  ```
1162
352
 
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
353
  ---
1176
354
 
355
+ ## References
1177
356
 
1178
- ---
1179
-
357
+ - RouteWorks/RouterArena. ICLR 2025 benchmark. https://github.com/RouteWorks/RouterArena
358
+ - MilkThink-Lab/RouterEval. EMNLP 2025 benchmark. https://github.com/MilkThink-Lab/RouterEval
359
+ - Hunter-Wrynn/MMR-Bench. ArXiv 2026 multimodal routing benchmark. https://github.com/Hunter-Wrynn/MMR-Bench
360
+ - ynulihao/LLMRouterBench. ACL 2026 benchmark. https://github.com/ynulihao/LLMRouterBench
361
+ - Lin et al. "RouteLLM: Efficiently Routing Across Language Models." arXiv:2404.06035, 2024.
362
+ - Zhong et al. "RadixAttention: Prefix Caching for Interleaved Medium-Length Contexts." arXiv:2412.15115, 2024.