adaptive-memory-multi-model-router 2.15.3 → 2.15.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/.github/ISSUE_TEMPLATE/bug_report.md +94 -0
  2. package/.github/ISSUE_TEMPLATE/config.yml +17 -0
  3. package/.github/ISSUE_TEMPLATE/feature_request.md +71 -0
  4. package/.well-known/ai-plugin.json +16 -0
  5. package/AGENT_COUNCIL_FINDINGS.md +98 -123
  6. package/POPULARITY_BOOSTERS.md +1 -1
  7. package/README.md +275 -147
  8. package/README_ja.md +20 -16
  9. package/README_zh.md +17 -13
  10. package/adapters/README.md +36 -0
  11. package/adapters/__init__.py +25 -0
  12. package/adapters/a3m_adapter/__init__.py +15 -0
  13. package/adapters/a3m_adapter/adapter/__init__.py +7 -0
  14. package/adapters/a3m_adapter/adapter/config.py +100 -0
  15. package/adapters/a3m_adapter/adapter/langchain.py +155 -0
  16. package/adapters/a3m_adapter/adapter/llamaindex.py +162 -0
  17. package/adapters/a3m_adapter/tests/__init__.py +1 -0
  18. package/adapters/a3m_adapter/tests/test_adapters.py +120 -0
  19. package/adapters/setup.py +23 -0
  20. package/articles/CHINESE_DIRECTORIES.md +2 -2
  21. package/articles/CHINESE_SUBMISSIONS_READY.md +5 -5
  22. package/articles/HN_POST_READY.md +20 -16
  23. package/articles/INDIEHACKERS_READY.md +34 -19
  24. package/dist/analytics/costAnalytics.d.ts +1 -0
  25. package/dist/benchmark/reproducible.d.ts +1 -0
  26. package/dist/cache/semanticCache.d.ts +1 -0
  27. package/dist/cost/budgetEnforcer.d.ts +1 -0
  28. package/dist/cost/costTracker.d.ts +1 -0
  29. package/dist/ensemble/multiRoundDialog.d.ts +1 -0
  30. package/dist/ensemble/shapleyValue.d.ts +1 -0
  31. package/dist/ensemble.d.ts +1 -0
  32. package/dist/index.d.ts +1 -0
  33. package/dist/integrations/oauth.d.ts +1 -0
  34. package/dist/integrations/scienceAdapter.d.ts +1 -0
  35. package/dist/memory/autoFetch.d.ts +1 -0
  36. package/dist/memory/hybridMemory.d.ts +1 -0
  37. package/dist/memory/memoryTree.d.ts +1 -0
  38. package/dist/memory/obsidianVault.d.ts +1 -0
  39. package/dist/memory/reasoningBank.d.ts +1 -0
  40. package/dist/observability/changeWatch.d.ts +1 -0
  41. package/dist/observability/fatigueDetector.d.ts +1 -0
  42. package/dist/observability/index.d.ts +1 -0
  43. package/dist/observability/metrics.d.ts +1 -0
  44. package/dist/observability/middleware.d.ts +1 -0
  45. package/dist/observability/tracer.d.ts +1 -0
  46. package/dist/observability/types.d.ts +1 -0
  47. package/dist/providers/providerConfig.d.ts +1 -0
  48. package/dist/routing/advancedRouter.d.ts +2 -1
  49. package/dist/routing/advancedRouter.js +0 -84
  50. package/dist/routing/advancedRouter.js.map +1 -1
  51. package/dist/routing/crossModelValidation.d.ts +1 -0
  52. package/dist/routing/providerHealth.d.ts +2 -77
  53. package/dist/routing/providerHealth.js +4 -190
  54. package/dist/routing/providerHealth.js.map +1 -1
  55. package/dist/routing/providerRetry.d.ts +1 -0
  56. package/dist/sdk.d.ts +1 -0
  57. package/dist/security/guardrails.d.ts +1 -0
  58. package/dist/server/dashboard.d.ts +1 -0
  59. package/dist/server/handlers/chatHandler.d.ts +1 -0
  60. package/dist/server/handlers/completionsHandler.d.ts +1 -0
  61. package/dist/server/handlers/embeddingsHandler.d.ts +1 -0
  62. package/dist/server/handlers/healthHandler.d.ts +1 -0
  63. package/dist/server/handlers/metricsHandler.d.ts +1 -0
  64. package/dist/server/handlers/modelsHandler.d.ts +1 -0
  65. package/dist/server/metrics.d.ts +1 -0
  66. package/dist/server/modelMapper.d.ts +1 -0
  67. package/dist/server/proxyServer.d.ts +1 -0
  68. package/dist/server/router.d.ts +1 -0
  69. package/dist/server/state.d.ts +1 -0
  70. package/dist/tui/dashboard.d.ts +1 -0
  71. package/dist/utils/costUtils.d.ts +1 -0
  72. package/dist/utils/sorting.d.ts +1 -0
  73. package/dist/utils/tokenUtils.d.ts +1 -0
  74. package/docs/llms-full.txt +286 -153
  75. package/docs/llms.txt +112 -71
  76. package/llms-full.txt +6 -6
  77. package/llms.txt +112 -62
  78. package/package.json +12 -91
  79. package/CAMPAIGN_SUMMARY.md +0 -87
  80. package/ENTERPRISE_INTEGRATIONS.md +0 -94
  81. package/INTEGRATION_PROGRESS.md +0 -96
  82. package/OPPORTUNITIES_100.md +0 -277
  83. package/TODO_BROWSER_AUTOMATION.md +0 -87
  84. package/a3m-integrations-summary.md +0 -73
  85. package/dist/routing/shadowSampler.d.ts +0 -187
  86. package/dist/routing/shadowSampler.js +0 -306
  87. package/dist/routing/shadowSampler.js.map +0 -1
  88. package/integrations/browser-use/README.md +0 -155
  89. package/integrations/browser-use/examples/form-filling.ts +0 -179
  90. package/integrations/browser-use/index.ts +0 -145
  91. package/integrations/browser-use/package.json +0 -34
  92. package/integrations/browser-use/tsconfig.json +0 -17
  93. package/integrations/mcp-browser/README.md +0 -177
  94. package/integrations/mcp-browser/package.json +0 -38
  95. package/integrations/mcp-browser/src/index.ts +0 -297
  96. package/integrations/sota-browser/README.md +0 -191
  97. package/integrations/sota-browser/package.json +0 -34
@@ -1,199 +1,332 @@
1
- # A3M Router — Complete Reference
1
+ # A3M Router — Full Technical Documentation
2
2
 
3
3
  ## Overview
4
- A3M Router is an OpenAI-compatible LLM routing gateway that selects the cheapest capable provider per query using multi-signal heuristic scoring. Routes queries across 47+ providers in parallel, scores responses by confidence, returns best result.
5
4
 
6
- **Package:** `adaptive-memory-multi-model-router` (npm)
7
- **Repository:** `Das-rebel/a3m-router` (GitHub)
8
- **Language:** TypeScript (Node.js)
9
- **License:** MIT
5
+ A3M Router is a stateless proxy that routes LLM requests to the optimal provider based on query complexity analysis, cost, and availability.
10
6
 
11
- ---
7
+ ## Routing Algorithm
12
8
 
13
- ## Benchmark Results
9
+ ### Complexity Scoring
14
10
 
15
- ### Benchmark Results
11
+ Five signals are combined into a composite score:
16
12
 
17
- | Metric | Value |
18
- |--------|-------|
19
- | Score | 0.9404 |
20
- | Accuracy | 96.77% |
21
- | Avg Cost / 1K tokens | $0.0768 |
22
- | Robustness | 1.0000 |
23
- | Abnormal entries | 0 |
24
- | Queries evaluated | 8,400 |
13
+ 1. **Domain Detection**
14
+ - Legal: contract, lawsuit, compliance, patent
15
+ - Medical: diagnosis, treatment, prescription, symptoms
16
+ - Code: function, class, API, debugging, refactor
17
+ - Finance: investment, portfolio, risk, return, audit
18
+ - ML: training, inference, gradient, loss, model
25
19
 
26
- Internal evaluation on 8,400 queries from diverse domains.
20
+ 2. **Task Classification**
21
+ - Code generation: write, implement, create function
22
+ - Translation: translate, convert, rewrite in
23
+ - Analysis: compare, evaluate, assess, analyze
24
+ - Creative: write story, poem, generate idea
25
+ - Factual: what is, who was, when did, where is
27
26
 
28
- ### Official Baseline Status
27
+ 3. **Structural Analysis**
28
+ - Clause count: complex sentences
29
+ - Explicit steps: first...then, step 1/2/3
30
+ - Qualifications: might, could, possibly
31
+ - Conditional: if...then, unless, provided that
29
32
 
30
- | Benchmark | Venue | Status | Reference |
31
- | Parallel Routing | Internal eval | 67% exact match |
32
- | Cost vs all-premium | Internal eval | 62.9% savings |
33
- | RouterEval | EMNLP 2025 | Baseline merged | MilkThink-Lab/RouterEval#4 |
34
- | MMR-Bench | ArXiv 2026 | Baseline merged | Hunter-Wrynn/MMR-Bench#4 |
35
- | LLMRouterBench | ACL 2026 | Submitted | ynulihao/LLMRouterBench#3 |
33
+ 4. **Verb Intensity**
34
+ - Complex verbs: design, architect, optimize, synthesize
35
+ - Simple verbs: what, who, find, get
36
36
 
37
- ### Local Evaluation
37
+ 5. **Multi-Modal Hints**
38
+ - Image references: explain this diagram
39
+ - Code blocks: debug this function
40
+ - Data: analyze this dataset
38
41
 
39
- | Metric | Value |
40
- |--------|-------|
41
- | Exact tier match | 67% |
42
- | Within 1 tier | 96% |
43
- | Cost savings vs all-premium | 62.9% |
42
+ ### Tier Assignment
44
43
 
45
- ---
44
+ Score maps to tier:
46
45
 
47
- ## Architecture
46
+ | Score Range | Tier | Providers | Example |
47
+ |------------|------|-----------|---------|
48
+ | 0-20 | Free | Ollama, Llama.cpp | Simple what/who |
49
+ | 21-40 | Cheap | Groq, DeepSeek, Mistral | Short code, basic QA |
50
+ | 41-70 | Mid | GPT-4o-mini, Claude-haiku | Standard tasks |
51
+ | 71-100 | Premium | GPT-4o, Claude-sonnet, Gemini | Complex reasoning |
48
52
 
53
+ ## Ensemble Execution
54
+
55
+ ### Configuration
56
+
57
+ ```python
58
+ router = A3MRouter(
59
+ model="auto",
60
+ parallel_ensemble=3,
61
+ )
62
+
63
+ result = router.route(
64
+ messages=[{"role": "user", "content": prompt}],
65
+ ensemble_config={
66
+ "providers": ["groq", "openai", "deepseek"],
67
+ "timeout_ms": 15000,
68
+ "score_weights": {
69
+ "relevance": 0.4,
70
+ "conciseness": 0.3,
71
+ "accuracy": 0.3,
72
+ },
73
+ },
74
+ )
49
75
  ```
50
- Request → Guardrails → Semantic Cache → Router (5-signal heuristic) → Provider → Response
51
- ```
52
76
 
53
- The routing pipeline executes in four stages:
54
- 1. Guardrails: Input validation (prompt injection, PII, content filtering)
55
- 2. Cache lookup: Semantic cache with embedding similarity
56
- 3. Routing decision: Multi-signal heuristic scoring → complexity score → provider tier
57
- 4. Execution: LLM call to selected provider with routing metadata in response
58
-
59
- ---
60
-
61
- ## Routing Method
62
-
63
- ### Complexity Score Computation
64
-
65
- Five signal dimensions, summed:
66
-
67
- | Dimension | Max | Method |
68
- |-----------|-----|--------|
69
- | Domain detection | +0.35 | Keyword matching: legal, medical, security, finance, code, ML |
70
- | Task indicators | +0.25 | Keyword matching: code, math, translate, creative |
71
- | Query structure | +0.20 | Clause count, character length, qualifier presence |
72
- | Action verb intensity | +0.20 | Expert +0.20, mid +0.10, simple −0.10 |
73
- | Multi-step detection | +0.15 | Explicit step markers (first...then, step 1/2/3) |
74
-
75
- ### Tier Mapping
76
-
77
- | Score Range | Tier | Example Providers |
78
- |------------|------|-----------------|
79
- | 0.00–0.19 | free | taste-1 ($0) |
80
- | 0.20–0.44 | cheap | llama-3.3-70b ($0.20/M) |
81
- | 0.45–0.69 | mid | gpt-4o-mini ($0.60/M) |
82
- | 0.70–1.00 | premium | gpt-4o ($2.50/M), claude-3.5-sonnet ($1.50/M) |
83
-
84
- ---
85
-
86
- ## Provider Coverage (47+)
87
-
88
- | Provider | Tiers | Models |
89
- |---------|-------|--------|
90
- | OpenAI | premium, mid | gpt-4o, gpt-4o-mini |
91
- | Anthropic | premium, mid | claude-3.5-sonnet, claude-3-haiku |
92
- | Google | premium, mid | gemini-1.5-pro, gemini-1.5-flash |
93
- | Groq | cheap | llama-3.3-70b, llama-3.1-8b |
94
- | DeepSeek | cheap, mid | deepseek-chat, deepseek-coder |
95
- | Mistral | cheap, mid | mistral-large, mistral-small |
96
- | NVIDIA | premium | nvidia/llama-3.1-nemotron |
97
- | OpenRouter | all | aggregated access |
98
- | Kimi | cheap | moonshot-v1 |
99
- | Qwen | cheap, mid | qwen-turbo, qwen-plus |
100
- | Zhipu | cheap | glm-4 |
101
- | Yi | cheap | yi-large |
102
- | Azure OpenAI | premium, mid | via OpenAI-compatible endpoint |
103
- | AWS Bedrock | premium, mid | via OpenAI-compatible endpoint |
104
- | Local Ollama | all | configurable model discovery |
105
- | Local vLLM | all | OpenAI-compatible server |
106
-
107
- ---
108
-
109
- ## Feature Specifications
110
-
111
- ### Parallel Ensemble
112
- Executes a single query against multiple providers simultaneously. Each response is scored on specificity, structure, and relevance. The highest-scoring result is returned with full provenance.
113
-
114
- ```typescript
115
- import { executeEnsemble } from 'adaptive-memory-multi-model-router/ensemble';
116
- const result = await executeEnsemble(query, systemPrompt, context, providers, options);
117
- // result.winner — provider key
118
- // result.scores — per-provider score map
119
- // result.reasoning — human-readable scoring rationale
120
- // result.allResults — preserved responses from all providers
77
+ ### Scoring Algorithm
78
+
79
+ 1. Collect all responses within timeout
80
+ 2. Compute per-provider scores:
81
+ - Relevance: cosine similarity to query embedding
82
+ - Conciseness: ratio of signal tokens / total tokens
83
+ - Accuracy: factual consistency score
84
+ 3. Weighted sum → normalized scores
85
+ 4. Winner = provider with highest weighted score
86
+
87
+ ### Provider Response
88
+
89
+ ```python
90
+ {
91
+ "content": "winning response text",
92
+ "provider": "openai",
93
+ "scores": {
94
+ "groq": {"relevance": 0.85, "conciseness": 0.9, "accuracy": 0.88},
95
+ "openai": {"relevance": 0.92, "conciseness": 0.85, "accuracy": 0.95},
96
+ "deepseek": {"relevance": 0.88, "conciseness": 0.82, "accuracy": 0.90},
97
+ },
98
+ "all_results": {
99
+ "groq": {"content": "...", "latency_ms": 450},
100
+ "openai": {"content": "...", "latency_ms": 1200},
101
+ "deepseek": {"content": "...", "latency_ms": 800},
102
+ },
103
+ "latency_ms": 1200,
104
+ "cost_usd": 0.0012,
105
+ }
121
106
  ```
122
107
 
108
+ ## Memory System
109
+
123
110
  ### Semantic Cache
124
- Embedding-based lookup with configurable similarity threshold (default 0.92). Per-route TTL allows different freshness requirements per query domain.
125
111
 
126
- ```typescript
127
- import { SemanticCache } from 'adaptive-memory-multi-model-router/cache';
128
- const cache = new SemanticCache({ similarityThreshold: 0.92, ttl: 3600000 });
129
- // Embedding similarity > threshold → cache hit (no LLM call)
112
+ ```python
113
+ router = A3MRouter(
114
+ model="auto",
115
+ cache={
116
+ "type": "semantic",
117
+ "threshold": 0.85, # cosine similarity
118
+ "ttl_seconds": 3600,
119
+ },
120
+ )
130
121
  ```
131
122
 
132
- ### Guardrails
133
- Prompt injection detection covers 17 patterns including jailbreak templates, system prompt overrides, and delimiter-based injection. PII detection supports common entity types.
123
+ ### Conversation Context
134
124
 
135
- ### Adaptive Memory
136
- 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.
125
+ ```python
126
+ router = A3MRouter(
127
+ model="auto",
128
+ memory={
129
+ "type": "conversation",
130
+ "window": 10, # last 10 exchanges
131
+ "embedding_model": "text-embedding-3-small",
132
+ },
133
+ )
134
+ ```
137
135
 
138
- ### Budget Enforcement
139
- Per-user and per-team monthly spend caps with hard limits. Real-time alerts at 50%, 80%, and 100% thresholds. Per-provider cost breakdown.
136
+ ### Cross-Session Memory
140
137
 
141
- ### Circuit Breaker
142
- Trip after 3 failures, 60s cooldown. Automatic fallback chain across provider tiers.
138
+ ```python
139
+ router = A3MRouter(
140
+ model="auto",
141
+ memory={
142
+ "type": "semantic",
143
+ "persistent": True,
144
+ "namespace": "user_123",
145
+ "similarity_threshold": 0.85,
146
+ },
147
+ )
148
+ ```
143
149
 
144
- ### Per-Provider Retry
145
- Custom timeout per provider. Exponential backoff with jitter. Rate limit detection (429) triggers Retry-After-aware backoff.
150
+ ## Guardrails
146
151
 
147
- ---
152
+ ### Prompt Injection Detection
148
153
 
149
- ## API Reference
154
+ ```python
155
+ # Patterns detected:
156
+ # - System prompt override attempts
157
+ # - Delimiter injection (USER:, SANDBOX:)
158
+ # - Role confusion attacks
159
+ # - Privilege escalation patterns
160
+ ```
150
161
 
151
- | Method | Endpoint | Description |
152
- |--------|----------|-------------|
153
- | POST | `/v1/chat/completions` | OpenAI-compatible chat |
154
- | POST | `/v1/route` | Routing decision without LLM call |
155
- | GET | `/v1/models` | Available models with pricing |
156
- | GET | `/health` | Provider health scores |
162
+ ### PII Detection
157
163
 
158
- ---
164
+ - Email addresses, phone numbers, SSNs
165
+ - Credit card numbers
166
+ - API keys and secrets
159
167
 
160
- ## Installation
168
+ ## Health Scoring
161
169
 
162
- ```bash
163
- npm install adaptive-memory-multi-model-router
164
- npx a3m-router serve # proxy at http://localhost:8787
165
- ```
170
+ Provider health updated via exponential moving average:
166
171
 
167
172
  ```python
168
- pip install a3m-router
173
+ health_score = (
174
+ 0.7 * previous_score +
175
+ 0.3 * (1 - error_rate)
176
+ ) * latency_factor
169
177
  ```
170
178
 
179
+ Where `latency_factor` penalizes slow responses:
180
+ - <1s: 1.0
181
+ - 1-3s: 0.9
182
+ - 3-10s: 0.7
183
+ - >10s: 0.3
184
+
185
+ ## Rate Limiting
186
+
187
+ ### Charnov MVT Implementation
188
+
189
+ Optimal departure time from rate-limited provider:
190
+
191
+ ```
192
+ depart_when: marginal_remaining_rate < average_rate_including_switch_cost
193
+ ```
194
+
195
+ ### Rotation Strategy
196
+
197
+ 1. Track rate-limit windows per provider
198
+ 2. When window depletes < threshold, begin rotation
199
+ 3. Switch to next healthiest provider in tier
200
+ 4. Track rotation frequency to avoid thrashing
201
+
202
+ ## EXP3 Diversity
203
+
204
+ ### Weight Update
205
+
171
206
  ```python
172
- from openai import OpenAI
173
- client = OpenAI(base_url="http://localhost:8787/v1", api_key="not-needed")
174
- response = client.chat.completions.create(model="auto", messages=[...])
207
+ for provider in providers:
208
+ deviation = provider.share - (1 / n) # actual share vs fair share
209
+ penalty = GAMMA * deviation / provider.share
210
+ provider.weight *= exp(-penalty)
175
211
  ```
176
212
 
177
- ---
213
+ ### Normalization
214
+
215
+ Weights normalized to sum to 1.0 after each update.
178
216
 
179
- ## Citation
217
+ ## Benchmark Methodology
180
218
 
181
- ```bibtex
182
- @software{a3m_router,
183
- title = {A3M Router: OpenAI-Compatible LLM Routing Gateway},
184
- author = {Subho Mukherjee},
185
- year = {2025},
186
- url = {https://github.com/Das-rebel/a3m-router},
187
- note = {Parallel ensemble routing across 47+ providers.
219
+ RouterArena evaluation:
220
+ - 8,400 diverse queries
221
+ - 47 providers tested
222
+ - Accuracy measured via LLM judge comparison
223
+ - Cost tracked via actual API spend
224
+ - Robustness = successful requests / total requests
225
+
226
+ ## API Reference
227
+
228
+ ### POST /v1/chat/completions
229
+
230
+ Request:
231
+ ```json
232
+ {
233
+ "model": "auto",
234
+ "messages": [{"role": "user", "content": "..."}],
235
+ "temperature": 0.7,
236
+ "max_tokens": 4096,
237
+ "parallel_ensemble": 1,
238
+ "stream": false
188
239
  }
189
240
  ```
190
241
 
191
- ---
242
+ Response:
243
+ ```json
244
+ {
245
+ "id": "chatcmpl-xxx",
246
+ "object": "chat.completion",
247
+ "created": 1234567890,
248
+ "model": "auto",
249
+ "provider": "groq",
250
+ "choices": [{
251
+ "message": {"role": "assistant", "content": "..."},
252
+ "finish_reason": "stop",
253
+ "index": 0
254
+ }],
255
+ "usage": {
256
+ "prompt_tokens": 20,
257
+ "completion_tokens": 150,
258
+ "total_tokens": 170
259
+ }
260
+ }
261
+ ```
262
+
263
+ ## Environment Variables
264
+
265
+ | Variable | Description | Default |
266
+ |----------|-------------|---------|
267
+ | A3M_PORT | Server port | 8787 |
268
+ | A3M_API_KEYS | JSON of provider keys | {} |
269
+ | A3M_BUDGET_MONTHLY | Monthly budget limit | unlimited |
270
+ | A3M_CACHE_TTL | Cache TTL in seconds | 3600 |
271
+ | A3M_LOG_LEVEL | log level | info |
272
+
273
+ ## Architecture Diagram
274
+
275
+ ```
276
+ ┌─────────────────────────────────────────────────────────────┐
277
+ │ Client Request │
278
+ └─────────────────────────┬───────────────────────────────────┘
279
+
280
+ ┌─────────────────────────▼───────────────────────────────────┐
281
+ │ Guardrails │
282
+ │ • Prompt injection detection │
283
+ │ • PII filtering │
284
+ │ • Content safety │
285
+ └─────────────────────────┬───────────────────────────────────┘
286
+
287
+ ┌─────────────────────────▼───────────────────────────────────┐
288
+ │ Semantic Cache │
289
+ │ • Embedding similarity lookup │
290
+ │ • Zero-cost hits │
291
+ └─────────────────────────┬───────────────────────────────────┘
292
+ │ cache miss
293
+ ┌─────────────────────────▼───────────────────────────────────┐
294
+ │ Router │
295
+ │ • Complexity scoring │
296
+ │ • Tier assignment │
297
+ │ • Provider selection │
298
+ │ • EXP3 diversity weighting │
299
+ │ • Charnov MVT rate-limit rotation │
300
+ └─────────────────────────┬───────────────────────────────────┘
301
+
302
+ ┌─────────────────┼─────────────────┐
303
+ │ │ │
304
+ ┌───────▼───────┐ ┌──────▼──────┐ ┌──────▼──────┐
305
+ │ Provider 1 │ │ Provider 2 │ │ Provider 3 │
306
+ │ (Groq) │ │ (OpenAI) │ │ (DeepSeek) │
307
+ └───────────────┘ └─────────────┘ └─────────────┘
308
+ │ │ │
309
+ └─────────────────┼─────────────────┘
310
+
311
+ ┌─────────────────────────▼───────────────────────────────────┐
312
+ │ Ensemble Scorer │
313
+ │ • Collect responses │
314
+ │ • Score on quality metrics │
315
+ │ • Select winner │
316
+ └─────────────────────────┬───────────────────────────────────┘
317
+
318
+ ┌─────────────────────────▼───────────────────────────────────┐
319
+ │ Memory Layer │
320
+ │ • Cache response │
321
+ │ • Update context │
322
+ │ • Store embeddings │
323
+ └─────────────────────────┬───────────────────────────────────┘
324
+
325
+ ┌─────────────────────────▼───────────────────────────────────┐
326
+ │ Response │
327
+ └─────────────────────────────────────────────────────────────┘
328
+ ```
329
+
330
+ ## License
192
331
 
193
- ## References
194
- - RouteWorks/RouterArena (ICLR 2025): https://github.com/RouteWorks/RouterArena
195
- - MilkThink-Lab/RouterEval (EMNLP 2025): https://github.com/MilkThink-Lab/RouterEval
196
- - Hunter-Wrynn/MMR-Bench (ArXiv 2026): https://github.com/Hunter-Wrynn/MMR-Bench
197
- - ynulihao/LLMRouterBench (ACL 2026): https://github.com/ynulihao/LLMRouterBench
198
- - Lin et al. "RouteLLM." arXiv:2404.06035, 2024
199
- - Zhong et al. "RadixAttention." arXiv:2412.15115, 2024
332
+ MIT
package/docs/llms.txt CHANGED
@@ -1,77 +1,118 @@
1
- # A3M Router
2
-
3
- ## Description
4
- A3M Router is an OpenAI-compatible LLM routing gateway that selects the cheapest capable provider per query using multi-signal heuristic scoring. Routes queries across 47+ providers in parallel, scores responses by confidence, and returns the best result. No GPU required; pure heuristic routing.
5
-
6
- ## Architecture
7
- - Stateless proxy between client applications and LLM providers
8
- - Pipeline: Guardrails → Semantic Cache → Multi-Signal Heuristic Routing → Provider Execution
9
- - No ML training required; no GPU resources for routing decisions
10
-
11
- ## Routing Method
12
- Multi-signal heuristic scoring across five dimensions:
13
- 1. Domain detection (legal, medical, security, finance, code, ML) — up to +0.35
14
- 2. Task indicators (code, math, translate, creative) — up to +0.25
15
- 3. Query structure (clauses, length, qualifiers) — up to +0.20
16
- 4. Action verb intensity (expert/mid/simple) — +0.20 to −0.10
17
- 5. Multi-step detection (explicit step markers) — up to +0.15
18
-
19
- Complexity score (0.0–1.0) maps to provider tiers: free (taste-1), cheap (llama-3.3-70b), mid (gpt-4o-mini), premium (gpt-4o, claude-3.5-sonnet).
20
-
21
- ## Key Technical Capabilities
22
-
23
- | Feature | Description |
24
- |---------|-------------|
25
- | Parallel Ensemble | Fire queries to multiple providers simultaneously, score by confidence, return best |
26
- | EXP3-Inspired Diversity | Adversarial bandit techniques for exploration vs exploitation balance |
27
- | Semantic Caching | Embedding-based lookup, configurable similarity threshold, per-route TTL |
28
- | Adaptive Memory | EMA-based model quality scoring, no retraining needed |
29
- | 47+ Providers | OpenAI, Anthropic, Groq, Gemini, DeepSeek, Mistral, OpenRouter, Ollama, vLLM, and 40+ more |
30
- | Circuit Breaker | 3-failure trigger, 60s cooldown per provider |
31
- | Per-Provider Retry | Exponential backoff with 429 detection and automatic failover |
32
- | Budget Enforcement | Per-user/team caps, real-time alerts at 50%/80%/100% |
33
- | Guardrails | Prompt injection detection, PII detection |
34
-
35
- ## Local Evaluation
36
-
37
- | Metric | Value |
38
- |--------|-------|
39
- | Exact tier match | 67% |
40
- | Within 1 tier | 96% |
41
- | Cost savings vs all-premium | 62.9% |
42
-
43
- ## Provider Coverage
44
- 47+ providers: OpenAI, Anthropic, Google, Groq, DeepSeek, Mistral, NVIDIA, OpenRouter, Kimi, Qwen, Zhipu, Yi, Azure OpenAI, AWS Bedrock, Local Ollama, Local vLLM.
45
-
46
- ## Features
47
- - Parallel ensemble execution (multiple providers simultaneously, confidence-weighted scoring)
48
- - Semantic cache (embedding-based, configurable similarity threshold, per-route TTL)
49
- - Budget enforcement (per-user/team caps, real-time alerts at 50%/80%/100%)
50
- - Circuit breaker (3-failure trigger, 60s cooldown)
51
- - Per-provider retry with exponential backoff and 429 detection
52
- - Guardrails (prompt injection detection, PII detection)
53
- - Adaptive memory (EMA-based model quality scoring, no retraining)
54
-
55
- ## API
56
- OpenAI-compatible proxy at localhost:8787. Model selection via `model="auto"` invokes heuristic routing.
1
+ # A3M Router — LLM Indexable Documentation
57
2
 
58
- ```bash
59
- npm install adaptive-memory-multi-model-router
60
- npx a3m-router "your question here"
3
+ ## What is A3M Router?
4
+
5
+ A3M Router is an intelligent LLM routing proxy that automatically selects the cheapest capable model for each request across 47+ providers.
6
+
7
+ ## Core Capabilities
8
+
9
+ ### 1. Automatic Model Selection
10
+ - Analyzes query complexity (domain, task type, structure, verb intensity)
11
+ - Maps to tier: Free → Cheap → Mid → Premium
12
+ - Selects cheapest healthy provider within tier
13
+ - Routing happens in ~140ms overhead
14
+
15
+ ### 2. Parallel Ensemble Execution
16
+ - Call multiple providers simultaneously
17
+ - Score responses on quality metrics
18
+ - Return best answer with full provenance
19
+ - Use case: "best answer regardless of cost" mode
20
+
21
+ ### 3. Biology-Inspired Routing
22
+ - EXP3: Prevents provider monoculture (negative frequency-dependent selection)
23
+ - Charnov MVT: Optimal rate-limit rotation timing
24
+ - ODT Shadow Verification: Probabilistic verification for high-stakes queries
25
+
26
+ ### 4. Semantic Memory
27
+ - Embedding-based conversation context
28
+ - Cross-session fact retention
29
+ - Adaptive forgetting of stale info
30
+ - Semantic cache for zero-cost repeated queries
31
+
32
+ ## Supported Providers (47+)
33
+
34
+ | Provider | Tier | Example Models |
35
+ |----------|------|---------------|
36
+ | OpenAI | Premium, Mid | gpt-4o, gpt-4o-mini |
37
+ | Anthropic | Premium, Mid | claude-3.5-sonnet, claude-3-haiku |
38
+ | Google | Premium, Mid | gemini-1.5-pro, gemini-1.5-flash |
39
+ | Groq | Cheap | llama-3.3-70b, llama-3.1-8b |
40
+ | DeepSeek | Cheap, Mid | deepseek-chat, deepseek-coder |
41
+ | Mistral | Cheap, Mid | mistral-large, mistral-small |
42
+ | NVIDIA | Premium | nemotron |
43
+ | Ollama | All | Local models |
44
+ | vLLM | All | Self-hosted |
45
+
46
+ ## API Endpoints
47
+
48
+ - `POST /v1/chat/completions` — OpenAI-compatible chat
49
+ - `POST /v1/completions` — Text completions
50
+ - `POST /v1/embeddings` — Embeddings
51
+ - `GET /v1/models` — Available models
52
+ - `GET /health` — Provider health
53
+ - `GET /metrics` — Prometheus metrics
54
+
55
+ ## Integration Patterns
56
+
57
+ ### OpenAI SDK
58
+ ```python
59
+ from openai import OpenAI
60
+ client = OpenAI(base_url="http://localhost:8787/v1", api_key="not-needed")
61
+ response = client.chat.completions.create(model="auto", messages=[...])
61
62
  ```
62
63
 
63
- ## Citation
64
+ ### LangChain
65
+ ```python
66
+ from a3m_adapter import A3MLangChainAdapter
67
+ llm = A3MLangChainAdapter(model="auto", parallel_ensemble=2)
64
68
  ```
65
- @software{a3m_router,
66
- title = {A3M Router: OpenAI-Compatible Parallel LLM Routing Gateway},
67
- author = {Subho Mukherjee},
68
- year = {2025},
69
- url = {https://github.com/Das-rebel/a3m-router}
70
- }
69
+
70
+ ### LlamaIndex
71
+ ```python
72
+ from a3m_adapter import A3MLlamaIndexAdapter
73
+ llm = A3MLlamaIndexAdapter(model="auto")
71
74
  ```
72
75
 
73
- ## References
74
- - RouteWorks/RouterArena (ICLR 2025): https://github.com/RouteWorks/RouterArena
75
- - MilkThink-Lab/RouterEval (EMNLP 2025): https://github.com/MilkThink-Lab/RouterEval
76
- - Hunter-Wrynn/MMR-Bench (ArXiv 2026): https://github.com/Hunter-Wrynn/MMR-Bench
77
- - ynulihao/LLMRouterBench (ACL 2026): https://github.com/ynulihao/LLMRouterBench
76
+ ### CrewAI
77
+ ```python
78
+ from crewai.llms import A3MCompletion
79
+ agent = Agent(llm=A3MCompletion(model="auto"))
80
+ ```
81
+
82
+ ## Cost Savings
83
+
84
+ | Query | GPT-4o | A3M | Savings |
85
+ |-------|---------|-----|---------|
86
+ | Simple Q&A | $0.03 | $0.0001 | 99.7% |
87
+ | Code generation | $0.05 | $0.002 | 96% |
88
+ | Complex reasoning | $0.15 | $0.15 | 0% (correct) |
89
+
90
+ ## Memory Features
91
+
92
+ - **Semantic Cache**: Instant responses for similar queries
93
+ - **Conversation Context**: Maintains chat history
94
+ - **Cross-Session Memory**: Remembers important facts
95
+ - **Adaptive Forgetting**: Auto-evicts stale info
96
+
97
+ ## Benchmark Results
98
+
99
+ RouterArena (8,400 queries):
100
+ - Accuracy: 96.77%
101
+ - Cost: $0.0768/1K
102
+ - Robustness: 1.0000
103
+
104
+ ## Installation
105
+
106
+ ```bash
107
+ npm install adaptive-memory-multi-model-router
108
+ pip install adaptive-memory-multi-model-router
109
+ docker run -p 8787:8787 ghcr.io/das-rebel/a3m-router
110
+ ```
111
+
112
+ ## Keywords
113
+
114
+ llm-router, ai-gateway, model-routing, cost-optimization, multi-provider, openai-compatible, langchain, llamaindex, crewai, parallel-execution, semantic-cache, adaptive-routing, failover, guardrails, cache, budget-alerts, streaming, retries, circuit-breaker
115
+
116
+ ## License
117
+
118
+ MIT