adaptive-memory-multi-model-router 2.14.16 → 2.14.18

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 (69) hide show
  1. package/.a3m-vault.json +23 -0
  2. package/.github/workflows/ci.yml +253 -5
  3. package/.publish-tick +1 -1
  4. package/AGENT_COUNCIL_FINDINGS.md +142 -0
  5. package/LAUNCH_CHECKLIST.md +141 -0
  6. package/README.md +15 -17
  7. package/README.md.bak +836 -0
  8. package/articles/CHINESE_SUBMISSIONS_READY.md +322 -0
  9. package/articles/DEVTO_READY.md +255 -0
  10. package/articles/HN_POST_READY.md +137 -0
  11. package/articles/INDIEHACKERS_READY.md +120 -0
  12. package/articles/NEWSLETTER_SEND_NOW.md +259 -0
  13. package/articles/PRODUCTHUNT_READY.md +106 -0
  14. package/articles/REDDIT_SUBMISSION_READY.md +348 -0
  15. package/articles/TWEET_STORM_READY.md +165 -0
  16. package/benchmark-results.json +45 -43
  17. package/council-votes/architecture-vote.md +121 -0
  18. package/council-votes/coverage-vote.md +93 -0
  19. package/dist/cost/costTracker.d.ts +109 -44
  20. package/dist/cost/costTracker.js +321 -98
  21. package/dist/cost/costTracker.js.map +1 -1
  22. package/dist/ensemble.d.ts +21 -0
  23. package/dist/ensemble.js +85 -0
  24. package/dist/index.d.ts +9 -5
  25. package/dist/index.js +12 -4
  26. package/dist/routing/advancedRouter.d.ts +38 -43
  27. package/dist/routing/advancedRouter.js +394 -408
  28. package/dist/routing/advancedRouter.js.map +1 -1
  29. package/dist/routing/providers/providerConfig.d.ts +49 -0
  30. package/dist/routing/providers/providerConfig.js +883 -0
  31. package/dist/routing/routing/advancedRouter.d.ts +62 -0
  32. package/dist/routing/routing/advancedRouter.js +447 -0
  33. package/dist/routing/utils/tokenUtils.d.ts +52 -0
  34. package/dist/routing/utils/tokenUtils.js +129 -0
  35. package/dist/server/proxyServer.d.ts +1 -1
  36. package/dist/tui/dashboard.js +66 -2
  37. package/dist/tui/dashboard.js.map +1 -1
  38. package/dist/utils/tokenUtils.d.ts +48 -1
  39. package/dist/utils/tokenUtils.js +117 -4
  40. package/dist/utils/tokenUtils.js.map +1 -1
  41. package/docs/CITATIONS.md +2 -2
  42. package/docs/GEO_STATUS.md +43 -157
  43. package/docs/ai-plugin.json +4 -4
  44. package/docs/llms.txt +21 -27
  45. package/docs/sitemap.xml +14 -20
  46. package/package.json +2 -2
  47. package/research-log.md +49 -0
  48. package/sitemap.xml +57 -0
  49. package/src/cost/costTracker.ts +576 -0
  50. package/src/ensemble.ts +103 -0
  51. package/src/index.ts +13 -3
  52. package/src/routing/advancedRouter.ts +536 -0
  53. package/src/tui/dashboard.ts +76 -3
  54. package/src/utils/tokenUtils.ts +142 -4
  55. package/test-council/1-structure-tests.test.js +353 -0
  56. package/test-council/1-structure-tests.test.ts +353 -0
  57. package/test-council/2-edge-case-tests.test.ts +361 -0
  58. package/test-council/3-performance-tests.test.ts +669 -0
  59. package/test-council/4-integration-tests.test.ts +391 -0
  60. package/test-council/5-agent-council-eval.test.ts +413 -0
  61. package/test-council/AGENT_COUNCIL_ARCHITECTURE.md +349 -0
  62. package/test-council/TEST_COUNCIL_REPORT.md +201 -0
  63. package/test-council/agents/edge-case-agent.ts +363 -0
  64. package/test-council/agents/performance-agent.ts +426 -0
  65. package/test-council/agents/structure-agent.ts +227 -0
  66. package/test-council/council.md +183 -0
  67. package/tests/security/guardrailEngine.test.ts +700 -0
  68. package/docs/.well-known/ai-plugin.json +0 -16
  69. package/research/PUBLISH_LOG.md +0 -3
@@ -0,0 +1,62 @@
1
+ /**
2
+ * A3M Router - Generic Adaptive Routing (RouteLLM Style)
3
+ *
4
+ * Routes queries to the best available LLM based on:
5
+ * - Query features (code, math, creative, etc.)
6
+ * - Provider availability (checks API keys)
7
+ * - Cost optimization
8
+ * - Quality vs speed tradeoff
9
+ *
10
+ * All provider references are dynamically loaded from providerConfig.
11
+ * Users can add/remove providers via environment variables or config files.
12
+ */
13
+ interface ModelProfile {
14
+ name: string;
15
+ provider: string;
16
+ providerName: string;
17
+ cost_per_1k_input: number;
18
+ cost_per_1k_output: number;
19
+ latency_ms: number;
20
+ quality_score: number;
21
+ strengths: string[];
22
+ context_window: number;
23
+ type: string;
24
+ priority: number;
25
+ }
26
+ export declare let MODEL_PROFILES: Record<string, ModelProfile>;
27
+ export interface QueryFeatures {
28
+ length: number;
29
+ wordCount: number;
30
+ complexity: number;
31
+ has_code: boolean;
32
+ requires_reasoning: boolean;
33
+ is_multilingual: boolean;
34
+ is_translation: boolean;
35
+ domain: string | null;
36
+ intent: string;
37
+ detected_language: string | null;
38
+ }
39
+ export interface RouteDecision {
40
+ primary_model: string | null;
41
+ fallback_models: string[];
42
+ confidence: number;
43
+ reasoning: string;
44
+ estimated_cost: number;
45
+ estimated_latency_ms: number;
46
+ features?: QueryFeatures;
47
+ provider_type?: string;
48
+ }
49
+ export declare function routeQuery(prompt: string, available_models?: string[], budget_multiplier?: number): RouteDecision;
50
+ export declare function routeBatch(prompts: string[], options?: {
51
+ same_model?: boolean;
52
+ max_cost_per_prompt?: number;
53
+ }): RouteDecision[];
54
+ export declare function recommendForTask(task: string): {
55
+ primary: string | null;
56
+ fallbacks: string[];
57
+ reason: string;
58
+ features: QueryFeatures;
59
+ };
60
+ export declare function updateModelProfile(model_name: string, actual_latency_ms: number, actual_cost: number, quality_rating: number): void;
61
+ export declare function getProviderHealth(): Promise<any>;
62
+ export {};
@@ -0,0 +1,447 @@
1
+ "use strict";
2
+ /**
3
+ * A3M Router - Generic Adaptive Routing (RouteLLM Style)
4
+ *
5
+ * Routes queries to the best available LLM based on:
6
+ * - Query features (code, math, creative, etc.)
7
+ * - Provider availability (checks API keys)
8
+ * - Cost optimization
9
+ * - Quality vs speed tradeoff
10
+ *
11
+ * All provider references are dynamically loaded from providerConfig.
12
+ * Users can add/remove providers via environment variables or config files.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.MODEL_PROFILES = void 0;
16
+ exports.routeQuery = routeQuery;
17
+ exports.routeBatch = routeBatch;
18
+ exports.recommendForTask = recommendForTask;
19
+ exports.updateModelProfile = updateModelProfile;
20
+ exports.getProviderHealth = getProviderHealth;
21
+ const providerConfig_1 = require("../providers/providerConfig");
22
+ const tokenUtils_1 = require("../utils/tokenUtils");
23
+ let cachedProfiles = null;
24
+ let cacheTimestamp = 0;
25
+ const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
26
+ function buildModelProfiles() {
27
+ const profiles = {};
28
+ const available = (0, providerConfig_1.getAvailableProviders)();
29
+ for (const [providerId, provider] of Object.entries(available)) {
30
+ for (const model of provider.models) {
31
+ const modelKey = model.includes('/') ? model : providerId + '/' + model;
32
+ const costPerKInput = provider.costPerK ? provider.costPerK.input : 0;
33
+ const costPerKOutput = provider.costPerK ? provider.costPerK.output : 0;
34
+ // Assign strengths based on model characteristics
35
+ const strengths = [];
36
+ if (provider.type === 'cli') {
37
+ strengths.push('free', 'local');
38
+ }
39
+ if (costPerKInput < 0.3) {
40
+ strengths.push('budget', 'fast');
41
+ }
42
+ else if (costPerKInput > 2) {
43
+ strengths.push('premium', 'reasoning');
44
+ }
45
+ if (provider.name === 'Mistral' || provider.name === 'Groq' || provider.name === 'Cerebras') {
46
+ strengths.push('fast', 'coding');
47
+ }
48
+ if (provider.name === 'CommandCode') {
49
+ strengths.push('code-aware', 'context-rich');
50
+ }
51
+ if (provider.name === 'OpenCode') {
52
+ strengths.push('free', 'multi-model');
53
+ }
54
+ if (provider.name === 'Google') {
55
+ strengths.push('multilingual', 'long-context');
56
+ }
57
+ if (provider.name === 'OpenAI') {
58
+ strengths.push('reasoning', 'coding', 'analysis');
59
+ }
60
+ if (provider.name === 'Anthropic') {
61
+ strengths.push('reasoning', 'creative', 'analysis');
62
+ }
63
+ profiles[modelKey] = {
64
+ name: modelKey,
65
+ provider: providerId,
66
+ providerName: provider.name,
67
+ cost_per_1k_input: costPerKInput,
68
+ cost_per_1k_output: costPerKOutput,
69
+ latency_ms: provider.type === 'cli' ? 5000 : (provider.priority * 200 + 300),
70
+ quality_score: strengths.includes('premium') ? 0.95 :
71
+ strengths.includes('reasoning') ? 0.90 :
72
+ strengths.includes('fast') ? 0.82 : 0.80,
73
+ strengths,
74
+ context_window: provider.maxTokens || 8192,
75
+ type: provider.type,
76
+ priority: provider.priority,
77
+ };
78
+ }
79
+ }
80
+ return profiles;
81
+ }
82
+ // Lazy cache with TTL - replaces refreshModelProfiles()
83
+ function getModelProfiles() {
84
+ const now = Date.now();
85
+ if (!cachedProfiles || (now - cacheTimestamp) > CACHE_TTL_MS) {
86
+ cachedProfiles = buildModelProfiles();
87
+ cacheTimestamp = now;
88
+ }
89
+ return cachedProfiles;
90
+ }
91
+ // Manual cache invalidation (call if provider config changes)
92
+ function invalidateProfileCache() {
93
+ cachedProfiles = null;
94
+ cacheTimestamp = 0;
95
+ }
96
+ exports.MODEL_PROFILES = {};
97
+ try {
98
+ exports.MODEL_PROFILES = buildModelProfiles();
99
+ }
100
+ catch (e) {
101
+ // Circular dependency at module load — will retry on first use
102
+ exports.MODEL_PROFILES = {};
103
+ }
104
+ function extractQueryFeatures(prompt) {
105
+ const lower = prompt.toLowerCase();
106
+ const words = prompt.split(/\s+/);
107
+ const wordCount = words.length;
108
+ // === SIGNAL 1: Domain Detection ===
109
+ const domainSignals = {
110
+ legal: {
111
+ keywords: ['legal', 'law', 'contract', 'liability', 'litigation', 'patent', 'copyright',
112
+ 'regulation', 'compliance', 'constitutional', 'statute', 'jurisdiction',
113
+ 'court', 'ruling', 'precedent', 'attorney', 'amicus', 'sec ', 'fda ',
114
+ 'gdpr', 'ccpa', 'cfpr', 'due diligence', 'merger', 'acquisition',
115
+ '10-k', 'sec filing', 'forensic', 'embezzlement', 'infringement'],
116
+ weight: 0.35
117
+ },
118
+ medical: {
119
+ keywords: ['clinical', 'medical', 'pharmaceutical', 'oncology', 'drug', 'trial protocol',
120
+ 'diagnosis', 'treatment', 'epidemiolog', 'genome', 'cohort study',
121
+ 'biomarker', 'efficacy', 'pharmacoeconomic', 'biologic', 'vaccine',
122
+ 'sepsis', 'ehr ', 'surgical', 'patient safety', 'fda approval'],
123
+ weight: 0.35
124
+ },
125
+ finance: {
126
+ keywords: ['financial model', 'valuation', 'revenue', 'portfolio', 'derivative',
127
+ 'hedge fund', 'series a', 'series b', 'startup valuation', 'sensitivity analysis',
128
+ 'investment thesis', 'earnings', 'tax optimization', 'forensic accounting',
129
+ 'multinational', 'jurisdiction', 'risk assessment', 'monte carlo',
130
+ 'black-scholes', 'options pricing', 'credit risk'],
131
+ weight: 0.30
132
+ },
133
+ security: {
134
+ keywords: ['security audit', 'penetration', 'vulnerability', 'exploit', 'zero-trust',
135
+ 'threat model', 'incident response', 'malware', 'ransomware',
136
+ 'authentication flow', 'cryptograph', 'encryption', 'timing attack',
137
+ 'supply chain attack', 'owasp', 'compliance', 'risk assessment',
138
+ 'mfa', 'zero-day', 'firewall', 'intrusion'],
139
+ weight: 0.30
140
+ },
141
+ architecture: {
142
+ keywords: ['system design', 'microservice', 'distributed system', 'fault-tolerant',
143
+ 'event-sourced', 'cqrs', 'consensus algorithm', 'real-time pipeline',
144
+ 'high availability', 'multi-region', 'latency sla', 'kafka',
145
+ 'event-driven', 'data warehouse', 'etl', 'streaming', '1m events',
146
+ 'million events', 'scalab', 'infrastruct', 'deploy'],
147
+ weight: 0.25
148
+ },
149
+ data_science: {
150
+ keywords: ['machine learning', 'deep learning', 'neural network', 'transformer',
151
+ 'training data', 'model accuracy', 'hyperparameter', 'cross-validation',
152
+ 'feature engineering', 'data pipeline', 'pandas', 'numpy', 'scikit',
153
+ 'tensorflow', 'pytorch', 'regression', 'classification', 'clustering'],
154
+ weight: 0.30
155
+ },
156
+ };
157
+ let detectedDomain = null;
158
+ let maxDomainScore = 0;
159
+ for (const [domain, signal] of Object.entries(domainSignals)) {
160
+ let domainScore = 0;
161
+ for (const kw of signal.keywords) {
162
+ if (lower.includes(kw)) {
163
+ domainScore += signal.weight;
164
+ }
165
+ }
166
+ if (domainScore > maxDomainScore) {
167
+ maxDomainScore = domainScore;
168
+ detectedDomain = domain;
169
+ }
170
+ }
171
+ // === SIGNAL 2: Code Detection ===
172
+ const codeSignals = [
173
+ 'function ', 'def ', 'class ', 'import ', 'from ', 'const ', 'let ', 'var ',
174
+ '=>', '->', 'async ', 'await ', 'return ', 'if (', 'for (', 'while (',
175
+ 'public ', 'private ', 'protected ', 'static ', 'void ', 'int ', 'string ',
176
+ '#include', 'std::', 'cout', 'cin', 'printf(', 'println!',
177
+ 'fn ', 'impl ', 'pub ', 'mut ', 'struct ', 'enum ',
178
+ '```', 'code', 'python', 'javascript', 'typescript', 'java', 'cpp', 'ruby',
179
+ 'write a', 'create a', 'implement', 'algorithm'
180
+ ];
181
+ const hasCode = codeSignals.some(sig => lower.includes(sig));
182
+ // === SIGNAL 3: Reasoning Detection ===
183
+ const reasoningSignals = [
184
+ 'why', 'how', 'explain', 'analyze', 'compare', 'contrast', 'evaluate',
185
+ 'think about', 'reason', 'logic', 'proof', 'derive', '证明', '分析',
186
+ 'reasoning', 'step by step', 'thinking', 'thought process'
187
+ ];
188
+ const requiresReasoning = reasoningSignals.some(sig => lower.includes(sig));
189
+ // === SIGNAL 4: Language Detection ===
190
+ const languagePatterns = [
191
+ [/[\u4e00-\u9fff]/, 'zh'],
192
+ [/[\u0900-\u097f]/, 'hi'],
193
+ [/[\u0600-\u06ff]/, 'ar'],
194
+ [/[\u0400-\u04ff]/, 'ru'],
195
+ [/[\u0900-\u097f]/, 'hi-latn'],
196
+ [/বাংলা|করুন|হিন্দি|ভারত|ভারতীয়/, 'bn'],
197
+ ];
198
+ let detectedLanguage = null;
199
+ for (const [pattern, lang] of languagePatterns) {
200
+ if (pattern.test(prompt)) {
201
+ detectedLanguage = lang;
202
+ break;
203
+ }
204
+ }
205
+ // Translation detection
206
+ const translationSignals = ['translate', 'translation', 'into english', 'to english',
207
+ 'traducir', 'traduction', 'traduzione', 'übersetzen'];
208
+ const isTranslation = translationSignals.some(sig => lower.includes(sig)) ||
209
+ /to (english|french|german|spanish|chinese|japanese|korean)/i.test(prompt);
210
+ const isMultilingual = detectedLanguage !== null || isTranslation;
211
+ // === SIGNAL 5: Intent Classification ===
212
+ let intent = 'general';
213
+ if (hasCode)
214
+ intent = 'code';
215
+ else if (isTranslation)
216
+ intent = 'translation';
217
+ else if (lower.includes('write') || lower.includes('create') || lower.includes('generate')) {
218
+ intent = 'creative';
219
+ }
220
+ else if (lower.includes('explain') || lower.includes('what is') || lower.includes('how does')) {
221
+ intent = 'explanation';
222
+ }
223
+ else if (lower.includes('calculate') || lower.includes('compute') || lower.includes('integral')) {
224
+ intent = 'math';
225
+ }
226
+ // === COMPLEXITY SCORING ===
227
+ // Base complexity from length
228
+ let complexity = Math.min(wordCount / 100, 1.0);
229
+ // Domain加成
230
+ if (detectedDomain)
231
+ complexity += 0.2;
232
+ // Code加成
233
+ if (hasCode)
234
+ complexity += 0.15;
235
+ // Reasoning加成
236
+ if (requiresReasoning)
237
+ complexity += 0.15;
238
+ // Multilingual加成
239
+ if (isMultilingual)
240
+ complexity += 0.1;
241
+ // Cap at 1.0
242
+ complexity = Math.min(complexity, 1.0);
243
+ return {
244
+ length: prompt.length,
245
+ wordCount,
246
+ complexity,
247
+ has_code: hasCode,
248
+ requires_reasoning: requiresReasoning,
249
+ is_multilingual: isMultilingual,
250
+ is_translation: isTranslation,
251
+ domain: detectedDomain,
252
+ intent,
253
+ detected_language: detectedLanguage,
254
+ };
255
+ }
256
+ function scoreModelFit(model, features) {
257
+ let score = model.quality_score * 0.6;
258
+ // Domain match
259
+ if (features.domain) {
260
+ const domainBonus = {
261
+ code: ['code-aware', 'coding', 'fast'],
262
+ medical: ['reasoning', 'analysis'],
263
+ legal: ['reasoning', 'analysis', 'context-rich'],
264
+ finance: ['analysis', 'reasoning'],
265
+ security: ['reasoning', 'analysis'],
266
+ architecture: ['context-rich', 'long-context'],
267
+ data_science: ['coding', 'fast', 'reasoning'],
268
+ };
269
+ const bonuses = domainBonus[features.domain] || [];
270
+ if (bonuses.some(b => model.strengths.includes(b))) {
271
+ score += 0.2;
272
+ }
273
+ }
274
+ // Code bonus
275
+ if (features.has_code && model.strengths.includes('coding')) {
276
+ score += 0.15;
277
+ }
278
+ // Multilingual bonus
279
+ if (features.is_multilingual && model.strengths.includes('multilingual')) {
280
+ score += 0.15;
281
+ }
282
+ // Free tier preference for simple queries
283
+ if (features.complexity < 0.5 && model.strengths.includes('free')) {
284
+ score += 0.2;
285
+ }
286
+ // Fast provider for simple queries
287
+ if (features.complexity < 0.4 && model.strengths.includes('fast')) {
288
+ score += 0.15;
289
+ }
290
+ // Premium for complex queries
291
+ if (features.complexity > 0.6 && model.strengths.includes('premium')) {
292
+ score += 0.15;
293
+ }
294
+ return Math.min(score, 1.0);
295
+ }
296
+ function costEfficiency(model, features) {
297
+ const avg_cost = (model.cost_per_1k_input + model.cost_per_1k_output) / 2;
298
+ if (features.complexity < 0.5) {
299
+ return (1 - Math.min(avg_cost / 10, 1)) * 0.6;
300
+ }
301
+ return (1 - Math.min(avg_cost / 10, 1)) * 0.2;
302
+ }
303
+ function routeQuery(prompt, available_models, budget_multiplier = 1.0) {
304
+ // Use cached profiles instead of rebuilding every time (5-10ms savings)
305
+ const profiles = getModelProfiles();
306
+ const features = extractQueryFeatures(prompt);
307
+ const candidate_names = available_models || Object.keys(profiles);
308
+ // Filter to available models
309
+ const candidates = candidate_names
310
+ .filter(name => profiles[name])
311
+ .map(name => {
312
+ const profile = profiles[name];
313
+ const quality = scoreModelFit(profile, features);
314
+ const cost = costEfficiency(profile, features);
315
+ return {
316
+ name,
317
+ profile,
318
+ quality_score: quality,
319
+ cost_score: cost,
320
+ total_score: quality + cost
321
+ };
322
+ });
323
+ if (candidates.length === 0) {
324
+ return {
325
+ primary_model: null,
326
+ fallback_models: [],
327
+ confidence: 0,
328
+ reasoning: "No providers available - configure API keys in ~/.config/a3m-router/providers.json",
329
+ estimated_cost: 0,
330
+ estimated_latency_ms: 0,
331
+ };
332
+ }
333
+ // Sort by total score (quality vs cost tradeoff based on complexity)
334
+ const complexity_bias = features.complexity > 0.6 ? 0.7 : 0.3;
335
+ candidates.sort((a, b) => {
336
+ const score_a = a.quality_score * complexity_bias + a.cost_score * (1 - complexity_bias);
337
+ const score_b = b.quality_score * complexity_bias + b.cost_score * (1 - complexity_bias);
338
+ return score_b - score_a;
339
+ });
340
+ const primary = candidates[0];
341
+ const secondary = candidates.slice(1, 3);
342
+ // Calculate confidence based on score gap
343
+ let confidence = 0.5;
344
+ if (candidates.length > 1) {
345
+ const gap = primary.total_score - candidates[1].total_score;
346
+ confidence = Math.min(0.95, 0.5 + gap * 2);
347
+ }
348
+ // Build reasoning
349
+ const reasons = [];
350
+ if (features.has_code)
351
+ reasons.push("code detected");
352
+ if (features.requires_reasoning)
353
+ reasons.push("reasoning needed");
354
+ if (features.complexity > 0.6)
355
+ reasons.push("high complexity");
356
+ if (features.is_multilingual)
357
+ reasons.push("multilingual");
358
+ if (features.is_translation)
359
+ reasons.push("translation");
360
+ if (primary.profile.strengths.includes("free"))
361
+ reasons.push("free tier");
362
+ const estimated_tokens = features.length * 1.5;
363
+ const estimated_cost = (0, tokenUtils_1.estimateCost)(features.length, estimated_tokens, primary.name);
364
+ return {
365
+ primary_model: primary.name,
366
+ fallback_models: secondary.map(c => c.name),
367
+ confidence,
368
+ reasoning: `Selected ${primary.profile.providerName || primary.profile.provider}/${primary.name} for ${reasons.join(", ") || "general query"}`,
369
+ estimated_cost: estimated_cost * budget_multiplier,
370
+ estimated_latency_ms: primary.profile.latency_ms,
371
+ features,
372
+ provider_type: primary.profile.type,
373
+ };
374
+ }
375
+ // ============================================================
376
+ // BATCH ROUTING
377
+ // ============================================================
378
+ function routeBatch(prompts, options = {}) {
379
+ const decisions = prompts.map(p => routeQuery(p));
380
+ if (options.same_model && decisions.length > 0) {
381
+ const primary_model = decisions[0].primary_model;
382
+ decisions.forEach(d => {
383
+ d.primary_model = primary_model;
384
+ d.fallback_models = decisions[0].fallback_models;
385
+ });
386
+ }
387
+ if (options.max_cost_per_prompt !== undefined) {
388
+ const profiles = getModelProfiles();
389
+ decisions.forEach(d => {
390
+ if (d.estimated_cost > options.max_cost_per_prompt) {
391
+ const cheap = Object.entries(profiles)
392
+ .find(([name, p]) => p.cost_per_1k_input < 0.5);
393
+ if (cheap) {
394
+ d.primary_model = cheap[0];
395
+ d.reasoning = `Budget-limited routing to ${cheap[1].providerName || cheap[1].provider}`;
396
+ }
397
+ }
398
+ });
399
+ }
400
+ return decisions;
401
+ }
402
+ // ============================================================
403
+ // TASK RECOMMENDATIONS
404
+ // ============================================================
405
+ function recommendForTask(task) {
406
+ const features = extractQueryFeatures(task);
407
+ const decision = routeQuery(task);
408
+ return {
409
+ primary: decision.primary_model,
410
+ fallbacks: decision.fallback_models,
411
+ reason: decision.reasoning,
412
+ features,
413
+ };
414
+ }
415
+ // ============================================================
416
+ // ONLINE LEARNING - Update model profiles from feedback
417
+ // ============================================================
418
+ function updateModelProfile(model_name, actual_latency_ms, actual_cost, quality_rating) {
419
+ const profiles = getModelProfiles();
420
+ const profile = profiles[model_name];
421
+ if (!profile)
422
+ return;
423
+ const alpha = 0.2; // Learning rate
424
+ profile.latency_ms = profile.latency_ms * (1 - alpha) + actual_latency_ms * alpha;
425
+ profile.quality_score = profile.quality_score * (1 - alpha) + quality_rating * alpha;
426
+ }
427
+ // ============================================================
428
+ // PROVIDER HEALTH CHECK
429
+ // ============================================================
430
+ async function getProviderHealth() {
431
+ const { checkAllProviders } = require("../providers/providerConfig");
432
+ return checkAllProviders();
433
+ }
434
+ // ============================================================
435
+ // Default export
436
+ // ============================================================
437
+ module.exports = {
438
+ extractQueryFeatures,
439
+ routeQuery,
440
+ routeBatch,
441
+ recommendForTask,
442
+ updateModelProfile,
443
+ getProviderHealth,
444
+ MODEL_PROFILES: exports.MODEL_PROFILES,
445
+ invalidateProfileCache,
446
+ };
447
+ module.exports.default = module.exports;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Token counting utilities for provider cost estimation
3
+ */
4
+ export interface TokenCost {
5
+ input_per_1k: number;
6
+ output_per_1k: number;
7
+ }
8
+ export declare const MODEL_COSTS: Record<string, TokenCost>;
9
+ /**
10
+ * Count tokens in text (approximate for English).
11
+ * Based on ~1.3 tokens per word for typical English text.
12
+ */
13
+ export declare function countTokens(text: string, model?: string): number;
14
+ /**
15
+ * Alias for countTokens for backward compatibility.
16
+ */
17
+ export declare function estimateTokens(text: string): number;
18
+ /**
19
+ * Estimate cost for a prompt/completion pair.
20
+ */
21
+ export declare function estimateCost(prompt_tokens: number, completion_tokens: number, model: string): number;
22
+ /**
23
+ * Estimate cost from raw text (approximates both prompt and completion).
24
+ */
25
+ export declare function estimateCostFromText(prompt: string, completion: string, model: string): number;
26
+ /**
27
+ * Get cost info for a model.
28
+ */
29
+ export declare function getModelCost(model: string): TokenCost;
30
+ /**
31
+ * List all supported models with their costs.
32
+ */
33
+ export declare function listModelsByCost(): Array<{
34
+ model: string;
35
+ input: number;
36
+ output: number;
37
+ }>;
38
+ /**
39
+ * Find cheapest models for a given task.
40
+ */
41
+ export declare function findCheapestModels(task: "fast" | "quality" | "balanced" | "coding", count?: number): string[];
42
+ declare const _default: {
43
+ countTokens: typeof countTokens;
44
+ estimateTokens: typeof estimateTokens;
45
+ estimateCost: typeof estimateCost;
46
+ estimateCostFromText: typeof estimateCostFromText;
47
+ getModelCost: typeof getModelCost;
48
+ listModelsByCost: typeof listModelsByCost;
49
+ findCheapestModels: typeof findCheapestModels;
50
+ MODEL_COSTS: Record<string, TokenCost>;
51
+ };
52
+ export default _default;
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ /**
3
+ * Token counting utilities for provider cost estimation
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MODEL_COSTS = void 0;
7
+ exports.countTokens = countTokens;
8
+ exports.estimateTokens = estimateTokens;
9
+ exports.estimateCost = estimateCost;
10
+ exports.estimateCostFromText = estimateCostFromText;
11
+ exports.getModelCost = getModelCost;
12
+ exports.listModelsByCost = listModelsByCost;
13
+ exports.findCheapestModels = findCheapestModels;
14
+ // Current provider rates (2024-2025)
15
+ exports.MODEL_COSTS = {
16
+ // OpenAI
17
+ "gpt-4o": { input_per_1k: 2.50, output_per_1k: 10.00 },
18
+ "gpt-4o-mini": { input_per_1k: 0.15, output_per_1k: 0.60 },
19
+ "gpt-4-turbo": { input_per_1k: 10.00, output_per_1k: 30.00 },
20
+ "gpt-3.5-turbo": { input_per_1k: 0.50, output_per_1k: 1.50 },
21
+ // Anthropic
22
+ "claude-3.5-sonnet": { input_per_1k: 3.00, output_per_1k: 15.00 },
23
+ "claude-3-opus": { input_per_1k: 15.00, output_per_1k: 75.00 },
24
+ "claude-3-haiku": { input_per_1k: 0.25, output_per_1k: 1.25 },
25
+ // Google
26
+ "gemini-2.0-flash": { input_per_1k: 0.00, output_per_1k: 0.00 }, // Free
27
+ "gemini-1.5-pro": { input_per_1k: 1.25, output_per_1k: 5.00 },
28
+ "gemini-1.5-flash": { input_per_1k: 0.075, output_per_1k: 0.30 },
29
+ // Groq
30
+ "groq/llama-3.3-70b": { input_per_1k: 0.59, output_per_1k: 0.79 },
31
+ "groq/llama-3.1-8b": { input_per_1k: 0.05, output_per_1k: 0.08 },
32
+ // Cerebras
33
+ "cerebras/llama-3.3-70b": { input_per_1k: 0.60, output_per_1k: 0.60 },
34
+ // Mistral
35
+ "mistral-large": { input_per_1k: 2.00, output_per_1k: 6.00 },
36
+ "mistral-small": { input_per_1k: 0.20, output_per_1k: 0.60 },
37
+ };
38
+ /**
39
+ * Count tokens in text (approximate for English).
40
+ * Based on ~1.3 tokens per word for typical English text.
41
+ */
42
+ function countTokens(text, model = "gpt-4o") {
43
+ if (!text || text.length === 0)
44
+ return 0;
45
+ // Use model-specific approximation if available
46
+ // Otherwise use generic word-based estimate
47
+ const words = text.trim().split(/\s+/).length;
48
+ // Fine-tune based on model family
49
+ if (model.includes("claude")) {
50
+ // Anthropic models: ~1.5 tokens per word
51
+ return Math.ceil(words * 1.5);
52
+ }
53
+ else if (model.includes("gemini")) {
54
+ // Google: ~1.2 tokens per word (SentencePiece)
55
+ return Math.ceil(words * 1.2);
56
+ }
57
+ else if (model.includes("llama")) {
58
+ // Llama: ~1.4 tokens per word (BPE)
59
+ return Math.ceil(words * 1.4);
60
+ }
61
+ // Default: ~1.3 tokens per word (GPT-4 average)
62
+ return Math.ceil(words * 1.3);
63
+ }
64
+ /**
65
+ * Alias for countTokens for backward compatibility.
66
+ */
67
+ function estimateTokens(text) {
68
+ return countTokens(text);
69
+ }
70
+ /**
71
+ * Estimate cost for a prompt/completion pair.
72
+ */
73
+ function estimateCost(prompt_tokens, completion_tokens, model) {
74
+ const costs = exports.MODEL_COSTS[model] || exports.MODEL_COSTS["gpt-4o"];
75
+ const input_cost = (prompt_tokens / 1000) * costs.input_per_1k;
76
+ const output_cost = (completion_tokens / 1000) * costs.output_per_1k;
77
+ return input_cost + output_cost;
78
+ }
79
+ /**
80
+ * Estimate cost from raw text (approximates both prompt and completion).
81
+ */
82
+ function estimateCostFromText(prompt, completion, model) {
83
+ const prompt_tokens = countTokens(prompt, model);
84
+ // Completion typically has higher token density
85
+ const completion_tokens = Math.ceil(countTokens(completion, model) * 1.2);
86
+ return estimateCost(prompt_tokens, completion_tokens, model);
87
+ }
88
+ /**
89
+ * Get cost info for a model.
90
+ */
91
+ function getModelCost(model) {
92
+ return exports.MODEL_COSTS[model] || exports.MODEL_COSTS["gpt-4o"];
93
+ }
94
+ /**
95
+ * List all supported models with their costs.
96
+ */
97
+ function listModelsByCost() {
98
+ return Object.entries(exports.MODEL_COSTS)
99
+ .map(([model, cost]) => ({
100
+ model,
101
+ input: cost.input_per_1k,
102
+ output: cost.output_per_1k
103
+ }))
104
+ .sort((a, b) => (a.input + a.output) - (b.input + b.output));
105
+ }
106
+ /**
107
+ * Find cheapest models for a given task.
108
+ */
109
+ function findCheapestModels(task, count = 3) {
110
+ const sorted = listModelsByCost();
111
+ // Different profiles for different needs
112
+ const profiles = {
113
+ fast: sorted.filter(m => m.output < 1.0).slice(0, count).map(m => m.model),
114
+ quality: sorted.filter(m => m.output > 10).slice(0, count).map(m => m.model),
115
+ balanced: sorted.slice(0, count * 2).slice(count, count * 2).map(m => m.model),
116
+ coding: sorted.filter(m => m.model.includes("codex") || m.model.includes("claude") || m.model.includes("llama")).slice(0, count).map(m => m.model)
117
+ };
118
+ return profiles[task] || profiles.balanced;
119
+ }
120
+ exports.default = {
121
+ countTokens,
122
+ estimateTokens,
123
+ estimateCost,
124
+ estimateCostFromText,
125
+ getModelCost,
126
+ listModelsByCost,
127
+ findCheapestModels,
128
+ MODEL_COSTS: exports.MODEL_COSTS
129
+ };