@memberjunction/ai-prompts 6.2.0-edge.5 → 6.2.0-edge.7
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/dist/AIPromptRunner.d.ts +81 -5
- package/dist/AIPromptRunner.d.ts.map +1 -1
- package/dist/AIPromptRunner.js +337 -122
- package/dist/AIPromptRunner.js.map +1 -1
- package/dist/BaseModelRunner.d.ts +79 -1
- package/dist/BaseModelRunner.d.ts.map +1 -1
- package/dist/BaseModelRunner.js +256 -27
- package/dist/BaseModelRunner.js.map +1 -1
- package/dist/ParallelExecutionCoordinator.d.ts.map +1 -1
- package/dist/ParallelExecutionCoordinator.js +7 -0
- package/dist/ParallelExecutionCoordinator.js.map +1 -1
- package/dist/PromptRunDataCapture.d.ts.map +1 -1
- package/dist/PromptRunDataCapture.js +7 -0
- package/dist/PromptRunDataCapture.js.map +1 -1
- package/dist/decision/AIDecisionRunner.d.ts +1 -3
- package/dist/decision/AIDecisionRunner.d.ts.map +1 -1
- package/dist/decision/AIDecisionRunner.js +6 -17
- package/dist/decision/AIDecisionRunner.js.map +1 -1
- package/dist/embedding/AIEmbeddingRunner.d.ts +0 -1
- package/dist/embedding/AIEmbeddingRunner.d.ts.map +1 -1
- package/dist/embedding/AIEmbeddingRunner.js +6 -14
- package/dist/embedding/AIEmbeddingRunner.js.map +1 -1
- package/dist/embedding/embedding-runner.types.d.ts +8 -0
- package/dist/embedding/embedding-runner.types.d.ts.map +1 -1
- package/dist/image/AIImageGenerationRunner.d.ts +1 -3
- package/dist/image/AIImageGenerationRunner.d.ts.map +1 -1
- package/dist/image/AIImageGenerationRunner.js +3 -15
- package/dist/image/AIImageGenerationRunner.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/media/BaseMediaRunner.d.ts +1 -3
- package/dist/media/BaseMediaRunner.d.ts.map +1 -1
- package/dist/media/BaseMediaRunner.js +3 -15
- package/dist/media/BaseMediaRunner.js.map +1 -1
- package/dist/no-model-found-message.d.ts +63 -0
- package/dist/no-model-found-message.d.ts.map +1 -0
- package/dist/no-model-found-message.js +95 -0
- package/dist/no-model-found-message.js.map +1 -0
- package/dist/replayedReasoningPrefix.d.ts +10 -0
- package/dist/replayedReasoningPrefix.d.ts.map +1 -0
- package/dist/replayedReasoningPrefix.js +35 -0
- package/dist/replayedReasoningPrefix.js.map +1 -0
- package/dist/video/AIVideoRunner.d.ts +39 -11
- package/dist/video/AIVideoRunner.d.ts.map +1 -1
- package/dist/video/AIVideoRunner.js +69 -10
- package/dist/video/AIVideoRunner.js.map +1 -1
- package/dist/video/VideoGenerationRunner.d.ts +40 -0
- package/dist/video/VideoGenerationRunner.d.ts.map +1 -0
- package/dist/video/VideoGenerationRunner.js +299 -0
- package/dist/video/VideoGenerationRunner.js.map +1 -0
- package/dist/video/video-runner.types.d.ts +45 -1
- package/dist/video/video-runner.types.d.ts.map +1 -1
- package/package.json +12 -12
package/dist/AIPromptRunner.js
CHANGED
|
@@ -2,12 +2,14 @@ import { BaseLLM, ChatParams, ChatMessageRole, ErrorAnalyzer, ResolveFileInputSt
|
|
|
2
2
|
import { BaseModelRunner, } from './BaseModelRunner.js';
|
|
3
3
|
import { GetToolCallingDecision, GetToolCallingMode, RecordToolCallingDecision, RecordToolCallingMode, ResolveNativeToolCalling, ResolveToolChoiceForRequest } from './nativeToolCallingGate.js';
|
|
4
4
|
import { AIModelRunner } from './AIModelRunner.js';
|
|
5
|
+
import { RecordSentPrefixFingerprint, ReplayedReasoningPrefixFingerprint, WithoutReplayedReasoning } from './replayedReasoningPrefix.js';
|
|
5
6
|
import { AIModelSelectionInfo, PickPromptExecutionScope } from '@memberjunction/ai-core-plus';
|
|
6
7
|
import { LogError, LogStatus, IsVerboseLoggingEnabled, Metadata } from '@memberjunction/core';
|
|
7
8
|
import { CleanJSON, RepairJSONEscaping, MJGlobal, JSONValidator, ValidationResult, ValidationErrorInfo, ValidationErrorType, UUIDsEqual, NormalizeUUID } from '@memberjunction/global';
|
|
8
9
|
import { TemplateEngineServer } from '@memberjunction/templates';
|
|
9
10
|
import { ExecutionPlanner } from './ExecutionPlanner.js';
|
|
10
11
|
import { AIPromptTimeoutError } from './AIPromptTimeoutError.js';
|
|
12
|
+
import { BuildNoModelFoundMessage, NOT_EVALUATED_REASON } from './no-model-found-message.js';
|
|
11
13
|
import { ParseManifestEntryMime, TrimSpacesAndTabs } from './linearTextScan.js';
|
|
12
14
|
import { AIEngine } from '@memberjunction/aiengine';
|
|
13
15
|
import { AIEngineBase } from '@memberjunction/ai-engine-base';
|
|
@@ -34,9 +36,11 @@ function mimeFromBlockType(type) {
|
|
|
34
36
|
}
|
|
35
37
|
}
|
|
36
38
|
export class AIPromptRunner extends BaseModelRunner {
|
|
37
|
-
/** The render options a prompt asks for: a raw render when `templateAutoescape` is false
|
|
39
|
+
/** The render options a prompt asks for: the prompt caller as the render user, and a raw render when `templateAutoescape` is false. */
|
|
38
40
|
static RenderOptions(params) {
|
|
39
|
-
return params.templateAutoescape === false
|
|
41
|
+
return params.templateAutoescape === false
|
|
42
|
+
? { autoescape: false, ContextUser: params.contextUser }
|
|
43
|
+
: { ContextUser: params.contextUser };
|
|
40
44
|
}
|
|
41
45
|
/**
|
|
42
46
|
* The model type this runner requires. Returns 'LLM' for AIPromptRunner.
|
|
@@ -48,6 +52,14 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
48
52
|
get DefaultLogCategory() {
|
|
49
53
|
return 'AIPromptRunner';
|
|
50
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* Per request: renders its template again with other template data (see `rerenderForNativeDecision`).
|
|
57
|
+
* Shared across runner instances, because the parallel coordinator runs each task on its own
|
|
58
|
+
* runner with a copy of the params (see {@link ShareNativeRerender}).
|
|
59
|
+
*/
|
|
60
|
+
static { this._nativeRerenderers = new WeakMap(); }
|
|
61
|
+
/** Per result: the prompt run's `Messages`, when the attempt sent a prompt rendered again for its own path. */
|
|
62
|
+
static { this._rerenderedMessages = new WeakMap(); }
|
|
51
63
|
/**
|
|
52
64
|
* Process-wide cache of parsed `OutputExample` JSON, keyed by the raw example string.
|
|
53
65
|
* A prompt's OutputExample is a static string reused across every run and every validation
|
|
@@ -62,7 +74,7 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
62
74
|
* that were intentionally NOT credential-checked because a higher-priority candidate had
|
|
63
75
|
* already been selected. See the DECISION note in {@link selectModelWithAPIKeyTracked}.
|
|
64
76
|
*/
|
|
65
|
-
static { this.NOT_EVALUATED_REASON =
|
|
77
|
+
static { this.NOT_EVALUATED_REASON = NOT_EVALUATED_REASON; }
|
|
66
78
|
constructor() {
|
|
67
79
|
super();
|
|
68
80
|
this._metadata =
|
|
@@ -188,9 +200,8 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
188
200
|
// (plan §8.4), and that is only safe if the flag is the gate's real answer rather than the
|
|
189
201
|
// caller's intent — a prompt that suppressed its catalog while the model received no tools
|
|
190
202
|
// would leave the agent unable to act at all.
|
|
191
|
-
//
|
|
192
|
-
// the
|
|
193
|
-
// correctly (no tools are sent); the prompt is merely quieter than it should be.
|
|
203
|
+
// Failover re-resolves the gate per attempt; an attempt whose decision differs from this one
|
|
204
|
+
// renders the template again for its own path (see `rerenderForNativeDecision`).
|
|
194
205
|
//
|
|
195
206
|
// This must resolve from the SAME inputs the request-time call uses (see
|
|
196
207
|
// `applyNativeToolCalling`), or the template can render for the opposite path: the vendor
|
|
@@ -214,6 +225,15 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
214
225
|
: await this.renderChildPromptTemplates(params.childPrompts, params, params.cancellationToken);
|
|
215
226
|
// Render the parent prompt with child templates embedded
|
|
216
227
|
renderedPromptText = await this.renderPromptWithChildTemplates(prompt, params, childTemplateRenderingResult.renderedTemplates);
|
|
228
|
+
// Child templates read the native flags too, so a re-render renders them again — unless the
|
|
229
|
+
// caller supplied them already rendered, in which case they are all there is.
|
|
230
|
+
const preRendered = params.PreRenderedChildTemplates;
|
|
231
|
+
this.registerNativeRerender(params, async (data) => {
|
|
232
|
+
const rerenderParams = this.withPromptData(params, data);
|
|
233
|
+
const children = preRendered
|
|
234
|
+
?? (await this.renderChildPromptTemplates(params.childPrompts, rerenderParams, params.cancellationToken)).renderedTemplates;
|
|
235
|
+
return this.renderPromptWithChildTemplates(prompt, rerenderParams, children);
|
|
236
|
+
});
|
|
217
237
|
}
|
|
218
238
|
// Create parent prompt run for the final composed prompt execution
|
|
219
239
|
parentPromptRun = await this.createPromptRun(prompt, selection.model, params, renderedPromptText, startTime, params.override?.vendorId, selection.selectionInfo);
|
|
@@ -240,6 +260,13 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
240
260
|
throw new Error(`Failed to render template for prompt ${prompt.Name}: ${renderedPrompt.Message}`);
|
|
241
261
|
}
|
|
242
262
|
renderedPromptText = renderedPrompt.Output;
|
|
263
|
+
this.registerNativeRerender(params, async (data) => {
|
|
264
|
+
const rerendered = await this.renderPromptTemplate(template, this.withPromptData(params, data));
|
|
265
|
+
if (!rerendered.Success) {
|
|
266
|
+
throw new Error(`Failed to re-render template for prompt ${prompt.Name}: ${rerendered.Message}`);
|
|
267
|
+
}
|
|
268
|
+
return rerendered.Output;
|
|
269
|
+
});
|
|
243
270
|
}
|
|
244
271
|
}
|
|
245
272
|
// Check for cancellation after template rendering
|
|
@@ -400,9 +427,6 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
400
427
|
// Calculate execution metrics
|
|
401
428
|
const endTime = new Date();
|
|
402
429
|
const executionTimeMS = endTime.getTime() - startTime.getTime();
|
|
403
|
-
// Layer 4 instrumentation: attribute this run to the path it actually took, before the update
|
|
404
|
-
// persists it. Left NULL when no model call happened, which is the honest value.
|
|
405
|
-
promptRun.ToolCallingMode = GetToolCallingMode(modelResult) ?? null;
|
|
406
430
|
// Update the prompt run with results including validation attempts and cumulative tokens
|
|
407
431
|
await this.updatePromptRun(promptRun, prompt, modelResult, parsedResult, endTime, executionTimeMS, validationAttempts, cumulativeTokens);
|
|
408
432
|
const chatResult = modelResult;
|
|
@@ -502,8 +526,7 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
502
526
|
const requiredTypeId = this.RequiredModelTypeID();
|
|
503
527
|
const typedModels = AIEngine.Instance.Models.filter(m => UUIDsEqual(m.AIModelTypeID, requiredTypeId));
|
|
504
528
|
// Get prompt-specific model associations using the model selection prompt
|
|
505
|
-
const promptModels =
|
|
506
|
-
(pm.Status === 'Active' || pm.Status === 'Preview') &&
|
|
529
|
+
const promptModels = this.getPromptModelsForPromptId(modelSelectionPrompt.ID).filter((pm) => (pm.Status === 'Active' || pm.Status === 'Preview') &&
|
|
507
530
|
(!params.configurationId || !pm.ConfigurationID || UUIDsEqual(pm.ConfigurationID, params.configurationId)) &&
|
|
508
531
|
UUIDsEqual(AIEngine.Instance.ModelsByID.get(NormalizeUUID(pm.ModelID))?.AIModelTypeID, requiredTypeId));
|
|
509
532
|
// Create execution plan using the modelSelectionPrompt for model configurations
|
|
@@ -1110,7 +1133,8 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1110
1133
|
selectionReason += ' using preferred vendor';
|
|
1111
1134
|
}
|
|
1112
1135
|
// Check if fallback was used (not the first candidate)
|
|
1113
|
-
|
|
1136
|
+
// A fallback: the top-ranked candidate had no credentials (not the row vendor serving the model it picked).
|
|
1137
|
+
const fallbackUsed = credentialAvailability.get(this.CandidateKey(candidates[0])) === false;
|
|
1114
1138
|
// Get selected vendor entity
|
|
1115
1139
|
let selectedVendor;
|
|
1116
1140
|
if (selected.vendorId) {
|
|
@@ -1180,10 +1204,6 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1180
1204
|
* @returns Object containing selected candidate and all considered models
|
|
1181
1205
|
*/
|
|
1182
1206
|
async selectModelWithAPIKeyTracked(candidates, promptId, params) {
|
|
1183
|
-
// Cache for credential availability checks
|
|
1184
|
-
// Key format: "driverClass:modelId:vendorId" to properly cache credential hierarchy
|
|
1185
|
-
const credentialCache = new Map();
|
|
1186
|
-
const consideredModels = [];
|
|
1187
1207
|
// DECISION (performance): candidates are ordered by priority, and we only need the
|
|
1188
1208
|
// highest-priority candidate that has working credentials. So once we find that first
|
|
1189
1209
|
// hit, we STOP credential-probing the remaining candidates and record them as
|
|
@@ -1195,50 +1215,20 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1195
1215
|
// is skipped. Callers that need a complete availability report (e.g. an admin diagnostic)
|
|
1196
1216
|
// can set `AIPromptParams.forceFullModelEvaluation = true` to probe every candidate.
|
|
1197
1217
|
const forceFullEval = params?.forceFullModelEvaluation === true;
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
const
|
|
1201
|
-
|
|
1202
|
-
: undefined;
|
|
1203
|
-
// Short-circuit: a usable candidate is already selected and full evaluation wasn't requested.
|
|
1204
|
-
if (selected && !forceFullEval) {
|
|
1205
|
-
consideredModels.push({
|
|
1206
|
-
model: candidate.model,
|
|
1207
|
-
vendor: vendorEntity,
|
|
1208
|
-
priority: candidate.priority,
|
|
1209
|
-
available: false,
|
|
1210
|
-
unavailableReason: AIPromptRunner.NOT_EVALUATED_REASON
|
|
1211
|
-
});
|
|
1212
|
-
continue;
|
|
1213
|
-
}
|
|
1214
|
-
// Build cache key including model and vendor for proper credential resolution
|
|
1215
|
-
const cacheKey = `${candidate.driverClass}:${candidate.model.ID}:${candidate.vendorId || 'default'}`;
|
|
1216
|
-
// Check cache first
|
|
1217
|
-
let hasCredentials;
|
|
1218
|
-
if (credentialCache.has(cacheKey)) {
|
|
1219
|
-
hasCredentials = credentialCache.get(cacheKey);
|
|
1220
|
-
}
|
|
1221
|
-
else {
|
|
1222
|
-
// Check for credentials using hierarchical resolution
|
|
1223
|
-
hasCredentials = this.HasCredentialsAvailable(candidate.driverClass, promptId, candidate.model.ID, candidate.vendorId, params);
|
|
1224
|
-
credentialCache.set(cacheKey, hasCredentials);
|
|
1225
|
-
}
|
|
1226
|
-
// Track this model as considered with availability status
|
|
1227
|
-
const considered = {
|
|
1218
|
+
const { Candidate: selectedCandidate, CredentialAvailability: credentialCache } = this.SelectCandidate(candidates, c => this.HasCredentialsAvailable(c.driverClass, promptId, c.model.ID, c.vendorId, params), forceFullEval);
|
|
1219
|
+
const consideredModels = candidates.map(candidate => {
|
|
1220
|
+
const available = credentialCache.get(this.CandidateKey(candidate));
|
|
1221
|
+
return {
|
|
1228
1222
|
model: candidate.model,
|
|
1229
|
-
vendor:
|
|
1223
|
+
vendor: candidate.vendorId ? AIEngine.Instance.VendorsByID.get(NormalizeUUID(candidate.vendorId)) : undefined,
|
|
1224
|
+
driverClass: candidate.driverClass,
|
|
1230
1225
|
priority: candidate.priority,
|
|
1231
|
-
available:
|
|
1232
|
-
unavailableReason:
|
|
1226
|
+
available: available === true,
|
|
1227
|
+
unavailableReason: available === undefined
|
|
1228
|
+
? AIPromptRunner.NOT_EVALUATED_REASON
|
|
1229
|
+
: available ? undefined : `No credentials configured for driver ${candidate.driverClass}`
|
|
1233
1230
|
};
|
|
1234
|
-
|
|
1235
|
-
// Record the first available candidate as the selection (highest priority with credentials)
|
|
1236
|
-
if (hasCredentials && !selected) {
|
|
1237
|
-
selected = considered;
|
|
1238
|
-
}
|
|
1239
|
-
}
|
|
1240
|
-
const selectedCandidate = selected ? candidates.find(c => UUIDsEqual(c.model.ID, selected.model.ID) &&
|
|
1241
|
-
UUIDsEqual(c.vendorId, selected.vendor?.ID)) : null;
|
|
1231
|
+
});
|
|
1242
1232
|
if (selectedCandidate) {
|
|
1243
1233
|
const validCount = consideredModels.filter(m => m.available).length;
|
|
1244
1234
|
this.logStatus(` Selected model ${selectedCandidate.model.Name} with ${selectedCandidate.vendorName || 'default'} vendor (driver: ${selectedCandidate.driverClass})`, true);
|
|
@@ -1264,37 +1254,14 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1264
1254
|
}
|
|
1265
1255
|
/**
|
|
1266
1256
|
* Builds a descriptive error message when no model could be selected for a prompt.
|
|
1267
|
-
*
|
|
1268
|
-
*
|
|
1257
|
+
*
|
|
1258
|
+
* The body lives in `no-model-found-message.ts` so it can be tested directly — as a private
|
|
1259
|
+
* method its only coverage was a re-implementation of it in the test file, which asserted
|
|
1260
|
+
* against its own copy rather than this code.
|
|
1269
1261
|
*/
|
|
1270
1262
|
buildNoModelFoundMessage(promptName, selectionInfo, credentialScope) {
|
|
1271
|
-
const
|
|
1272
|
-
|
|
1273
|
-
// rather than the generic "no candidates" text. Every other reason keeps its detailed message below.
|
|
1274
|
-
if (selectionInfo?.selectionReason?.startsWith('Error during model selection:')) {
|
|
1275
|
-
return `${base}. ${selectionInfo.selectionReason}`;
|
|
1276
|
-
}
|
|
1277
|
-
if (!selectionInfo?.modelsConsidered || selectionInfo.modelsConsidered.length === 0) {
|
|
1278
|
-
return `${base}. No model-vendor candidates were available. Please ensure AI models are configured for this prompt.`;
|
|
1279
|
-
}
|
|
1280
|
-
// Check if all models were unavailable due to missing credentials
|
|
1281
|
-
const unavailableModels = selectionInfo.modelsConsidered.filter(m => !m.available);
|
|
1282
|
-
if (unavailableModels.length === selectionInfo.modelsConsidered.length) {
|
|
1283
|
-
const triedSummary = unavailableModels.slice(0, 5).map(m => {
|
|
1284
|
-
const vendorName = m.vendor?.Name || 'default';
|
|
1285
|
-
return `${m.model.Name}/${vendorName}`;
|
|
1286
|
-
}).join(', ');
|
|
1287
|
-
const suffix = unavailableModels.length > 5 ? ` (${unavailableModels.length} total)` : '';
|
|
1288
|
-
// When the scope rules out the platform's credentials, "configure them" would point the reader
|
|
1289
|
-
// at exactly the fallback the caller ruled out.
|
|
1290
|
-
const platformAllowed = CredentialScopeAllows(credentialScope, 'Environment') || CredentialScopeAllows(credentialScope, 'PlatformCredential');
|
|
1291
|
-
const remedy = platformAllowed
|
|
1292
|
-
? `Please configure API credentials in your environment or AI Credential settings.`
|
|
1293
|
-
: `The credential scope is ${credentialScope}, so only the API keys supplied with this run count; supply a key for one of these vendors.`;
|
|
1294
|
-
return `${base}. No valid API credentials/keys are configured for any of the candidate model-vendor combinations. ` +
|
|
1295
|
-
`Tried: ${triedSummary}${suffix}. ${remedy}`;
|
|
1296
|
-
}
|
|
1297
|
-
return `${base}. ${selectionInfo.selectionReason || 'Unknown reason'}`;
|
|
1263
|
+
const platformAllowed = CredentialScopeAllows(credentialScope, 'Environment') || CredentialScopeAllows(credentialScope, 'PlatformCredential');
|
|
1264
|
+
return BuildNoModelFoundMessage(promptName, selectionInfo, credentialScope ? { Name: credentialScope, PlatformAllowed: platformAllowed } : undefined);
|
|
1298
1265
|
}
|
|
1299
1266
|
/**
|
|
1300
1267
|
* Renders the prompt template with provided data
|
|
@@ -1495,6 +1462,91 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1495
1462
|
_NATIVE_CONTROL_FLOW: current._NATIVE_CONTROL_FLOW ?? 'envelope'
|
|
1496
1463
|
};
|
|
1497
1464
|
}
|
|
1465
|
+
/**
|
|
1466
|
+
* Remembers how to render this request's template again with different template data, so a
|
|
1467
|
+
* failover attempt whose native decision differs from the one the template was rendered for can
|
|
1468
|
+
* get a prompt that matches what it actually sends (see {@link rerenderForNativeDecision}).
|
|
1469
|
+
*/
|
|
1470
|
+
registerNativeRerender(params, render) {
|
|
1471
|
+
AIPromptRunner._nativeRerenderers.set(params, render);
|
|
1472
|
+
}
|
|
1473
|
+
/** Lets a copy of the params re-render the template the original registered — for the parallel path's per-task copies. */
|
|
1474
|
+
ShareNativeRerender(original, copy) {
|
|
1475
|
+
const render = AIPromptRunner._nativeRerenderers.get(original);
|
|
1476
|
+
if (render) {
|
|
1477
|
+
AIPromptRunner._nativeRerenderers.set(copy, render);
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
/** A copy of the params with other template data — the original is shared with parallel attempts and must not change. */
|
|
1481
|
+
withPromptData(params, data) {
|
|
1482
|
+
return Object.assign(Object.create(Object.getPrototypeOf(params)), params, { data });
|
|
1483
|
+
}
|
|
1484
|
+
/**
|
|
1485
|
+
* The prompt text for this attempt's native decision.
|
|
1486
|
+
*
|
|
1487
|
+
* The template's native wording is set once, from the first candidate's decision. Failover
|
|
1488
|
+
* re-resolves the decision per attempt, so an attempt can land on a model on another path —
|
|
1489
|
+
* envelope after native, or hybrid after implicit — and would otherwise be taught a protocol it
|
|
1490
|
+
* is not being asked to use. When the decision differs from the one the template was rendered
|
|
1491
|
+
* for, the template is rendered again for this attempt; otherwise the text is returned as is.
|
|
1492
|
+
*/
|
|
1493
|
+
async rerenderForNativeDecision(renderedPrompt, chatParams, params, model) {
|
|
1494
|
+
const decision = GetToolCallingDecision(chatParams);
|
|
1495
|
+
// A prompt rendered without the native flags (no agent-type system prompt) has no native
|
|
1496
|
+
// wording to correct, whatever the decision.
|
|
1497
|
+
if (!decision || params.data?._NATIVE_TOOL_CALLING === undefined) {
|
|
1498
|
+
return renderedPrompt;
|
|
1499
|
+
}
|
|
1500
|
+
const renderedNative = params.data?._NATIVE_TOOL_CALLING === true;
|
|
1501
|
+
const renderedFlow = params.data?._NATIVE_CONTROL_FLOW ?? 'envelope';
|
|
1502
|
+
if (renderedNative === decision.useNativeTools && (!decision.useNativeTools || renderedFlow === decision.controlFlow)) {
|
|
1503
|
+
return renderedPrompt;
|
|
1504
|
+
}
|
|
1505
|
+
this.logStatus(` Re-rendering the prompt for ${model.Name}: its tool-calling path (${decision.mode}) differs from the one the prompt was rendered for`, true, params);
|
|
1506
|
+
return this.rerenderOrKeep(renderedPrompt, params, this.ApplyNativeTemplateFlags(params.data, decision));
|
|
1507
|
+
}
|
|
1508
|
+
/**
|
|
1509
|
+
* The template rendered again with `data`, or `renderedPrompt` unchanged when the request
|
|
1510
|
+
* registered no renderer or the render fails. A failed re-render is the template's problem, not
|
|
1511
|
+
* the model's: the attempt goes ahead with the text it already had, and the error is logged.
|
|
1512
|
+
*/
|
|
1513
|
+
async rerenderOrKeep(renderedPrompt, params, data) {
|
|
1514
|
+
const render = AIPromptRunner._nativeRerenderers.get(params);
|
|
1515
|
+
if (!render) {
|
|
1516
|
+
return renderedPrompt;
|
|
1517
|
+
}
|
|
1518
|
+
try {
|
|
1519
|
+
return await render(data);
|
|
1520
|
+
}
|
|
1521
|
+
catch (error) {
|
|
1522
|
+
LogError(`AIPromptRunner: re-rendering the prompt failed; sending the prompt as first rendered`, null, error);
|
|
1523
|
+
return renderedPrompt;
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
/**
|
|
1527
|
+
* Swaps the rendered prompt inside an already-built message array, keeping anything appended to
|
|
1528
|
+
* it (the prefill fallback instruction). Returns the messages unchanged when the prompt is not found.
|
|
1529
|
+
*/
|
|
1530
|
+
replaceRenderedPrompt(messages, from, to) {
|
|
1531
|
+
const at = messages.findIndex((m) => typeof m.content === 'string' && m.content.startsWith(from));
|
|
1532
|
+
if (at < 0 || from === to) {
|
|
1533
|
+
return messages;
|
|
1534
|
+
}
|
|
1535
|
+
const copy = [...messages];
|
|
1536
|
+
copy[at] = { ...copy[at], content: to + copy[at].content.slice(from.length) };
|
|
1537
|
+
return copy;
|
|
1538
|
+
}
|
|
1539
|
+
/** The prompt run's `Messages` for a result whose attempt sent a re-rendered prompt, or undefined. */
|
|
1540
|
+
RerenderedMessagesFor(result) {
|
|
1541
|
+
return AIPromptRunner._rerenderedMessages.get(result);
|
|
1542
|
+
}
|
|
1543
|
+
/** Records, for the prompt run, the messages an attempt sent when its prompt was rendered again. */
|
|
1544
|
+
recordRerenderedMessages(result, prompt, params, model, vendorId, renderedPrompt) {
|
|
1545
|
+
const json = this.storedMessagesJSON(prompt, params, model, renderedPrompt, vendorId ?? undefined);
|
|
1546
|
+
if (json) {
|
|
1547
|
+
AIPromptRunner._rerenderedMessages.set(result, json);
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1498
1550
|
/** @deprecated Use {@link ResolveNativeToolCallingDecision}. */
|
|
1499
1551
|
resolveNativeToolCallingDecision(prompt, params, model, vendorId, promptModelConfiguration) {
|
|
1500
1552
|
return this.ResolveNativeToolCallingDecision(prompt, params, model, vendorId, promptModelConfiguration);
|
|
@@ -1559,7 +1611,27 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1559
1611
|
if (this.IsCallerCancellation(result.errorInfo)) {
|
|
1560
1612
|
return false;
|
|
1561
1613
|
}
|
|
1562
|
-
return this.
|
|
1614
|
+
return this.isToolEligibleError(result.errorInfo)
|
|
1615
|
+
&& this.isToolSpecificFailureText(`${result.errorMessage ?? ''} ${result.statusText ?? ''}`);
|
|
1616
|
+
}
|
|
1617
|
+
/**
|
|
1618
|
+
* Whether the provider's error could be a rejected tools payload.
|
|
1619
|
+
*
|
|
1620
|
+
* A 400 or 422 is a request error whatever the classifier made of its text: the classifier reads
|
|
1621
|
+
* keywords such as "balance" or "timeout" before the status, and a schema rejection quoting a
|
|
1622
|
+
* `Get_Account_Balance` tool or a `TimeoutMS` property would otherwise pass as a credit or network
|
|
1623
|
+
* failure. Without one of those statuses, only the classifications that are never about the
|
|
1624
|
+
* tools payload — a rate limit, an authentication failure, a cancellation, a context-length
|
|
1625
|
+
* error — are ruled out. An error with no classification is judged by its text alone.
|
|
1626
|
+
*/
|
|
1627
|
+
isToolEligibleError(errorInfo) {
|
|
1628
|
+
if (!errorInfo) {
|
|
1629
|
+
return true;
|
|
1630
|
+
}
|
|
1631
|
+
if (errorInfo.httpStatusCode === 400 || errorInfo.httpStatusCode === 422) {
|
|
1632
|
+
return true;
|
|
1633
|
+
}
|
|
1634
|
+
return !AIPromptRunner.TOOL_INELIGIBLE_ERROR_TYPES.includes(errorInfo.errorType);
|
|
1563
1635
|
}
|
|
1564
1636
|
/**
|
|
1565
1637
|
* Retries a native call once on today's exact path, with the tool declarations stripped.
|
|
@@ -1572,7 +1644,7 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1572
1644
|
*
|
|
1573
1645
|
* @param reason What the provider said, for the warning — a misconfiguration should be visible
|
|
1574
1646
|
*/
|
|
1575
|
-
async retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, reason) {
|
|
1647
|
+
async retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, reason, params, renderedPrompt, firstRenderedPrompt) {
|
|
1576
1648
|
console.warn(`AIPromptRunner: native tool calling failed on ${model.Name}${vendorId ? ` (vendor ${vendorId})` : ''} ` +
|
|
1577
1649
|
`for prompt "${prompt.Name}" — retrying once on the envelope path with tools stripped. ` +
|
|
1578
1650
|
`Provider error: ${reason}`);
|
|
@@ -1585,10 +1657,36 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1585
1657
|
// the same request. Show the retry what the envelope path has always
|
|
1586
1658
|
// shown: the calls' prose, and each result as an "[Action Result]" user message.
|
|
1587
1659
|
chatParams.messages = EncodeToolTurnsAsText(chatParams.messages);
|
|
1660
|
+
// The prompt was rendered for native tools — no action catalog, "call the tool" wording. With
|
|
1661
|
+
// the tools gone, render it for the envelope, so the model can still act.
|
|
1662
|
+
const envelopePrompt = await this.rerenderOrKeep(renderedPrompt, params, { ...(params.data ?? {}), _NATIVE_TOOL_CALLING: false, _NATIVE_CONTROL_FLOW: 'envelope' });
|
|
1663
|
+
chatParams.messages = this.replaceRenderedPrompt(chatParams.messages, renderedPrompt, envelopePrompt);
|
|
1664
|
+
const sentPrefix = this.guardReplayedReasoningPrefix(chatParams, params, model);
|
|
1588
1665
|
const fallbackResult = await this.runChatCompletionBounded(llm, chatParams, executionBound);
|
|
1589
1666
|
RecordToolCallingMode(fallbackResult, 'NativeFallback');
|
|
1667
|
+
RecordSentPrefixFingerprint(fallbackResult, sentPrefix);
|
|
1668
|
+
// The prompt run holds the first-rendered prompt; record what this retry sent whenever it differs.
|
|
1669
|
+
if (envelopePrompt !== firstRenderedPrompt) {
|
|
1670
|
+
this.recordRerenderedMessages(fallbackResult, prompt, params, model, vendorId, envelopePrompt);
|
|
1671
|
+
}
|
|
1590
1672
|
return fallbackResult;
|
|
1591
1673
|
}
|
|
1674
|
+
/**
|
|
1675
|
+
* Sends a request without replayed reasoning when its system prompt or tools differ from the
|
|
1676
|
+
* previous request's (`params.ReplayedReasoningPrefix`): a provider that binds reasoning to an
|
|
1677
|
+
* unchanged prefix rejects it then — a skill that activated mid-run, a failover re-render.
|
|
1678
|
+
*
|
|
1679
|
+
* @returns This request's fingerprint, recorded on its result for the caller's next request
|
|
1680
|
+
*/
|
|
1681
|
+
guardReplayedReasoningPrefix(chatParams, params, model) {
|
|
1682
|
+
const fingerprint = ReplayedReasoningPrefixFingerprint(chatParams);
|
|
1683
|
+
const previous = params.ReplayedReasoningPrefix;
|
|
1684
|
+
if (previous !== undefined && previous !== fingerprint && chatParams.messages.some((m) => m.reasoning)) {
|
|
1685
|
+
this.logStatus(` The system prompt or tools changed since the previous request to ${model.Name}; sending it without replayed reasoning`, true, params);
|
|
1686
|
+
chatParams.messages = WithoutReplayedReasoning(chatParams.messages);
|
|
1687
|
+
}
|
|
1688
|
+
return fingerprint;
|
|
1689
|
+
}
|
|
1592
1690
|
/** Scans provider prose for a tools marker. Shared by the thrown-error and failed-result paths. */
|
|
1593
1691
|
isToolSpecificFailureText(text) {
|
|
1594
1692
|
const lowered = text.toLowerCase();
|
|
@@ -1742,6 +1840,8 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1742
1840
|
// Resolved HERE rather than once per run because failover may land on a different
|
|
1743
1841
|
// (model, vendor) that does not support tools.
|
|
1744
1842
|
this.applyNativeToolCalling(chatParams, prompt, params, model, vendorId, promptModelConfiguration);
|
|
1843
|
+
const firstRenderedPrompt = renderedPrompt;
|
|
1844
|
+
renderedPrompt = await this.rerenderForNativeDecision(renderedPrompt, chatParams, params, model);
|
|
1745
1845
|
// Build message array with rendered prompt and conversation messages
|
|
1746
1846
|
chatParams.messages = this.buildMessageArray(renderedPrompt, conversationMessages, templateMessageRole);
|
|
1747
1847
|
// Declarations and tool turns must travel TOGETHER. The gate above is re-resolved per
|
|
@@ -1770,13 +1870,68 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1770
1870
|
// place streaming is configured for prompt execution, so the single-model path and the parallel
|
|
1771
1871
|
// path (which bridges its per-task callbacks into params.onStreaming) stream through identical
|
|
1772
1872
|
// code — no second streaming implementation that can drift.
|
|
1873
|
+
// Coalesce rapid token chunks within a 35ms window (~28 fps) to avoid flooding WebSocket/PubSub
|
|
1874
|
+
// while emitting the first chunk immediately and flushing synchronously on completion.
|
|
1875
|
+
let flushStreamingBuffer;
|
|
1773
1876
|
if (params.onStreaming) {
|
|
1774
1877
|
const onStreaming = params.onStreaming;
|
|
1878
|
+
const coalesceIntervalMs = 35;
|
|
1879
|
+
let bufferedContent = '';
|
|
1880
|
+
let lastEmitMs = 0;
|
|
1881
|
+
let flushTimer = null;
|
|
1882
|
+
const clearTimer = () => {
|
|
1883
|
+
if (flushTimer !== null) {
|
|
1884
|
+
clearTimeout(flushTimer);
|
|
1885
|
+
flushTimer = null;
|
|
1886
|
+
}
|
|
1887
|
+
};
|
|
1888
|
+
const emitNow = (content, isComplete) => {
|
|
1889
|
+
clearTimer();
|
|
1890
|
+
lastEmitMs = Date.now();
|
|
1891
|
+
onStreaming({ content, isComplete, modelName: model.Name });
|
|
1892
|
+
};
|
|
1893
|
+
flushStreamingBuffer = () => {
|
|
1894
|
+
clearTimer();
|
|
1895
|
+
if (bufferedContent.length > 0) {
|
|
1896
|
+
const pending = bufferedContent;
|
|
1897
|
+
bufferedContent = '';
|
|
1898
|
+
lastEmitMs = Date.now();
|
|
1899
|
+
onStreaming({ content: pending, isComplete: false, modelName: model.Name });
|
|
1900
|
+
}
|
|
1901
|
+
};
|
|
1775
1902
|
chatParams.streaming = true;
|
|
1776
1903
|
chatParams.streamingCallbacks = {
|
|
1777
|
-
OnContent: (chunk, isComplete) =>
|
|
1904
|
+
OnContent: (chunk, isComplete) => {
|
|
1905
|
+
if (isComplete) {
|
|
1906
|
+
const combined = bufferedContent + chunk;
|
|
1907
|
+
bufferedContent = '';
|
|
1908
|
+
emitNow(combined, true);
|
|
1909
|
+
return;
|
|
1910
|
+
}
|
|
1911
|
+
const now = Date.now();
|
|
1912
|
+
if (lastEmitMs === 0 || now - lastEmitMs >= coalesceIntervalMs) {
|
|
1913
|
+
const combined = bufferedContent + chunk;
|
|
1914
|
+
bufferedContent = '';
|
|
1915
|
+
emitNow(combined, false);
|
|
1916
|
+
return;
|
|
1917
|
+
}
|
|
1918
|
+
bufferedContent += chunk;
|
|
1919
|
+
if (flushTimer === null) {
|
|
1920
|
+
const delay = Math.max(1, coalesceIntervalMs - (now - lastEmitMs));
|
|
1921
|
+
flushTimer = setTimeout(() => {
|
|
1922
|
+
flushTimer = null;
|
|
1923
|
+
if (bufferedContent.length > 0) {
|
|
1924
|
+
const pending = bufferedContent;
|
|
1925
|
+
bufferedContent = '';
|
|
1926
|
+
lastEmitMs = Date.now();
|
|
1927
|
+
onStreaming({ content: pending, isComplete: false, modelName: model.Name });
|
|
1928
|
+
}
|
|
1929
|
+
}, delay);
|
|
1930
|
+
}
|
|
1931
|
+
},
|
|
1778
1932
|
};
|
|
1779
1933
|
}
|
|
1934
|
+
const sentPrefix = this.guardReplayedReasoningPrefix(chatParams, params, model);
|
|
1780
1935
|
// Execute the model bounded by the composed abort signal (caller cancellation + prompt TimeoutMS)
|
|
1781
1936
|
//
|
|
1782
1937
|
// Layer 4 fallback, part one: some providers REJECT a tools payload instead of returning a
|
|
@@ -1786,13 +1941,21 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1786
1941
|
// for gpt-5.6-luna in /v1/chat/completions`. Both shapes get the same one-shot retry.
|
|
1787
1942
|
let chatResult;
|
|
1788
1943
|
try {
|
|
1789
|
-
|
|
1944
|
+
try {
|
|
1945
|
+
chatResult = await this.runChatCompletionBounded(llm, chatParams, executionBound);
|
|
1946
|
+
}
|
|
1947
|
+
finally {
|
|
1948
|
+
flushStreamingBuffer?.();
|
|
1949
|
+
}
|
|
1790
1950
|
}
|
|
1791
1951
|
catch (error) {
|
|
1792
|
-
|
|
1952
|
+
const thrownText = error instanceof Error ? error.message : String(error ?? '');
|
|
1953
|
+
if (!chatParams.tools?.length
|
|
1954
|
+
|| !this.isToolEligibleError(ErrorAnalyzer.analyzeError(error, driverClass))
|
|
1955
|
+
|| !this.isToolSpecificFailureText(thrownText)) {
|
|
1793
1956
|
throw error;
|
|
1794
1957
|
}
|
|
1795
|
-
return await this.retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, error instanceof Error ? error.message : String(error));
|
|
1958
|
+
return await this.retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, error instanceof Error ? error.message : String(error), params, renderedPrompt, firstRenderedPrompt);
|
|
1796
1959
|
}
|
|
1797
1960
|
// Carry the gate's WHOLE decision from the request onto the result, which is what flows back up
|
|
1798
1961
|
// to the prompt run (mode) and to the agent loop (`toolResults` — the loop answers native
|
|
@@ -1807,8 +1970,12 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1807
1970
|
// TOOLS-specific reason retries the same way. Non-tool failures fall through to the existing
|
|
1808
1971
|
// retry/failover machinery untouched.
|
|
1809
1972
|
if (chatParams.tools?.length && this.isToolSpecificFailure(chatResult)) {
|
|
1810
|
-
return await this.retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, chatResult.errorMessage || chatResult.statusText || 'unspecified');
|
|
1973
|
+
return await this.retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, chatResult.errorMessage || chatResult.statusText || 'unspecified', params, renderedPrompt, firstRenderedPrompt);
|
|
1974
|
+
}
|
|
1975
|
+
if (renderedPrompt !== firstRenderedPrompt) {
|
|
1976
|
+
this.recordRerenderedMessages(chatResult, prompt, params, model, vendorId, renderedPrompt);
|
|
1811
1977
|
}
|
|
1978
|
+
RecordSentPrefixFingerprint(chatResult, sentPrefix);
|
|
1812
1979
|
return chatResult;
|
|
1813
1980
|
}
|
|
1814
1981
|
catch (error) {
|
|
@@ -2099,6 +2266,8 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
2099
2266
|
}
|
|
2100
2267
|
return messages;
|
|
2101
2268
|
}
|
|
2269
|
+
/** Classified error types a rejected tools payload never arrives as. */
|
|
2270
|
+
static { this.TOOL_INELIGIBLE_ERROR_TYPES = ['RateLimit', 'Authentication', 'NoCredentials', 'Cancelled', 'ContextLengthExceeded']; }
|
|
2102
2271
|
/**
|
|
2103
2272
|
* Substrings that mark a provider failure as TOOLS-specific, so the native call is worth one
|
|
2104
2273
|
* envelope retry (see {@link AIPromptRunner.isToolSpecificFailure}). Drawn from how the
|
|
@@ -2108,16 +2277,33 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
2108
2277
|
* Substring matching over provider prose is inherently approximate. It is deliberately biased
|
|
2109
2278
|
* toward MISSING a tool failure rather than catching an unrelated one: a missed match just means
|
|
2110
2279
|
* the existing retry/failover logic handles the error as it does today, whereas a false positive
|
|
2111
|
-
* would silently strip tools from a run that should have kept them.
|
|
2280
|
+
* would silently strip tools from a run that should have kept them. So the markers name the
|
|
2281
|
+
* request's tool fields and the providers' own phrasing — never the bare words "tools" or
|
|
2282
|
+
* "tool call", which appear in errors that have nothing to do with the tools payload — and only
|
|
2283
|
+
* an error classified as a request error is matched at all (see `isToolEligibleError`).
|
|
2112
2284
|
*/
|
|
2113
2285
|
static { this.TOOL_FAILURE_MARKERS = [
|
|
2114
2286
|
'tool_use',
|
|
2115
2287
|
'tool use',
|
|
2116
2288
|
'tool_call',
|
|
2117
|
-
'tool call',
|
|
2289
|
+
'tool call validation',
|
|
2290
|
+
'invalid tool call',
|
|
2291
|
+
'tool calling',
|
|
2292
|
+
'tools is not supported',
|
|
2293
|
+
'tools param',
|
|
2294
|
+
'param: tools',
|
|
2118
2295
|
'tool_choice',
|
|
2119
2296
|
'tool choice',
|
|
2120
|
-
'tools',
|
|
2297
|
+
'tools:',
|
|
2298
|
+
'"tools"',
|
|
2299
|
+
'`tools`',
|
|
2300
|
+
"'tools'",
|
|
2301
|
+
'argument supplied: tools',
|
|
2302
|
+
'tools.',
|
|
2303
|
+
'tools[',
|
|
2304
|
+
'function tools',
|
|
2305
|
+
'support tools',
|
|
2306
|
+
'tools are not supported',
|
|
2121
2307
|
'function_call',
|
|
2122
2308
|
'function call',
|
|
2123
2309
|
'function_declaration',
|
|
@@ -2349,7 +2535,10 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
2349
2535
|
// Validation failed, check if we should retry
|
|
2350
2536
|
// BUG FIX: Only retry in Strict mode, not in Warn or None modes
|
|
2351
2537
|
const effectiveValidationBehavior = params?.validationBehavior || prompt.ValidationBehavior;
|
|
2352
|
-
|
|
2538
|
+
// A turn that called tools is answered by its calls; only its narration failed. Retrying
|
|
2539
|
+
// would ask again and throw the calls away, so the turn is kept as it is.
|
|
2540
|
+
const calledTools = (modelResult.data?.choices?.[0]?.message?.toolCalls?.length ?? 0) > 0;
|
|
2541
|
+
if (effectiveValidationBehavior === 'Strict' && attempt < maxRetries && !calledTools) {
|
|
2353
2542
|
lastError = new Error(`Validation failed: ${validationErrors?.map(e => e.Message).join('; ')}`);
|
|
2354
2543
|
LogStatus(` ⚠️ Validation failed on attempt ${attempt + 1}, will retry (Strict mode)`);
|
|
2355
2544
|
continue; // Retry
|
|
@@ -2358,7 +2547,7 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
2358
2547
|
// Either not strict mode or no more retries, return what we have
|
|
2359
2548
|
const reason = effectiveValidationBehavior !== 'Strict'
|
|
2360
2549
|
? `${effectiveValidationBehavior || 'None'} mode - continuing with invalid output (no retry)`
|
|
2361
|
-
: 'max retries exceeded';
|
|
2550
|
+
: calledTools ? 'the turn called tools — its calls are kept' : 'max retries exceeded';
|
|
2362
2551
|
LogStatus(` ⚠️ Validation failed on attempt ${attempt + 1}, stopping retries (${reason})`);
|
|
2363
2552
|
return {
|
|
2364
2553
|
modelResult,
|
|
@@ -3164,29 +3353,9 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
3164
3353
|
// (data, templateData) that the run's template-data capture mode allows.
|
|
3165
3354
|
// Also capture callers that supply conversationMessages directly (e.g. templateMessageRole='none',
|
|
3166
3355
|
// no rendered system prompt) — otherwise their assembled prompt would never be persisted.
|
|
3167
|
-
|
|
3168
|
-
|
|
3169
|
-
|
|
3170
|
-
// Build the system prompt content, including prefill fallback if applicable
|
|
3171
|
-
let systemContent = systemPromptText;
|
|
3172
|
-
if (prompt.AssistantPrefill && prompt.PrefillFallbackMode === 'SystemInstruction') {
|
|
3173
|
-
const fallbackTemplate = this.resolvePrefillFallbackText(model, vendorId);
|
|
3174
|
-
// Function replacement: prefill text is authored content that routinely
|
|
3175
|
-
// contains `$` (LaTeX `$$`, currency, JSON fragments), and a string
|
|
3176
|
-
// replacement would expand it. See issue #3171.
|
|
3177
|
-
const prefill = prompt.AssistantPrefill;
|
|
3178
|
-
const fallbackInstruction = fallbackTemplate.replace(/\{\{prefill\}\}/g, () => prefill);
|
|
3179
|
-
systemContent += '\n\n' + fallbackInstruction;
|
|
3180
|
-
}
|
|
3181
|
-
messages.push({
|
|
3182
|
-
role: 'system',
|
|
3183
|
-
content: systemContent
|
|
3184
|
-
});
|
|
3185
|
-
}
|
|
3186
|
-
// Always include any caller-supplied conversation messages (previously only recorded when a
|
|
3187
|
-
// template system prompt was present, which dropped them for the pure-conversationMessages path).
|
|
3188
|
-
messages.push(...(params.conversationMessages || []));
|
|
3189
|
-
promptRun.Messages = this.buildStoredMessagesJSON(prompt, params, messages);
|
|
3356
|
+
const storedMessages = this.storedMessagesJSON(prompt, params, model, systemPromptText, vendorId);
|
|
3357
|
+
if (storedMessages) {
|
|
3358
|
+
promptRun.Messages = storedMessages;
|
|
3190
3359
|
}
|
|
3191
3360
|
// Populate new retry tracking columns with initial values
|
|
3192
3361
|
promptRun.ValidationBehavior = params.validationBehavior || prompt.ValidationBehavior || 'Warn';
|
|
@@ -3204,6 +3373,39 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
3204
3373
|
}
|
|
3205
3374
|
return AIPromptRunner.serverTemplateDataCaptureDefault;
|
|
3206
3375
|
}
|
|
3376
|
+
/**
|
|
3377
|
+
* The prompt run's `Messages`: the messages the model received, plus the template inputs (data,
|
|
3378
|
+
* templateData) the run's template-data capture mode allows. Undefined when there is nothing to
|
|
3379
|
+
* store. Also captures callers that supply conversationMessages directly (templateMessageRole
|
|
3380
|
+
* 'none', no rendered system prompt), whose assembled prompt would otherwise never be persisted.
|
|
3381
|
+
*/
|
|
3382
|
+
storedMessagesJSON(prompt, params, model, systemPromptText, vendorId) {
|
|
3383
|
+
if (!(params.data || params.templateData || systemPromptText || (params.conversationMessages?.length ?? 0) > 0)) {
|
|
3384
|
+
return undefined;
|
|
3385
|
+
}
|
|
3386
|
+
const messages = [];
|
|
3387
|
+
if (systemPromptText) {
|
|
3388
|
+
// Build the system prompt content, including prefill fallback if applicable
|
|
3389
|
+
let systemContent = systemPromptText;
|
|
3390
|
+
if (prompt.AssistantPrefill && prompt.PrefillFallbackMode === 'SystemInstruction') {
|
|
3391
|
+
const fallbackTemplate = this.resolvePrefillFallbackText(model, vendorId);
|
|
3392
|
+
// Function replacement: prefill text is authored content that routinely
|
|
3393
|
+
// contains `$` (LaTeX `$$`, currency, JSON fragments), and a string
|
|
3394
|
+
// replacement would expand it. See issue #3171.
|
|
3395
|
+
const prefill = prompt.AssistantPrefill;
|
|
3396
|
+
const fallbackInstruction = fallbackTemplate.replace(/\{\{prefill\}\}/g, () => prefill);
|
|
3397
|
+
systemContent += '\n\n' + fallbackInstruction;
|
|
3398
|
+
}
|
|
3399
|
+
messages.push({
|
|
3400
|
+
role: 'system',
|
|
3401
|
+
content: systemContent
|
|
3402
|
+
});
|
|
3403
|
+
}
|
|
3404
|
+
// Always include any caller-supplied conversation messages (previously only recorded when a
|
|
3405
|
+
// template system prompt was present, which dropped them for the pure-conversationMessages path).
|
|
3406
|
+
messages.push(...(params.conversationMessages || []));
|
|
3407
|
+
return this.buildStoredMessagesJSON(prompt, params, messages);
|
|
3408
|
+
}
|
|
3207
3409
|
/**
|
|
3208
3410
|
* Serializes what this run stores in `AIPromptRun.Messages`, applying the template-data capture mode.
|
|
3209
3411
|
* A capture error never fails the run: it is logged, and the run stores `None` with a fixed note and no template data.
|
|
@@ -3272,7 +3474,20 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
3272
3474
|
async updatePromptRun(promptRun, prompt, modelResult, parsedResult, endTime, executionTimeMS, validationAttempts, cumulativeTokens) {
|
|
3273
3475
|
// A chat run succeeds only if the model call succeeded AND its output did not fail validation.
|
|
3274
3476
|
const success = modelResult.success && (parsedResult.validationResult?.Success !== false);
|
|
3275
|
-
return this.FinalizeRunRecord(promptRun, success, endTime, executionTimeMS, (run) =>
|
|
3477
|
+
return this.FinalizeRunRecord(promptRun, success, endTime, executionTimeMS, (run) => {
|
|
3478
|
+
// Layer 4 instrumentation: attribute this run to the path it actually took. Set inside the
|
|
3479
|
+
// finalize callback, like every result field: FinalizeRunRecord re-applies only what it saw
|
|
3480
|
+
// change, after an in-flight INSERT's reload has reverted the record — a value set before it
|
|
3481
|
+
// is lost on any call that returns faster than the INSERT. Left NULL when no model call
|
|
3482
|
+
// happened, which is the honest value.
|
|
3483
|
+
run.ToolCallingMode = GetToolCallingMode(modelResult) ?? null;
|
|
3484
|
+
// The prompt this attempt actually sent, when it was rendered again for its own path.
|
|
3485
|
+
const rerenderedMessages = AIPromptRunner._rerenderedMessages.get(modelResult);
|
|
3486
|
+
if (rerenderedMessages) {
|
|
3487
|
+
run.Messages = rerenderedMessages;
|
|
3488
|
+
}
|
|
3489
|
+
this.applyChatResultFields(run, prompt, modelResult, parsedResult, endTime, executionTimeMS, validationAttempts, cumulativeTokens);
|
|
3490
|
+
});
|
|
3276
3491
|
}
|
|
3277
3492
|
/**
|
|
3278
3493
|
* Populates a prompt-run's chat-specific finalized fields (result, tokens, cost, timing, validation)
|