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
@@ -1,463 +1,449 @@
1
1
  "use strict";
2
2
  /**
3
3
  * A3M Router - Generic Adaptive Routing (RouteLLM Style)
4
- *
4
+ *
5
5
  * Routes queries to the best available LLM based on:
6
6
  * - Query features (code, math, creative, etc.)
7
7
  * - Provider availability (checks API keys)
8
8
  * - Cost optimization
9
9
  * - Quality vs speed tradeoff
10
- *
10
+ *
11
11
  * All provider references are dynamically loaded from providerConfig.
12
12
  * Users can add/remove providers via environment variables or config files.
13
13
  */
14
-
15
- const { getAvailableProviders } = require("../providers/providerConfig");
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.MODEL_PROFILES = void 0;
16
+ exports.extractQueryFeatures = extractQueryFeatures;
17
+ exports.routeQuery = routeQuery;
18
+ exports.routeBatch = routeBatch;
19
+ exports.recommendForTask = recommendForTask;
20
+ exports.updateModelProfile = updateModelProfile;
21
+ exports.getProviderHealth = getProviderHealth;
22
+ const providerConfig_1 = require("../providers/providerConfig");
16
23
  const tokenUtils_1 = require("../utils/tokenUtils");
17
-
18
- // ============================================================
19
- // DYNAMIC MODEL PROFILES (built from available providers)
20
- // ============================================================
21
-
24
+ let cachedProfiles = null;
25
+ let cacheTimestamp = 0;
26
+ const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
22
27
  function buildModelProfiles() {
23
- const profiles = {};
24
- const available = getAvailableProviders();
25
-
26
- for (const [providerId, provider] of Object.entries(available)) {
27
- for (const model of provider.models) {
28
- const modelKey = model.includes('/') ? model : providerId + '/' + model;
29
- const costPerKInput = provider.costPerK ? provider.costPerK.input : 0;
30
- const costPerKOutput = provider.costPerK ? provider.costPerK.output : 0;
31
-
32
- // Assign strengths based on model characteristics
33
- const strengths = [];
34
- if (provider.type === 'cli') {
35
- strengths.push('free', 'local');
36
- }
37
- if (costPerKInput < 0.3) {
38
- strengths.push('budget', 'fast');
39
- } else if (costPerKInput > 2) {
40
- strengths.push('premium', 'reasoning');
41
- }
42
- if (provider.name === 'Mistral' || provider.name === 'Groq' || provider.name === 'Cerebras') {
43
- strengths.push('fast', 'coding');
44
- }
45
- if (provider.name === 'CommandCode') {
46
- strengths.push('code-aware', 'context-rich');
47
- }
48
- if (provider.name === 'OpenCode') {
49
- strengths.push('free', 'multi-model');
50
- }
51
- if (provider.name === 'Google') {
52
- strengths.push('multilingual', 'long-context');
53
- }
54
- if (provider.name === 'OpenAI') {
55
- strengths.push('reasoning', 'coding', 'analysis');
56
- }
57
- if (provider.name === 'Anthropic') {
58
- strengths.push('reasoning', 'creative', 'analysis');
59
- }
60
-
61
- profiles[modelKey] = {
62
- name: modelKey,
63
- provider: providerId,
64
- providerName: provider.name,
65
- cost_per_1k_input: costPerKInput,
66
- cost_per_1k_output: costPerKOutput,
67
- latency_ms: provider.type === 'cli' ? 5000 : (provider.priority * 200 + 300),
68
- quality_score: strengths.includes('premium') ? 0.95 :
69
- strengths.includes('reasoning') ? 0.90 :
70
- strengths.includes('fast') ? 0.82 : 0.80,
71
- strengths,
72
- context_window: provider.maxTokens || 8192,
73
- type: provider.type,
74
- priority: provider.priority,
75
- };
28
+ const profiles = {};
29
+ const available = (0, providerConfig_1.getAvailableProviders)();
30
+ for (const [providerId, provider] of Object.entries(available)) {
31
+ for (const model of provider.models) {
32
+ const modelKey = model.includes('/') ? model : providerId + '/' + model;
33
+ const costPerKInput = provider.costPerK ? provider.costPerK.input : 0;
34
+ const costPerKOutput = provider.costPerK ? provider.costPerK.output : 0;
35
+ // Assign strengths based on model characteristics
36
+ const strengths = [];
37
+ if (provider.type === 'cli') {
38
+ strengths.push('free', 'local');
39
+ }
40
+ if (costPerKInput < 0.3) {
41
+ strengths.push('budget', 'fast');
42
+ }
43
+ else if (costPerKInput > 2) {
44
+ strengths.push('premium', 'reasoning');
45
+ }
46
+ if (provider.name === 'Mistral' || provider.name === 'Groq' || provider.name === 'Cerebras') {
47
+ strengths.push('fast', 'coding');
48
+ }
49
+ if (provider.name === 'CommandCode') {
50
+ strengths.push('code-aware', 'context-rich');
51
+ }
52
+ if (provider.name === 'OpenCode') {
53
+ strengths.push('free', 'multi-model');
54
+ }
55
+ if (provider.name === 'Google') {
56
+ strengths.push('multilingual', 'long-context');
57
+ }
58
+ if (provider.name === 'OpenAI') {
59
+ strengths.push('reasoning', 'coding', 'analysis');
60
+ }
61
+ if (provider.name === 'Anthropic') {
62
+ strengths.push('reasoning', 'creative', 'analysis');
63
+ }
64
+ profiles[modelKey] = {
65
+ name: modelKey,
66
+ provider: providerId,
67
+ providerName: provider.name,
68
+ cost_per_1k_input: costPerKInput,
69
+ cost_per_1k_output: costPerKOutput,
70
+ latency_ms: provider.type === 'cli' ? 5000 : (provider.priority * 200 + 300),
71
+ quality_score: strengths.includes('premium') ? 0.95 :
72
+ strengths.includes('reasoning') ? 0.90 :
73
+ strengths.includes('fast') ? 0.82 : 0.80,
74
+ strengths,
75
+ context_window: provider.maxTokens || 8192,
76
+ type: provider.type,
77
+ priority: provider.priority,
78
+ };
79
+ }
76
80
  }
77
- }
78
-
79
- return profiles;
81
+ return profiles;
80
82
  }
81
-
82
- var MODEL_PROFILES = {};
83
- try {
84
- MODEL_PROFILES = buildModelProfiles();
85
- } catch (e) {
86
- // Circular dependency at module load — will retry on first use
87
- MODEL_PROFILES = {};
83
+ // Lazy cache with TTL - replaces refreshModelProfiles()
84
+ function getModelProfiles() {
85
+ const now = Date.now();
86
+ if (!cachedProfiles || (now - cacheTimestamp) > CACHE_TTL_MS) {
87
+ cachedProfiles = buildModelProfiles();
88
+ cacheTimestamp = now;
89
+ }
90
+ return cachedProfiles;
88
91
  }
89
-
90
- // Refresh profiles when providers change
91
- function refreshModelProfiles() {
92
- MODEL_PROFILES = buildModelProfiles();
92
+ // Manual cache invalidation (call if provider config changes)
93
+ function invalidateProfileCache() {
94
+ cachedProfiles = null;
95
+ cacheTimestamp = 0;
93
96
  }
94
-
95
- exports.MODEL_PROFILES = MODEL_PROFILES;
96
-
97
- // Ensure exports stay in sync if profiles are rebuilt
98
- function updateExports() {
99
- exports.MODEL_PROFILES = MODEL_PROFILES;
97
+ exports.MODEL_PROFILES = {};
98
+ try {
99
+ exports.MODEL_PROFILES = buildModelProfiles();
100
+ }
101
+ catch (e) {
102
+ // Circular dependency at module load — will retry on first use
103
+ exports.MODEL_PROFILES = {};
100
104
  }
101
- // ============================================================
102
- // FEATURE EXTRACTION (v3 — multi-signal complexity scorer)
103
- // ============================================================
104
-
105
105
  function extractQueryFeatures(prompt) {
106
- const lower = prompt.toLowerCase();
107
- const words = prompt.split(/\s+/);
108
- const wordCount = words.length;
109
-
110
- // === SIGNAL 1: Domain Detection ===
111
- // Professional domains that indicate expert-level queries
112
- const domainSignals = {
113
- legal: {
114
- keywords: ['legal', 'law', 'contract', 'liability', 'litigation', 'patent', 'copyright',
115
- 'regulation', 'compliance', 'constitutional', 'statute', 'jurisdiction',
116
- 'court', 'ruling', 'precedent', 'attorney', 'amicus', 'sec ', 'fda ',
117
- 'gdpr', 'ccpa', 'cfpr', 'due diligence', 'merger', 'acquisition',
118
- '10-k', 'sec filing', 'forensic', 'embezzlement', 'infringement'],
119
- weight: 0.35
120
- },
121
- medical: {
122
- keywords: ['clinical', 'medical', 'pharmaceutical', 'oncology', 'drug', 'trial protocol',
123
- 'diagnosis', 'treatment', 'epidemiolog', 'genome', 'cohort study',
124
- 'biomarker', 'efficacy', 'pharmacoeconomic', 'biologic', 'vaccine',
125
- 'sepsis', 'ehr ', 'surgical', 'patient safety', 'fda approval'],
126
- weight: 0.35
127
- },
128
- finance: {
129
- keywords: ['financial model', 'valuation', 'revenue', 'portfolio', 'derivative',
130
- 'hedge fund', 'series a', 'series b', 'startup valuation', 'sensitivity analysis',
131
- 'investment thesis', 'earnings', 'tax optimization', 'forensic accounting',
132
- 'multinational', 'jurisdiction', 'risk assessment', 'monte carlo',
133
- 'black-scholes', 'options pricing', 'credit risk'],
134
- weight: 0.30
135
- },
136
- security: {
137
- keywords: ['security audit', 'penetration', 'vulnerability', 'exploit', 'zero-trust',
138
- 'threat model', 'incident response', 'malware', 'ransomware',
139
- 'authentication flow', 'cryptograph', 'encryption', 'timing attack',
140
- 'supply chain attack', 'owasp', 'compliance', 'risk assessment',
141
- 'mfa', 'zero-day', 'firewall', 'intrusion'],
142
- weight: 0.30
143
- },
144
- architecture: {
145
- keywords: ['system design', 'microservice', 'distributed system', 'fault-tolerant',
146
- 'event-sourced', 'cqrs', 'consensus algorithm', 'real-time pipeline',
147
- 'high availability', 'multi-region', 'latency sla', 'kafka',
148
- 'event-driven', 'data warehouse', 'etl', 'streaming', '1m events',
149
- 'million events', 'scalab', 'infrastruct', 'deploy'],
150
- weight: 0.25
151
- },
152
- ml_research: {
153
- keywords: ['neural network', 'transformer', 'backpropagation', 'gradient',
154
- 'reinforcement learning', 'rlhf', 'fine-tun', 'bert ', 'gpt ',
155
- 'attention mechanism', 'training pipeline', 'model monitoring',
156
- 'data drift', 'feature engine', 'deep learn', 'benchmark',
157
- 'ablation', 'sota', 'state of the art', 'paper', 'arxiv'],
158
- weight: 0.25
106
+ const lower = prompt.toLowerCase();
107
+ const words = prompt.split(/\s+/);
108
+ const wordCount = words.length;
109
+ // === SIGNAL 1: Domain Detection ===
110
+ const domainSignals = {
111
+ legal: {
112
+ keywords: ['legal', 'law', 'contract', 'liability', 'litigation', 'patent', 'copyright',
113
+ 'regulation', 'compliance', 'constitutional', 'statute', 'jurisdiction',
114
+ 'court', 'ruling', 'precedent', 'attorney', 'amicus', 'sec ', 'fda ',
115
+ 'gdpr', 'ccpa', 'cfpr', 'due diligence', 'merger', 'acquisition',
116
+ '10-k', 'sec filing', 'forensic', 'embezzlement', 'infringement'],
117
+ weight: 0.35
118
+ },
119
+ medical: {
120
+ keywords: ['clinical', 'medical', 'pharmaceutical', 'oncology', 'drug', 'trial protocol',
121
+ 'diagnosis', 'treatment', 'epidemiolog', 'genome', 'cohort study',
122
+ 'biomarker', 'efficacy', 'pharmacoeconomic', 'biologic', 'vaccine',
123
+ 'sepsis', 'ehr ', 'surgical', 'patient safety', 'fda approval'],
124
+ weight: 0.35
125
+ },
126
+ finance: {
127
+ keywords: ['financial model', 'valuation', 'revenue', 'portfolio', 'derivative',
128
+ 'hedge fund', 'series a', 'series b', 'startup valuation', 'sensitivity analysis',
129
+ 'investment thesis', 'earnings', 'tax optimization', 'forensic accounting',
130
+ 'multinational', 'jurisdiction', 'risk assessment', 'monte carlo',
131
+ 'black-scholes', 'options pricing', 'credit risk'],
132
+ weight: 0.30
133
+ },
134
+ security: {
135
+ keywords: ['security audit', 'penetration', 'vulnerability', 'exploit', 'zero-trust',
136
+ 'threat model', 'incident response', 'malware', 'ransomware',
137
+ 'authentication flow', 'cryptograph', 'encryption', 'timing attack',
138
+ 'supply chain attack', 'owasp', 'compliance', 'risk assessment',
139
+ 'mfa', 'zero-day', 'firewall', 'intrusion'],
140
+ weight: 0.30
141
+ },
142
+ architecture: {
143
+ keywords: ['system design', 'microservice', 'distributed system', 'fault-tolerant',
144
+ 'event-sourced', 'cqrs', 'consensus algorithm', 'real-time pipeline',
145
+ 'high availability', 'multi-region', 'latency sla', 'kafka',
146
+ 'event-driven', 'data warehouse', 'etl', 'streaming', '1m events',
147
+ 'million events', 'scalab', 'infrastruct', 'deploy'],
148
+ weight: 0.25
149
+ },
150
+ data_science: {
151
+ keywords: ['machine learning', 'deep learning', 'neural network', 'transformer',
152
+ 'training data', 'model accuracy', 'hyperparameter', 'cross-validation',
153
+ 'feature engineering', 'data pipeline', 'pandas', 'numpy', 'scikit',
154
+ 'tensorflow', 'pytorch', 'regression', 'classification', 'clustering'],
155
+ weight: 0.30
156
+ },
157
+ };
158
+ let detectedDomain = null;
159
+ let maxDomainScore = 0;
160
+ for (const [domain, signal] of Object.entries(domainSignals)) {
161
+ let domainScore = 0;
162
+ for (const kw of signal.keywords) {
163
+ if (lower.includes(kw)) {
164
+ domainScore += signal.weight;
165
+ }
166
+ }
167
+ if (domainScore > maxDomainScore) {
168
+ maxDomainScore = domainScore;
169
+ detectedDomain = domain;
170
+ }
171
+ }
172
+ // === SIGNAL 2: Code Detection ===
173
+ const codeSignals = [
174
+ 'function ', 'def ', 'class ', 'import ', 'from ', 'const ', 'let ', 'var ',
175
+ '=>', '->', 'async ', 'await ', 'return ', 'if (', 'for (', 'while (',
176
+ 'public ', 'private ', 'protected ', 'static ', 'void ', 'int ', 'string ',
177
+ '#include', 'std::', 'cout', 'cin', 'printf(', 'println!',
178
+ 'fn ', 'impl ', 'pub ', 'mut ', 'struct ', 'enum ',
179
+ '```', 'code', 'python', 'javascript', 'typescript', 'java', 'cpp', 'ruby',
180
+ 'write a', 'create a', 'implement', 'algorithm'
181
+ ];
182
+ const hasCode = codeSignals.some(sig => lower.includes(sig));
183
+ // === SIGNAL 3: Reasoning Detection ===
184
+ const reasoningSignals = [
185
+ 'why', 'how', 'explain', 'analyze', 'compare', 'contrast', 'evaluate',
186
+ 'think about', 'reason', 'logic', 'proof', 'derive', '证明', '分析',
187
+ 'reasoning', 'step by step', 'thinking', 'thought process'
188
+ ];
189
+ const requiresReasoning = reasoningSignals.some(sig => lower.includes(sig));
190
+ // === SIGNAL 4: Language Detection ===
191
+ const languagePatterns = [
192
+ [/[\u4e00-\u9fff]/, 'zh'],
193
+ [/[\u0900-\u097f]/, 'hi'],
194
+ [/[\u0600-\u06ff]/, 'ar'],
195
+ [/[\u0400-\u04ff]/, 'ru'],
196
+ [/[\u0900-\u097f]/, 'hi-latn'],
197
+ [/বাংলা|করুন|হিন্দি|ভারত|ভারতীয়/, 'bn'],
198
+ ];
199
+ let detectedLanguage = null;
200
+ for (const [pattern, lang] of languagePatterns) {
201
+ if (pattern.test(prompt)) {
202
+ detectedLanguage = lang;
203
+ break;
204
+ }
159
205
  }
160
- };
161
-
162
- let domainScore = 0;
163
- let detectedDomain = '';
164
- for (const [domain, config] of Object.entries(domainSignals)) {
165
- const matchCount = config.keywords.filter(kw => lower.includes(kw)).length;
166
- if (matchCount > 0) {
167
- const score = config.weight * Math.min(matchCount / 2, 1.5); // cap at 1.5x
168
- if (score > domainScore) {
169
- domainScore = score;
170
- detectedDomain = domain;
171
- }
206
+ // Translation detection
207
+ const translationSignals = ['translate', 'translation', 'into english', 'to english',
208
+ 'traducir', 'traduction', 'traduzione', 'übersetzen'];
209
+ const isTranslation = translationSignals.some(sig => lower.includes(sig)) ||
210
+ /to (english|french|german|spanish|chinese|japanese|korean)/i.test(prompt);
211
+ const isMultilingual = detectedLanguage !== null || isTranslation;
212
+ // === SIGNAL 5: Intent Classification ===
213
+ let intent = 'general';
214
+ if (hasCode)
215
+ intent = 'code';
216
+ else if (isTranslation)
217
+ intent = 'translation';
218
+ else if (lower.includes('write') || lower.includes('create') || lower.includes('generate')) {
219
+ intent = 'creative';
172
220
  }
173
- }
174
-
175
- // === SIGNAL 2: Task Complexity Indicators ===
176
- const has_code = /function|class |def |import |const |let |python|javascript|typescript|java |cpp|rust|```|=>|->|async|await|sql|css|html|react|node|express|docker|kubernetes/i.test(prompt);
177
- const has_math = /equation|formula|calculate|sqrt|\^|log|sin|cos|integral|derivative|math|∫|∂|∑|∏|√|∞|π|compute|theorem|proof|complexity|algorithm/i.test(prompt);
178
- const requires_reasoning = /analyze|compare|contrast|evaluate|assess|implications|impact|consequence|why|because|therefore|reason|logic|argue|debate|critique|synthesize/i.test(prompt);
179
- const is_creative = /write a|story|poem|creative|imagine|narrative|joke|compose|fiction/i.test(lower);
180
- const is_translation = /translate|translation|in french|in spanish|in japanese|in chinese/i.test(lower);
181
- const is_multilingual = /[\u4e00-\u9fff]|[\u3040-\u309f\u30a0-\u30ff]|[\uac00-\ud7af]|[а-яА-Я]/.test(prompt);
182
-
183
- // === SIGNAL 3: Query Structure ===
184
- // Longer, more structured queries = more complex
185
- const avgWordLength = words.reduce((sum, w) => sum + w.length, 0) / Math.max(wordCount, 1);
186
- const hasMultipleClauses = (prompt.match(/[,;:]/g) || []).length >= 2;
187
- const hasQualifiers = /detailed|comprehensive|thorough|in-depth|extensive|step-by-step|systematic|formal|rigorous/i.test(prompt);
188
-
189
- // === SIGNAL 4: Action Verb Intensity ===
190
- // Expert verbs indicate higher cognitive demands
191
- const expertVerbs = /design|architect|review|audit|investigate|diagnose|optimize|strategize|formulate|derive|prove|verify|validate/i;
192
- const midVerbs = /analyze|evaluate|compare|assess|implement|create|build|develop|construct|derive|explain/i;
193
- const simpleVerbs = /what is|who|when|where|how many|define|list|name|convert|translate|summarize briefly/i;
194
-
195
- let verbScore = 0;
196
- if (expertVerbs.test(lower)) verbScore = 0.20;
197
- else if (midVerbs.test(lower)) verbScore = 0.10;
198
- if (simpleVerbs.test(lower)) verbScore = -0.10; // deboost simple questions
199
-
200
- // === SIGNAL 5: Specificity ===
201
- // Specific details = more complex
202
- const hasSpecifics = /\d+%|\$\d+|million|billion|specific|particular|given|according to|based on/i.test(prompt);
203
- const hasMultiStep = /and then|first.*then|after that|next|finally|additionally|furthermore|moreover/i.test(prompt);
204
-
205
- // === COMPLEXITY SCORING (weighted multi-signal) ===
206
- let complexity = 0.15; // Base: simple query
207
-
208
- // Domain signal (strongest predictor)
209
- complexity += domainScore;
210
-
211
- // Length signal (longer = harder, but diminishing)
212
- if (wordCount > 5) complexity += 0.03;
213
- if (wordCount > 10) complexity += 0.05;
214
- if (wordCount > 15) complexity += 0.05;
215
- if (wordCount > 20) complexity += 0.03;
216
-
217
- // Feature signals
218
- if (has_code) complexity += 0.10;
219
- if (has_math) complexity += 0.12;
220
- if (requires_reasoning) complexity += 0.08;
221
- if (is_creative) complexity += 0.05;
222
- if (is_translation) complexity += 0.02;
223
-
224
- // Structure signals
225
- if (hasQualifiers) complexity += 0.08;
226
- if (hasMultipleClauses) complexity += 0.05;
227
- if (hasSpecifics) complexity += 0.05;
228
- if (hasMultiStep) complexity += 0.05;
229
-
230
- // Verb intensity
231
- complexity += verbScore;
232
-
233
- // Long words = technical language
234
- if (avgWordLength > 6) complexity += 0.05;
235
- if (avgWordLength > 8) complexity += 0.05;
236
-
237
- complexity = Math.max(0.10, Math.min(1.0, complexity));
238
-
239
- return {
240
- complexity,
241
- length: wordCount,
242
- has_code,
243
- has_math,
244
- is_multilingual,
245
- is_translation,
246
- is_creative,
247
- requires_reasoning,
248
- is_security: /security|vulnerability|inject|exploit|attack|encryption|auth/i.test(lower),
249
- is_devops: /ci\/cd|docker|kubernetes|k8s|deploy|pipeline|github action|terraform/i.test(lower),
250
- is_data: /dataset|pandas|numpy|training|model|neural|transformer|bert|llm/i.test(lower),
251
- detected_domain: detectedDomain,
252
- domain_score: domainScore,
253
- };
221
+ else if (lower.includes('explain') || lower.includes('what is') || lower.includes('how does')) {
222
+ intent = 'explanation';
223
+ }
224
+ else if (lower.includes('calculate') || lower.includes('compute') || lower.includes('integral')) {
225
+ intent = 'math';
226
+ }
227
+ // === COMPLEXITY SCORING ===
228
+ // Base complexity from length
229
+ let complexity = Math.min(wordCount / 100, 1.0);
230
+ // Domain加成
231
+ if (detectedDomain)
232
+ complexity += 0.2;
233
+ // Code加成
234
+ if (hasCode)
235
+ complexity += 0.15;
236
+ // Reasoning加成
237
+ if (requiresReasoning)
238
+ complexity += 0.15;
239
+ // Multilingual加成
240
+ if (isMultilingual)
241
+ complexity += 0.1;
242
+ // Cap at 1.0
243
+ complexity = Math.min(complexity, 1.0);
244
+ return {
245
+ length: prompt.length,
246
+ wordCount,
247
+ complexity,
248
+ has_code: hasCode,
249
+ requires_reasoning: requiresReasoning,
250
+ is_multilingual: isMultilingual,
251
+ is_translation: isTranslation,
252
+ domain: detectedDomain,
253
+ intent,
254
+ detected_language: detectedLanguage,
255
+ };
254
256
  }
255
-
256
- exports.extractQueryFeatures = extractQueryFeatures;
257
-
258
- // ============================================================
259
- // SCORING FUNCTIONS
260
- // ============================================================
261
-
262
257
  function scoreModelFit(model, features) {
263
- let score = model.quality_score * 0.4; // Base quality
264
-
265
- if (features.has_code && model.strengths.includes("coding")) score += 0.2;
266
- if (features.requires_reasoning && model.strengths.includes("reasoning")) score += 0.2;
267
- if (features.is_creative && model.strengths.includes("creative")) score += 0.15;
268
- if (features.is_multilingual && model.strengths.includes("multilingual")) score += 0.15;
269
- if (features.has_math && model.strengths.includes("analysis")) score += 0.15;
270
- if (features.is_security && model.strengths.includes("reasoning")) score += 0.1;
271
- if (features.is_data && model.strengths.includes("analysis")) score += 0.1;
272
-
273
- // Free/local providers bonus for simple tasks
274
- if (features.complexity < 0.4 && model.strengths.includes("free")) score += 0.15;
275
- if (features.complexity < 0.4 && model.latency_ms < 1000) score += 0.1;
276
-
277
- // Code-aware providers for code tasks
278
- if (features.has_code && model.strengths.includes("code-aware")) score += 0.2;
279
-
280
- return score;
258
+ let score = model.quality_score * 0.6;
259
+ // Domain match
260
+ if (features.domain) {
261
+ const domainBonus = {
262
+ code: ['code-aware', 'coding', 'fast'],
263
+ medical: ['reasoning', 'analysis'],
264
+ legal: ['reasoning', 'analysis', 'context-rich'],
265
+ finance: ['analysis', 'reasoning'],
266
+ security: ['reasoning', 'analysis'],
267
+ architecture: ['context-rich', 'long-context'],
268
+ data_science: ['coding', 'fast', 'reasoning'],
269
+ };
270
+ const bonuses = domainBonus[features.domain] || [];
271
+ if (bonuses.some(b => model.strengths.includes(b))) {
272
+ score += 0.2;
273
+ }
274
+ }
275
+ // Code bonus
276
+ if (features.has_code && model.strengths.includes('coding')) {
277
+ score += 0.15;
278
+ }
279
+ // Multilingual bonus
280
+ if (features.is_multilingual && model.strengths.includes('multilingual')) {
281
+ score += 0.15;
282
+ }
283
+ // Free tier preference for simple queries
284
+ if (features.complexity < 0.5 && model.strengths.includes('free')) {
285
+ score += 0.2;
286
+ }
287
+ // Fast provider for simple queries
288
+ if (features.complexity < 0.4 && model.strengths.includes('fast')) {
289
+ score += 0.15;
290
+ }
291
+ // Premium for complex queries
292
+ if (features.complexity > 0.6 && model.strengths.includes('premium')) {
293
+ score += 0.15;
294
+ }
295
+ return Math.min(score, 1.0);
281
296
  }
282
-
283
297
  function costEfficiency(model, features) {
284
- const avg_cost = (model.cost_per_1k_input + model.cost_per_1k_output) / 2;
285
- if (features.complexity < 0.5) {
286
- return (1 - Math.min(avg_cost / 10, 1)) * 0.6;
287
- }
288
- return (1 - Math.min(avg_cost / 10, 1)) * 0.2;
298
+ const avg_cost = (model.cost_per_1k_input + model.cost_per_1k_output) / 2;
299
+ if (features.complexity < 0.5) {
300
+ return (1 - Math.min(avg_cost / 10, 1)) * 0.6;
301
+ }
302
+ return (1 - Math.min(avg_cost / 10, 1)) * 0.2;
289
303
  }
290
-
291
- // ============================================================
292
- // ROUTING
293
- // ============================================================
294
-
295
304
  function routeQuery(prompt, available_models, budget_multiplier = 1.0) {
296
- // Refresh profiles to ensure we have latest provider config
297
- refreshModelProfiles();
298
-
299
- const features = extractQueryFeatures(prompt);
300
- const candidate_names = available_models || Object.keys(MODEL_PROFILES);
301
-
302
- // Filter to available models
303
- const candidates = candidate_names
304
- .filter(name => MODEL_PROFILES[name])
305
- .map(name => {
306
- const profile = MODEL_PROFILES[name];
307
- const quality = scoreModelFit(profile, features);
308
- const cost = costEfficiency(profile, features);
309
- return {
310
- name,
311
- profile,
312
- quality_score: quality,
313
- cost_score: cost,
314
- total_score: quality + cost
315
- };
305
+ // Use cached profiles instead of rebuilding every time (5-10ms savings)
306
+ const profiles = getModelProfiles();
307
+ const features = extractQueryFeatures(prompt);
308
+ const candidate_names = available_models || Object.keys(profiles);
309
+ // Filter to available models
310
+ const candidates = candidate_names
311
+ .filter(name => profiles[name])
312
+ .map(name => {
313
+ const profile = profiles[name];
314
+ const quality = scoreModelFit(profile, features);
315
+ const cost = costEfficiency(profile, features);
316
+ return {
317
+ name,
318
+ profile,
319
+ quality_score: quality,
320
+ cost_score: cost,
321
+ total_score: quality + cost
322
+ };
323
+ });
324
+ if (candidates.length === 0) {
325
+ return {
326
+ primary_model: null,
327
+ fallback_models: [],
328
+ confidence: 0,
329
+ reasoning: "No providers available - configure API keys in ~/.config/a3m-router/providers.json",
330
+ estimated_cost: 0,
331
+ estimated_latency_ms: 0,
332
+ };
333
+ }
334
+ // Sort by total score (quality vs cost tradeoff based on complexity)
335
+ const complexity_bias = features.complexity > 0.6 ? 0.7 : 0.3;
336
+ candidates.sort((a, b) => {
337
+ const score_a = a.quality_score * complexity_bias + a.cost_score * (1 - complexity_bias);
338
+ const score_b = b.quality_score * complexity_bias + b.cost_score * (1 - complexity_bias);
339
+ return score_b - score_a;
316
340
  });
317
-
318
- if (candidates.length === 0) {
341
+ const primary = candidates[0];
342
+ const secondary = candidates.slice(1, 3);
343
+ // Calculate confidence based on score gap
344
+ let confidence = 0.5;
345
+ if (candidates.length > 1) {
346
+ const gap = primary.total_score - candidates[1].total_score;
347
+ confidence = Math.min(0.95, 0.5 + gap * 2);
348
+ }
349
+ // Build reasoning
350
+ const reasons = [];
351
+ if (features.has_code)
352
+ reasons.push("code detected");
353
+ if (features.requires_reasoning)
354
+ reasons.push("reasoning needed");
355
+ if (features.complexity > 0.6)
356
+ reasons.push("high complexity");
357
+ if (features.is_multilingual)
358
+ reasons.push("multilingual");
359
+ if (features.is_translation)
360
+ reasons.push("translation");
361
+ if (primary.profile.strengths.includes("free"))
362
+ reasons.push("free tier");
363
+ const estimated_tokens = features.length * 1.5;
364
+ const estimated_cost = (0, tokenUtils_1.estimateCost)(features.length, estimated_tokens, primary.name);
319
365
  return {
320
- primary_model: null,
321
- fallback_models: [],
322
- confidence: 0,
323
- reasoning: "No providers available - configure API keys in ~/.config/a3m-router/providers.json",
324
- estimated_cost: 0,
325
- estimated_latency_ms: 0,
366
+ primary_model: primary.name,
367
+ fallback_models: secondary.map(c => c.name),
368
+ confidence,
369
+ reasoning: `Selected ${primary.profile.providerName || primary.profile.provider}/${primary.name} for ${reasons.join(", ") || "general query"}`,
370
+ estimated_cost: estimated_cost * budget_multiplier,
371
+ estimated_latency_ms: primary.profile.latency_ms,
372
+ features,
373
+ provider_type: primary.profile.type,
326
374
  };
327
- }
328
-
329
- // Sort by total score (quality vs cost tradeoff based on complexity)
330
- const complexity_bias = features.complexity > 0.6 ? 0.7 : 0.3;
331
- candidates.sort((a, b) => {
332
- const score_a = a.quality_score * complexity_bias + a.cost_score * (1 - complexity_bias);
333
- const score_b = b.quality_score * complexity_bias + b.cost_score * (1 - complexity_bias);
334
- return score_b - score_a;
335
- });
336
-
337
- const primary = candidates[0];
338
- const secondary = candidates.slice(1, 3);
339
-
340
- // Calculate confidence based on score gap
341
- let confidence = 0.5;
342
- if (candidates.length > 1) {
343
- const gap = primary.total_score - candidates[1].total_score;
344
- confidence = Math.min(0.95, 0.5 + gap * 2);
345
- }
346
-
347
- // Build reasoning
348
- const reasons = [];
349
- if (features.has_code) reasons.push("code detected");
350
- if (features.requires_reasoning) reasons.push("reasoning needed");
351
- if (features.complexity > 0.6) reasons.push("high complexity");
352
- if (features.is_multilingual) reasons.push("multilingual");
353
- if (features.is_translation) reasons.push("translation");
354
- if (primary.profile.strengths.includes("free")) reasons.push("free tier");
355
-
356
- const estimated_tokens = features.length * 1.5;
357
- const estimated_cost = tokenUtils_1.estimateCost(features.length, estimated_tokens, primary.name);
358
-
359
- return {
360
- primary_model: primary.name,
361
- fallback_models: secondary.map(c => c.name),
362
- confidence,
363
- reasoning: `Selected ${primary.profile.providerName || primary.profile.provider}/${primary.name} for ${reasons.join(", ") || "general query"}`,
364
- estimated_cost: estimated_cost * budget_multiplier,
365
- estimated_latency_ms: primary.profile.latency_ms,
366
- features,
367
- provider_type: primary.profile.type,
368
- };
369
375
  }
370
-
371
- exports.routeQuery = routeQuery;
372
-
373
376
  // ============================================================
374
377
  // BATCH ROUTING
375
378
  // ============================================================
376
-
377
379
  function routeBatch(prompts, options = {}) {
378
- const decisions = prompts.map(p => routeQuery(p));
379
-
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
-
388
- if (options.max_cost_per_prompt) {
389
- decisions.forEach(d => {
390
- if (d.estimated_cost > options.max_cost_per_prompt) {
391
- const cheap = Object.entries(MODEL_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
-
401
- return decisions;
380
+ const decisions = prompts.map(p => routeQuery(p));
381
+ if (options.same_model && decisions.length > 0) {
382
+ const primary_model = decisions[0].primary_model;
383
+ decisions.forEach(d => {
384
+ d.primary_model = primary_model;
385
+ d.fallback_models = decisions[0].fallback_models;
386
+ });
387
+ }
388
+ if (options.max_cost_per_prompt !== undefined) {
389
+ const profiles = getModelProfiles();
390
+ decisions.forEach(d => {
391
+ if (d.estimated_cost > options.max_cost_per_prompt) {
392
+ const cheap = Object.entries(profiles)
393
+ .find(([name, p]) => p.cost_per_1k_input < 0.5);
394
+ if (cheap) {
395
+ d.primary_model = cheap[0];
396
+ d.reasoning = `Budget-limited routing to ${cheap[1].providerName || cheap[1].provider}`;
397
+ }
398
+ }
399
+ });
400
+ }
401
+ return decisions;
402
402
  }
403
-
404
- exports.routeBatch = routeBatch;
405
-
406
403
  // ============================================================
407
404
  // TASK RECOMMENDATIONS
408
405
  // ============================================================
409
-
410
406
  function recommendForTask(task) {
411
- refreshModelProfiles();
412
- const features = extractQueryFeatures(task);
413
- const decision = routeQuery(task);
414
- return {
415
- primary: decision.primary_model,
416
- fallbacks: decision.fallback_models,
417
- reason: decision.reasoning,
418
- features,
419
- };
407
+ const features = extractQueryFeatures(task);
408
+ const decision = routeQuery(task);
409
+ return {
410
+ primary: decision.primary_model,
411
+ fallbacks: decision.fallback_models,
412
+ reason: decision.reasoning,
413
+ features,
414
+ };
420
415
  }
421
-
422
- exports.recommendForTask = recommendForTask;
423
-
424
416
  // ============================================================
425
417
  // ONLINE LEARNING - Update model profiles from feedback
426
418
  // ============================================================
427
-
428
419
  function updateModelProfile(model_name, actual_latency_ms, actual_cost, quality_rating) {
429
- refreshModelProfiles();
430
- const profile = MODEL_PROFILES[model_name];
431
- if (!profile) return;
432
-
433
- const alpha = 0.2; // Learning rate
434
- profile.latency_ms = profile.latency_ms * (1 - alpha) + actual_latency_ms * alpha;
435
- profile.quality_score = profile.quality_score * (1 - alpha) + quality_rating * alpha;
420
+ const profiles = getModelProfiles();
421
+ const profile = profiles[model_name];
422
+ if (!profile)
423
+ return;
424
+ const alpha = 0.2; // Learning rate
425
+ profile.latency_ms = profile.latency_ms * (1 - alpha) + actual_latency_ms * alpha;
426
+ profile.quality_score = profile.quality_score * (1 - alpha) + quality_rating * alpha;
436
427
  }
437
-
438
- exports.updateModelProfile = updateModelProfile;
439
-
440
428
  // ============================================================
441
429
  // PROVIDER HEALTH CHECK
442
430
  // ============================================================
443
-
444
431
  async function getProviderHealth() {
445
- const { checkAllProviders } = require("../providers/providerConfig");
446
- return checkAllProviders();
432
+ const { checkAllProviders } = require("../providers/providerConfig");
433
+ return checkAllProviders();
447
434
  }
448
-
449
- exports.getProviderHealth = getProviderHealth;
450
-
451
435
  // ============================================================
452
436
  // Default export
453
437
  // ============================================================
454
-
455
- exports.default = {
456
- extractQueryFeatures,
457
- routeQuery,
458
- routeBatch,
459
- recommendForTask,
460
- updateModelProfile,
461
- getProviderHealth,
462
- MODEL_PROFILES,
438
+ module.exports = {
439
+ extractQueryFeatures,
440
+ routeQuery,
441
+ routeBatch,
442
+ recommendForTask,
443
+ updateModelProfile,
444
+ getProviderHealth,
445
+ MODEL_PROFILES: exports.MODEL_PROFILES,
446
+ invalidateProfileCache,
463
447
  };
448
+ module.exports.default = module.exports;
449
+ //# sourceMappingURL=advancedRouter.js.map