@memberjunction/ai-prompts 6.2.0-edge.4 → 6.2.0-edge.6
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 +54 -2
- package/dist/AIModelRunner.d.ts +4 -0
- package/dist/AIModelRunner.d.ts.map +1 -1
- package/dist/AIModelRunner.js +7 -1
- package/dist/AIModelRunner.js.map +1 -1
- package/dist/AIPromptRunner.d.ts +125 -8
- package/dist/AIPromptRunner.d.ts.map +1 -1
- package/dist/AIPromptRunner.js +585 -181
- package/dist/AIPromptRunner.js.map +1 -1
- package/dist/AIPromptTimeoutError.d.ts +7 -1
- package/dist/AIPromptTimeoutError.d.ts.map +1 -1
- package/dist/AIPromptTimeoutError.js +5 -0
- package/dist/AIPromptTimeoutError.js.map +1 -1
- package/dist/BaseModelRunner.d.ts +88 -11
- package/dist/BaseModelRunner.d.ts.map +1 -1
- package/dist/BaseModelRunner.js +423 -52
- 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 +54 -0
- package/dist/PromptRunDataCapture.d.ts.map +1 -0
- package/dist/PromptRunDataCapture.js +181 -0
- package/dist/PromptRunDataCapture.js.map +1 -0
- package/dist/audio/AISpeechToTextRunner.d.ts +2 -1
- package/dist/audio/AISpeechToTextRunner.d.ts.map +1 -1
- package/dist/audio/AISpeechToTextRunner.js +5 -3
- package/dist/audio/AISpeechToTextRunner.js.map +1 -1
- package/dist/audio/AITextToSpeechRunner.js +1 -1
- package/dist/audio/AITextToSpeechRunner.js.map +1 -1
- package/dist/decision/AIDecisionRunner.d.ts.map +1 -1
- package/dist/decision/AIDecisionRunner.js +8 -3
- package/dist/decision/AIDecisionRunner.js.map +1 -1
- package/dist/embedding/AIEmbeddingRunner.d.ts +24 -1
- package/dist/embedding/AIEmbeddingRunner.d.ts.map +1 -1
- package/dist/embedding/AIEmbeddingRunner.js +80 -21
- package/dist/embedding/AIEmbeddingRunner.js.map +1 -1
- package/dist/embedding/embedding-runner.types.d.ts +14 -0
- package/dist/embedding/embedding-runner.types.d.ts.map +1 -1
- package/dist/image/AIImageGenerationRunner.d.ts +31 -5
- package/dist/image/AIImageGenerationRunner.d.ts.map +1 -1
- package/dist/image/AIImageGenerationRunner.js +75 -13
- package/dist/image/AIImageGenerationRunner.js.map +1 -1
- package/dist/image/image-runner.types.d.ts +14 -0
- package/dist/image/image-runner.types.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- 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 +20 -18
- package/dist/media/BaseMediaRunner.d.ts.map +1 -1
- package/dist/media/BaseMediaRunner.js +35 -51
- package/dist/media/BaseMediaRunner.js.map +1 -1
- package/dist/media/media-runner.types.d.ts +9 -6
- package/dist/media/media-runner.types.d.ts.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.js +1 -1
- package/dist/video/AIVideoRunner.js.map +1 -1
- package/package.json +13 -12
package/dist/AIPromptRunner.js
CHANGED
|
@@ -1,18 +1,21 @@
|
|
|
1
|
-
import { BaseLLM, ChatParams, ChatMessageRole, ErrorAnalyzer, ResolveFileInputStrategy, EncodeToolTurnsAsText, CredentialScopeAllows } from '@memberjunction/ai';
|
|
1
|
+
import { BaseLLM, ChatParams, ChatMessageRole, ErrorAnalyzer, ResolveFileInputStrategy, EncodeToolTurnsAsText, CredentialScopeAllows, ResolveEffectiveModelConfiguration } from '@memberjunction/ai';
|
|
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
|
-
import { LogStatus, IsVerboseLoggingEnabled, Metadata } from '@memberjunction/core';
|
|
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';
|
|
14
16
|
import { SystemPlaceholderManager } from '@memberjunction/ai-core-plus';
|
|
15
|
-
import { ResolvePromptRunUserID } from '@memberjunction/ai-core-plus';
|
|
17
|
+
import { ResolvePromptRunUserID, } from '@memberjunction/ai-core-plus';
|
|
18
|
+
import { BuildCaptureFailedPromptRunMessages, BuildStoredPromptRunMessages, ReadServerTemplateDataCaptureDefault, ResolveTemplateDataCaptureMode, } from './PromptRunDataCapture.js';
|
|
16
19
|
// json5 is a CJS module: under this package's ESM output its import namespace has no
|
|
17
20
|
// `parse` — only the default export does. `import * as JSON5` made JSON5.parse
|
|
18
21
|
// undefined at runtime ("JSON5.parse is not a function"), silently disabling the
|
|
@@ -33,6 +36,12 @@ function mimeFromBlockType(type) {
|
|
|
33
36
|
}
|
|
34
37
|
}
|
|
35
38
|
export class AIPromptRunner extends BaseModelRunner {
|
|
39
|
+
/** The render options a prompt asks for: the prompt caller as the render user, and a raw render when `templateAutoescape` is false. */
|
|
40
|
+
static RenderOptions(params) {
|
|
41
|
+
return params.templateAutoescape === false
|
|
42
|
+
? { autoescape: false, ContextUser: params.contextUser }
|
|
43
|
+
: { ContextUser: params.contextUser };
|
|
44
|
+
}
|
|
36
45
|
/**
|
|
37
46
|
* The model type this runner requires. Returns 'LLM' for AIPromptRunner.
|
|
38
47
|
*/
|
|
@@ -43,6 +52,14 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
43
52
|
get DefaultLogCategory() {
|
|
44
53
|
return 'AIPromptRunner';
|
|
45
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(); }
|
|
46
63
|
/**
|
|
47
64
|
* Process-wide cache of parsed `OutputExample` JSON, keyed by the raw example string.
|
|
48
65
|
* A prompt's OutputExample is a static string reused across every run and every validation
|
|
@@ -57,10 +74,12 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
57
74
|
* that were intentionally NOT credential-checked because a higher-priority candidate had
|
|
58
75
|
* already been selected. See the DECISION note in {@link selectModelWithAPIKeyTracked}.
|
|
59
76
|
*/
|
|
60
|
-
static { this.NOT_EVALUATED_REASON =
|
|
77
|
+
static { this.NOT_EVALUATED_REASON = NOT_EVALUATED_REASON; }
|
|
61
78
|
constructor() {
|
|
62
79
|
super();
|
|
63
|
-
this._metadata =
|
|
80
|
+
this._metadata =
|
|
81
|
+
this._provider ??
|
|
82
|
+
(typeof Metadata === 'function' ? new Metadata() : {}); // global-provider-ok: the same no-provider fallback as `provider ?? new Metadata()`; the typeof guard keeps core mocks without Metadata working
|
|
64
83
|
this._templateEngine = TemplateEngineServer.Instance;
|
|
65
84
|
this._executionPlanner = new ExecutionPlanner();
|
|
66
85
|
this._jsonValidator = new JSONValidator();
|
|
@@ -181,9 +200,8 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
181
200
|
// (plan §8.4), and that is only safe if the flag is the gate's real answer rather than the
|
|
182
201
|
// caller's intent — a prompt that suppressed its catalog while the model received no tools
|
|
183
202
|
// would leave the agent unable to act at all.
|
|
184
|
-
//
|
|
185
|
-
// the
|
|
186
|
-
// 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`).
|
|
187
205
|
//
|
|
188
206
|
// This must resolve from the SAME inputs the request-time call uses (see
|
|
189
207
|
// `applyNativeToolCalling`), or the template can render for the opposite path: the vendor
|
|
@@ -207,6 +225,15 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
207
225
|
: await this.renderChildPromptTemplates(params.childPrompts, params, params.cancellationToken);
|
|
208
226
|
// Render the parent prompt with child templates embedded
|
|
209
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
|
+
});
|
|
210
237
|
}
|
|
211
238
|
// Create parent prompt run for the final composed prompt execution
|
|
212
239
|
parentPromptRun = await this.createPromptRun(prompt, selection.model, params, renderedPromptText, startTime, params.override?.vendorId, selection.selectionInfo);
|
|
@@ -233,6 +260,13 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
233
260
|
throw new Error(`Failed to render template for prompt ${prompt.Name}: ${renderedPrompt.Message}`);
|
|
234
261
|
}
|
|
235
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
|
+
});
|
|
236
270
|
}
|
|
237
271
|
}
|
|
238
272
|
// Check for cancellation after template rendering
|
|
@@ -268,14 +302,19 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
268
302
|
return result;
|
|
269
303
|
}
|
|
270
304
|
catch (error) {
|
|
271
|
-
this.
|
|
272
|
-
prompt:
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
305
|
+
if (this.isCancellation(error, params)) {
|
|
306
|
+
this.logStatus(`⏹️ Prompt "${params.prompt?.Name}" was cancelled: ${error.message}`, false, params);
|
|
307
|
+
}
|
|
308
|
+
else {
|
|
309
|
+
this.logError(error, {
|
|
310
|
+
prompt: params.prompt,
|
|
311
|
+
metadata: {
|
|
312
|
+
executionPhase: 'main-execution',
|
|
313
|
+
hasChildPrompts: !!params.childPrompts?.length
|
|
314
|
+
},
|
|
315
|
+
maxErrorLength: params.maxErrorLength
|
|
316
|
+
});
|
|
317
|
+
}
|
|
279
318
|
const endTime = new Date();
|
|
280
319
|
const executionTimeMS = endTime.getTime() - startTime.getTime();
|
|
281
320
|
// Update prompt run with error if it was created
|
|
@@ -294,7 +333,7 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
294
333
|
promptRun.Status = 'Failed';
|
|
295
334
|
promptRun.ErrorDetails = error.message;
|
|
296
335
|
}
|
|
297
|
-
const saveResult = await promptRun.Save();
|
|
336
|
+
const saveResult = await promptRun.Save({ SaveReturnMode: 'datestamps_only' });
|
|
298
337
|
if (!saveResult) {
|
|
299
338
|
this.logError(`Failed to save error to AIPromptRun: ${promptRun.LatestResult?.CompleteMessage || 'Unknown error'}`, {
|
|
300
339
|
category: 'PromptRunSave',
|
|
@@ -388,9 +427,6 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
388
427
|
// Calculate execution metrics
|
|
389
428
|
const endTime = new Date();
|
|
390
429
|
const executionTimeMS = endTime.getTime() - startTime.getTime();
|
|
391
|
-
// Layer 4 instrumentation: attribute this run to the path it actually took, before the update
|
|
392
|
-
// persists it. Left NULL when no model call happened, which is the honest value.
|
|
393
|
-
promptRun.ToolCallingMode = GetToolCallingMode(modelResult) ?? null;
|
|
394
430
|
// Update the prompt run with results including validation attempts and cumulative tokens
|
|
395
431
|
await this.updatePromptRun(promptRun, prompt, modelResult, parsedResult, endTime, executionTimeMS, validationAttempts, cumulativeTokens);
|
|
396
432
|
const chatResult = modelResult;
|
|
@@ -406,8 +442,10 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
406
442
|
// Validation failed (Warn or Strict mode)
|
|
407
443
|
errorMessage = `Validation failed: ${parsedResult.validationResult.Errors?.map(e => e.Message).join('; ')}`;
|
|
408
444
|
}
|
|
445
|
+
const cancelled = !chatResult.success && this.IsCallerCancellation(chatResult.errorInfo);
|
|
409
446
|
return {
|
|
410
447
|
success: chatResult.success,
|
|
448
|
+
...(cancelled ? { status: 'Cancelled', cancelled: true, cancellationReason: 'user_requested' } : {}),
|
|
411
449
|
rawResult: chatResult.data?.choices?.[0]?.message?.content,
|
|
412
450
|
result: parsedResult?.result ? parsedResult.result : parsedResult,
|
|
413
451
|
errorMessage, // Include error message for proper error propagation
|
|
@@ -535,18 +573,21 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
535
573
|
selectedResult = aiSelectedResult;
|
|
536
574
|
}
|
|
537
575
|
}
|
|
538
|
-
// Update parent with selected arm's model and vendor
|
|
539
|
-
consolidatedPromptRun
|
|
540
|
-
|
|
541
|
-
|
|
576
|
+
// Update parent with selected arm's model and vendor (also re-applied inside applyConsolidatedFields
|
|
577
|
+
// so an in-flight INSERT reload on consolidatedPromptRun can never revert them).
|
|
578
|
+
const selectedModelId = selectedResult.task.model.ID;
|
|
579
|
+
const selectedVendorId = selectedResult.task.vendorId ?? selectedResult.task.promptModel?.VendorID;
|
|
580
|
+
consolidatedPromptRun.ModelID = selectedModelId;
|
|
581
|
+
if (selectedVendorId) {
|
|
582
|
+
consolidatedPromptRun.VendorID = selectedVendorId;
|
|
542
583
|
}
|
|
543
|
-
|
|
544
|
-
consolidatedPromptRun.VendorID = selectedResult.task.promptModel.VendorID;
|
|
545
|
-
}
|
|
546
|
-
// Ensure selectedResult child is marked WasSelectedResult = true
|
|
584
|
+
// Ensure selectedResult child is marked WasSelectedResult = true via the fire-and-forget prompt run queue
|
|
547
585
|
if (selectedResult.promptRun) {
|
|
548
|
-
selectedResult.promptRun
|
|
549
|
-
|
|
586
|
+
const selectedRun = selectedResult.promptRun;
|
|
587
|
+
selectedRun.WasSelectedResult = true;
|
|
588
|
+
this._promptRunQueue.Update(selectedRun, () => {
|
|
589
|
+
selectedRun.WasSelectedResult = true;
|
|
590
|
+
});
|
|
550
591
|
}
|
|
551
592
|
// Calculate total tokens and costs from all parallel executions
|
|
552
593
|
let totalPromptTokens = 0;
|
|
@@ -570,67 +611,67 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
570
611
|
}
|
|
571
612
|
}
|
|
572
613
|
}
|
|
573
|
-
// Update with parallel execution metadata
|
|
614
|
+
// Update with parallel execution metadata (applied immediately in memory and re-applied inside the
|
|
615
|
+
// queued Update callback so an in-flight INSERT reload can never clobber the consolidated fields).
|
|
574
616
|
const endTime = new Date();
|
|
575
|
-
|
|
576
|
-
consolidatedPromptRun.ExecutionTimeMS = parallelResult.totalExecutionTimeMS;
|
|
577
|
-
consolidatedPromptRun.Result = selectedResult.rawResult || '';
|
|
578
|
-
consolidatedPromptRun.TokensUsed = parallelResult.totalTokensUsed;
|
|
579
|
-
// Layer 4 instrumentation, same as the single-model path. This path reaches the same
|
|
580
|
-
// `executeModel` and therefore declares tools, so leaving the column NULL here would tell the
|
|
581
|
-
// agent loop a NativeImplicit turn was not implicit — every control-flow call would then be
|
|
582
|
-
// rejected as an undeclared tool and the loop would retry on tools it declared itself.
|
|
583
|
-
consolidatedPromptRun.ToolCallingMode = GetToolCallingMode(selectedResult.modelResult) ?? null;
|
|
584
|
-
// Extract token and cost info from selected result
|
|
585
|
-
const selectedResultUsage = selectedResult.modelResult?.data?.usage;
|
|
586
|
-
if (selectedResultUsage) {
|
|
587
|
-
consolidatedPromptRun.TokensPrompt = selectedResultUsage.promptTokens;
|
|
588
|
-
consolidatedPromptRun.TokensCompletion = selectedResultUsage.completionTokens;
|
|
589
|
-
// Persist the selected result's cache token counts so (a) they are recorded and (b) any
|
|
590
|
-
// downstream cost recompute (MJAIPromptRunEntityServer, when no provider cost is present)
|
|
591
|
-
// prices the full input including cached tokens rather than dropping them.
|
|
592
|
-
consolidatedPromptRun.TokensCacheRead = selectedResultUsage.cacheReadTokens ?? 0;
|
|
593
|
-
consolidatedPromptRun.TokensCacheWrite = selectedResultUsage.cacheWriteTokens ?? 0;
|
|
594
|
-
// NOTE (§5.1): On the parent, do NOT assign Cost from the selected arm. Leave Cost = null.
|
|
595
|
-
// TotalCost is maintained by server-side TriggerParentCostRollup.
|
|
596
|
-
if (selectedResultUsage.costCurrency !== undefined) {
|
|
597
|
-
consolidatedPromptRun.CostCurrency = selectedResultUsage.costCurrency;
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
// Add parallel execution metadata to Messages field
|
|
601
|
-
const parallelMetadata = {
|
|
617
|
+
const storedMessagesJSON = this.buildStoredMessagesJSON(prompt, params, params.conversationMessages || [], {
|
|
602
618
|
parallelizationMode: prompt.ParallelizationMode,
|
|
603
619
|
totalTasks: executionTasks.length,
|
|
604
620
|
successfulTasks: parallelResult.successCount,
|
|
605
621
|
failedTasks: parallelResult.failureCount,
|
|
606
622
|
selectedTaskId: selectedResult.task.taskId,
|
|
607
623
|
executionGroups: Array.from(parallelResult.groupResults.keys()),
|
|
624
|
+
});
|
|
625
|
+
const selectedToolCallingMode = GetToolCallingMode(selectedResult.modelResult) ?? null;
|
|
626
|
+
const selectedResultUsage = selectedResult.modelResult?.data?.usage;
|
|
627
|
+
const consolidatedStatus = parallelResult.successCount > 0 ? 'Completed' : 'Failed';
|
|
628
|
+
const applyConsolidatedFields = () => {
|
|
629
|
+
consolidatedPromptRun.ModelID = selectedModelId;
|
|
630
|
+
if (selectedVendorId) {
|
|
631
|
+
consolidatedPromptRun.VendorID = selectedVendorId;
|
|
632
|
+
}
|
|
633
|
+
consolidatedPromptRun.CompletedAt = endTime;
|
|
634
|
+
consolidatedPromptRun.ExecutionTimeMS = parallelResult.totalExecutionTimeMS;
|
|
635
|
+
consolidatedPromptRun.Result = selectedResult.rawResult || '';
|
|
636
|
+
consolidatedPromptRun.TokensUsed = parallelResult.totalTokensUsed;
|
|
637
|
+
// Layer 4 instrumentation, same as the single-model path. This path reaches the same
|
|
638
|
+
// `executeModel` and therefore declares tools, so leaving the column NULL here would tell the
|
|
639
|
+
// agent loop a NativeImplicit turn was not implicit — every control-flow call would then be
|
|
640
|
+
// rejected as an undeclared tool and the loop would retry on tools it declared itself.
|
|
641
|
+
consolidatedPromptRun.ToolCallingMode = selectedToolCallingMode;
|
|
642
|
+
// Extract token and cost info from selected result
|
|
643
|
+
if (selectedResultUsage) {
|
|
644
|
+
consolidatedPromptRun.TokensPrompt = selectedResultUsage.promptTokens;
|
|
645
|
+
consolidatedPromptRun.TokensCompletion = selectedResultUsage.completionTokens;
|
|
646
|
+
// Persist the selected result's cache token counts so (a) they are recorded and (b) any
|
|
647
|
+
// downstream cost recompute (MJAIPromptRunEntityServer, when no provider cost is present)
|
|
648
|
+
// prices the full input including cached tokens rather than dropping them.
|
|
649
|
+
consolidatedPromptRun.TokensCacheRead = selectedResultUsage.cacheReadTokens ?? 0;
|
|
650
|
+
consolidatedPromptRun.TokensCacheWrite = selectedResultUsage.cacheWriteTokens ?? 0;
|
|
651
|
+
// NOTE (§5.1): On the parent, do NOT assign Cost from the selected arm. Leave Cost = null.
|
|
652
|
+
// TotalCost is maintained by server-side TriggerParentCostRollup.
|
|
653
|
+
if (selectedResultUsage.costCurrency !== undefined) {
|
|
654
|
+
consolidatedPromptRun.CostCurrency = selectedResultUsage.costCurrency;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
// Store the parallel execution summary in the Messages field, with the messages and the allowed template inputs
|
|
658
|
+
consolidatedPromptRun.Messages = storedMessagesJSON;
|
|
659
|
+
// For parallel execution, set rollup fields to match totals
|
|
660
|
+
consolidatedPromptRun.TokensPromptRollup = totalPromptTokens;
|
|
661
|
+
consolidatedPromptRun.TokensCompletionRollup = totalCompletionTokens;
|
|
662
|
+
consolidatedPromptRun.TokensUsedRollup = totalPromptTokens + totalCompletionTokens;
|
|
663
|
+
consolidatedPromptRun.TokensCacheReadRollup = totalCacheReadTokens;
|
|
664
|
+
consolidatedPromptRun.TokensCacheWriteRollup = totalCacheWriteTokens;
|
|
665
|
+
if (hasCost) {
|
|
666
|
+
consolidatedPromptRun.DescendantCost = totalCost;
|
|
667
|
+
consolidatedPromptRun.TotalCost = totalCost;
|
|
668
|
+
}
|
|
669
|
+
// Set Status and WasSelectedResult for parallel execution
|
|
670
|
+
consolidatedPromptRun.Status = consolidatedStatus;
|
|
671
|
+
consolidatedPromptRun.WasSelectedResult = false; // WasSelectedResult stays on the selected child, not the parent
|
|
608
672
|
};
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
data: params.data,
|
|
612
|
-
templateData: params.templateData,
|
|
613
|
-
parallelExecution: parallelMetadata,
|
|
614
|
-
messages: params.conversationMessages || [],
|
|
615
|
-
});
|
|
616
|
-
}
|
|
617
|
-
// For parallel execution, set rollup fields to match totals
|
|
618
|
-
consolidatedPromptRun.TokensPromptRollup = totalPromptTokens;
|
|
619
|
-
consolidatedPromptRun.TokensCompletionRollup = totalCompletionTokens;
|
|
620
|
-
consolidatedPromptRun.TokensUsedRollup = totalPromptTokens + totalCompletionTokens;
|
|
621
|
-
consolidatedPromptRun.TokensCacheReadRollup = totalCacheReadTokens;
|
|
622
|
-
consolidatedPromptRun.TokensCacheWriteRollup = totalCacheWriteTokens;
|
|
623
|
-
if (hasCost) {
|
|
624
|
-
consolidatedPromptRun.DescendantCost = totalCost;
|
|
625
|
-
consolidatedPromptRun.TotalCost = totalCost;
|
|
626
|
-
}
|
|
627
|
-
// Set Status and WasSelectedResult for parallel execution
|
|
628
|
-
consolidatedPromptRun.Status = parallelResult.successCount > 0 ? 'Completed' : 'Failed';
|
|
629
|
-
consolidatedPromptRun.WasSelectedResult = false; // WasSelectedResult stays on the selected child, not the parent
|
|
630
|
-
// Persist the consolidated run fire-and-forget; the finalize UPDATE chains after its INSERT via
|
|
631
|
-
// the save queue. These fields are set after all the awaited parallel work, so the INSERT has long
|
|
632
|
-
// landed — a plain Update (no post-INSERT callback) is race-safe here.
|
|
633
|
-
this._promptRunQueue.Update(consolidatedPromptRun);
|
|
673
|
+
applyConsolidatedFields();
|
|
674
|
+
this._promptRunQueue.Update(consolidatedPromptRun, () => applyConsolidatedFields());
|
|
634
675
|
// Create additional results from all other successful results (excluding the best one)
|
|
635
676
|
const additionalResults = [];
|
|
636
677
|
// Sort successful results by ranking (if available) or keep original order
|
|
@@ -711,7 +752,9 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
711
752
|
async loadTemplate(templateId, _contextUser) {
|
|
712
753
|
try {
|
|
713
754
|
// Use the template engine to find the template
|
|
714
|
-
const template = this._templateEngine.
|
|
755
|
+
const template = typeof this._templateEngine.FindTemplateByID === 'function'
|
|
756
|
+
? this._templateEngine.FindTemplateByID(templateId)
|
|
757
|
+
: this._templateEngine.Templates.find((t) => UUIDsEqual(t.ID, templateId));
|
|
715
758
|
return template || null;
|
|
716
759
|
}
|
|
717
760
|
catch (error) {
|
|
@@ -965,8 +1008,8 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
965
1008
|
//this.logStatus(` 📝 ${placeholder} -> ${truncatedTemplate}`, true, params);
|
|
966
1009
|
}
|
|
967
1010
|
// Render the template with the full params context
|
|
968
|
-
// We already have system placeholders resolved, so we'll render directly
|
|
969
|
-
const renderedPrompt = await this._templateEngine.RenderTemplate(template, template.GetHighestPriorityContent(), mergedData);
|
|
1011
|
+
// We already have system placeholders resolved, so we'll render directly.
|
|
1012
|
+
const renderedPrompt = await this._templateEngine.RenderTemplate(template, template.GetHighestPriorityContent(), mergedData, undefined, undefined, AIPromptRunner.RenderOptions(params));
|
|
970
1013
|
if (!renderedPrompt.Success) {
|
|
971
1014
|
throw new Error(`Failed to render template for prompt ${prompt.Name}: ${renderedPrompt.Message}`);
|
|
972
1015
|
}
|
|
@@ -1186,6 +1229,7 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1186
1229
|
consideredModels.push({
|
|
1187
1230
|
model: candidate.model,
|
|
1188
1231
|
vendor: vendorEntity,
|
|
1232
|
+
driverClass: candidate.driverClass,
|
|
1189
1233
|
priority: candidate.priority,
|
|
1190
1234
|
available: false,
|
|
1191
1235
|
unavailableReason: AIPromptRunner.NOT_EVALUATED_REASON
|
|
@@ -1208,6 +1252,7 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1208
1252
|
const considered = {
|
|
1209
1253
|
model: candidate.model,
|
|
1210
1254
|
vendor: vendorEntity,
|
|
1255
|
+
driverClass: candidate.driverClass,
|
|
1211
1256
|
priority: candidate.priority,
|
|
1212
1257
|
available: hasCredentials,
|
|
1213
1258
|
unavailableReason: hasCredentials ? undefined : `No credentials configured for driver ${candidate.driverClass}`
|
|
@@ -1245,37 +1290,14 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1245
1290
|
}
|
|
1246
1291
|
/**
|
|
1247
1292
|
* Builds a descriptive error message when no model could be selected for a prompt.
|
|
1248
|
-
*
|
|
1249
|
-
*
|
|
1293
|
+
*
|
|
1294
|
+
* The body lives in `no-model-found-message.ts` so it can be tested directly — as a private
|
|
1295
|
+
* method its only coverage was a re-implementation of it in the test file, which asserted
|
|
1296
|
+
* against its own copy rather than this code.
|
|
1250
1297
|
*/
|
|
1251
1298
|
buildNoModelFoundMessage(promptName, selectionInfo, credentialScope) {
|
|
1252
|
-
const
|
|
1253
|
-
|
|
1254
|
-
// rather than the generic "no candidates" text. Every other reason keeps its detailed message below.
|
|
1255
|
-
if (selectionInfo?.selectionReason?.startsWith('Error during model selection:')) {
|
|
1256
|
-
return `${base}. ${selectionInfo.selectionReason}`;
|
|
1257
|
-
}
|
|
1258
|
-
if (!selectionInfo?.modelsConsidered || selectionInfo.modelsConsidered.length === 0) {
|
|
1259
|
-
return `${base}. No model-vendor candidates were available. Please ensure AI models are configured for this prompt.`;
|
|
1260
|
-
}
|
|
1261
|
-
// Check if all models were unavailable due to missing credentials
|
|
1262
|
-
const unavailableModels = selectionInfo.modelsConsidered.filter(m => !m.available);
|
|
1263
|
-
if (unavailableModels.length === selectionInfo.modelsConsidered.length) {
|
|
1264
|
-
const triedSummary = unavailableModels.slice(0, 5).map(m => {
|
|
1265
|
-
const vendorName = m.vendor?.Name || 'default';
|
|
1266
|
-
return `${m.model.Name}/${vendorName}`;
|
|
1267
|
-
}).join(', ');
|
|
1268
|
-
const suffix = unavailableModels.length > 5 ? ` (${unavailableModels.length} total)` : '';
|
|
1269
|
-
// When the scope rules out the platform's credentials, "configure them" would point the reader
|
|
1270
|
-
// at exactly the fallback the caller ruled out.
|
|
1271
|
-
const platformAllowed = CredentialScopeAllows(credentialScope, 'Environment') || CredentialScopeAllows(credentialScope, 'PlatformCredential');
|
|
1272
|
-
const remedy = platformAllowed
|
|
1273
|
-
? `Please configure API credentials in your environment or AI Credential settings.`
|
|
1274
|
-
: `The credential scope is ${credentialScope}, so only the API keys supplied with this run count; supply a key for one of these vendors.`;
|
|
1275
|
-
return `${base}. No valid API credentials/keys are configured for any of the candidate model-vendor combinations. ` +
|
|
1276
|
-
`Tried: ${triedSummary}${suffix}. ${remedy}`;
|
|
1277
|
-
}
|
|
1278
|
-
return `${base}. ${selectionInfo.selectionReason || 'Unknown reason'}`;
|
|
1299
|
+
const platformAllowed = CredentialScopeAllows(credentialScope, 'Environment') || CredentialScopeAllows(credentialScope, 'PlatformCredential');
|
|
1300
|
+
return BuildNoModelFoundMessage(promptName, selectionInfo, credentialScope ? { Name: credentialScope, PlatformAllowed: platformAllowed } : undefined);
|
|
1279
1301
|
}
|
|
1280
1302
|
/**
|
|
1281
1303
|
* Renders the prompt template with provided data
|
|
@@ -1312,7 +1334,7 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1312
1334
|
// almost always what the author meant. If real param validation is
|
|
1313
1335
|
// needed (e.g., catching typos at template-author time), it should
|
|
1314
1336
|
// live in the authoring tools, not in the runtime render path.
|
|
1315
|
-
return await this._templateEngine.RenderTemplate(template, templateContent, mergedData, true, false);
|
|
1337
|
+
return await this._templateEngine.RenderTemplate(template, templateContent, mergedData, true, false, AIPromptRunner.RenderOptions(params));
|
|
1316
1338
|
}
|
|
1317
1339
|
catch (error) {
|
|
1318
1340
|
this.logError(error, {
|
|
@@ -1376,7 +1398,7 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1376
1398
|
errorMessage: lastError?.message || 'Unknown error',
|
|
1377
1399
|
exception: lastError,
|
|
1378
1400
|
errorInfo: errorInfo,
|
|
1379
|
-
statusText: `Failover failed after ${failoverAttempts.length} attempts`,
|
|
1401
|
+
statusText: this.IsCallerCancellation(errorInfo) ? 'Cancelled' : `Failover failed after ${failoverAttempts.length} attempts`,
|
|
1380
1402
|
timeElapsed: endTime.getTime() - startTime.getTime(),
|
|
1381
1403
|
data: null
|
|
1382
1404
|
};
|
|
@@ -1417,7 +1439,7 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1417
1439
|
try {
|
|
1418
1440
|
return ResolveNativeToolCalling({
|
|
1419
1441
|
catalogConfiguration: this.catalogConfigurationFor(model, vendorId),
|
|
1420
|
-
promptConfiguration: prompt
|
|
1442
|
+
promptConfiguration: this.ResolveEffectivePromptConfiguration(prompt, params),
|
|
1421
1443
|
promptModelConfiguration,
|
|
1422
1444
|
// Action tools and control-flow tools are counted separately: under the hybrid the control
|
|
1423
1445
|
// tools are stripped, so on their own they must not open the gate (spec §5).
|
|
@@ -1431,6 +1453,24 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1431
1453
|
return { useNativeTools: false, mode: 'Envelope', controlFlow: 'envelope', toolResults: false };
|
|
1432
1454
|
}
|
|
1433
1455
|
}
|
|
1456
|
+
/**
|
|
1457
|
+
* The prompt layer of the native tool-calling cascade, with a hierarchical run's child prompt
|
|
1458
|
+
* merged over its parent.
|
|
1459
|
+
*
|
|
1460
|
+
* An agent runs its agent type's system prompt as `prompt` and its own prompt as the first
|
|
1461
|
+
* child, so the parent's bag alone describes the agent TYPE, not the agent. Native tool calling
|
|
1462
|
+
* is a property of the agent's own prompt, so the child's bag sits between the parent and the
|
|
1463
|
+
* selected `AIPromptModel` row: parent → child → row. The merge is per key, so an explicit value
|
|
1464
|
+
* in the child (including `false`) overrides the parent, and an absent key inherits.
|
|
1465
|
+
*
|
|
1466
|
+
* @param prompt The prompt being run (the parent on a hierarchical run)
|
|
1467
|
+
* @param params The caller's params — supplies the child prompts, if any
|
|
1468
|
+
* @returns The merged prompt configuration, or null when neither layer sets one
|
|
1469
|
+
*/
|
|
1470
|
+
ResolveEffectivePromptConfiguration(prompt, params) {
|
|
1471
|
+
const childPrompt = params.childPrompts?.[0]?.childPrompt?.prompt;
|
|
1472
|
+
return ResolveEffectiveModelConfiguration(prompt.PromptConfigurationObject ?? null, childPrompt?.PromptConfigurationObject ?? null);
|
|
1473
|
+
}
|
|
1434
1474
|
/**
|
|
1435
1475
|
* Returns the template data with `_NATIVE_TOOL_CALLING` and `_NATIVE_CONTROL_FLOW` set.
|
|
1436
1476
|
*
|
|
@@ -1458,6 +1498,91 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1458
1498
|
_NATIVE_CONTROL_FLOW: current._NATIVE_CONTROL_FLOW ?? 'envelope'
|
|
1459
1499
|
};
|
|
1460
1500
|
}
|
|
1501
|
+
/**
|
|
1502
|
+
* Remembers how to render this request's template again with different template data, so a
|
|
1503
|
+
* failover attempt whose native decision differs from the one the template was rendered for can
|
|
1504
|
+
* get a prompt that matches what it actually sends (see {@link rerenderForNativeDecision}).
|
|
1505
|
+
*/
|
|
1506
|
+
registerNativeRerender(params, render) {
|
|
1507
|
+
AIPromptRunner._nativeRerenderers.set(params, render);
|
|
1508
|
+
}
|
|
1509
|
+
/** Lets a copy of the params re-render the template the original registered — for the parallel path's per-task copies. */
|
|
1510
|
+
ShareNativeRerender(original, copy) {
|
|
1511
|
+
const render = AIPromptRunner._nativeRerenderers.get(original);
|
|
1512
|
+
if (render) {
|
|
1513
|
+
AIPromptRunner._nativeRerenderers.set(copy, render);
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
/** A copy of the params with other template data — the original is shared with parallel attempts and must not change. */
|
|
1517
|
+
withPromptData(params, data) {
|
|
1518
|
+
return Object.assign(Object.create(Object.getPrototypeOf(params)), params, { data });
|
|
1519
|
+
}
|
|
1520
|
+
/**
|
|
1521
|
+
* The prompt text for this attempt's native decision.
|
|
1522
|
+
*
|
|
1523
|
+
* The template's native wording is set once, from the first candidate's decision. Failover
|
|
1524
|
+
* re-resolves the decision per attempt, so an attempt can land on a model on another path —
|
|
1525
|
+
* envelope after native, or hybrid after implicit — and would otherwise be taught a protocol it
|
|
1526
|
+
* is not being asked to use. When the decision differs from the one the template was rendered
|
|
1527
|
+
* for, the template is rendered again for this attempt; otherwise the text is returned as is.
|
|
1528
|
+
*/
|
|
1529
|
+
async rerenderForNativeDecision(renderedPrompt, chatParams, params, model) {
|
|
1530
|
+
const decision = GetToolCallingDecision(chatParams);
|
|
1531
|
+
// A prompt rendered without the native flags (no agent-type system prompt) has no native
|
|
1532
|
+
// wording to correct, whatever the decision.
|
|
1533
|
+
if (!decision || params.data?._NATIVE_TOOL_CALLING === undefined) {
|
|
1534
|
+
return renderedPrompt;
|
|
1535
|
+
}
|
|
1536
|
+
const renderedNative = params.data?._NATIVE_TOOL_CALLING === true;
|
|
1537
|
+
const renderedFlow = params.data?._NATIVE_CONTROL_FLOW ?? 'envelope';
|
|
1538
|
+
if (renderedNative === decision.useNativeTools && (!decision.useNativeTools || renderedFlow === decision.controlFlow)) {
|
|
1539
|
+
return renderedPrompt;
|
|
1540
|
+
}
|
|
1541
|
+
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);
|
|
1542
|
+
return this.rerenderOrKeep(renderedPrompt, params, this.ApplyNativeTemplateFlags(params.data, decision));
|
|
1543
|
+
}
|
|
1544
|
+
/**
|
|
1545
|
+
* The template rendered again with `data`, or `renderedPrompt` unchanged when the request
|
|
1546
|
+
* registered no renderer or the render fails. A failed re-render is the template's problem, not
|
|
1547
|
+
* the model's: the attempt goes ahead with the text it already had, and the error is logged.
|
|
1548
|
+
*/
|
|
1549
|
+
async rerenderOrKeep(renderedPrompt, params, data) {
|
|
1550
|
+
const render = AIPromptRunner._nativeRerenderers.get(params);
|
|
1551
|
+
if (!render) {
|
|
1552
|
+
return renderedPrompt;
|
|
1553
|
+
}
|
|
1554
|
+
try {
|
|
1555
|
+
return await render(data);
|
|
1556
|
+
}
|
|
1557
|
+
catch (error) {
|
|
1558
|
+
LogError(`AIPromptRunner: re-rendering the prompt failed; sending the prompt as first rendered`, null, error);
|
|
1559
|
+
return renderedPrompt;
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
/**
|
|
1563
|
+
* Swaps the rendered prompt inside an already-built message array, keeping anything appended to
|
|
1564
|
+
* it (the prefill fallback instruction). Returns the messages unchanged when the prompt is not found.
|
|
1565
|
+
*/
|
|
1566
|
+
replaceRenderedPrompt(messages, from, to) {
|
|
1567
|
+
const at = messages.findIndex((m) => typeof m.content === 'string' && m.content.startsWith(from));
|
|
1568
|
+
if (at < 0 || from === to) {
|
|
1569
|
+
return messages;
|
|
1570
|
+
}
|
|
1571
|
+
const copy = [...messages];
|
|
1572
|
+
copy[at] = { ...copy[at], content: to + copy[at].content.slice(from.length) };
|
|
1573
|
+
return copy;
|
|
1574
|
+
}
|
|
1575
|
+
/** The prompt run's `Messages` for a result whose attempt sent a re-rendered prompt, or undefined. */
|
|
1576
|
+
RerenderedMessagesFor(result) {
|
|
1577
|
+
return AIPromptRunner._rerenderedMessages.get(result);
|
|
1578
|
+
}
|
|
1579
|
+
/** Records, for the prompt run, the messages an attempt sent when its prompt was rendered again. */
|
|
1580
|
+
recordRerenderedMessages(result, prompt, params, model, vendorId, renderedPrompt) {
|
|
1581
|
+
const json = this.storedMessagesJSON(prompt, params, model, renderedPrompt, vendorId ?? undefined);
|
|
1582
|
+
if (json) {
|
|
1583
|
+
AIPromptRunner._rerenderedMessages.set(result, json);
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1461
1586
|
/** @deprecated Use {@link ResolveNativeToolCallingDecision}. */
|
|
1462
1587
|
resolveNativeToolCallingDecision(prompt, params, model, vendorId, promptModelConfiguration) {
|
|
1463
1588
|
return this.ResolveNativeToolCallingDecision(prompt, params, model, vendorId, promptModelConfiguration);
|
|
@@ -1496,6 +1621,13 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1496
1621
|
// decision travels so the agent loop can read `toolResults` off the result later.
|
|
1497
1622
|
RecordToolCallingDecision(chatParams, decision);
|
|
1498
1623
|
}
|
|
1624
|
+
/**
|
|
1625
|
+
* Whether an error ended a prompt run because the caller cancelled it: the caller's token is aborted,
|
|
1626
|
+
* or the error is classified as a cancellation.
|
|
1627
|
+
*/
|
|
1628
|
+
isCancellation(error, params) {
|
|
1629
|
+
return params.cancellationToken?.aborted === true || this.IsCallerCancellation(ErrorAnalyzer.analyzeError(error));
|
|
1630
|
+
}
|
|
1499
1631
|
/**
|
|
1500
1632
|
* Whether a failed result failed for a TOOLS-specific reason, and so is worth one retry with the
|
|
1501
1633
|
* declarations stripped.
|
|
@@ -1512,10 +1644,30 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1512
1644
|
return false;
|
|
1513
1645
|
}
|
|
1514
1646
|
// A cancellation is the caller's decision, never a tool problem.
|
|
1515
|
-
if (
|
|
1647
|
+
if (this.IsCallerCancellation(result.errorInfo)) {
|
|
1516
1648
|
return false;
|
|
1517
1649
|
}
|
|
1518
|
-
return this.
|
|
1650
|
+
return this.isToolEligibleError(result.errorInfo)
|
|
1651
|
+
&& this.isToolSpecificFailureText(`${result.errorMessage ?? ''} ${result.statusText ?? ''}`);
|
|
1652
|
+
}
|
|
1653
|
+
/**
|
|
1654
|
+
* Whether the provider's error could be a rejected tools payload.
|
|
1655
|
+
*
|
|
1656
|
+
* A 400 or 422 is a request error whatever the classifier made of its text: the classifier reads
|
|
1657
|
+
* keywords such as "balance" or "timeout" before the status, and a schema rejection quoting a
|
|
1658
|
+
* `Get_Account_Balance` tool or a `TimeoutMS` property would otherwise pass as a credit or network
|
|
1659
|
+
* failure. Without one of those statuses, only the classifications that are never about the
|
|
1660
|
+
* tools payload — a rate limit, an authentication failure, a cancellation, a context-length
|
|
1661
|
+
* error — are ruled out. An error with no classification is judged by its text alone.
|
|
1662
|
+
*/
|
|
1663
|
+
isToolEligibleError(errorInfo) {
|
|
1664
|
+
if (!errorInfo) {
|
|
1665
|
+
return true;
|
|
1666
|
+
}
|
|
1667
|
+
if (errorInfo.httpStatusCode === 400 || errorInfo.httpStatusCode === 422) {
|
|
1668
|
+
return true;
|
|
1669
|
+
}
|
|
1670
|
+
return !AIPromptRunner.TOOL_INELIGIBLE_ERROR_TYPES.includes(errorInfo.errorType);
|
|
1519
1671
|
}
|
|
1520
1672
|
/**
|
|
1521
1673
|
* Retries a native call once on today's exact path, with the tool declarations stripped.
|
|
@@ -1528,7 +1680,7 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1528
1680
|
*
|
|
1529
1681
|
* @param reason What the provider said, for the warning — a misconfiguration should be visible
|
|
1530
1682
|
*/
|
|
1531
|
-
async retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, reason) {
|
|
1683
|
+
async retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, reason, params, renderedPrompt, firstRenderedPrompt) {
|
|
1532
1684
|
console.warn(`AIPromptRunner: native tool calling failed on ${model.Name}${vendorId ? ` (vendor ${vendorId})` : ''} ` +
|
|
1533
1685
|
`for prompt "${prompt.Name}" — retrying once on the envelope path with tools stripped. ` +
|
|
1534
1686
|
`Provider error: ${reason}`);
|
|
@@ -1541,10 +1693,36 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1541
1693
|
// the same request. Show the retry what the envelope path has always
|
|
1542
1694
|
// shown: the calls' prose, and each result as an "[Action Result]" user message.
|
|
1543
1695
|
chatParams.messages = EncodeToolTurnsAsText(chatParams.messages);
|
|
1696
|
+
// The prompt was rendered for native tools — no action catalog, "call the tool" wording. With
|
|
1697
|
+
// the tools gone, render it for the envelope, so the model can still act.
|
|
1698
|
+
const envelopePrompt = await this.rerenderOrKeep(renderedPrompt, params, { ...(params.data ?? {}), _NATIVE_TOOL_CALLING: false, _NATIVE_CONTROL_FLOW: 'envelope' });
|
|
1699
|
+
chatParams.messages = this.replaceRenderedPrompt(chatParams.messages, renderedPrompt, envelopePrompt);
|
|
1700
|
+
const sentPrefix = this.guardReplayedReasoningPrefix(chatParams, params, model);
|
|
1544
1701
|
const fallbackResult = await this.runChatCompletionBounded(llm, chatParams, executionBound);
|
|
1545
1702
|
RecordToolCallingMode(fallbackResult, 'NativeFallback');
|
|
1703
|
+
RecordSentPrefixFingerprint(fallbackResult, sentPrefix);
|
|
1704
|
+
// The prompt run holds the first-rendered prompt; record what this retry sent whenever it differs.
|
|
1705
|
+
if (envelopePrompt !== firstRenderedPrompt) {
|
|
1706
|
+
this.recordRerenderedMessages(fallbackResult, prompt, params, model, vendorId, envelopePrompt);
|
|
1707
|
+
}
|
|
1546
1708
|
return fallbackResult;
|
|
1547
1709
|
}
|
|
1710
|
+
/**
|
|
1711
|
+
* Sends a request without replayed reasoning when its system prompt or tools differ from the
|
|
1712
|
+
* previous request's (`params.ReplayedReasoningPrefix`): a provider that binds reasoning to an
|
|
1713
|
+
* unchanged prefix rejects it then — a skill that activated mid-run, a failover re-render.
|
|
1714
|
+
*
|
|
1715
|
+
* @returns This request's fingerprint, recorded on its result for the caller's next request
|
|
1716
|
+
*/
|
|
1717
|
+
guardReplayedReasoningPrefix(chatParams, params, model) {
|
|
1718
|
+
const fingerprint = ReplayedReasoningPrefixFingerprint(chatParams);
|
|
1719
|
+
const previous = params.ReplayedReasoningPrefix;
|
|
1720
|
+
if (previous !== undefined && previous !== fingerprint && chatParams.messages.some((m) => m.reasoning)) {
|
|
1721
|
+
this.logStatus(` The system prompt or tools changed since the previous request to ${model.Name}; sending it without replayed reasoning`, true, params);
|
|
1722
|
+
chatParams.messages = WithoutReplayedReasoning(chatParams.messages);
|
|
1723
|
+
}
|
|
1724
|
+
return fingerprint;
|
|
1725
|
+
}
|
|
1548
1726
|
/** Scans provider prose for a tools marker. Shared by the thrown-error and failed-result paths. */
|
|
1549
1727
|
isToolSpecificFailureText(text) {
|
|
1550
1728
|
const lowered = text.toLowerCase();
|
|
@@ -1698,6 +1876,8 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1698
1876
|
// Resolved HERE rather than once per run because failover may land on a different
|
|
1699
1877
|
// (model, vendor) that does not support tools.
|
|
1700
1878
|
this.applyNativeToolCalling(chatParams, prompt, params, model, vendorId, promptModelConfiguration);
|
|
1879
|
+
const firstRenderedPrompt = renderedPrompt;
|
|
1880
|
+
renderedPrompt = await this.rerenderForNativeDecision(renderedPrompt, chatParams, params, model);
|
|
1701
1881
|
// Build message array with rendered prompt and conversation messages
|
|
1702
1882
|
chatParams.messages = this.buildMessageArray(renderedPrompt, conversationMessages, templateMessageRole);
|
|
1703
1883
|
// Declarations and tool turns must travel TOGETHER. The gate above is re-resolved per
|
|
@@ -1726,13 +1906,68 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1726
1906
|
// place streaming is configured for prompt execution, so the single-model path and the parallel
|
|
1727
1907
|
// path (which bridges its per-task callbacks into params.onStreaming) stream through identical
|
|
1728
1908
|
// code — no second streaming implementation that can drift.
|
|
1909
|
+
// Coalesce rapid token chunks within a 35ms window (~28 fps) to avoid flooding WebSocket/PubSub
|
|
1910
|
+
// while emitting the first chunk immediately and flushing synchronously on completion.
|
|
1911
|
+
let flushStreamingBuffer;
|
|
1729
1912
|
if (params.onStreaming) {
|
|
1730
1913
|
const onStreaming = params.onStreaming;
|
|
1914
|
+
const coalesceIntervalMs = 35;
|
|
1915
|
+
let bufferedContent = '';
|
|
1916
|
+
let lastEmitMs = 0;
|
|
1917
|
+
let flushTimer = null;
|
|
1918
|
+
const clearTimer = () => {
|
|
1919
|
+
if (flushTimer !== null) {
|
|
1920
|
+
clearTimeout(flushTimer);
|
|
1921
|
+
flushTimer = null;
|
|
1922
|
+
}
|
|
1923
|
+
};
|
|
1924
|
+
const emitNow = (content, isComplete) => {
|
|
1925
|
+
clearTimer();
|
|
1926
|
+
lastEmitMs = Date.now();
|
|
1927
|
+
onStreaming({ content, isComplete, modelName: model.Name });
|
|
1928
|
+
};
|
|
1929
|
+
flushStreamingBuffer = () => {
|
|
1930
|
+
clearTimer();
|
|
1931
|
+
if (bufferedContent.length > 0) {
|
|
1932
|
+
const pending = bufferedContent;
|
|
1933
|
+
bufferedContent = '';
|
|
1934
|
+
lastEmitMs = Date.now();
|
|
1935
|
+
onStreaming({ content: pending, isComplete: false, modelName: model.Name });
|
|
1936
|
+
}
|
|
1937
|
+
};
|
|
1731
1938
|
chatParams.streaming = true;
|
|
1732
1939
|
chatParams.streamingCallbacks = {
|
|
1733
|
-
OnContent: (chunk, isComplete) =>
|
|
1940
|
+
OnContent: (chunk, isComplete) => {
|
|
1941
|
+
if (isComplete) {
|
|
1942
|
+
const combined = bufferedContent + chunk;
|
|
1943
|
+
bufferedContent = '';
|
|
1944
|
+
emitNow(combined, true);
|
|
1945
|
+
return;
|
|
1946
|
+
}
|
|
1947
|
+
const now = Date.now();
|
|
1948
|
+
if (lastEmitMs === 0 || now - lastEmitMs >= coalesceIntervalMs) {
|
|
1949
|
+
const combined = bufferedContent + chunk;
|
|
1950
|
+
bufferedContent = '';
|
|
1951
|
+
emitNow(combined, false);
|
|
1952
|
+
return;
|
|
1953
|
+
}
|
|
1954
|
+
bufferedContent += chunk;
|
|
1955
|
+
if (flushTimer === null) {
|
|
1956
|
+
const delay = Math.max(1, coalesceIntervalMs - (now - lastEmitMs));
|
|
1957
|
+
flushTimer = setTimeout(() => {
|
|
1958
|
+
flushTimer = null;
|
|
1959
|
+
if (bufferedContent.length > 0) {
|
|
1960
|
+
const pending = bufferedContent;
|
|
1961
|
+
bufferedContent = '';
|
|
1962
|
+
lastEmitMs = Date.now();
|
|
1963
|
+
onStreaming({ content: pending, isComplete: false, modelName: model.Name });
|
|
1964
|
+
}
|
|
1965
|
+
}, delay);
|
|
1966
|
+
}
|
|
1967
|
+
},
|
|
1734
1968
|
};
|
|
1735
1969
|
}
|
|
1970
|
+
const sentPrefix = this.guardReplayedReasoningPrefix(chatParams, params, model);
|
|
1736
1971
|
// Execute the model bounded by the composed abort signal (caller cancellation + prompt TimeoutMS)
|
|
1737
1972
|
//
|
|
1738
1973
|
// Layer 4 fallback, part one: some providers REJECT a tools payload instead of returning a
|
|
@@ -1742,13 +1977,21 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1742
1977
|
// for gpt-5.6-luna in /v1/chat/completions`. Both shapes get the same one-shot retry.
|
|
1743
1978
|
let chatResult;
|
|
1744
1979
|
try {
|
|
1745
|
-
|
|
1980
|
+
try {
|
|
1981
|
+
chatResult = await this.runChatCompletionBounded(llm, chatParams, executionBound);
|
|
1982
|
+
}
|
|
1983
|
+
finally {
|
|
1984
|
+
flushStreamingBuffer?.();
|
|
1985
|
+
}
|
|
1746
1986
|
}
|
|
1747
1987
|
catch (error) {
|
|
1748
|
-
|
|
1988
|
+
const thrownText = error instanceof Error ? error.message : String(error ?? '');
|
|
1989
|
+
if (!chatParams.tools?.length
|
|
1990
|
+
|| !this.isToolEligibleError(ErrorAnalyzer.analyzeError(error, driverClass))
|
|
1991
|
+
|| !this.isToolSpecificFailureText(thrownText)) {
|
|
1749
1992
|
throw error;
|
|
1750
1993
|
}
|
|
1751
|
-
return await this.retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, error instanceof Error ? error.message : String(error));
|
|
1994
|
+
return await this.retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, error instanceof Error ? error.message : String(error), params, renderedPrompt, firstRenderedPrompt);
|
|
1752
1995
|
}
|
|
1753
1996
|
// Carry the gate's WHOLE decision from the request onto the result, which is what flows back up
|
|
1754
1997
|
// to the prompt run (mode) and to the agent loop (`toolResults` — the loop answers native
|
|
@@ -1763,12 +2006,20 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1763
2006
|
// TOOLS-specific reason retries the same way. Non-tool failures fall through to the existing
|
|
1764
2007
|
// retry/failover machinery untouched.
|
|
1765
2008
|
if (chatParams.tools?.length && this.isToolSpecificFailure(chatResult)) {
|
|
1766
|
-
return await this.retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, chatResult.errorMessage || chatResult.statusText || 'unspecified');
|
|
2009
|
+
return await this.retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, chatResult.errorMessage || chatResult.statusText || 'unspecified', params, renderedPrompt, firstRenderedPrompt);
|
|
2010
|
+
}
|
|
2011
|
+
if (renderedPrompt !== firstRenderedPrompt) {
|
|
2012
|
+
this.recordRerenderedMessages(chatResult, prompt, params, model, vendorId, renderedPrompt);
|
|
1767
2013
|
}
|
|
2014
|
+
RecordSentPrefixFingerprint(chatResult, sentPrefix);
|
|
1768
2015
|
return chatResult;
|
|
1769
2016
|
}
|
|
1770
2017
|
catch (error) {
|
|
1771
2018
|
const errorInfo = ErrorAnalyzer.analyzeError(error, driverClass);
|
|
2019
|
+
// A caller cancellation is not a model failure. Whoever handles it logs it once, at info level.
|
|
2020
|
+
if (this.IsCallerCancellation(errorInfo)) {
|
|
2021
|
+
throw error;
|
|
2022
|
+
}
|
|
1772
2023
|
this.logError(error, {
|
|
1773
2024
|
category: 'ModelExecution',
|
|
1774
2025
|
model: model,
|
|
@@ -1791,9 +2042,9 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1791
2042
|
* as a rejected promise the caller's failover/retry logic can act on.
|
|
1792
2043
|
*
|
|
1793
2044
|
* A timeout rejects with a typed {@link AIPromptTimeoutError} (classified by ErrorAnalyzer as a
|
|
1794
|
-
* retriable NetworkError); a caller cancellation rejects with
|
|
1795
|
-
*
|
|
1796
|
-
*
|
|
2045
|
+
* retriable NetworkError); a caller cancellation rejects with a `'Chat completion was cancelled'`
|
|
2046
|
+
* error classified as a cancellation (see {@link BaseModelRunner.BuildCancellationError}), so
|
|
2047
|
+
* failover stops instead of trying the next candidate.
|
|
1797
2048
|
*
|
|
1798
2049
|
* NOTE: `Promise.race` ignores the losing `ChatCompletion()` promise's eventual result, but the
|
|
1799
2050
|
* underlying request IS torn down — the composed signal is on `ChatParams.cancellationToken`, and
|
|
@@ -1807,29 +2058,37 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
1807
2058
|
// Neither a caller token nor a prompt timeout — execute unbounded (legacy behavior).
|
|
1808
2059
|
return await llm.ChatCompletion(chatParams);
|
|
1809
2060
|
}
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
2061
|
+
let fail;
|
|
2062
|
+
const aborted = new Promise((_, reject) => {
|
|
2063
|
+
fail = () => reject(this.buildAbortError(signal, bound));
|
|
2064
|
+
if (signal.aborted) {
|
|
2065
|
+
fail();
|
|
2066
|
+
}
|
|
2067
|
+
else {
|
|
2068
|
+
signal.addEventListener('abort', fail, { once: true });
|
|
2069
|
+
}
|
|
2070
|
+
});
|
|
2071
|
+
try {
|
|
2072
|
+
return await Promise.race([llm.ChatCompletion(chatParams), aborted]);
|
|
2073
|
+
}
|
|
2074
|
+
finally {
|
|
2075
|
+
// With no prompt timeout the signal is the caller's own token, which outlives this call: a
|
|
2076
|
+
// listener left on it would pile up across every prompt the caller runs.
|
|
2077
|
+
if (fail) {
|
|
2078
|
+
signal.removeEventListener('abort', fail);
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
1822
2081
|
}
|
|
1823
2082
|
/**
|
|
1824
2083
|
* Builds the rejection error for an aborted model call — a typed {@link AIPromptTimeoutError} when
|
|
1825
|
-
* the prompt's TimeoutMS fired, otherwise
|
|
2084
|
+
* the prompt's TimeoutMS fired, otherwise a caller cancellation that is not eligible for failover.
|
|
1826
2085
|
*/
|
|
1827
2086
|
buildAbortError(signal, bound) {
|
|
1828
2087
|
if (bound.TimedOut()) {
|
|
1829
2088
|
const reason = signal.reason;
|
|
1830
2089
|
return reason instanceof AIPromptTimeoutError ? reason : new Error('Chat completion timed out');
|
|
1831
2090
|
}
|
|
1832
|
-
return
|
|
2091
|
+
return this.BuildCancellationError();
|
|
1833
2092
|
}
|
|
1834
2093
|
/**
|
|
1835
2094
|
* Walks every message in chatParams and rewrites media content blocks
|
|
@@ -2043,6 +2302,8 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
2043
2302
|
}
|
|
2044
2303
|
return messages;
|
|
2045
2304
|
}
|
|
2305
|
+
/** Classified error types a rejected tools payload never arrives as. */
|
|
2306
|
+
static { this.TOOL_INELIGIBLE_ERROR_TYPES = ['RateLimit', 'Authentication', 'NoCredentials', 'Cancelled', 'ContextLengthExceeded']; }
|
|
2046
2307
|
/**
|
|
2047
2308
|
* Substrings that mark a provider failure as TOOLS-specific, so the native call is worth one
|
|
2048
2309
|
* envelope retry (see {@link AIPromptRunner.isToolSpecificFailure}). Drawn from how the
|
|
@@ -2052,16 +2313,33 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
2052
2313
|
* Substring matching over provider prose is inherently approximate. It is deliberately biased
|
|
2053
2314
|
* toward MISSING a tool failure rather than catching an unrelated one: a missed match just means
|
|
2054
2315
|
* the existing retry/failover logic handles the error as it does today, whereas a false positive
|
|
2055
|
-
* would silently strip tools from a run that should have kept them.
|
|
2316
|
+
* would silently strip tools from a run that should have kept them. So the markers name the
|
|
2317
|
+
* request's tool fields and the providers' own phrasing — never the bare words "tools" or
|
|
2318
|
+
* "tool call", which appear in errors that have nothing to do with the tools payload — and only
|
|
2319
|
+
* an error classified as a request error is matched at all (see `isToolEligibleError`).
|
|
2056
2320
|
*/
|
|
2057
2321
|
static { this.TOOL_FAILURE_MARKERS = [
|
|
2058
2322
|
'tool_use',
|
|
2059
2323
|
'tool use',
|
|
2060
2324
|
'tool_call',
|
|
2061
|
-
'tool call',
|
|
2325
|
+
'tool call validation',
|
|
2326
|
+
'invalid tool call',
|
|
2327
|
+
'tool calling',
|
|
2328
|
+
'tools is not supported',
|
|
2329
|
+
'tools param',
|
|
2330
|
+
'param: tools',
|
|
2062
2331
|
'tool_choice',
|
|
2063
2332
|
'tool choice',
|
|
2064
|
-
'tools',
|
|
2333
|
+
'tools:',
|
|
2334
|
+
'"tools"',
|
|
2335
|
+
'`tools`',
|
|
2336
|
+
"'tools'",
|
|
2337
|
+
'argument supplied: tools',
|
|
2338
|
+
'tools.',
|
|
2339
|
+
'tools[',
|
|
2340
|
+
'function tools',
|
|
2341
|
+
'support tools',
|
|
2342
|
+
'tools are not supported',
|
|
2065
2343
|
'function_call',
|
|
2066
2344
|
'function call',
|
|
2067
2345
|
'function_declaration',
|
|
@@ -2293,7 +2571,10 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
2293
2571
|
// Validation failed, check if we should retry
|
|
2294
2572
|
// BUG FIX: Only retry in Strict mode, not in Warn or None modes
|
|
2295
2573
|
const effectiveValidationBehavior = params?.validationBehavior || prompt.ValidationBehavior;
|
|
2296
|
-
|
|
2574
|
+
// A turn that called tools is answered by its calls; only its narration failed. Retrying
|
|
2575
|
+
// would ask again and throw the calls away, so the turn is kept as it is.
|
|
2576
|
+
const calledTools = (modelResult.data?.choices?.[0]?.message?.toolCalls?.length ?? 0) > 0;
|
|
2577
|
+
if (effectiveValidationBehavior === 'Strict' && attempt < maxRetries && !calledTools) {
|
|
2297
2578
|
lastError = new Error(`Validation failed: ${validationErrors?.map(e => e.Message).join('; ')}`);
|
|
2298
2579
|
LogStatus(` ⚠️ Validation failed on attempt ${attempt + 1}, will retry (Strict mode)`);
|
|
2299
2580
|
continue; // Retry
|
|
@@ -2302,7 +2583,7 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
2302
2583
|
// Either not strict mode or no more retries, return what we have
|
|
2303
2584
|
const reason = effectiveValidationBehavior !== 'Strict'
|
|
2304
2585
|
? `${effectiveValidationBehavior || 'None'} mode - continuing with invalid output (no retry)`
|
|
2305
|
-
: 'max retries exceeded';
|
|
2586
|
+
: calledTools ? 'the turn called tools — its calls are kept' : 'max retries exceeded';
|
|
2306
2587
|
LogStatus(` ⚠️ Validation failed on attempt ${attempt + 1}, stopping retries (${reason})`);
|
|
2307
2588
|
return {
|
|
2308
2589
|
modelResult,
|
|
@@ -2317,6 +2598,10 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
2317
2598
|
}
|
|
2318
2599
|
}
|
|
2319
2600
|
catch (error) {
|
|
2601
|
+
// A cancellation ends the retries; the caller logs it and records the run as cancelled.
|
|
2602
|
+
if (this.isCancellation(error, params)) {
|
|
2603
|
+
throw error;
|
|
2604
|
+
}
|
|
2320
2605
|
lastError = error;
|
|
2321
2606
|
this.logError(error, {
|
|
2322
2607
|
category: 'ExecutionRetry',
|
|
@@ -2492,6 +2777,16 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
2492
2777
|
* for "is this an envelope or plain prose?" under implicit control flow. Never throws.
|
|
2493
2778
|
*/
|
|
2494
2779
|
parsesAsJSON(text) {
|
|
2780
|
+
const trimmed = text.trimStart();
|
|
2781
|
+
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
|
2782
|
+
try {
|
|
2783
|
+
JSON.parse(text);
|
|
2784
|
+
return true;
|
|
2785
|
+
}
|
|
2786
|
+
catch {
|
|
2787
|
+
// Fall through to CleanJSON extraction
|
|
2788
|
+
}
|
|
2789
|
+
}
|
|
2495
2790
|
try {
|
|
2496
2791
|
JSON.parse(CleanJSON(text) ?? text);
|
|
2497
2792
|
return true;
|
|
@@ -2710,8 +3005,20 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
2710
3005
|
async parseObjectOutput(rawOutput, prompt, skipValidation, cleanValidationSyntax, validationErrors, currentPromptRun, params) {
|
|
2711
3006
|
let parsedResult;
|
|
2712
3007
|
try {
|
|
2713
|
-
//
|
|
2714
|
-
|
|
3008
|
+
// Fast path: when rawOutput already begins with '{' or '[', try native JSON.parse
|
|
3009
|
+
// directly before running CleanJSON's multi-pass regex extraction.
|
|
3010
|
+
const trimmed = rawOutput.trimStart();
|
|
3011
|
+
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
|
3012
|
+
try {
|
|
3013
|
+
parsedResult = JSON.parse(rawOutput);
|
|
3014
|
+
}
|
|
3015
|
+
catch {
|
|
3016
|
+
parsedResult = JSON.parse(CleanJSON(rawOutput));
|
|
3017
|
+
}
|
|
3018
|
+
}
|
|
3019
|
+
else {
|
|
3020
|
+
parsedResult = JSON.parse(CleanJSON(rawOutput));
|
|
3021
|
+
}
|
|
2715
3022
|
}
|
|
2716
3023
|
catch (jsonError) {
|
|
2717
3024
|
// If attemptJSONRepair is enabled and we're dealing with object output
|
|
@@ -2730,8 +3037,7 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
2730
3037
|
}
|
|
2731
3038
|
// Clean validation syntax if needed
|
|
2732
3039
|
if (parsedResult && (cleanValidationSyntax || (!skipValidation && prompt.OutputExample))) {
|
|
2733
|
-
|
|
2734
|
-
parsedResult = validator.cleanValidationSyntax(parsedResult);
|
|
3040
|
+
parsedResult = this._jsonValidator.cleanValidationSyntax(parsedResult);
|
|
2735
3041
|
}
|
|
2736
3042
|
return parsedResult;
|
|
2737
3043
|
}
|
|
@@ -3079,36 +3385,13 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
3079
3385
|
if (params.additionalParameters?.stopSequences !== undefined && params.additionalParameters.stopSequences.length > 0) {
|
|
3080
3386
|
promptRun.StopSequences = JSON.stringify(params.additionalParameters.stopSequences);
|
|
3081
3387
|
}
|
|
3082
|
-
// Store the
|
|
3388
|
+
// Store the messages the model received in the Messages field, plus the template inputs
|
|
3389
|
+
// (data, templateData) that the run's template-data capture mode allows.
|
|
3083
3390
|
// Also capture callers that supply conversationMessages directly (e.g. templateMessageRole='none',
|
|
3084
3391
|
// no rendered system prompt) — otherwise their assembled prompt would never be persisted.
|
|
3085
|
-
|
|
3086
|
-
|
|
3087
|
-
|
|
3088
|
-
// Build the system prompt content, including prefill fallback if applicable
|
|
3089
|
-
let systemContent = systemPromptText;
|
|
3090
|
-
if (prompt.AssistantPrefill && prompt.PrefillFallbackMode === 'SystemInstruction') {
|
|
3091
|
-
const fallbackTemplate = this.resolvePrefillFallbackText(model, vendorId);
|
|
3092
|
-
// Function replacement: prefill text is authored content that routinely
|
|
3093
|
-
// contains `$` (LaTeX `$$`, currency, JSON fragments), and a string
|
|
3094
|
-
// replacement would expand it. See issue #3171.
|
|
3095
|
-
const prefill = prompt.AssistantPrefill;
|
|
3096
|
-
const fallbackInstruction = fallbackTemplate.replace(/\{\{prefill\}\}/g, () => prefill);
|
|
3097
|
-
systemContent += '\n\n' + fallbackInstruction;
|
|
3098
|
-
}
|
|
3099
|
-
messages.push({
|
|
3100
|
-
role: 'system',
|
|
3101
|
-
content: systemContent
|
|
3102
|
-
});
|
|
3103
|
-
}
|
|
3104
|
-
// Always include any caller-supplied conversation messages (previously only recorded when a
|
|
3105
|
-
// template system prompt was present, which dropped them for the pure-conversationMessages path).
|
|
3106
|
-
messages.push(...(params.conversationMessages || []));
|
|
3107
|
-
promptRun.Messages = JSON.stringify({
|
|
3108
|
-
data: params.data,
|
|
3109
|
-
templateData: params.templateData,
|
|
3110
|
-
messages: messages || [],
|
|
3111
|
-
});
|
|
3392
|
+
const storedMessages = this.storedMessagesJSON(prompt, params, model, systemPromptText, vendorId);
|
|
3393
|
+
if (storedMessages) {
|
|
3394
|
+
promptRun.Messages = storedMessages;
|
|
3112
3395
|
}
|
|
3113
3396
|
// Populate new retry tracking columns with initial values
|
|
3114
3397
|
promptRun.ValidationBehavior = params.validationBehavior || prompt.ValidationBehavior || 'Warn';
|
|
@@ -3119,13 +3402,128 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
3119
3402
|
promptRun.SuccessfulValidationCount = 0;
|
|
3120
3403
|
promptRun.FinalValidationPassed = false; // Will be updated after execution
|
|
3121
3404
|
}
|
|
3405
|
+
/** The server default template-data capture mode (`aiPromptRuns.templateDataCapture` in mj.config). */
|
|
3406
|
+
GetServerTemplateDataCaptureDefault() {
|
|
3407
|
+
if (AIPromptRunner.serverTemplateDataCaptureDefault === undefined) {
|
|
3408
|
+
AIPromptRunner.serverTemplateDataCaptureDefault = ReadServerTemplateDataCaptureDefault();
|
|
3409
|
+
}
|
|
3410
|
+
return AIPromptRunner.serverTemplateDataCaptureDefault;
|
|
3411
|
+
}
|
|
3412
|
+
/**
|
|
3413
|
+
* The prompt run's `Messages`: the messages the model received, plus the template inputs (data,
|
|
3414
|
+
* templateData) the run's template-data capture mode allows. Undefined when there is nothing to
|
|
3415
|
+
* store. Also captures callers that supply conversationMessages directly (templateMessageRole
|
|
3416
|
+
* 'none', no rendered system prompt), whose assembled prompt would otherwise never be persisted.
|
|
3417
|
+
*/
|
|
3418
|
+
storedMessagesJSON(prompt, params, model, systemPromptText, vendorId) {
|
|
3419
|
+
if (!(params.data || params.templateData || systemPromptText || (params.conversationMessages?.length ?? 0) > 0)) {
|
|
3420
|
+
return undefined;
|
|
3421
|
+
}
|
|
3422
|
+
const messages = [];
|
|
3423
|
+
if (systemPromptText) {
|
|
3424
|
+
// Build the system prompt content, including prefill fallback if applicable
|
|
3425
|
+
let systemContent = systemPromptText;
|
|
3426
|
+
if (prompt.AssistantPrefill && prompt.PrefillFallbackMode === 'SystemInstruction') {
|
|
3427
|
+
const fallbackTemplate = this.resolvePrefillFallbackText(model, vendorId);
|
|
3428
|
+
// Function replacement: prefill text is authored content that routinely
|
|
3429
|
+
// contains `$` (LaTeX `$$`, currency, JSON fragments), and a string
|
|
3430
|
+
// replacement would expand it. See issue #3171.
|
|
3431
|
+
const prefill = prompt.AssistantPrefill;
|
|
3432
|
+
const fallbackInstruction = fallbackTemplate.replace(/\{\{prefill\}\}/g, () => prefill);
|
|
3433
|
+
systemContent += '\n\n' + fallbackInstruction;
|
|
3434
|
+
}
|
|
3435
|
+
messages.push({
|
|
3436
|
+
role: 'system',
|
|
3437
|
+
content: systemContent
|
|
3438
|
+
});
|
|
3439
|
+
}
|
|
3440
|
+
// Always include any caller-supplied conversation messages (previously only recorded when a
|
|
3441
|
+
// template system prompt was present, which dropped them for the pure-conversationMessages path).
|
|
3442
|
+
messages.push(...(params.conversationMessages || []));
|
|
3443
|
+
return this.buildStoredMessagesJSON(prompt, params, messages);
|
|
3444
|
+
}
|
|
3445
|
+
/**
|
|
3446
|
+
* Serializes what this run stores in `AIPromptRun.Messages`, applying the template-data capture mode.
|
|
3447
|
+
* A capture error never fails the run: it is logged, and the run stores `None` with a fixed note and no template data.
|
|
3448
|
+
*/
|
|
3449
|
+
buildStoredMessagesJSON(prompt, params, messages, parallelExecution) {
|
|
3450
|
+
try {
|
|
3451
|
+
const mode = ResolveTemplateDataCaptureMode(params.TemplateDataCapture, this.promptTemplateDataCaptureSettings(prompt, params), this.GetServerTemplateDataCaptureDefault());
|
|
3452
|
+
return JSON.stringify(BuildStoredPromptRunMessages({
|
|
3453
|
+
Mode: mode,
|
|
3454
|
+
Data: params.data,
|
|
3455
|
+
TemplateData: params.templateData,
|
|
3456
|
+
Messages: messages,
|
|
3457
|
+
GetReferencedVariables: () => this.collectReferencedVariables(prompt, params),
|
|
3458
|
+
ParallelExecution: parallelExecution,
|
|
3459
|
+
}));
|
|
3460
|
+
}
|
|
3461
|
+
catch (error) {
|
|
3462
|
+
LogError(`Template data capture failed for prompt "${prompt.Name}"; the run stores no template data`, null, error);
|
|
3463
|
+
return JSON.stringify(BuildCaptureFailedPromptRunMessages(messages, parallelExecution));
|
|
3464
|
+
}
|
|
3465
|
+
}
|
|
3466
|
+
/** The child prompts rendered in a run, depth first: each child prompt, then its own child prompts. */
|
|
3467
|
+
childPromptsDepthFirst(children) {
|
|
3468
|
+
const prompts = [];
|
|
3469
|
+
for (const child of children ?? []) {
|
|
3470
|
+
prompts.push(child.childPrompt.prompt, ...this.childPromptsDepthFirst(child.childPrompt.childPrompts));
|
|
3471
|
+
}
|
|
3472
|
+
return prompts;
|
|
3473
|
+
}
|
|
3474
|
+
/**
|
|
3475
|
+
* `TemplateDataCapture` of each prompt in the run, most specific first: the child prompts depth first, then the
|
|
3476
|
+
* main prompt. For a Loop or Harness agent, the agent's own prompt is a child prompt of the agent-type system prompt.
|
|
3477
|
+
*/
|
|
3478
|
+
promptTemplateDataCaptureSettings(prompt, params) {
|
|
3479
|
+
return [...this.childPromptsDepthFirst(params.childPrompts).map((child) => child.TemplateDataCapture), prompt.TemplateDataCapture];
|
|
3480
|
+
}
|
|
3481
|
+
/** Variables read by the prompt's template and by every child prompt template rendered in the same run. */
|
|
3482
|
+
collectReferencedVariables(prompt, params) {
|
|
3483
|
+
const names = new Set();
|
|
3484
|
+
const problems = [];
|
|
3485
|
+
const addPromptTemplate = (templateId, promptName) => {
|
|
3486
|
+
if (!templateId)
|
|
3487
|
+
return;
|
|
3488
|
+
const template = typeof this._templateEngine.FindTemplateByID === 'function'
|
|
3489
|
+
? this._templateEngine.FindTemplateByID(templateId)
|
|
3490
|
+
: this._templateEngine.Templates.find((t) => UUIDsEqual(t.ID, templateId));
|
|
3491
|
+
const text = template?.GetHighestPriorityContent()?.TemplateText;
|
|
3492
|
+
if (!text) {
|
|
3493
|
+
problems.push(`the template of prompt "${promptName}" was not found`);
|
|
3494
|
+
return;
|
|
3495
|
+
}
|
|
3496
|
+
const result = this._templateEngine.GetReferencedVariables(text);
|
|
3497
|
+
result.Names.forEach((name) => names.add(name));
|
|
3498
|
+
if (!result.Complete)
|
|
3499
|
+
problems.push(`prompt "${promptName}": ${result.Reason ?? 'incomplete analysis'}`);
|
|
3500
|
+
};
|
|
3501
|
+
addPromptTemplate(prompt.TemplateID, prompt.Name);
|
|
3502
|
+
for (const child of this.childPromptsDepthFirst(params.childPrompts)) {
|
|
3503
|
+
addPromptTemplate(child.TemplateID, child.Name);
|
|
3504
|
+
}
|
|
3505
|
+
return problems.length === 0 ? { Names: names, Complete: true } : { Names: names, Complete: false, Reason: problems.join('; ') };
|
|
3506
|
+
}
|
|
3122
3507
|
/**
|
|
3123
3508
|
* Updates the AIPromptRun entity with execution results
|
|
3124
3509
|
*/
|
|
3125
3510
|
async updatePromptRun(promptRun, prompt, modelResult, parsedResult, endTime, executionTimeMS, validationAttempts, cumulativeTokens) {
|
|
3126
3511
|
// A chat run succeeds only if the model call succeeded AND its output did not fail validation.
|
|
3127
3512
|
const success = modelResult.success && (parsedResult.validationResult?.Success !== false);
|
|
3128
|
-
return this.FinalizeRunRecord(promptRun, success, endTime, executionTimeMS, (run) =>
|
|
3513
|
+
return this.FinalizeRunRecord(promptRun, success, endTime, executionTimeMS, (run) => {
|
|
3514
|
+
// Layer 4 instrumentation: attribute this run to the path it actually took. Set inside the
|
|
3515
|
+
// finalize callback, like every result field: FinalizeRunRecord re-applies only what it saw
|
|
3516
|
+
// change, after an in-flight INSERT's reload has reverted the record — a value set before it
|
|
3517
|
+
// is lost on any call that returns faster than the INSERT. Left NULL when no model call
|
|
3518
|
+
// happened, which is the honest value.
|
|
3519
|
+
run.ToolCallingMode = GetToolCallingMode(modelResult) ?? null;
|
|
3520
|
+
// The prompt this attempt actually sent, when it was rendered again for its own path.
|
|
3521
|
+
const rerenderedMessages = AIPromptRunner._rerenderedMessages.get(modelResult);
|
|
3522
|
+
if (rerenderedMessages) {
|
|
3523
|
+
run.Messages = rerenderedMessages;
|
|
3524
|
+
}
|
|
3525
|
+
this.applyChatResultFields(run, prompt, modelResult, parsedResult, endTime, executionTimeMS, validationAttempts, cumulativeTokens);
|
|
3526
|
+
});
|
|
3129
3527
|
}
|
|
3130
3528
|
/**
|
|
3131
3529
|
* Populates a prompt-run's chat-specific finalized fields (result, tokens, cost, timing, validation)
|
|
@@ -3295,6 +3693,12 @@ export class AIPromptRunner extends BaseModelRunner {
|
|
|
3295
3693
|
}
|
|
3296
3694
|
}
|
|
3297
3695
|
// Success and Status were set by FinalizeRunRecord from the outcome updatePromptRun passed it.
|
|
3696
|
+
// A call the caller cancelled is recorded as cancelled, not as a failed model call.
|
|
3697
|
+
if (!modelResult.success && this.IsCallerCancellation(modelResult.errorInfo)) {
|
|
3698
|
+
promptRun.Status = 'Cancelled';
|
|
3699
|
+
promptRun.Cancelled = true;
|
|
3700
|
+
promptRun.CancellationReason = 'user_requested';
|
|
3701
|
+
}
|
|
3298
3702
|
// Set ErrorDetails if failed
|
|
3299
3703
|
if (!promptRun.Success) {
|
|
3300
3704
|
if (!modelResult.success && modelResult.errorMessage) {
|