adaptive-memory-multi-model-router 2.14.17 → 2.14.19
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/AGENT_COUNCIL_FINDINGS.md +142 -0
- package/LAUNCH_CHECKLIST.md +141 -0
- package/README.md.bak +836 -0
- package/articles/CHINESE_SUBMISSIONS_READY.md +322 -0
- package/articles/DEVTO_READY.md +255 -0
- package/articles/HN_POST_READY.md +137 -0
- package/articles/INDIEHACKERS_READY.md +120 -0
- package/articles/NEWSLETTER_SEND_NOW.md +259 -0
- package/articles/PRODUCTHUNT_READY.md +106 -0
- package/articles/REDDIT_SUBMISSION_READY.md +348 -0
- package/articles/TWEET_STORM_READY.md +165 -0
- package/benchmark-results.json +24 -24
- package/council-votes/architecture-vote.md +121 -0
- package/council-votes/coverage-vote.md +93 -0
- package/dist/cost/costTracker.d.ts +109 -44
- package/dist/cost/costTracker.js +321 -98
- package/dist/cost/costTracker.js.map +1 -1
- package/dist/index.d.ts +6 -4
- package/dist/routing/advancedRouter.d.ts +38 -43
- package/dist/routing/advancedRouter.js +396 -408
- package/dist/routing/advancedRouter.js.map +1 -1
- package/dist/routing/providers/providerConfig.d.ts +49 -0
- package/dist/routing/providers/providerConfig.js +883 -0
- package/dist/routing/routing/advancedRouter.d.ts +62 -0
- package/dist/routing/routing/advancedRouter.js +447 -0
- package/dist/routing/utils/tokenUtils.d.ts +52 -0
- package/dist/routing/utils/tokenUtils.js +129 -0
- package/dist/server/proxyServer.d.ts +1 -1
- package/dist/utils/costUtils.d.ts +57 -0
- package/dist/utils/costUtils.js +150 -0
- package/dist/utils/costUtils.js.map +1 -0
- package/dist/utils/sorting.d.ts +12 -0
- package/dist/utils/sorting.js +37 -0
- package/dist/utils/sorting.js.map +1 -0
- package/package.json +1 -1
- package/research/ensemble-voting.md +324 -0
- package/research/loss-functions.md +545 -0
- package/research-log.md +49 -0
- package/src/cost/costTracker.ts +576 -0
- package/src/routing/advancedRouter.ts +540 -0
- package/src/utils/costUtils.ts +157 -0
- package/src/utils/sorting.ts +42 -0
- package/test-council/AGENT_COUNCIL_ARCHITECTURE.md +349 -0
- package/tests/security/guardrailEngine.test.ts +700 -0
- package/research/PUBLISH_LOG.md +0 -3
|
@@ -1,463 +1,451 @@
|
|
|
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
|
-
|
|
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
|
-
|
|
20
|
-
|
|
21
|
-
|
|
24
|
+
const costUtils_1 = require("../utils/costUtils");
|
|
25
|
+
const sorting_1 = require("../utils/sorting");
|
|
26
|
+
let cachedProfiles = null;
|
|
27
|
+
let cacheTimestamp = 0;
|
|
28
|
+
const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
|
|
22
29
|
function buildModelProfiles() {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
};
|
|
30
|
+
const profiles = {};
|
|
31
|
+
const available = (0, providerConfig_1.getAvailableProviders)();
|
|
32
|
+
for (const [providerId, provider] of Object.entries(available)) {
|
|
33
|
+
for (const model of provider.models) {
|
|
34
|
+
const modelKey = model.includes('/') ? model : providerId + '/' + model;
|
|
35
|
+
const costPerKInput = provider.costPerK ? provider.costPerK.input : 0;
|
|
36
|
+
const costPerKOutput = provider.costPerK ? provider.costPerK.output : 0;
|
|
37
|
+
// Assign strengths based on model characteristics
|
|
38
|
+
const strengths = [];
|
|
39
|
+
if (provider.type === 'cli') {
|
|
40
|
+
strengths.push('free', 'local');
|
|
41
|
+
}
|
|
42
|
+
if (costPerKInput < 0.3) {
|
|
43
|
+
strengths.push('budget', 'fast');
|
|
44
|
+
}
|
|
45
|
+
else if (costPerKInput > 2) {
|
|
46
|
+
strengths.push('premium', 'reasoning');
|
|
47
|
+
}
|
|
48
|
+
if (provider.name === 'Mistral' || provider.name === 'Groq' || provider.name === 'Cerebras') {
|
|
49
|
+
strengths.push('fast', 'coding');
|
|
50
|
+
}
|
|
51
|
+
if (provider.name === 'CommandCode') {
|
|
52
|
+
strengths.push('code-aware', 'context-rich');
|
|
53
|
+
}
|
|
54
|
+
if (provider.name === 'OpenCode') {
|
|
55
|
+
strengths.push('free', 'multi-model');
|
|
56
|
+
}
|
|
57
|
+
if (provider.name === 'Google') {
|
|
58
|
+
strengths.push('multilingual', 'long-context');
|
|
59
|
+
}
|
|
60
|
+
if (provider.name === 'OpenAI') {
|
|
61
|
+
strengths.push('reasoning', 'coding', 'analysis');
|
|
62
|
+
}
|
|
63
|
+
if (provider.name === 'Anthropic') {
|
|
64
|
+
strengths.push('reasoning', 'creative', 'analysis');
|
|
65
|
+
}
|
|
66
|
+
profiles[modelKey] = {
|
|
67
|
+
name: modelKey,
|
|
68
|
+
provider: providerId,
|
|
69
|
+
providerName: provider.name,
|
|
70
|
+
cost_per_1k_input: costPerKInput,
|
|
71
|
+
cost_per_1k_output: costPerKOutput,
|
|
72
|
+
latency_ms: provider.type === 'cli' ? 5000 : (provider.priority * 200 + 300),
|
|
73
|
+
quality_score: strengths.includes('premium') ? 0.95 :
|
|
74
|
+
strengths.includes('reasoning') ? 0.90 :
|
|
75
|
+
strengths.includes('fast') ? 0.82 : 0.80,
|
|
76
|
+
strengths,
|
|
77
|
+
context_window: provider.maxTokens || 8192,
|
|
78
|
+
type: provider.type,
|
|
79
|
+
priority: provider.priority,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
76
82
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
return profiles;
|
|
83
|
+
return profiles;
|
|
80
84
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
85
|
+
// Lazy cache with TTL - replaces refreshModelProfiles()
|
|
86
|
+
function getModelProfiles() {
|
|
87
|
+
const now = Date.now();
|
|
88
|
+
if (!cachedProfiles || (now - cacheTimestamp) > CACHE_TTL_MS) {
|
|
89
|
+
cachedProfiles = buildModelProfiles();
|
|
90
|
+
cacheTimestamp = now;
|
|
91
|
+
}
|
|
92
|
+
return cachedProfiles;
|
|
88
93
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
94
|
+
// Manual cache invalidation (call if provider config changes)
|
|
95
|
+
function invalidateProfileCache() {
|
|
96
|
+
cachedProfiles = null;
|
|
97
|
+
cacheTimestamp = 0;
|
|
93
98
|
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
99
|
+
exports.MODEL_PROFILES = {};
|
|
100
|
+
try {
|
|
101
|
+
exports.MODEL_PROFILES = buildModelProfiles();
|
|
102
|
+
}
|
|
103
|
+
catch (e) {
|
|
104
|
+
// Circular dependency at module load — will retry on first use
|
|
105
|
+
exports.MODEL_PROFILES = {};
|
|
100
106
|
}
|
|
101
|
-
// ============================================================
|
|
102
|
-
// FEATURE EXTRACTION (v3 — multi-signal complexity scorer)
|
|
103
|
-
// ============================================================
|
|
104
|
-
|
|
105
107
|
function extractQueryFeatures(prompt) {
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
108
|
+
const lower = prompt.toLowerCase();
|
|
109
|
+
const words = prompt.split(/\s+/);
|
|
110
|
+
const wordCount = words.length;
|
|
111
|
+
// === SIGNAL 1: Domain Detection ===
|
|
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
|
+
data_science: {
|
|
153
|
+
keywords: ['machine learning', 'deep learning', 'neural network', 'transformer',
|
|
154
|
+
'training data', 'model accuracy', 'hyperparameter', 'cross-validation',
|
|
155
|
+
'feature engineering', 'data pipeline', 'pandas', 'numpy', 'scikit',
|
|
156
|
+
'tensorflow', 'pytorch', 'regression', 'classification', 'clustering'],
|
|
157
|
+
weight: 0.30
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
let detectedDomain = null;
|
|
161
|
+
let maxDomainScore = 0;
|
|
162
|
+
for (const [domain, signal] of Object.entries(domainSignals)) {
|
|
163
|
+
let domainScore = 0;
|
|
164
|
+
for (const kw of signal.keywords) {
|
|
165
|
+
if (lower.includes(kw)) {
|
|
166
|
+
domainScore += signal.weight;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (domainScore > maxDomainScore) {
|
|
170
|
+
maxDomainScore = domainScore;
|
|
171
|
+
detectedDomain = domain;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
// === SIGNAL 2: Code Detection ===
|
|
175
|
+
const codeSignals = [
|
|
176
|
+
'function ', 'def ', 'class ', 'import ', 'from ', 'const ', 'let ', 'var ',
|
|
177
|
+
'=>', '->', 'async ', 'await ', 'return ', 'if (', 'for (', 'while (',
|
|
178
|
+
'public ', 'private ', 'protected ', 'static ', 'void ', 'int ', 'string ',
|
|
179
|
+
'#include', 'std::', 'cout', 'cin', 'printf(', 'println!',
|
|
180
|
+
'fn ', 'impl ', 'pub ', 'mut ', 'struct ', 'enum ',
|
|
181
|
+
'```', 'code', 'python', 'javascript', 'typescript', 'java', 'cpp', 'ruby',
|
|
182
|
+
'write a', 'create a', 'implement', 'algorithm'
|
|
183
|
+
];
|
|
184
|
+
const hasCode = codeSignals.some(sig => lower.includes(sig));
|
|
185
|
+
// === SIGNAL 3: Reasoning Detection ===
|
|
186
|
+
const reasoningSignals = [
|
|
187
|
+
'why', 'how', 'explain', 'analyze', 'compare', 'contrast', 'evaluate',
|
|
188
|
+
'think about', 'reason', 'logic', 'proof', 'derive', '证明', '分析',
|
|
189
|
+
'reasoning', 'step by step', 'thinking', 'thought process'
|
|
190
|
+
];
|
|
191
|
+
const requiresReasoning = reasoningSignals.some(sig => lower.includes(sig));
|
|
192
|
+
// === SIGNAL 4: Language Detection ===
|
|
193
|
+
const languagePatterns = [
|
|
194
|
+
[/[\u4e00-\u9fff]/, 'zh'],
|
|
195
|
+
[/[\u0900-\u097f]/, 'hi'],
|
|
196
|
+
[/[\u0600-\u06ff]/, 'ar'],
|
|
197
|
+
[/[\u0400-\u04ff]/, 'ru'],
|
|
198
|
+
[/[\u0900-\u097f]/, 'hi-latn'],
|
|
199
|
+
[/বাংলা|করুন|হিন্দি|ভারত|ভারতীয়/, 'bn'],
|
|
200
|
+
];
|
|
201
|
+
let detectedLanguage = null;
|
|
202
|
+
for (const [pattern, lang] of languagePatterns) {
|
|
203
|
+
if (pattern.test(prompt)) {
|
|
204
|
+
detectedLanguage = lang;
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
// Translation detection
|
|
209
|
+
const translationSignals = ['translate', 'translation', 'into english', 'to english',
|
|
210
|
+
'traducir', 'traduction', 'traduzione', 'übersetzen'];
|
|
211
|
+
const isTranslation = translationSignals.some(sig => lower.includes(sig)) ||
|
|
212
|
+
/to (english|french|german|spanish|chinese|japanese|korean)/i.test(prompt);
|
|
213
|
+
const isMultilingual = detectedLanguage !== null || isTranslation;
|
|
214
|
+
// === SIGNAL 5: Intent Classification ===
|
|
215
|
+
let intent = 'general';
|
|
216
|
+
if (hasCode)
|
|
217
|
+
intent = 'code';
|
|
218
|
+
else if (isTranslation)
|
|
219
|
+
intent = 'translation';
|
|
220
|
+
else if (lower.includes('write') || lower.includes('create') || lower.includes('generate')) {
|
|
221
|
+
intent = 'creative';
|
|
222
|
+
}
|
|
223
|
+
else if (lower.includes('explain') || lower.includes('what is') || lower.includes('how does')) {
|
|
224
|
+
intent = 'explanation';
|
|
159
225
|
}
|
|
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
|
-
}
|
|
226
|
+
else if (lower.includes('calculate') || lower.includes('compute') || lower.includes('integral')) {
|
|
227
|
+
intent = 'math';
|
|
172
228
|
}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
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
|
-
};
|
|
229
|
+
// === COMPLEXITY SCORING ===
|
|
230
|
+
// Base complexity from length
|
|
231
|
+
let complexity = Math.min(wordCount / 100, 1.0);
|
|
232
|
+
// Domain加成
|
|
233
|
+
if (detectedDomain)
|
|
234
|
+
complexity += 0.2;
|
|
235
|
+
// Code加成
|
|
236
|
+
if (hasCode)
|
|
237
|
+
complexity += 0.15;
|
|
238
|
+
// Reasoning加成
|
|
239
|
+
if (requiresReasoning)
|
|
240
|
+
complexity += 0.15;
|
|
241
|
+
// Multilingual加成
|
|
242
|
+
if (isMultilingual)
|
|
243
|
+
complexity += 0.1;
|
|
244
|
+
// Cap at 1.0
|
|
245
|
+
complexity = Math.min(complexity, 1.0);
|
|
246
|
+
return {
|
|
247
|
+
length: prompt.length,
|
|
248
|
+
wordCount,
|
|
249
|
+
complexity,
|
|
250
|
+
has_code: hasCode,
|
|
251
|
+
requires_reasoning: requiresReasoning,
|
|
252
|
+
is_multilingual: isMultilingual,
|
|
253
|
+
is_translation: isTranslation,
|
|
254
|
+
domain: detectedDomain,
|
|
255
|
+
intent,
|
|
256
|
+
detected_language: detectedLanguage,
|
|
257
|
+
};
|
|
254
258
|
}
|
|
255
|
-
|
|
256
|
-
exports.extractQueryFeatures = extractQueryFeatures;
|
|
257
|
-
|
|
258
|
-
// ============================================================
|
|
259
|
-
// SCORING FUNCTIONS
|
|
260
|
-
// ============================================================
|
|
261
|
-
|
|
262
259
|
function scoreModelFit(model, features) {
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
260
|
+
let score = model.quality_score * 0.6;
|
|
261
|
+
// Domain match
|
|
262
|
+
if (features.domain) {
|
|
263
|
+
const domainBonus = {
|
|
264
|
+
code: ['code-aware', 'coding', 'fast'],
|
|
265
|
+
medical: ['reasoning', 'analysis'],
|
|
266
|
+
legal: ['reasoning', 'analysis', 'context-rich'],
|
|
267
|
+
finance: ['analysis', 'reasoning'],
|
|
268
|
+
security: ['reasoning', 'analysis'],
|
|
269
|
+
architecture: ['context-rich', 'long-context'],
|
|
270
|
+
data_science: ['coding', 'fast', 'reasoning'],
|
|
271
|
+
};
|
|
272
|
+
const bonuses = domainBonus[features.domain] || [];
|
|
273
|
+
if (bonuses.some(b => model.strengths.includes(b))) {
|
|
274
|
+
score += 0.2;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
// Code bonus
|
|
278
|
+
if (features.has_code && model.strengths.includes('coding')) {
|
|
279
|
+
score += 0.15;
|
|
280
|
+
}
|
|
281
|
+
// Multilingual bonus
|
|
282
|
+
if (features.is_multilingual && model.strengths.includes('multilingual')) {
|
|
283
|
+
score += 0.15;
|
|
284
|
+
}
|
|
285
|
+
// Free tier preference for simple queries
|
|
286
|
+
if (features.complexity < 0.5 && model.strengths.includes('free')) {
|
|
287
|
+
score += 0.2;
|
|
288
|
+
}
|
|
289
|
+
// Fast provider for simple queries
|
|
290
|
+
if (features.complexity < 0.4 && model.strengths.includes('fast')) {
|
|
291
|
+
score += 0.15;
|
|
292
|
+
}
|
|
293
|
+
// Premium for complex queries
|
|
294
|
+
if (features.complexity > 0.6 && model.strengths.includes('premium')) {
|
|
295
|
+
score += 0.15;
|
|
296
|
+
}
|
|
297
|
+
return Math.min(score, 1.0);
|
|
281
298
|
}
|
|
282
|
-
|
|
283
299
|
function costEfficiency(model, features) {
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
300
|
+
// Use log-scale cost score for better mid-range differentiation
|
|
301
|
+
// Lower cost → higher score (thanks to logScaleCostScore inverse mapping)
|
|
302
|
+
const avg_cost = (model.cost_per_1k_input + model.cost_per_1k_output) / 2;
|
|
303
|
+
const cost_score = (0, costUtils_1.logScaleCostScore)(avg_cost);
|
|
304
|
+
// Simple queries weigh cost more heavily (0.6)
|
|
305
|
+
// Complex queries weigh cost less (0.2) since quality matters more
|
|
306
|
+
const weight = features.complexity < 0.5 ? 0.6 : 0.2;
|
|
307
|
+
return cost_score * weight;
|
|
289
308
|
}
|
|
290
|
-
|
|
291
|
-
// ============================================================
|
|
292
|
-
// ROUTING
|
|
293
|
-
// ============================================================
|
|
294
|
-
|
|
295
309
|
function routeQuery(prompt, available_models, budget_multiplier = 1.0) {
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
total_score: quality + cost
|
|
315
|
-
};
|
|
310
|
+
// Use cached profiles instead of rebuilding every time (5-10ms savings)
|
|
311
|
+
const profiles = getModelProfiles();
|
|
312
|
+
const features = extractQueryFeatures(prompt);
|
|
313
|
+
const candidate_names = available_models || Object.keys(profiles);
|
|
314
|
+
// Filter to available models
|
|
315
|
+
const candidates = candidate_names
|
|
316
|
+
.filter(name => profiles[name])
|
|
317
|
+
.map(name => {
|
|
318
|
+
const profile = profiles[name];
|
|
319
|
+
const quality = scoreModelFit(profile, features);
|
|
320
|
+
const cost = costEfficiency(profile, features);
|
|
321
|
+
return {
|
|
322
|
+
name,
|
|
323
|
+
profile,
|
|
324
|
+
quality_score: quality,
|
|
325
|
+
cost_score: cost,
|
|
326
|
+
total_score: quality + cost
|
|
327
|
+
};
|
|
316
328
|
});
|
|
317
|
-
|
|
318
|
-
|
|
329
|
+
if (candidates.length === 0) {
|
|
330
|
+
return {
|
|
331
|
+
primary_model: null,
|
|
332
|
+
fallback_models: [],
|
|
333
|
+
confidence: 0,
|
|
334
|
+
reasoning: "No providers available - configure API keys in ~/.config/a3m-router/providers.json",
|
|
335
|
+
estimated_cost: 0,
|
|
336
|
+
estimated_latency_ms: 0,
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
// Sort by total score (quality vs cost tradeoff based on complexity)
|
|
340
|
+
const complexity_bias = features.complexity > 0.6 ? 0.7 : 0.3;
|
|
341
|
+
const scoreFn = (c) => c.quality_score * complexity_bias + c.cost_score * (1 - complexity_bias);
|
|
342
|
+
const topCandidates = (0, sorting_1.quickselectTopK)(candidates, 4, scoreFn);
|
|
343
|
+
const primary = topCandidates[0];
|
|
344
|
+
const secondary = topCandidates.slice(1, 3);
|
|
345
|
+
// Calculate confidence based on score gap
|
|
346
|
+
let confidence = 0.5;
|
|
347
|
+
if (candidates.length > 1) {
|
|
348
|
+
const gap = primary.total_score - candidates[1].total_score;
|
|
349
|
+
confidence = Math.min(0.95, 0.5 + gap * 2);
|
|
350
|
+
}
|
|
351
|
+
// Build reasoning
|
|
352
|
+
const reasons = [];
|
|
353
|
+
if (features.has_code)
|
|
354
|
+
reasons.push("code detected");
|
|
355
|
+
if (features.requires_reasoning)
|
|
356
|
+
reasons.push("reasoning needed");
|
|
357
|
+
if (features.complexity > 0.6)
|
|
358
|
+
reasons.push("high complexity");
|
|
359
|
+
if (features.is_multilingual)
|
|
360
|
+
reasons.push("multilingual");
|
|
361
|
+
if (features.is_translation)
|
|
362
|
+
reasons.push("translation");
|
|
363
|
+
if (primary.profile.strengths.includes("free"))
|
|
364
|
+
reasons.push("free tier");
|
|
365
|
+
const estimated_tokens = features.length * 1.5;
|
|
366
|
+
const estimated_cost = (0, tokenUtils_1.estimateCost)(features.length, estimated_tokens, primary.name);
|
|
319
367
|
return {
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
368
|
+
primary_model: primary.name,
|
|
369
|
+
fallback_models: secondary.map(c => c.name),
|
|
370
|
+
confidence,
|
|
371
|
+
reasoning: `Selected ${primary.profile.providerName || primary.profile.provider}/${primary.name} for ${reasons.join(", ") || "general query"}`,
|
|
372
|
+
estimated_cost: estimated_cost * budget_multiplier,
|
|
373
|
+
estimated_latency_ms: primary.profile.latency_ms,
|
|
374
|
+
features,
|
|
375
|
+
provider_type: primary.profile.type,
|
|
326
376
|
};
|
|
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
377
|
}
|
|
370
|
-
|
|
371
|
-
exports.routeQuery = routeQuery;
|
|
372
|
-
|
|
373
378
|
// ============================================================
|
|
374
379
|
// BATCH ROUTING
|
|
375
380
|
// ============================================================
|
|
376
|
-
|
|
377
381
|
function routeBatch(prompts, options = {}) {
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
return decisions;
|
|
382
|
+
const decisions = prompts.map(p => routeQuery(p));
|
|
383
|
+
if (options.same_model && decisions.length > 0) {
|
|
384
|
+
const primary_model = decisions[0].primary_model;
|
|
385
|
+
decisions.forEach(d => {
|
|
386
|
+
d.primary_model = primary_model;
|
|
387
|
+
d.fallback_models = decisions[0].fallback_models;
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
if (options.max_cost_per_prompt !== undefined) {
|
|
391
|
+
const profiles = getModelProfiles();
|
|
392
|
+
decisions.forEach(d => {
|
|
393
|
+
if (d.estimated_cost > options.max_cost_per_prompt) {
|
|
394
|
+
const cheap = Object.entries(profiles)
|
|
395
|
+
.find(([name, p]) => p.cost_per_1k_input < 0.5);
|
|
396
|
+
if (cheap) {
|
|
397
|
+
d.primary_model = cheap[0];
|
|
398
|
+
d.reasoning = `Budget-limited routing to ${cheap[1].providerName || cheap[1].provider}`;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
return decisions;
|
|
402
404
|
}
|
|
403
|
-
|
|
404
|
-
exports.routeBatch = routeBatch;
|
|
405
|
-
|
|
406
405
|
// ============================================================
|
|
407
406
|
// TASK RECOMMENDATIONS
|
|
408
407
|
// ============================================================
|
|
409
|
-
|
|
410
408
|
function recommendForTask(task) {
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
};
|
|
409
|
+
const features = extractQueryFeatures(task);
|
|
410
|
+
const decision = routeQuery(task);
|
|
411
|
+
return {
|
|
412
|
+
primary: decision.primary_model,
|
|
413
|
+
fallbacks: decision.fallback_models,
|
|
414
|
+
reason: decision.reasoning,
|
|
415
|
+
features,
|
|
416
|
+
};
|
|
420
417
|
}
|
|
421
|
-
|
|
422
|
-
exports.recommendForTask = recommendForTask;
|
|
423
|
-
|
|
424
418
|
// ============================================================
|
|
425
419
|
// ONLINE LEARNING - Update model profiles from feedback
|
|
426
420
|
// ============================================================
|
|
427
|
-
|
|
428
421
|
function updateModelProfile(model_name, actual_latency_ms, actual_cost, quality_rating) {
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
422
|
+
const profiles = getModelProfiles();
|
|
423
|
+
const profile = profiles[model_name];
|
|
424
|
+
if (!profile)
|
|
425
|
+
return;
|
|
426
|
+
const alpha = 0.2; // Learning rate
|
|
427
|
+
profile.latency_ms = profile.latency_ms * (1 - alpha) + actual_latency_ms * alpha;
|
|
428
|
+
profile.quality_score = profile.quality_score * (1 - alpha) + quality_rating * alpha;
|
|
436
429
|
}
|
|
437
|
-
|
|
438
|
-
exports.updateModelProfile = updateModelProfile;
|
|
439
|
-
|
|
440
430
|
// ============================================================
|
|
441
431
|
// PROVIDER HEALTH CHECK
|
|
442
432
|
// ============================================================
|
|
443
|
-
|
|
444
433
|
async function getProviderHealth() {
|
|
445
|
-
|
|
446
|
-
|
|
434
|
+
const { checkAllProviders } = require("../providers/providerConfig");
|
|
435
|
+
return checkAllProviders();
|
|
447
436
|
}
|
|
448
|
-
|
|
449
|
-
exports.getProviderHealth = getProviderHealth;
|
|
450
|
-
|
|
451
437
|
// ============================================================
|
|
452
438
|
// Default export
|
|
453
439
|
// ============================================================
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
440
|
+
module.exports = {
|
|
441
|
+
extractQueryFeatures,
|
|
442
|
+
routeQuery,
|
|
443
|
+
routeBatch,
|
|
444
|
+
recommendForTask,
|
|
445
|
+
updateModelProfile,
|
|
446
|
+
getProviderHealth,
|
|
447
|
+
MODEL_PROFILES: exports.MODEL_PROFILES,
|
|
448
|
+
invalidateProfileCache,
|
|
463
449
|
};
|
|
450
|
+
module.exports.default = module.exports;
|
|
451
|
+
//# sourceMappingURL=advancedRouter.js.map
|