adaptive-memory-multi-model-router 2.2.5 → 2.2.6

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 (63) hide show
  1. package/README.md +17 -22
  2. package/README.md.bak +836 -0
  3. package/dist/analytics/costAnalytics.d.ts +1 -0
  4. package/dist/cache/cacheKeyGenerator.d.ts +67 -0
  5. package/dist/cache/cacheKeyGenerator.d.ts.map +1 -0
  6. package/dist/cache/cacheKeyGenerator.js +211 -0
  7. package/dist/cache/cacheKeyGenerator.js.map +1 -0
  8. package/dist/cache/semanticCache.d.ts +41 -0
  9. package/dist/cache/semanticCache.d.ts.map +1 -1
  10. package/dist/cache/semanticCache.js +142 -0
  11. package/dist/cache/semanticCache.js.map +1 -1
  12. package/dist/cli.js +35 -478
  13. package/dist/cost/costTracker.js +0 -3
  14. package/dist/cost/preCallCostEstimator.d.ts +114 -0
  15. package/dist/cost/preCallCostEstimator.d.ts.map +1 -0
  16. package/dist/cost/preCallCostEstimator.js +256 -0
  17. package/dist/cost/preCallCostEstimator.js.map +1 -0
  18. package/dist/index.d.ts +16 -0
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +264 -64
  21. package/dist/index.js.map +1 -1
  22. package/dist/inference/speculativeDecoding.d.ts +133 -0
  23. package/dist/inference/speculativeDecoding.d.ts.map +1 -0
  24. package/dist/inference/speculativeDecoding.js +276 -0
  25. package/dist/inference/speculativeDecoding.js.map +1 -0
  26. package/dist/integrations/langchainAdapter.d.ts +1 -0
  27. package/dist/integrations/oauth.d.ts +1 -0
  28. package/dist/memory/autoFetch.d.ts +1 -0
  29. package/dist/memory/memoryTree.d.ts +1 -0
  30. package/dist/memory/obsidianVault.d.ts +1 -0
  31. package/dist/providers/providerConfig.d.ts +1 -0
  32. package/dist/providers/providerConfig.js +2 -0
  33. package/dist/providers/providerHealth.d.ts +117 -0
  34. package/dist/providers/providerHealth.d.ts.map +1 -0
  35. package/dist/providers/providerHealth.js +309 -0
  36. package/dist/providers/providerHealth.js.map +1 -0
  37. package/dist/providers/registry.js +126 -128
  38. package/dist/routing/advancedRouter.js +310 -427
  39. package/dist/routing/difficultyClassifier.d.ts +79 -0
  40. package/dist/routing/difficultyClassifier.d.ts.map +1 -0
  41. package/dist/routing/difficultyClassifier.js +329 -0
  42. package/dist/routing/difficultyClassifier.js.map +1 -0
  43. package/dist/sdk.d.ts +125 -0
  44. package/dist/sdk.d.ts.map +1 -0
  45. package/dist/sdk.js +109 -100
  46. package/dist/sdk.js.map +1 -0
  47. package/dist/security/guardrails.d.ts +1 -0
  48. package/dist/server/dashboard.d.ts +1 -0
  49. package/dist/server/modelMapper.d.ts +1 -0
  50. package/dist/server/proxyServer.d.ts +1 -0
  51. package/package.json +4 -2
  52. package/src/cache/cacheKeyGenerator.ts +242 -0
  53. package/src/cache/semanticCache.ts +148 -0
  54. package/src/cost/preCallCostEstimator.ts +345 -0
  55. package/src/inference/speculativeDecoding.ts +373 -0
  56. package/src/providers/providerHealth.ts +397 -0
  57. package/src/routing/difficultyClassifier.ts +420 -0
  58. package/test/provider-test.js +2 -2
  59. package/test.js +7 -7
  60. package/test.js.bak +376 -0
  61. package/tsconfig.json +15 -5
  62. package/src/index.ts +0 -99
  63. package/src/skills/__tests__/skill_manager.test.ts +0 -328
@@ -7,8 +7,12 @@
7
7
  * No external embedding API needed. Trigram overlap catches paraphrases like:
8
8
  * "What is Python?" ≈ "Tell me about Python" ≈ "Explain Python"
9
9
  * "Write a sort fn" ≈ "Create a sorting fn" ≈ "How to sort an array"
10
+ *
11
+ * Also supports cross-provider cache key generation via generateCacheKey().
10
12
  */
11
13
 
14
+ import * as crypto from 'crypto';
15
+
12
16
  // ============================================================
13
17
  // Types
14
18
  // ============================================================
@@ -53,6 +57,150 @@ function normalize(text: string): string {
53
57
  .trim();
54
58
  }
55
59
 
60
+ // ============================================================
61
+ // Cross-Provider Cache Key Generation
62
+ // ============================================================
63
+
64
+ /**
65
+ * Provider-specific formatting patterns to strip for cross-provider cache keys.
66
+ */
67
+ const PROVIDER_SYSTEM_PATTERNS: Record<string, RegExp[]> = {
68
+ anthropic: [
69
+ /<anthropic_thinking>[\s\S]*?<\/anthropic_thinking>/gi,
70
+ /<thinking>[\s\S]*?<\/thinking>/gi,
71
+ /Human:/gi,
72
+ /Assistant:/gi,
73
+ ],
74
+ openai: [
75
+ /<|im_start|>/gi,
76
+ /<|im_end|>/gi,
77
+ ],
78
+ google: [
79
+ /<content>[\s\S]*?<\/content>/gi,
80
+ /[Parts|thought]/gi,
81
+ ],
82
+ };
83
+
84
+ export interface GenerateCacheKeyOptions {
85
+ /** Target provider (affects normalization rules) */
86
+ provider?: string;
87
+ /** Target model (for model-specific normalization) */
88
+ model?: string;
89
+ /** Custom normalization rules */
90
+ customRules?: Array<{ pattern: RegExp; replacement: string }>;
91
+ }
92
+
93
+ export interface CacheKeyResult {
94
+ /** The normalized cache key string */
95
+ key: string;
96
+ /** Hash of the normalized content */
97
+ hash: string;
98
+ /** Metadata about what was normalized */
99
+ metadata: {
100
+ originalLength: number;
101
+ normalizedLength: number;
102
+ rulesApplied: number;
103
+ provider?: string;
104
+ };
105
+ }
106
+
107
+ /**
108
+ * Generate a deterministic cache key from a query.
109
+ * Same semantic content = same key across providers.
110
+ *
111
+ * @example
112
+ * const key1 = semanticCache.generateCacheKey("What is Python?", { provider: "openai" });
113
+ * const key2 = semanticCache.generateCacheKey("What is Python?", { provider: "anthropic" });
114
+ * // key1.key === key2.key (same semantic content = same key)
115
+ */
116
+ export function generateCacheKey(
117
+ query: string,
118
+ options: GenerateCacheKeyOptions = {}
119
+ ): CacheKeyResult {
120
+ const originalLength = query.length;
121
+
122
+ // Step 1: Unicode normalization (NFC)
123
+ let normalized = query.normalize('NFC');
124
+
125
+ // Step 2: Collapse whitespace
126
+ normalized = normalized.replace(/\s+/g, ' ');
127
+
128
+ // Step 3: Remove control characters
129
+ normalized = normalized.replace(/[\x00-\x1F\x7F]/g, '');
130
+
131
+ // Step 4: Strip provider-specific formatting
132
+ if (options.provider) {
133
+ const patterns = PROVIDER_SYSTEM_PATTERNS[options.provider] || [];
134
+ for (const pattern of patterns) {
135
+ normalized = normalized.replace(pattern, '');
136
+ }
137
+ }
138
+
139
+ // Step 5: General system/assistant role removal
140
+ normalized = normalized
141
+ .replace(/\b(system|user|assistant|human|bot)\s*:/gi, '')
142
+ .replace(/^(system|user|assistant|human|bot)\s*/gim, '');
143
+
144
+ // Step 6: Remove markdown formatting
145
+ normalized = normalized
146
+ .replace(/```[\s\S]*?```/g, '[CODE_BLOCK]')
147
+ .replace(/`([^`]+)`/g, '$1')
148
+ .replace(/\*\*([^*]+)\*\*/g, '$1')
149
+ .replace(/_([^_]+)_/g, '$1')
150
+ .replace(/#+\s*/g, '')
151
+ .replace(/^\s*[-*+]\s+/gm, '')
152
+ .replace(/^\s*\d+\.\s+/gm, '');
153
+
154
+ // Step 7: Apply custom rules
155
+ if (options.customRules) {
156
+ for (const rule of options.customRules) {
157
+ normalized = normalized.replace(rule.pattern, rule.replacement);
158
+ }
159
+ }
160
+
161
+ // Step 8: Final whitespace collapse
162
+ normalized = normalized.replace(/\s+/g, ' ').trim();
163
+
164
+ // Count rules applied
165
+ let rulesApplied = 3; // Base normalizations
166
+ if (options.provider) rulesApplied += 2;
167
+ if (options.customRules) rulesApplied += options.customRules.length;
168
+
169
+ // Generate hash
170
+ const hash = crypto
171
+ .createHash('sha256')
172
+ .update(normalized)
173
+ .digest('hex')
174
+ .substring(0, 16);
175
+
176
+ // Build key
177
+ let key = `v1:${hash}`;
178
+ if (options.provider) {
179
+ key += `:${options.provider}`;
180
+ if (options.model) {
181
+ key += `:${options.model}`;
182
+ }
183
+ }
184
+
185
+ return {
186
+ key,
187
+ hash,
188
+ metadata: {
189
+ originalLength,
190
+ normalizedLength: normalized.length,
191
+ rulesApplied,
192
+ provider: options.provider,
193
+ },
194
+ };
195
+ }
196
+
197
+ /**
198
+ * Quick cache key generation (simplified API).
199
+ */
200
+ export function toCacheKey(query: string, provider?: string): string {
201
+ return generateCacheKey(query, { provider }).key;
202
+ }
203
+
56
204
  /**
57
205
  * Extract character trigrams from text.
58
206
  * Pads with spaces so short words still produce trigrams.
@@ -0,0 +1,345 @@
1
+ /**
2
+ * A3M Router - Pre-Call Cost Estimator
3
+ *
4
+ * Estimates cost BEFORE making an API call based on input features.
5
+ * Uses historical data patterns and token count estimation via character ratio.
6
+ *
7
+ * No external API calls - all estimation is local.
8
+ *
9
+ * Usage:
10
+ * const estimator = new PreCallCostEstimator();
11
+ * const estimate = estimator.estimate({
12
+ * query: "What is Python?",
13
+ * modelTier: 'mid',
14
+ * provider: 'groq'
15
+ * });
16
+ * console.log(estimate); // { estimatedTokens: 24, estimatedCost: 0.0014, estimatedLatency: 200 }
17
+ */
18
+
19
+ import { ProviderTier } from '../providers/providerConfig';
20
+
21
+ // ============================================================
22
+ // Types
23
+ // ============================================================
24
+
25
+ export interface CostEstimateInput {
26
+ /** Query text to estimate tokens for */
27
+ query: string;
28
+ /** Model tier (free|cheap|mid|premium|enterprise) */
29
+ modelTier?: ProviderTier;
30
+ /** Provider ID for provider-specific cost lookup */
31
+ provider?: string;
32
+ /** Optional: explicit token count (if already known) */
33
+ explicitTokens?: number;
34
+ /** System prompt length (if using a system prompt) */
35
+ systemPromptLength?: number;
36
+ }
37
+
38
+ export interface CostEstimate {
39
+ /** Estimated total tokens (input + output) */
40
+ estimatedTokens: number;
41
+ /** Estimated input tokens */
42
+ estimatedInputTokens: number;
43
+ /** Estimated output tokens */
44
+ estimatedOutputTokens: number;
45
+ /** Estimated cost in USD */
46
+ estimatedCost: number;
47
+ /** Estimated latency in milliseconds */
48
+ estimatedLatency: number;
49
+ /** Confidence score 0-1 */
50
+ confidence: number;
51
+ /** Breakdown of estimation */
52
+ breakdown: {
53
+ inputCostPerM: number;
54
+ outputCostPerM: number;
55
+ charToTokenRatio: number;
56
+ };
57
+ }
58
+
59
+ export interface ProviderCostConfig {
60
+ input: number; // per 1M tokens
61
+ output: number; // per 1M tokens
62
+ }
63
+
64
+ // Default latency estimates per tier (ms)
65
+ const TIER_LATENCY: Record<ProviderTier, { min: number; max: number; avg: number }> = {
66
+ free: { min: 500, max: 5000, avg: 2000 },
67
+ cheap: { min: 100, max: 800, avg: 300 },
68
+ mid: { min: 200, max: 1500, avg: 600 },
69
+ premium:{ min: 300, max: 2000, avg: 800 },
70
+ enterprise: { min: 200, max: 1500, avg: 500 },
71
+ };
72
+
73
+ // ============================================================
74
+ // PreCallCostEstimator
75
+ // ============================================================
76
+
77
+ export class PreCallCostEstimator {
78
+ // Historical data for regression: [charCount, actualTokens][] tuples
79
+ private historicalData: Array<{ chars: number; tokens: number }> = [];
80
+ // Linear regression coefficients
81
+ private slope = 0.25; // chars per token ratio
82
+ private intercept = 10;
83
+ // EWMA for latency estimation
84
+ private latencyHistory: number[] = [];
85
+ private ewmaAlpha = 0.3;
86
+
87
+ constructor(historicalData?: Array<{ chars: number; tokens: number }>) {
88
+ if (historicalData && historicalData.length > 0) {
89
+ this.fitLinearRegression(historicalData);
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Main estimation method - estimates tokens, cost, and latency.
95
+ */
96
+ estimate(input: CostEstimateInput): CostEstimate {
97
+ const {
98
+ query,
99
+ modelTier = 'mid',
100
+ provider,
101
+ explicitTokens,
102
+ systemPromptLength = 0,
103
+ } = input;
104
+
105
+ // Token estimation
106
+ let inputTokens: number;
107
+ if (explicitTokens !== undefined) {
108
+ inputTokens = explicitTokens;
109
+ } else {
110
+ inputTokens = this.estimateTokens(query, systemPromptLength);
111
+ }
112
+
113
+ // Output token estimation based on query complexity
114
+ const outputTokens = this.estimateOutputTokens(query, inputTokens);
115
+
116
+ const totalTokens = inputTokens + outputTokens;
117
+
118
+ // Cost estimation
119
+ const costConfig = this.getCostConfig(provider, modelTier);
120
+ const estimatedCost = this.calculateCost(totalTokens, costConfig);
121
+
122
+ // Latency estimation
123
+ const estimatedLatency = this.estimateLatency(modelTier, inputTokens, totalTokens);
124
+
125
+ // Confidence based on amount of historical data we have
126
+ const confidence = this.calculateConfidence();
127
+
128
+ return {
129
+ estimatedTokens: totalTokens,
130
+ estimatedInputTokens: inputTokens,
131
+ estimatedOutputTokens: outputTokens,
132
+ estimatedCost: Math.round(estimatedCost * 1000000) / 1000000, // 6 decimal places
133
+ estimatedLatency,
134
+ confidence,
135
+ breakdown: {
136
+ inputCostPerM: costConfig.input,
137
+ outputCostPerM: costConfig.output,
138
+ charToTokenRatio: this.slope,
139
+ },
140
+ };
141
+ }
142
+
143
+ /**
144
+ * Estimate input tokens using character-to-token ratio.
145
+ * Uses linear regression if historical data is available.
146
+ */
147
+ estimateTokens(text: string, systemPromptLength = 0): number {
148
+ const totalChars = text.length + systemPromptLength;
149
+
150
+ if (this.historicalData.length >= 5) {
151
+ // Use linear regression
152
+ return Math.max(1, Math.round(this.slope * totalChars + this.intercept));
153
+ }
154
+
155
+ // Fallback: general English average ~4 chars per token
156
+ return Math.max(1, Math.round(totalChars / 4));
157
+ }
158
+
159
+ /**
160
+ * Estimate output tokens based on query complexity.
161
+ * More complex queries (code, analysis) tend to need more output.
162
+ */
163
+ estimateOutputTokens(query: string, inputTokens: number): number {
164
+ const lower = query.toLowerCase();
165
+
166
+ // Base estimate: ~30% of input tokens as output
167
+ let multiplier = 0.3;
168
+
169
+ // Complexity adjustments
170
+ if (this.containsKeyword(lower, ['code', 'implement', 'function', 'class', 'algorithm'])) {
171
+ multiplier = 0.5; // Code needs more output
172
+ } else if (this.containsKeyword(lower, ['explain', 'describe', 'what is', 'how does'])) {
173
+ multiplier = 0.35; // Explanations need moderate output
174
+ } else if (this.containsKeyword(lower, ['list', 'count', 'find all'])) {
175
+ multiplier = 0.4; // List queries need more output
176
+ } else if (this.containsKeyword(lower, ['yes', 'no', 'is', 'are', 'does'])) {
177
+ multiplier = 0.1; // Simple questions need minimal output
178
+ }
179
+
180
+ // Cap to reasonable bounds
181
+ return Math.min(
182
+ Math.max(10, Math.round(inputTokens * multiplier)),
183
+ 4000 // Max 4k output tokens
184
+ );
185
+ }
186
+
187
+ /**
188
+ * Calculate cost in USD.
189
+ */
190
+ calculateCost(totalTokens: number, config: ProviderCostConfig): number {
191
+ const inputM = this.estimateInputTokensFromTotal(totalTokens) / 1_000_000;
192
+ const outputM = this.estimateOutputTokensFromTotal(totalTokens) / 1_000_000;
193
+ return inputM * config.input + outputM * config.output;
194
+ }
195
+
196
+ /**
197
+ * Estimate latency in milliseconds.
198
+ */
199
+ estimateLatency(tier: ProviderTier, inputTokens: number, totalTokens: number): number {
200
+ const tierLatency = TIER_LATENCY[tier];
201
+
202
+ // Base latency from tier
203
+ let latency = tierLatency.avg;
204
+
205
+ // Scale by token count (rough linear approximation)
206
+ const tokenScale = totalTokens / 100;
207
+ latency *= Math.max(0.5, Math.min(3, tokenScale));
208
+
209
+ // Adjust for historical EWMA if available
210
+ if (this.latencyHistory.length > 0) {
211
+ const ewmaLatency = this.calculateEwma();
212
+ latency = latency * 0.7 + ewmaLatency * 0.3;
213
+ }
214
+
215
+ return Math.round(latency);
216
+ }
217
+
218
+ /**
219
+ * Record actual tokens for future regression improvements.
220
+ */
221
+ recordActualTokens(queryLength: number, actualTokens: number): void {
222
+ this.historicalData.push({ chars: queryLength, tokens: actualTokens });
223
+
224
+ // Keep only last 100 data points
225
+ if (this.historicalData.length > 100) {
226
+ this.historicalData.shift();
227
+ }
228
+
229
+ // Refit regression periodically
230
+ if (this.historicalData.length % 10 === 0) {
231
+ this.fitLinearRegression(this.historicalData);
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Record actual latency for EWMA updates.
237
+ */
238
+ recordActualLatency(latencyMs: number): void {
239
+ this.latencyHistory.push(latencyMs);
240
+ if (this.latencyHistory.length > 50) {
241
+ this.latencyHistory.shift();
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Fit linear regression to historical data.
247
+ * Uses ordinary least squares.
248
+ */
249
+ fitLinearRegression(data: Array<{ chars: number; tokens: number }>): void {
250
+ if (data.length < 2) return;
251
+
252
+ const n = data.length;
253
+ let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
254
+
255
+ for (const { chars, tokens } of data) {
256
+ sumX += chars;
257
+ sumY += tokens;
258
+ sumXY += chars * tokens;
259
+ sumX2 += chars * chars;
260
+ }
261
+
262
+ const denominator = n * sumX2 - sumX * sumX;
263
+ if (denominator === 0) return;
264
+
265
+ this.slope = (n * sumXY - sumX * sumY) / denominator;
266
+ this.intercept = (sumY - this.slope * sumX) / n;
267
+
268
+ // Sanity check
269
+ if (this.slope <= 0 || this.slope > 1) {
270
+ this.slope = 0.25; // Reset to default if outlier
271
+ this.intercept = 10;
272
+ }
273
+ }
274
+
275
+ // ---- Private helpers ----
276
+
277
+ private getCostConfig(provider?: string, tier?: ProviderTier): ProviderCostConfig {
278
+ // Provider-specific costs (from providerConfig.ts patterns)
279
+ const providerCosts: Partial<Record<string, ProviderCostConfig>> = {
280
+ groq: { input: 0.59, output: 0.79 },
281
+ cerebras: { input: 0.60, output: 0.60 },
282
+ deepseek: { input: 0.14, output: 0.28 },
283
+ deepinfra: { input: 0.05, output: 0.05 },
284
+ together: { input: 0.18, output: 0.18 },
285
+ fireworks: { input: 0.20, output: 0.20 },
286
+ mistral: { input: 0.20, output: 0.60 },
287
+ openai: { input: 2.50, output: 10.00 },
288
+ anthropic: { input: 3.00, output: 15.00 },
289
+ };
290
+
291
+ if (provider && providerCosts[provider]) {
292
+ return providerCosts[provider]!;
293
+ }
294
+
295
+ // Tier fallback
296
+ const tierCosts: Record<ProviderTier, ProviderCostConfig> = {
297
+ free: { input: 0, output: 0 },
298
+ cheap: { input: 0.20, output: 0.40 },
299
+ mid: { input: 1.00, output: 3.00 },
300
+ premium: { input: 3.00, output: 12.00 },
301
+ enterprise: { input: 5.00, output: 20.00 },
302
+ };
303
+
304
+ return tier ? tierCosts[tier] : tierCosts.mid;
305
+ }
306
+
307
+ private containsKeyword(text: string, keywords: string[]): boolean {
308
+ return keywords.some(kw => text.includes(kw));
309
+ }
310
+
311
+ private calculateEwma(): number {
312
+ if (this.latencyHistory.length === 0) return 0;
313
+ let ewma = this.latencyHistory[0];
314
+ for (let i = 1; i < this.latencyHistory.length; i++) {
315
+ ewma = this.ewmaAlpha * this.latencyHistory[i] + (1 - this.ewmaAlpha) * ewma;
316
+ }
317
+ return ewma;
318
+ }
319
+
320
+ private calculateConfidence(): number {
321
+ // More historical data = higher confidence
322
+ const dataFactor = Math.min(this.historicalData.length / 50, 1.0);
323
+ // More latency history = higher confidence
324
+ const latencyFactor = Math.min(this.latencyHistory.length / 20, 1.0);
325
+ return Math.round((dataFactor * 0.6 + latencyFactor * 0.4) * 100) / 100;
326
+ }
327
+
328
+ private estimateInputTokensFromTotal(total: number): number {
329
+ return Math.round(total * 0.7); // Assume 70% input
330
+ }
331
+
332
+ private estimateOutputTokensFromTotal(total: number): number {
333
+ return Math.round(total * 0.3); // Assume 30% output
334
+ }
335
+ }
336
+
337
+ // ============================================================
338
+ // Factory
339
+ // ============================================================
340
+
341
+ export function createPreCallCostEstimator(
342
+ historicalData?: Array<{ chars: number; tokens: number }>
343
+ ): PreCallCostEstimator {
344
+ return new PreCallCostEstimator(historicalData);
345
+ }