@memberjunction/ai-prompts 6.2.2 → 6.3.0-edge.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -0
- package/dist/AIPromptRunner.d.ts +6 -5
- package/dist/AIPromptRunner.d.ts.map +1 -1
- package/dist/AIPromptRunner.js +96 -41
- package/dist/AIPromptRunner.js.map +1 -1
- package/dist/BaseModelRunner.d.ts +33 -62
- package/dist/BaseModelRunner.d.ts.map +1 -1
- package/dist/BaseModelRunner.js +93 -231
- package/dist/BaseModelRunner.js.map +1 -1
- package/dist/ParallelExecutionCoordinator.js +3 -3
- package/dist/ParallelExecutionCoordinator.js.map +1 -1
- package/dist/decision/AIDecisionRunner.d.ts +34 -10
- package/dist/decision/AIDecisionRunner.d.ts.map +1 -1
- package/dist/decision/AIDecisionRunner.js +72 -38
- package/dist/decision/AIDecisionRunner.js.map +1 -1
- package/dist/decision/LLMDecision.d.ts +8 -0
- package/dist/decision/LLMDecision.d.ts.map +1 -1
- package/dist/decision/LLMDecision.js +15 -2
- package/dist/decision/LLMDecision.js.map +1 -1
- package/dist/decision/decision-limits.d.ts +80 -0
- package/dist/decision/decision-limits.d.ts.map +1 -0
- package/dist/decision/decision-limits.js +142 -0
- package/dist/decision/decision-limits.js.map +1 -0
- package/dist/decision/decision-runner.types.d.ts +7 -1
- package/dist/decision/decision-runner.types.d.ts.map +1 -1
- package/dist/decision/decision-runner.types.js.map +1 -1
- package/dist/decision/decision-use.d.ts +77 -0
- package/dist/decision/decision-use.d.ts.map +1 -0
- package/dist/decision/decision-use.js +104 -0
- package/dist/decision/decision-use.js.map +1 -0
- package/dist/decision/shadow-decision.d.ts +90 -0
- package/dist/decision/shadow-decision.d.ts.map +1 -0
- package/dist/decision/shadow-decision.js +85 -0
- package/dist/decision/shadow-decision.js.map +1 -0
- package/dist/embedding/AIEmbeddingRunner.d.ts +10 -2
- package/dist/embedding/AIEmbeddingRunner.d.ts.map +1 -1
- package/dist/embedding/AIEmbeddingRunner.js +22 -5
- package/dist/embedding/AIEmbeddingRunner.js.map +1 -1
- package/dist/embedding/embedding-runner.types.d.ts +24 -3
- package/dist/embedding/embedding-runner.types.d.ts.map +1 -1
- package/dist/embedding/embedding-runner.types.js +13 -1
- package/dist/embedding/embedding-runner.types.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/jsonRecovery.d.ts +31 -0
- package/dist/jsonRecovery.d.ts.map +1 -0
- package/dist/jsonRecovery.js +79 -0
- package/dist/jsonRecovery.js.map +1 -0
- package/dist/linearTextScan.d.ts +12 -0
- package/dist/linearTextScan.d.ts.map +1 -1
- package/dist/linearTextScan.js +36 -0
- package/dist/linearTextScan.js.map +1 -1
- package/dist/nativeToolCallingGate.d.ts +23 -4
- package/dist/nativeToolCallingGate.d.ts.map +1 -1
- package/dist/nativeToolCallingGate.js +19 -2
- package/dist/nativeToolCallingGate.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +12 -12
package/dist/BaseModelRunner.js
CHANGED
|
@@ -162,7 +162,7 @@ export class BaseModelRunner {
|
|
|
162
162
|
* 2. Prompt-Model specific: AIPromptModel.CredentialID
|
|
163
163
|
* 3. Model-Vendor specific: AIModelVendor.CredentialID
|
|
164
164
|
* 4. Vendor default: AIVendor.CredentialID
|
|
165
|
-
* 5. Legacy: params.apiKeys[] array
|
|
165
|
+
* 5. Legacy: params.apiKeys[] array, then params.APIKeyResolver
|
|
166
166
|
* 6. Legacy: AI_VENDOR_API_KEY__<DRIVER> environment variables
|
|
167
167
|
*
|
|
168
168
|
* IMPORTANT: When ANY credential ID is found (priorities 1-4), the system uses
|
|
@@ -197,8 +197,27 @@ export class BaseModelRunner {
|
|
|
197
197
|
if (verbose) {
|
|
198
198
|
this.logStatus(` Using legacy API key resolution for driver ${driverClass}`, true, params);
|
|
199
199
|
}
|
|
200
|
-
// Priority 6 & 7: Legacy apiKeys array and environment variables (the latter only if the scope allows)
|
|
201
|
-
return
|
|
200
|
+
// Priority 6 & 7: Legacy apiKeys array (then the run's key resolver) and environment variables (the latter only if the scope allows)
|
|
201
|
+
return this.resolveLegacyAPIKey(driverClass, params, verbose);
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* The legacy tier of credential resolution: the explicit {@link AIPromptParams.apiKeys} entry for
|
|
205
|
+
* the driver class, then {@link AIPromptParams.APIKeyResolver}, then the environment key when the
|
|
206
|
+
* run's {@link AIPromptParams.CredentialScope} allows it. Explicit keys win over the resolver; the
|
|
207
|
+
* resolver's answer is a runtime credential, so it applies under `'RuntimeOnly'` as well.
|
|
208
|
+
*/
|
|
209
|
+
resolveLegacyAPIKey(driverClass, params, verbose) {
|
|
210
|
+
const hasExplicitKey = params?.apiKeys?.some(k => k.driverClass === driverClass) ?? false;
|
|
211
|
+
if (!hasExplicitKey && params?.APIKeyResolver) {
|
|
212
|
+
const resolved = params.APIKeyResolver(driverClass);
|
|
213
|
+
if (resolved) {
|
|
214
|
+
if (verbose) {
|
|
215
|
+
this.logStatus(` Using the run's API key resolver for driver class: ${driverClass}`, true, params);
|
|
216
|
+
}
|
|
217
|
+
return resolved;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return GetAIAPIKey(driverClass, params?.apiKeys, verbose, params?.CredentialScope);
|
|
202
221
|
}
|
|
203
222
|
/**
|
|
204
223
|
* Priorities 2-5 of {@link ResolveCredentialForExecution}: the platform's MJ Credentials —
|
|
@@ -259,7 +278,7 @@ export class BaseModelRunner {
|
|
|
259
278
|
* 3. ModelVendor bindings: AICredentialBinding WHERE BindingType='ModelVendor'
|
|
260
279
|
* 4. Vendor bindings: AICredentialBinding WHERE BindingType='Vendor'
|
|
261
280
|
* 5. Type-based default: Credential.IsDefault=1 matching AIVendor.CredentialTypeID
|
|
262
|
-
* 6. Legacy: params.apiKeys[] array
|
|
281
|
+
* 6. Legacy: params.apiKeys[] array, then params.APIKeyResolver
|
|
263
282
|
* 7. Legacy: AI_VENDOR_API_KEY__<DRIVER> environment variables
|
|
264
283
|
*
|
|
265
284
|
* Each tier counts only if {@link CredentialScopeAllows} the run's scope to use its source: under
|
|
@@ -284,7 +303,7 @@ export class BaseModelRunner {
|
|
|
284
303
|
return true;
|
|
285
304
|
}
|
|
286
305
|
// Priority 6 & 7: Legacy methods - check if API key is available (the environment only if the scope allows)
|
|
287
|
-
const apiKey =
|
|
306
|
+
const apiKey = this.resolveLegacyAPIKey(driverClass, params, params?.verbose);
|
|
288
307
|
return this.isValidAPIKey(apiKey);
|
|
289
308
|
}
|
|
290
309
|
/** Priorities 2-5 of {@link HasCredentialsAvailable}: whether a platform MJ Credential applies. */
|
|
@@ -1265,9 +1284,8 @@ export class BaseModelRunner {
|
|
|
1265
1284
|
// prompt's type crossed with every active inference vendor, which is 317 entries on a stock
|
|
1266
1285
|
// tenant — and until now nothing consulted the configured cap, so a provider returning 5xx (or
|
|
1267
1286
|
// stalling, where there is no per-call deadline either) was retried against candidate after
|
|
1268
|
-
// candidate.
|
|
1269
|
-
//
|
|
1270
|
-
// the TOTAL number of calls including the first, not the number of retries after it.
|
|
1287
|
+
// candidate. maxAttempts is the TOTAL number of calls including the first, not the number of
|
|
1288
|
+
// retries after it.
|
|
1271
1289
|
// A non-positive value would stop the walk before the FIRST call and fail every prompt on the
|
|
1272
1290
|
// tenant, so it is treated as "not configured" rather than "no calls allowed". `|| 3` in
|
|
1273
1291
|
// getFailoverConfiguration already turns 0/null into 3; this covers a negative row.
|
|
@@ -1403,19 +1421,28 @@ export class BaseModelRunner {
|
|
|
1403
1421
|
continue;
|
|
1404
1422
|
}
|
|
1405
1423
|
if (decision.shouldContinue) {
|
|
1406
|
-
|
|
1424
|
+
i = decision.nextIndex - 1; // The loop's i++ lands on the next surviving candidate
|
|
1425
|
+
continue;
|
|
1407
1426
|
}
|
|
1408
1427
|
// Otherwise break (fatal error or last candidate)
|
|
1409
1428
|
break;
|
|
1410
1429
|
}
|
|
1411
1430
|
// A failure that is not eligible for failover (structural error, or none diagnosed) is
|
|
1412
|
-
// returned as-is — but never silently: callers often see only an empty result.
|
|
1431
|
+
// returned as-is — but never silently: callers often see only an empty result. It is still
|
|
1432
|
+
// an attempt on this candidate, so it is counted like a thrown or eligible failure.
|
|
1413
1433
|
if (!result.success) {
|
|
1414
1434
|
this.logError(`Model call failed and is not eligible for failover (${result.errorInfo?.errorType ?? 'undiagnosed'}): ${result.errorMessage ?? 'no error message'}`, { prompt, model: candidate.model, metadata: { vendorId: candidate.vendorId, driverClass: candidate.driverClass } });
|
|
1435
|
+
this.recordFailoverAttempt(this.failedResultError(result), result.errorInfo?.errorType ?? 'Unknown', candidate, attemptStartTime, i, failoverAttempts);
|
|
1415
1436
|
}
|
|
1416
|
-
//
|
|
1437
|
+
// Record the attempts on the prompt run. Only a successful result moves the run's
|
|
1438
|
+
// ModelID / VendorID to this candidate: a failed one did not answer the prompt.
|
|
1417
1439
|
if (failoverAttempts.length > 0 && promptRun) {
|
|
1418
|
-
|
|
1440
|
+
if (result.success) {
|
|
1441
|
+
this.updatePromptRunWithFailoverSuccess(promptRun, failoverAttempts, candidate.model, candidate.vendorId || null);
|
|
1442
|
+
}
|
|
1443
|
+
else {
|
|
1444
|
+
this.updatePromptRunWithFailoverFailure(promptRun, failoverAttempts);
|
|
1445
|
+
}
|
|
1419
1446
|
}
|
|
1420
1447
|
return result;
|
|
1421
1448
|
}
|
|
@@ -1436,7 +1463,8 @@ export class BaseModelRunner {
|
|
|
1436
1463
|
continue;
|
|
1437
1464
|
}
|
|
1438
1465
|
if (decision.shouldContinue) {
|
|
1439
|
-
|
|
1466
|
+
i = decision.nextIndex - 1; // The loop's i++ lands on the next surviving candidate
|
|
1467
|
+
continue;
|
|
1440
1468
|
}
|
|
1441
1469
|
// Otherwise break (fatal error or last candidate)
|
|
1442
1470
|
break;
|
|
@@ -1565,10 +1593,10 @@ export class BaseModelRunner {
|
|
|
1565
1593
|
});
|
|
1566
1594
|
}
|
|
1567
1595
|
/**
|
|
1568
|
-
* Engine-level default model-call timeout, in milliseconds, applied when the caller
|
|
1569
|
-
* `AIPromptParams.timeoutMS
|
|
1570
|
-
*
|
|
1571
|
-
*
|
|
1596
|
+
* Engine-level default model-call timeout, in milliseconds, applied when neither the caller
|
|
1597
|
+
* (`AIPromptParams.timeoutMS`) nor the prompt (`AIPrompt.TimeoutMS`) supplies one. `undefined`
|
|
1598
|
+
* (the default) means NO implicit bound — a prompt run with no timeout from any source and no
|
|
1599
|
+
* cancellation token stays unbounded.
|
|
1572
1600
|
*
|
|
1573
1601
|
* Subclasses (or a host application's runner subclass) can override this to impose a global
|
|
1574
1602
|
* safety ceiling on every prompt call.
|
|
@@ -1577,20 +1605,21 @@ export class BaseModelRunner {
|
|
|
1577
1605
|
return undefined;
|
|
1578
1606
|
}
|
|
1579
1607
|
/**
|
|
1580
|
-
* Resolves the per-model-call timeout
|
|
1581
|
-
*
|
|
1608
|
+
* Resolves the per-model-call timeout, most specific source first:
|
|
1609
|
+
*
|
|
1610
|
+
* 1. the caller's `AIPromptParams.timeoutMS`
|
|
1611
|
+
* 2. the prompt's own `AIPrompt.TimeoutMS` column
|
|
1612
|
+
* 3. the runner's {@link DefaultPromptTimeoutMS}
|
|
1613
|
+
*
|
|
1614
|
+
* The first source that is set wins, even when it is not positive: a caller passing `0` opts this
|
|
1615
|
+
* call out of any bound. Non-positive / non-numeric results mean "no timeout".
|
|
1582
1616
|
*
|
|
1583
1617
|
* The bound is applied PER MODEL CALL (not per prompt execution), which mirrors the parallel
|
|
1584
1618
|
* path's existing `taskTimeoutMS` semantics: each failover candidate / validation retry gets a
|
|
1585
1619
|
* fresh budget rather than sharing one wall-clock window.
|
|
1586
|
-
*
|
|
1587
|
-
* NOTE (issue #3064): there is deliberately NO prompt-entity source here yet — the `AIPrompt`
|
|
1588
|
-
* table has no `TimeoutMS` column today. Once a migration adds one and CodeGen regenerates the
|
|
1589
|
-
* entity, this becomes `prompt.TimeoutMS ?? params.timeoutMS ?? this.DefaultPromptTimeoutMS`
|
|
1590
|
-
* and every bound below starts honoring the per-prompt configuration with no other change.
|
|
1591
1620
|
*/
|
|
1592
|
-
getEffectiveTimeoutMS(params) {
|
|
1593
|
-
const timeoutMS = params.timeoutMS ?? this.DefaultPromptTimeoutMS;
|
|
1621
|
+
getEffectiveTimeoutMS(prompt, params) {
|
|
1622
|
+
const timeoutMS = params.timeoutMS ?? prompt?.TimeoutMS ?? this.DefaultPromptTimeoutMS;
|
|
1594
1623
|
return typeof timeoutMS === 'number' && timeoutMS > 0 ? timeoutMS : undefined;
|
|
1595
1624
|
}
|
|
1596
1625
|
/**
|
|
@@ -1607,7 +1636,7 @@ export class BaseModelRunner {
|
|
|
1607
1636
|
* on Node 18 (where `AbortSignal.any` does not exist — it landed in Node 20.3).
|
|
1608
1637
|
*/
|
|
1609
1638
|
createExecutionBound(prompt, params, cancellationToken) {
|
|
1610
|
-
const timeoutMS = this.getEffectiveTimeoutMS(params);
|
|
1639
|
+
const timeoutMS = this.getEffectiveTimeoutMS(prompt, params);
|
|
1611
1640
|
if (timeoutMS === undefined) {
|
|
1612
1641
|
// No prompt timeout: use the caller's token as-is (or nothing at all).
|
|
1613
1642
|
return { Signal: cancellationToken, TimeoutMS: undefined, TimedOut: () => false, Dispose: () => { } };
|
|
@@ -1786,60 +1815,81 @@ export class BaseModelRunner {
|
|
|
1786
1815
|
return false; // Too many retries, proceed to failover
|
|
1787
1816
|
}
|
|
1788
1817
|
/**
|
|
1789
|
-
*
|
|
1790
|
-
*
|
|
1791
|
-
*
|
|
1792
|
-
* @returns Decision object indicating whether to retry same model, continue to next candidate, or stop
|
|
1818
|
+
* Records one failed call on a candidate as a failover attempt: its error, classification and
|
|
1819
|
+
* duration. Every failed call is recorded, whether it threw or returned, and whether or not it
|
|
1820
|
+
* was eligible for failover.
|
|
1793
1821
|
*/
|
|
1794
|
-
|
|
1795
|
-
const attemptDuration = Date.now() - attemptStartTime;
|
|
1796
|
-
// Create failover attempt record
|
|
1822
|
+
recordFailoverAttempt(error, errorType, candidate, attemptStartTime, attemptIndex, failoverAttempts) {
|
|
1797
1823
|
const failoverAttempt = {
|
|
1798
1824
|
attemptNumber: attemptIndex + 1,
|
|
1799
1825
|
modelId: candidate.model.ID,
|
|
1800
1826
|
vendorId: candidate.vendorId,
|
|
1801
|
-
error
|
|
1802
|
-
errorType
|
|
1803
|
-
duration:
|
|
1827
|
+
error,
|
|
1828
|
+
errorType,
|
|
1829
|
+
duration: Date.now() - attemptStartTime,
|
|
1804
1830
|
timestamp: new Date()
|
|
1805
1831
|
};
|
|
1806
1832
|
failoverAttempts.push(failoverAttempt);
|
|
1833
|
+
return failoverAttempt;
|
|
1834
|
+
}
|
|
1835
|
+
/**
|
|
1836
|
+
* How many of `before[0..attemptIndex]` are still in `after`. A filter keeps the candidate
|
|
1837
|
+
* objects themselves, so this is the index in `after` of the first candidate past the attempt.
|
|
1838
|
+
*/
|
|
1839
|
+
survivorsThrough(attemptIndex, before, after) {
|
|
1840
|
+
if (after === before) {
|
|
1841
|
+
return attemptIndex + 1;
|
|
1842
|
+
}
|
|
1843
|
+
const kept = new Set(after);
|
|
1844
|
+
return before.slice(0, attemptIndex + 1).filter(c => kept.has(c)).length;
|
|
1845
|
+
}
|
|
1846
|
+
/**
|
|
1847
|
+
* Processes a failover error (either from catch block or from failed ChatResult).
|
|
1848
|
+
* Handles vendor filtering, rate limit retries, fatal error detection, and failover logic.
|
|
1849
|
+
*
|
|
1850
|
+
* @returns Decision object indicating whether to retry same model, continue to next candidate, or stop
|
|
1851
|
+
*/
|
|
1852
|
+
async processFailoverError(error, errorInfo, candidate, attemptStartTime, attemptIndex, allCandidates, failoverAttempts, prompt, failoverConfig) {
|
|
1853
|
+
const failoverAttempt = this.recordFailoverAttempt(error, errorInfo.errorType, candidate, attemptStartTime, attemptIndex, failoverAttempts);
|
|
1807
1854
|
// Vendor-level errors: filter out all candidates from this vendor
|
|
1808
1855
|
let updatedCandidates = allCandidates;
|
|
1809
1856
|
if (errorInfo.errorType === 'Authentication' || errorInfo.errorType === 'VendorValidationError') {
|
|
1810
1857
|
updatedCandidates = this.filterVendorCandidates(errorInfo.errorType, candidate.vendorId, allCandidates);
|
|
1811
1858
|
}
|
|
1812
|
-
|
|
1859
|
+
// The filter can remove candidates at or before the attempt index (this one included), which
|
|
1860
|
+
// shifts the survivors left. The next candidate sits after the survivors up to this attempt.
|
|
1861
|
+
const nextIndex = this.survivorsThrough(attemptIndex, allCandidates, updatedCandidates);
|
|
1862
|
+
const isLastCandidate = nextIndex >= updatedCandidates.length;
|
|
1813
1863
|
// Fatal errors: stop immediately
|
|
1814
1864
|
if (errorInfo.severity === 'Fatal') {
|
|
1815
1865
|
const errorMessage = error?.message || 'Unknown error';
|
|
1816
1866
|
LogErrorEx(`Stopping failover: Fatal error (${errorInfo.errorType}): ${errorMessage}`);
|
|
1817
1867
|
this.logFailoverAttempt(prompt.ID, failoverAttempt, false);
|
|
1818
|
-
return { shouldRetry: false, shouldContinue: false, updatedCandidates };
|
|
1868
|
+
return { shouldRetry: false, shouldContinue: false, updatedCandidates, nextIndex };
|
|
1819
1869
|
}
|
|
1820
1870
|
// Check errorScope filter if configured
|
|
1821
1871
|
if (failoverConfig.errorScope && failoverConfig.errorScope !== 'All') {
|
|
1822
1872
|
const matchesScope = this.errorMatchesScope(errorInfo.errorType, failoverConfig.errorScope);
|
|
1823
1873
|
if (!matchesScope) {
|
|
1824
1874
|
this.logFailoverAttempt(prompt.ID, failoverAttempt, false);
|
|
1825
|
-
return { shouldRetry: false, shouldContinue: false, updatedCandidates };
|
|
1875
|
+
return { shouldRetry: false, shouldContinue: false, updatedCandidates, nextIndex };
|
|
1826
1876
|
}
|
|
1827
1877
|
}
|
|
1828
1878
|
// Rate limit errors: check if we should retry the same model before failing over
|
|
1829
1879
|
if (errorInfo.errorType === 'RateLimit') {
|
|
1830
1880
|
const shouldRetry = await this.handleRateLimitRetry(errorInfo, candidate.model, candidate.vendorId, failoverAttempts, prompt, attemptIndex, updatedCandidates.length, failoverAttempt);
|
|
1831
1881
|
if (shouldRetry) {
|
|
1832
|
-
return { shouldRetry: true, shouldContinue: false, updatedCandidates };
|
|
1882
|
+
return { shouldRetry: true, shouldContinue: false, updatedCandidates, nextIndex };
|
|
1833
1883
|
}
|
|
1834
1884
|
}
|
|
1835
1885
|
// If this is the last candidate, we're done
|
|
1836
1886
|
if (isLastCandidate) {
|
|
1837
1887
|
this.logFailoverAttempt(prompt.ID, failoverAttempt, false);
|
|
1838
|
-
return { shouldRetry: false, shouldContinue: false, updatedCandidates };
|
|
1888
|
+
return { shouldRetry: false, shouldContinue: false, updatedCandidates, nextIndex };
|
|
1839
1889
|
}
|
|
1840
1890
|
// Log and signal to continue to next candidate
|
|
1841
1891
|
this.logFailoverAttempt(prompt.ID, failoverAttempt, true);
|
|
1842
|
-
return { shouldRetry: false, shouldContinue: true, updatedCandidates };
|
|
1892
|
+
return { shouldRetry: false, shouldContinue: true, updatedCandidates, nextIndex };
|
|
1843
1893
|
}
|
|
1844
1894
|
/**
|
|
1845
1895
|
* Standard `MJAIPromptRunEntityExtended` columns that may be populated or updated during
|
|
@@ -2139,44 +2189,6 @@ export class BaseModelRunner {
|
|
|
2139
2189
|
errorScope: prompt.FailoverErrorScope || 'All'
|
|
2140
2190
|
};
|
|
2141
2191
|
}
|
|
2142
|
-
/**
|
|
2143
|
-
* Determines whether a failover attempt should be made based on the error and configuration.
|
|
2144
|
-
*
|
|
2145
|
-
* @param error - The error that occurred during execution
|
|
2146
|
-
* @param config - The failover configuration
|
|
2147
|
-
* @param attemptNumber - The current attempt number (1-based)
|
|
2148
|
-
* @returns True if failover should be attempted, false otherwise
|
|
2149
|
-
*
|
|
2150
|
-
* @remarks
|
|
2151
|
-
* This method uses the ErrorAnalyzer to classify errors and determine if they are
|
|
2152
|
-
* eligible for failover based on the configured error scope. Override this method
|
|
2153
|
-
* to implement custom failover decision logic.
|
|
2154
|
-
*/
|
|
2155
|
-
shouldAttemptFailover(error, config, attemptNumber) {
|
|
2156
|
-
// Don't failover if strategy is None or we've exceeded max attempts
|
|
2157
|
-
if (config.strategy === 'None' || attemptNumber > config.maxAttempts) {
|
|
2158
|
-
return false;
|
|
2159
|
-
}
|
|
2160
|
-
// Analyze the error to determine if it's eligible for failover
|
|
2161
|
-
const errorAnalysis = ErrorAnalyzer.analyzeError(error);
|
|
2162
|
-
// Check if error analysis allows failover
|
|
2163
|
-
if (!errorAnalysis.canFailover) {
|
|
2164
|
-
return false;
|
|
2165
|
-
}
|
|
2166
|
-
// Check error scope configuration
|
|
2167
|
-
switch (config.errorScope) {
|
|
2168
|
-
case 'NetworkOnly':
|
|
2169
|
-
return errorAnalysis.errorType === 'NetworkError';
|
|
2170
|
-
case 'RateLimitOnly':
|
|
2171
|
-
return errorAnalysis.errorType === 'RateLimit';
|
|
2172
|
-
case 'ServiceErrorOnly':
|
|
2173
|
-
return errorAnalysis.errorType === 'ServiceUnavailable' ||
|
|
2174
|
-
errorAnalysis.errorType === 'InternalServerError';
|
|
2175
|
-
case 'All':
|
|
2176
|
-
default:
|
|
2177
|
-
return true;
|
|
2178
|
-
}
|
|
2179
|
-
}
|
|
2180
2192
|
/**
|
|
2181
2193
|
* Checks if an error type matches the configured error scope
|
|
2182
2194
|
*
|
|
@@ -2197,156 +2209,6 @@ export class BaseModelRunner {
|
|
|
2197
2209
|
return true;
|
|
2198
2210
|
}
|
|
2199
2211
|
}
|
|
2200
|
-
/**
|
|
2201
|
-
* Calculates the delay before the next failover attempt.
|
|
2202
|
-
*
|
|
2203
|
-
* @param attemptNumber - The current attempt number (1-based)
|
|
2204
|
-
* @param baseDelaySeconds - The base delay in seconds from configuration
|
|
2205
|
-
* @param previousError - The error from the previous attempt
|
|
2206
|
-
* @returns Delay in milliseconds before the next attempt
|
|
2207
|
-
*
|
|
2208
|
-
* @remarks
|
|
2209
|
-
* Implements exponential backoff with jitter by default. The delay increases
|
|
2210
|
-
* exponentially with each attempt and includes random jitter to prevent
|
|
2211
|
-
* thundering herd problems. Override this method to implement custom delay logic.
|
|
2212
|
-
*/
|
|
2213
|
-
calculateFailoverDelay(attemptNumber, baseDelaySeconds) {
|
|
2214
|
-
// Exponential backoff: delay = base * 2^(attempt-1)
|
|
2215
|
-
const exponentialDelay = baseDelaySeconds * Math.pow(2, attemptNumber - 1);
|
|
2216
|
-
// Add jitter (0-25% of delay) to prevent thundering herd
|
|
2217
|
-
const jitter = exponentialDelay * 0.25 * Math.random();
|
|
2218
|
-
// Cap at 30 seconds to prevent excessive delays
|
|
2219
|
-
const totalDelay = Math.min(exponentialDelay + jitter, 30);
|
|
2220
|
-
return totalDelay * 1000; // Convert to milliseconds
|
|
2221
|
-
}
|
|
2222
|
-
/**
|
|
2223
|
-
* Selects candidate models for failover based on the strategy and current failure.
|
|
2224
|
-
*
|
|
2225
|
-
* @param currentModel - The model that just failed
|
|
2226
|
-
* @param currentVendorId - The vendor ID that just failed
|
|
2227
|
-
* @param strategy - The failover strategy to use
|
|
2228
|
-
* @param modelStrategy - The model selection preference
|
|
2229
|
-
* @param allCandidates - All available model-vendor candidates
|
|
2230
|
-
* @param attemptHistory - History of previous failover attempts
|
|
2231
|
-
* @returns Array of candidates sorted by priority (highest first)
|
|
2232
|
-
*
|
|
2233
|
-
* @remarks
|
|
2234
|
-
* This method implements different strategies for selecting failover candidates:
|
|
2235
|
-
* - SameModelDifferentVendor: Try the same model with different vendors
|
|
2236
|
-
* - NextBestModel: Try different models in order of preference
|
|
2237
|
-
* - PowerRank: Use the global power ranking of models
|
|
2238
|
-
*
|
|
2239
|
-
* Override this method to implement custom candidate selection logic.
|
|
2240
|
-
*/
|
|
2241
|
-
selectFailoverCandidates(currentModel, currentVendorId, strategy, modelStrategy, allCandidates, attemptHistory) {
|
|
2242
|
-
// Filter out candidates that have already failed
|
|
2243
|
-
// Note: Authentication errors are already filtered from allCandidates upstream,
|
|
2244
|
-
// so we only need to filter out specific model/vendor pairs that have failed
|
|
2245
|
-
const failedPairs = new Set(attemptHistory.map(a => `${a.modelId}:${a.vendorId || 'default'}`));
|
|
2246
|
-
const availableCandidates = allCandidates.filter(c => {
|
|
2247
|
-
const key = `${c.model.ID}:${c.vendorId || 'default'}`;
|
|
2248
|
-
return !failedPairs.has(key);
|
|
2249
|
-
});
|
|
2250
|
-
// Check if we have context length exceeded errors in the attempt history
|
|
2251
|
-
const hasContextLengthError = attemptHistory.some(a => a.errorType === 'ContextLengthExceeded' ||
|
|
2252
|
-
ErrorAnalyzer.analyzeError(a.error).errorType === 'ContextLengthExceeded');
|
|
2253
|
-
// Apply strategy-specific filtering and sorting
|
|
2254
|
-
let candidates;
|
|
2255
|
-
switch (strategy) {
|
|
2256
|
-
case 'SameModelDifferentVendor':
|
|
2257
|
-
// Only consider same model with different vendors
|
|
2258
|
-
candidates = availableCandidates.filter(c => UUIDsEqual(c.model.ID, currentModel.ID) && !UUIDsEqual(c.vendorId, currentVendorId));
|
|
2259
|
-
break;
|
|
2260
|
-
case 'NextBestModel':
|
|
2261
|
-
// Consider all models, apply model strategy preference
|
|
2262
|
-
candidates = availableCandidates;
|
|
2263
|
-
if (modelStrategy === 'RequireSameModel') {
|
|
2264
|
-
candidates = candidates.filter(c => UUIDsEqual(c.model.ID, currentModel.ID));
|
|
2265
|
-
}
|
|
2266
|
-
else if (modelStrategy === 'PreferSameModel') {
|
|
2267
|
-
// Sort to put same model first
|
|
2268
|
-
candidates.sort((a, b) => {
|
|
2269
|
-
const aSameModel = UUIDsEqual(a.model.ID, currentModel.ID) ? 1 : 0;
|
|
2270
|
-
const bSameModel = UUIDsEqual(b.model.ID, currentModel.ID) ? 1 : 0;
|
|
2271
|
-
return bSameModel - aSameModel;
|
|
2272
|
-
});
|
|
2273
|
-
}
|
|
2274
|
-
else if (modelStrategy === 'PreferDifferentModel') {
|
|
2275
|
-
// Sort to put different models first
|
|
2276
|
-
candidates.sort((a, b) => {
|
|
2277
|
-
const aDiffModel = !UUIDsEqual(a.model.ID, currentModel.ID) ? 1 : 0;
|
|
2278
|
-
const bDiffModel = !UUIDsEqual(b.model.ID, currentModel.ID) ? 1 : 0;
|
|
2279
|
-
return bDiffModel - aDiffModel;
|
|
2280
|
-
});
|
|
2281
|
-
}
|
|
2282
|
-
break;
|
|
2283
|
-
case 'PowerRank':
|
|
2284
|
-
// Use all candidates, they're already sorted by power rank
|
|
2285
|
-
candidates = availableCandidates;
|
|
2286
|
-
break;
|
|
2287
|
-
default:
|
|
2288
|
-
candidates = [];
|
|
2289
|
-
}
|
|
2290
|
-
// If we have context length errors, prioritize models with larger context windows
|
|
2291
|
-
if (hasContextLengthError) {
|
|
2292
|
-
const currentMaxTokens = currentModel.ModelVendors?.length > 0 ?
|
|
2293
|
-
Math.max(...currentModel.ModelVendors.map(mv => mv.MaxInputTokens || 0)) : 0;
|
|
2294
|
-
// Filter out models with same or smaller context windows
|
|
2295
|
-
candidates = candidates.filter(c => {
|
|
2296
|
-
const candidateMaxTokens = c.model.ModelVendors?.length > 0 ?
|
|
2297
|
-
Math.max(...c.model.ModelVendors.map(mv => mv.MaxInputTokens || 0)) : 0;
|
|
2298
|
-
return candidateMaxTokens > currentMaxTokens;
|
|
2299
|
-
});
|
|
2300
|
-
// If no larger models exist, this is a fatal error - return empty to stop retrying
|
|
2301
|
-
if (candidates.length === 0) {
|
|
2302
|
-
LogStatusEx({
|
|
2303
|
-
message: `❌ Context length exceeded and no models with larger context windows available. Current model: ${currentModel.Name} (${currentMaxTokens} max tokens). This is a fatal error.`,
|
|
2304
|
-
category: 'AI',
|
|
2305
|
-
additionalArgs: [{
|
|
2306
|
-
currentModel: currentModel.Name,
|
|
2307
|
-
currentMaxTokens,
|
|
2308
|
-
availableModels: allCandidates.map(c => c.model.Name).join(', '),
|
|
2309
|
-
reason: 'No models with larger context windows available for failover'
|
|
2310
|
-
}]
|
|
2311
|
-
});
|
|
2312
|
-
// Return empty array - caller will see no candidates and stop retrying
|
|
2313
|
-
return [];
|
|
2314
|
-
}
|
|
2315
|
-
// Sort by priority first (existing algorithm), then by context window size as tiebreaker
|
|
2316
|
-
candidates.sort((a, b) => {
|
|
2317
|
-
// Primary sort: priority (higher is better) - maintains existing algorithm
|
|
2318
|
-
if (a.priority !== b.priority) {
|
|
2319
|
-
return b.priority - a.priority;
|
|
2320
|
-
}
|
|
2321
|
-
// Secondary sort: context window size (largest first) - only as tiebreaker
|
|
2322
|
-
const aMaxTokens = a.model.ModelVendors?.length > 0 ?
|
|
2323
|
-
Math.max(...a.model.ModelVendors.map((mv) => mv.MaxInputTokens || 0)) : 0;
|
|
2324
|
-
const bMaxTokens = b.model.ModelVendors?.length > 0 ?
|
|
2325
|
-
Math.max(...b.model.ModelVendors.map((mv) => mv.MaxInputTokens || 0)) : 0;
|
|
2326
|
-
return bMaxTokens - aMaxTokens;
|
|
2327
|
-
});
|
|
2328
|
-
// Log context-aware failover selection
|
|
2329
|
-
const bestCandidate = candidates[0];
|
|
2330
|
-
const bestCandidateMaxTokens = bestCandidate.model.ModelVendors?.length > 0 ?
|
|
2331
|
-
Math.max(...bestCandidate.model.ModelVendors.map((mv) => mv.MaxInputTokens || 0)) : 0;
|
|
2332
|
-
LogStatusEx({
|
|
2333
|
-
message: `🔄 Context-aware failover: Selected model ${bestCandidate.model.Name} with ${bestCandidateMaxTokens} max input tokens (vs ${currentMaxTokens} for failed model)`,
|
|
2334
|
-
category: 'AI',
|
|
2335
|
-
additionalArgs: [{
|
|
2336
|
-
currentModel: currentModel.Name,
|
|
2337
|
-
currentMaxTokens,
|
|
2338
|
-
selectedModel: bestCandidate.model.Name,
|
|
2339
|
-
selectedMaxTokens: bestCandidateMaxTokens,
|
|
2340
|
-
candidateCount: candidates.length
|
|
2341
|
-
}]
|
|
2342
|
-
});
|
|
2343
|
-
}
|
|
2344
|
-
else {
|
|
2345
|
-
// Final sort by priority (higher is better) for non-context-length errors
|
|
2346
|
-
candidates.sort((a, b) => b.priority - a.priority);
|
|
2347
|
-
}
|
|
2348
|
-
return candidates;
|
|
2349
|
-
}
|
|
2350
2212
|
/**
|
|
2351
2213
|
* Logs a failover attempt for tracking and debugging.
|
|
2352
2214
|
*
|