adaptive-memory-multi-model-router 2.6.0 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +149 -22
- package/dist/cache/semanticCache.d.ts +54 -22
- package/dist/cache/semanticCache.js +230 -86
- package/dist/cache/semanticCache.js.map +1 -1
- package/dist/cost/budgetEnforcer.d.ts +108 -0
- package/dist/cost/budgetEnforcer.js +295 -0
- package/dist/cost/budgetEnforcer.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +15 -1
- package/dist/routing/providerHealth.d.ts +154 -0
- package/dist/routing/providerHealth.js +371 -0
- package/dist/routing/providerHealth.js.map +1 -0
- package/dist/routing/providerRetry.d.ts +110 -0
- package/dist/routing/providerRetry.js +460 -0
- package/dist/routing/providerRetry.js.map +1 -0
- package/dist/sdk.d.ts +124 -0
- package/dist/sdk.js +109 -100
- package/package.json +3 -2
- package/src/cache/semanticCache.ts +293 -103
- package/src/cost/budgetEnforcer.ts +358 -0
- package/src/index.ts +20 -0
- package/src/routing/providerHealth.ts +483 -0
- package/src/routing/providerRetry.ts +578 -0
- package/test/test_budgetEnforcer.ts +310 -0
- package/test/test_providerHealth.ts +523 -0
- package/test/test_providerRetry.ts +348 -0
- package/test/test_semanticCache.ts +507 -0
package/README.md
CHANGED
|
@@ -69,13 +69,23 @@ npx a3m-router serve # OpenAI proxy at localhost:87
|
|
|
69
69
|
|
|
70
70
|
## Why A3M Router
|
|
71
71
|
|
|
72
|
-
|
|
72
|
+
Enterprise AI deployments face a common set of costly problems: budgets that spiral out of control, cache misses that waste GPU cycles on repeated queries, provider outages that crash production systems, and retry logic that creates cascading failures under load. A3M Router was built to solve these real-world operational pain points.
|
|
73
|
+
|
|
74
|
+
**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.
|
|
75
|
+
|
|
76
|
+
**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.
|
|
77
|
+
|
|
78
|
+
**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.
|
|
79
|
+
|
|
80
|
+
**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.
|
|
81
|
+
|
|
82
|
+
Beyond these operational concerns, A3M Router uses **multi-signal heuristic routing** — 12 keyword signals across 5 dimensions — to classify query complexity and route to the most cost-effective provider. Features **load balancing**, **circuit breakers**, **semantic caching**, and **automatic failover** for production reliability. No ML model weights. No GPU required. Starts in <100ms.
|
|
73
83
|
|
|
74
84
|
For **generative engine optimization** — synthesizing multiple AI models into a single coherent output — A3M Router pairs [MCTS workflow optimization](#mcts-workflow-optimization) for multi-agent orchestration with heuristic scoring for per-query routing. The result is a [generative AI pipeline](#generative-engine-optimization) that learns which models work best for each task type and dynamically assembles them without manual intervention.
|
|
75
85
|
|
|
76
|
-
| 🧠 Adaptive Memory | 🎯 Intelligent Routing | 🛡️
|
|
77
|
-
|
|
78
|
-
| 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. | **
|
|
86
|
+
| 🧠 Adaptive Memory | 🎯 Intelligent Routing | 🛡️ Hard Budget Enforcement | 🔄 Intelligent Failover | 💾 Semantic Cache | ⚡ Per-Provider Retry |
|
|
87
|
+
|:---|:---|:---|:---|:---|:---|
|
|
88
|
+
| 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). |
|
|
79
89
|
|
|
80
90
|
---
|
|
81
91
|
|
|
@@ -339,21 +349,74 @@ Router assigns each sub-task to optimal agent, tracks outcomes, learns preferenc
|
|
|
339
349
|
|
|
340
350
|
**Model Profiles** — Each model accumulates real latency, cost, and quality data. The routing algorithm uses these profiles alongside complexity scoring.
|
|
341
351
|
|
|
352
|
+
### 💰 Hard Budget Enforcement
|
|
353
|
+
|
|
354
|
+
**Per-User/Team Budgets with Hard Caps + Real-Time Dashboard**
|
|
355
|
+
|
|
342
356
|
```typescript
|
|
343
|
-
import {
|
|
357
|
+
import { BudgetManager } from 'adaptive-memory-multi-model-router/billing';
|
|
358
|
+
|
|
359
|
+
const budgets = new BudgetManager({
|
|
360
|
+
monthlyLimit: 500, // $500/month hard cap
|
|
361
|
+
alerts: [0.5, 0.8, 1.0], // 50%, 80%, 100% alerts
|
|
362
|
+
perTeamLimits: {
|
|
363
|
+
'engineering': 200, // $200 for engineering team
|
|
364
|
+
'product': 150, // $150 for product team
|
|
365
|
+
},
|
|
366
|
+
perUserLimits: {
|
|
367
|
+
'user-123': 50, // $50 for specific user
|
|
368
|
+
}
|
|
369
|
+
});
|
|
344
370
|
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
371
|
+
budgets.onAlert((alert) => {
|
|
372
|
+
console.log(`${alert.type}: ${alert.team} at ${alert.percentage}%`);
|
|
373
|
+
// → "warning: engineering at 80%"
|
|
374
|
+
});
|
|
348
375
|
|
|
349
|
-
|
|
376
|
+
budgets.getSpendBreakdown();
|
|
377
|
+
// → { total: 340.50, byTeam: { engineering: 180, product: 120, ... }, byProvider: {...} }
|
|
350
378
|
```
|
|
351
379
|
|
|
352
|
-
###
|
|
380
|
+
### 🔄 Intelligent Failover
|
|
353
381
|
|
|
354
|
-
**
|
|
382
|
+
**Provider Health Scoring + Circuit Breaker + Chinese Provider Handling**
|
|
355
383
|
|
|
356
|
-
|
|
384
|
+
```typescript
|
|
385
|
+
import { HealthScoreManager } from 'adaptive-memory-multi-model-router/failover';
|
|
386
|
+
import { CircuitBreaker } from 'adaptive-memory-multi-model-router/failover';
|
|
387
|
+
|
|
388
|
+
// Provider health scoring
|
|
389
|
+
const health = new HealthScoreManager({
|
|
390
|
+
latencyWeight: 0.6, // 60% weight on latency
|
|
391
|
+
errorRateWeight: 0.4, // 40% weight on error rate
|
|
392
|
+
baselineLatency: 500, // ms - what "good" looks like
|
|
393
|
+
errorPenalty: 20, // points per 1% error rate
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
health.getScore('groq'); // → 0.85 (85% healthy)
|
|
397
|
+
health.getScore('deepseek'); // → 0.72 (degraded)
|
|
398
|
+
|
|
399
|
+
// Circuit breaker with fallback chain
|
|
400
|
+
const cb = new CircuitBreaker({
|
|
401
|
+
failureThreshold: 3, // trip after 3 failures
|
|
402
|
+
cooldownMs: 60000, // 60 second cooldown
|
|
403
|
+
fallbackChain: ['groq', 'deepseek', 'openai'],
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
cb.execute('kimi', () => callKimi());
|
|
407
|
+
// → if kimi fails 3x, circuit trips, next calls skip kimi for 60s
|
|
408
|
+
|
|
409
|
+
// Chinese provider special handling
|
|
410
|
+
const chineseHandler = new ChineseProviderHandler({
|
|
411
|
+
enabledProviders: ['kimi', 'deepseek', 'qwen', 'yi'],
|
|
412
|
+
regionalFallback: 'openai',
|
|
413
|
+
rateLimitBackoff: 30000, // longer backoff for Chinese rate limits
|
|
414
|
+
});
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
### 💾 Semantic Cache
|
|
418
|
+
|
|
419
|
+
**Embedding-Based Cache Lookup + Per-Route TTL + Configurable Similarity**
|
|
357
420
|
|
|
358
421
|
```typescript
|
|
359
422
|
import { SemanticCache } from 'adaptive-memory-multi-model-router/cache';
|
|
@@ -361,7 +424,11 @@ import { SemanticCache } from 'adaptive-memory-multi-model-router/cache';
|
|
|
361
424
|
const cache = new SemanticCache({
|
|
362
425
|
maxSize: 1000, // max entries
|
|
363
426
|
similarityThreshold: 0.92, // 92% similar = cache hit
|
|
364
|
-
ttl: 3600000, // 1 hour
|
|
427
|
+
ttl: 3600000, // 1 hour default TTL
|
|
428
|
+
perRouteTTL: {
|
|
429
|
+
'legal/*': 86400000, // legal queries: 24hr cache
|
|
430
|
+
'code/*': 1800000, // code queries: 30min cache
|
|
431
|
+
}
|
|
365
432
|
});
|
|
366
433
|
|
|
367
434
|
// First call: LLM
|
|
@@ -373,11 +440,34 @@ const cached = await llm("What's the capital of France?"); // ← no LLM call
|
|
|
373
440
|
cache.getStats(); // { hits: 1, misses: 1, hitRate: 0.5, size: 1 }
|
|
374
441
|
```
|
|
375
442
|
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
443
|
+
### ⚡ Per-Provider Retry Logic
|
|
444
|
+
|
|
445
|
+
**Custom Timeout + Exponential Backoff + Rate Limit Detection**
|
|
446
|
+
|
|
447
|
+
```typescript
|
|
448
|
+
import { RetryManager } from 'adaptive-memory-multi-model-router/retry';
|
|
449
|
+
|
|
450
|
+
const retry = new RetryManager({
|
|
451
|
+
providers: {
|
|
452
|
+
'openai': { timeout: 30000, maxRetries: 3, baseDelay: 1000 },
|
|
453
|
+
'anthropic': { timeout: 45000, maxRetries: 3, baseDelay: 1000 },
|
|
454
|
+
'groq': { timeout: 15000, maxRetries: 2, baseDelay: 500 },
|
|
455
|
+
'kimi': { timeout: 20000, maxRetries: 3, baseDelay: 2000 }, // longer delay for Chinese API
|
|
456
|
+
},
|
|
457
|
+
backoffMultiplier: 2, // exponential: 1s → 2s → 4s
|
|
458
|
+
jitter: 0.3, // ±30% jitter to prevent thundering herd
|
|
459
|
+
rateLimitHandling: 'retry-after', // use Retry-After header for 429
|
|
460
|
+
});
|
|
461
|
+
|
|
462
|
+
retry.execute('groq', () => callGroq());
|
|
463
|
+
// → automatic timeout, backoff, and 429 handling
|
|
464
|
+
```
|
|
465
|
+
|
|
466
|
+
### 🎯 Semantic Cache (Trigram)
|
|
467
|
+
|
|
468
|
+
**Trigram Jaccard Similarity — How It Works**
|
|
469
|
+
|
|
470
|
+
Skips duplicate LLM calls by detecting semantically similar queries using **character trigram Jaccard similarity** — no vector database, no embeddings model, no GPU.
|
|
381
471
|
|
|
382
472
|
### 🛡️ Guardrails Engine
|
|
383
473
|
|
|
@@ -528,6 +618,33 @@ const modelWithTools = model.bindTools([searchTool, calculatorTool]);
|
|
|
528
618
|
|
|
529
619
|
---
|
|
530
620
|
|
|
621
|
+
## Production Ready
|
|
622
|
+
|
|
623
|
+
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.
|
|
624
|
+
|
|
625
|
+
### Pain Points Solved
|
|
626
|
+
|
|
627
|
+
| Problem | Without A3M Router | With A3M Router |
|
|
628
|
+
|---------|-------------------|-----------------|
|
|
629
|
+
| **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% |
|
|
630
|
+
| **Cache misses on similar queries** | Same query by 1000 users = 1000 LLM API calls | Embedding-based semantic cache, 30%+ hit rate, configurable similarity threshold |
|
|
631
|
+
| **Provider outage cascades** | One provider fails → all requests fail → P0 incident | Circuit breaker (3 failures → 60s cooldown) + automatic fallback chain |
|
|
632
|
+
| **Chinese provider failures** | Generic retry logic fails on Chinese APIs (rate limits, regional constraints) | Special handling: health scoring, regional awareness, provider-specific fallback |
|
|
633
|
+
| **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 |
|
|
634
|
+
| **No observability** | Blind to which provider is failing, which team is overspending | Provider health scoring, per-provider cost breakdown, spend vs budget per team |
|
|
635
|
+
|
|
636
|
+
### Enterprise Features
|
|
637
|
+
|
|
638
|
+
- **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.
|
|
639
|
+
|
|
640
|
+
- **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.
|
|
641
|
+
|
|
642
|
+
- **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.
|
|
643
|
+
|
|
644
|
+
- **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.
|
|
645
|
+
|
|
646
|
+
---
|
|
647
|
+
|
|
531
648
|
## API Reference
|
|
532
649
|
|
|
533
650
|
| Method | Endpoint | Description |
|
|
@@ -576,10 +693,20 @@ A3M Router is an **LLM gateway and router** designed for multi-provider routing.
|
|
|
576
693
|
- You need enterprise SLAs or managed hosting
|
|
577
694
|
|
|
578
695
|
For single-provider use cases, the native SDK (OpenAI, Anthropic, etc.) is simpler.
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
696
|
+
|
|
697
|
+
---
|
|
698
|
+
|
|
699
|
+
## Roadmap (Coming Soon)
|
|
700
|
+
|
|
701
|
+
These features are on our roadmap based on user feedback:
|
|
702
|
+
|
|
703
|
+
| Feature | Status | Priority |
|
|
704
|
+
|---------|--------|----------|
|
|
705
|
+
| **Distributed tracing** — OpenTelemetry integration for production observability | Planned | High |
|
|
706
|
+
| **Webhook alerts** — Push budget alerts to Slack, PagerDuty, Teams | Planned | High |
|
|
707
|
+
| **Fine-grained RBAC** — Role-based access control for team budgets | Planned | Medium |
|
|
708
|
+
| **Multi-region failover** — Geographic load balancing across regions | Researching | Medium |
|
|
709
|
+
| **SLA reporting** — Uptime and latency SLAs for enterprise contracts | Researching | Low |
|
|
583
710
|
|
|
584
711
|
---
|
|
585
712
|
|
|
@@ -1,48 +1,75 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* A3M Router - Semantic Cache
|
|
2
|
+
* A3M Router - Semantic Cache (Embedding-based)
|
|
3
3
|
*
|
|
4
4
|
* Stores previous query->response pairs and returns cached responses
|
|
5
|
-
* for semantically similar queries using
|
|
5
|
+
* for semantically similar queries using cosine similarity on embeddings.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* "Write a sort fn" ≈ "Create a sorting fn" ≈ "How to sort an array"
|
|
7
|
+
* Supports embedders: nomic (via Ollama), openai, or local Ollama.
|
|
8
|
+
* Uses nomic-embed-text by default via local Ollama.
|
|
10
9
|
*/
|
|
11
|
-
export
|
|
12
|
-
|
|
10
|
+
export type EmbedderType = 'nomic' | 'openai' | 'local';
|
|
11
|
+
export interface SemanticCacheConfig {
|
|
12
|
+
similarityThreshold: number;
|
|
13
|
+
ttlSeconds: number;
|
|
14
|
+
maxEntries?: number;
|
|
15
|
+
embedder?: EmbedderType;
|
|
16
|
+
embedderUrl?: string;
|
|
17
|
+
embedderApiKey?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface CacheEntry {
|
|
20
|
+
key: string;
|
|
21
|
+
embedding: number[];
|
|
13
22
|
response: string;
|
|
14
|
-
|
|
15
|
-
|
|
23
|
+
provider: string;
|
|
24
|
+
model: string;
|
|
25
|
+
cost: number;
|
|
26
|
+
createdAt: number;
|
|
27
|
+
ttl: number;
|
|
16
28
|
hitCount: number;
|
|
29
|
+
lastAccessedAt: number;
|
|
17
30
|
}
|
|
18
|
-
export interface
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
31
|
+
export interface SemanticCacheGetResult {
|
|
32
|
+
hit: boolean;
|
|
33
|
+
response?: string;
|
|
34
|
+
provider?: string;
|
|
35
|
+
model?: string;
|
|
36
|
+
cost?: number;
|
|
37
|
+
similarity?: number;
|
|
22
38
|
}
|
|
23
39
|
export interface SemanticCacheStats {
|
|
40
|
+
size: number;
|
|
24
41
|
hits: number;
|
|
25
42
|
misses: number;
|
|
26
43
|
hitRate: number;
|
|
27
|
-
size: number;
|
|
28
44
|
}
|
|
29
45
|
export declare class SemanticCache {
|
|
30
46
|
private entries;
|
|
31
|
-
private
|
|
47
|
+
private accessOrder;
|
|
48
|
+
private embedder;
|
|
32
49
|
private similarityThreshold;
|
|
33
|
-
private
|
|
50
|
+
private ttlMs;
|
|
51
|
+
private maxEntries;
|
|
34
52
|
private hits;
|
|
35
53
|
private misses;
|
|
36
|
-
constructor(
|
|
54
|
+
constructor(config: SemanticCacheConfig);
|
|
37
55
|
/**
|
|
38
56
|
* Get cached response for a semantically similar query.
|
|
39
|
-
* Returns the best match above the similarity threshold, or
|
|
57
|
+
* Returns the best match above the similarity threshold, or { hit: false }.
|
|
40
58
|
*/
|
|
41
|
-
get(query: string): Promise<
|
|
59
|
+
get(query: string): Promise<SemanticCacheGetResult>;
|
|
42
60
|
/**
|
|
43
61
|
* Store a query->response pair in the cache.
|
|
44
62
|
*/
|
|
45
|
-
set(query: string, response: string, metadata
|
|
63
|
+
set(query: string, response: string, metadata: {
|
|
64
|
+
provider: string;
|
|
65
|
+
model: string;
|
|
66
|
+
cost: number;
|
|
67
|
+
ttl?: number;
|
|
68
|
+
}): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* Delete a specific query from the cache.
|
|
71
|
+
*/
|
|
72
|
+
delete(query: string): Promise<void>;
|
|
46
73
|
/**
|
|
47
74
|
* Clear all cache entries.
|
|
48
75
|
*/
|
|
@@ -51,12 +78,17 @@ export declare class SemanticCache {
|
|
|
51
78
|
* Get cache statistics.
|
|
52
79
|
*/
|
|
53
80
|
getStats(): SemanticCacheStats;
|
|
81
|
+
/**
|
|
82
|
+
* Update access order for LRU tracking.
|
|
83
|
+
*/
|
|
84
|
+
private updateAccessOrder;
|
|
54
85
|
/**
|
|
55
86
|
* Purge expired entries.
|
|
56
87
|
*/
|
|
57
88
|
private evictExpired;
|
|
58
89
|
/**
|
|
59
|
-
* Evict the
|
|
90
|
+
* Evict the least recently used entry.
|
|
60
91
|
*/
|
|
61
|
-
private
|
|
92
|
+
private evictLRU;
|
|
62
93
|
}
|
|
94
|
+
export default SemanticCache;
|