@memberjunction/record-set-processor 6.2.0-edge.1 → 6.2.0-edge.2
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/RecordProcessExecutor.d.ts.map +1 -1
- package/dist/RecordProcessExecutor.js +5 -38
- package/dist/RecordProcessExecutor.js.map +1 -1
- package/dist/feature-pipeline-drivers/BaseFeaturePipelineDriver.d.ts +92 -0
- package/dist/feature-pipeline-drivers/BaseFeaturePipelineDriver.d.ts.map +1 -0
- package/dist/feature-pipeline-drivers/BaseFeaturePipelineDriver.js +26 -0
- package/dist/feature-pipeline-drivers/BaseFeaturePipelineDriver.js.map +1 -0
- package/dist/feature-pipeline-drivers/DecisionFeaturePipelineDriver.d.ts +79 -0
- package/dist/feature-pipeline-drivers/DecisionFeaturePipelineDriver.d.ts.map +1 -0
- package/dist/feature-pipeline-drivers/DecisionFeaturePipelineDriver.js +257 -0
- package/dist/feature-pipeline-drivers/DecisionFeaturePipelineDriver.js.map +1 -0
- package/dist/feature-pipeline-drivers/LLMFeaturePipelineDriver.d.ts +23 -0
- package/dist/feature-pipeline-drivers/LLMFeaturePipelineDriver.d.ts.map +1 -0
- package/dist/feature-pipeline-drivers/LLMFeaturePipelineDriver.js +85 -0
- package/dist/feature-pipeline-drivers/LLMFeaturePipelineDriver.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/processors/FeaturePipelineEscalation.d.ts +155 -0
- package/dist/processors/FeaturePipelineEscalation.d.ts.map +1 -0
- package/dist/processors/FeaturePipelineEscalation.js +208 -0
- package/dist/processors/FeaturePipelineEscalation.js.map +1 -0
- package/dist/processors/InferProcessor.d.ts +206 -4
- package/dist/processors/InferProcessor.d.ts.map +1 -1
- package/dist/processors/InferProcessor.js +600 -93
- package/dist/processors/InferProcessor.js.map +1 -1
- package/dist/processors/WriteBackProcessor.d.ts.map +1 -1
- package/dist/processors/WriteBackProcessor.js +2 -0
- package/dist/processors/WriteBackProcessor.js.map +1 -1
- package/package.json +17 -16
|
@@ -6,19 +6,32 @@
|
|
|
6
6
|
*
|
|
7
7
|
* Supports DataFeatureSpec context (EntityDocumentID template rendering with __Parent context,
|
|
8
8
|
* QueryID parameterized execution, Field projections), Layer-1 constraint injection, Layer-2
|
|
9
|
-
* constraint validation with OnViolation policies, and lifecycle hooks (P1-6).
|
|
9
|
+
* constraint validation with OnViolation policies, and lifecycle hooks (P1-6). A Decision pipeline
|
|
10
|
+
* whose spec sets `Escalation` re-runs its below-floor records through an LLM pipeline
|
|
11
|
+
* (see `FeaturePipelineEscalation`).
|
|
10
12
|
*
|
|
11
13
|
* @module @memberjunction/record-set-processor
|
|
12
14
|
*/
|
|
13
15
|
import { createHash } from 'node:crypto';
|
|
14
|
-
import { LogError, Metadata, RunQuery, RunView } from '@memberjunction/core';
|
|
15
|
-
import { UUIDsEqual, Canonicalize, ComputeContentHashAsync, EscapeSQLString, resolveMappingRef, resolveValueMapping } from '@memberjunction/global';
|
|
16
|
+
import { LogError, LogStatus, Metadata, RunQuery, RunView } from '@memberjunction/core';
|
|
17
|
+
import { MJGlobal, UUIDsEqual, Canonicalize, ComputeContentHashAsync, EscapeSQLString, ResolveMappingRef, SafeJSONParse, resolveMappingRef, resolveValueMapping } from '@memberjunction/global';
|
|
18
|
+
import { KnowledgeHubMetadataEngine } from '@memberjunction/core-entities';
|
|
16
19
|
import { AIEngine } from '@memberjunction/aiengine';
|
|
17
|
-
import {
|
|
18
|
-
import { AIPromptParams } from '@memberjunction/ai-core-plus';
|
|
19
|
-
import { FeatureValueCacheService, renderConstraintBlock, validateOutputValue, } from '@memberjunction/feature-pipelines';
|
|
20
|
+
import { FeatureValueCacheService, ResolveConstraint, BuildEntityFieldValueLookup, IsDecisionPipelineType, IsLLMPipelineType, LLM_PIPELINE_TYPE, renderConstraintBlock, validateMaterializationTargets, validateOutputValue, validateSpec, FindOutputByName, } from '@memberjunction/feature-pipelines';
|
|
20
21
|
import { EntityDocumentCache, EntityDocumentTemplateParser } from '@memberjunction/entity-documents';
|
|
21
|
-
|
|
22
|
+
import { BaseFeaturePipelineDriver, } from '../feature-pipeline-drivers/BaseFeaturePipelineDriver.js';
|
|
23
|
+
import { LLMFeaturePipelineDriver } from '../feature-pipeline-drivers/LLMFeaturePipelineDriver.js';
|
|
24
|
+
import { DescribeEscalationFailure, FeaturePipelineEscalator, } from './FeaturePipelineEscalation.js';
|
|
25
|
+
/** Whether a value is a plain JSON object (not null, not an array). */
|
|
26
|
+
function isPlainRecord(value) {
|
|
27
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Runs an AI Prompt per record and returns its structured output (write-back is the wrapper's job).
|
|
31
|
+
* A pipeline whose spec sets `Escalation` computes a whole batch before recording any of it, so its batch
|
|
32
|
+
* path does not call {@link ProcessRecord} once per record: an extension that overrides `ProcessRecord`
|
|
33
|
+
* does not see those records.
|
|
34
|
+
*/
|
|
22
35
|
export class InferProcessor {
|
|
23
36
|
/**
|
|
24
37
|
* @param promptID - The `MJ: AI Prompts` ID to run for each record.
|
|
@@ -29,20 +42,99 @@ export class InferProcessor {
|
|
|
29
42
|
this.promptID = promptID;
|
|
30
43
|
this.inputMapping = inputMapping;
|
|
31
44
|
this.spec = spec;
|
|
45
|
+
/** How many records this processor has escalated. */
|
|
46
|
+
this.escalatedRecordCount = 0;
|
|
47
|
+
/**
|
|
48
|
+
* Whether this processor writes `MJ: Feature Values` history rows. On for every pipeline run. A
|
|
49
|
+
* Decision pipeline turns it off on its escalation target, because it records the final answers of
|
|
50
|
+
* the records it escalates itself.
|
|
51
|
+
*/
|
|
52
|
+
this.WritesHistory = true;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Builds the processor for an Infer Feature Pipeline from its `MJ: Record Processes` row: parses and
|
|
56
|
+
* validates the DataFeatureSpec in `Configuration` (and its materialization targets), and creates the
|
|
57
|
+
* spec's `ProcessorExtensionKey` subclass when it names one. `RecordProcessExecutor` builds every
|
|
58
|
+
* Infer pipeline this way, and so does a Decision pipeline's escalation to an LLM pipeline.
|
|
59
|
+
*
|
|
60
|
+
* @param rp - The pipeline's row (WorkType `Infer`).
|
|
61
|
+
* @param provider - The provider whose metadata the materialization targets are checked against (default: the global one).
|
|
62
|
+
* @throws Error when the row has no PromptID, its Configuration is not valid JSON, its spec or
|
|
63
|
+
* materialization targets are invalid, or its ProcessorExtensionKey is not registered.
|
|
64
|
+
*/
|
|
65
|
+
static FromRecordProcess(rp, provider) {
|
|
66
|
+
if (!rp.PromptID) {
|
|
67
|
+
throw new Error(`Record Process '${rp.Name}': WorkType=Infer requires PromptID`);
|
|
68
|
+
}
|
|
69
|
+
const inputMapping = rp.InputMapping ? SafeJSONParse(rp.InputMapping) : undefined;
|
|
70
|
+
const spec = InferProcessor.parseSpec(rp, provider);
|
|
71
|
+
if (spec?.ProcessorExtensionKey) {
|
|
72
|
+
const custom = MJGlobal.Instance.ClassFactory.CreateInstance(InferProcessor, spec.ProcessorExtensionKey, rp.PromptID, inputMapping, spec);
|
|
73
|
+
if (custom && custom.constructor !== InferProcessor) {
|
|
74
|
+
return custom;
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
throw new Error(`Record Process '${rp.Name}': ProcessorExtensionKey '${spec.ProcessorExtensionKey}' not found in ClassFactory`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return new InferProcessor(rp.PromptID, inputMapping, spec);
|
|
81
|
+
}
|
|
82
|
+
/** Parses and validates the DataFeatureSpec in an Infer pipeline row's `Configuration`; undefined when it has none. */
|
|
83
|
+
static parseSpec(rp, provider) {
|
|
84
|
+
let spec;
|
|
85
|
+
if (rp.Configuration && rp.Configuration.trim().length > 0) {
|
|
86
|
+
try {
|
|
87
|
+
spec = JSON.parse(rp.Configuration);
|
|
88
|
+
}
|
|
89
|
+
catch (e) {
|
|
90
|
+
throw new Error(`Record Process '${rp.Name}': Configuration is invalid JSON: ${e instanceof Error ? e.message : String(e)}`);
|
|
91
|
+
}
|
|
92
|
+
const issues = validateSpec(spec);
|
|
93
|
+
const errors = issues.filter((i) => i.Severity === 'error');
|
|
94
|
+
if (errors.length > 0) {
|
|
95
|
+
throw new Error(`Record Process '${rp.Name}': invalid DataFeatureSpec in Configuration: ${errors.map((err) => err.Message).join('; ')}`);
|
|
96
|
+
}
|
|
97
|
+
const targetProvider = provider ?? Metadata.Provider;
|
|
98
|
+
if (targetProvider && rp.EntityID) {
|
|
99
|
+
const materializationIssues = validateMaterializationTargets(spec, targetProvider, rp.EntityID);
|
|
100
|
+
const matErrors = materializationIssues.filter((i) => i.Severity === 'error');
|
|
101
|
+
if (matErrors.length > 0) {
|
|
102
|
+
throw new Error(`Record Process '${rp.Name}': invalid materialization targets: ${matErrors.map((err) => `${err.Field ? `[${err.Field}] ` : ''}${err.Message} Fix: ${err.FixRecommendation}`).join('; ')}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return spec;
|
|
107
|
+
}
|
|
108
|
+
/** The pipeline's DataFeatureSpec, when it has one. */
|
|
109
|
+
get Spec() {
|
|
110
|
+
return this.spec;
|
|
111
|
+
}
|
|
112
|
+
/** The `MJ: AI Prompts` ID this processor runs for each record. */
|
|
113
|
+
get PromptID() {
|
|
114
|
+
return this.promptID;
|
|
115
|
+
}
|
|
116
|
+
/** The hash that versions this pipeline's output constraints, as its Dedup Cache and history record it. */
|
|
117
|
+
get ConstraintHash() {
|
|
118
|
+
return this.computeConstraintHash(this.spec);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* How many records this processor has escalated to its spec's `Escalation` pipeline. A processor
|
|
122
|
+
* serves one run, so this is the run's count. It counts every record whose answer was escalated,
|
|
123
|
+
* including the records that shared a Dedup Cache key with one, and the escalations that failed.
|
|
124
|
+
*/
|
|
125
|
+
get EscalatedRecordCount() {
|
|
126
|
+
return this.escalatedRecordCount;
|
|
32
127
|
}
|
|
33
128
|
async ProcessRecord(record, context, options) {
|
|
34
129
|
await this.ensureRecordsLoaded([record], context);
|
|
35
|
-
await
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
return { Status: 'Failed', ErrorMessage: `AI Prompt '${this.promptID}' not found` };
|
|
130
|
+
const run = await this.resolveRunState(context);
|
|
131
|
+
if ('ErrorMessage' in run) {
|
|
132
|
+
return { Status: 'Failed', ErrorMessage: run.ErrorMessage };
|
|
39
133
|
}
|
|
40
|
-
const
|
|
41
|
-
const promptVersionHash = this.computePromptVersionHash(prompt, this.spec);
|
|
42
|
-
const constraintHash = this.computeConstraintHash(this.spec);
|
|
134
|
+
const { Prompt: prompt, PromptVersionHash: promptVersionHash, ConstraintHash: constraintHash } = run;
|
|
43
135
|
let keyInfo;
|
|
44
136
|
// P1-7c Dedup Cache lookup
|
|
45
|
-
if (
|
|
137
|
+
if (run.IsCacheable) {
|
|
46
138
|
keyInfo =
|
|
47
139
|
options?.keyInfo ??
|
|
48
140
|
(await FeatureValueCacheService.Instance.computeCacheKey({
|
|
@@ -91,46 +183,55 @@ export class InferProcessor {
|
|
|
91
183
|
}
|
|
92
184
|
}
|
|
93
185
|
}
|
|
94
|
-
//
|
|
95
|
-
await this.
|
|
96
|
-
//
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
186
|
+
// The pipeline type's driver turns the record's context into its outputs (for LLM: the prompt run and its hooks)
|
|
187
|
+
const sample = await this.computeSample({ keyInfo, records: [record] }, context, run);
|
|
188
|
+
// A decision below the escalation floor escalates; any other answer is validated and recorded as it is
|
|
189
|
+
const [finalized] = await this.finalizeSamples([sample], context, run);
|
|
190
|
+
return finalized.Result;
|
|
191
|
+
}
|
|
192
|
+
/** Runs the driver on a key group's first record, and notes which outputs, if any, are below the escalation floor. */
|
|
193
|
+
async computeSample(group, context, run) {
|
|
194
|
+
const sample = group.records[0];
|
|
195
|
+
const fieldValues = this.buildFieldValuesLookup(context);
|
|
196
|
+
const computed = await run.Driver.ComputeOutputs({
|
|
197
|
+
Record: sample,
|
|
198
|
+
Context: context,
|
|
199
|
+
Prompt: run.Prompt,
|
|
200
|
+
Spec: this.spec,
|
|
201
|
+
Hooks: this.buildComputeHooks(),
|
|
202
|
+
FieldValues: fieldValues,
|
|
107
203
|
});
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
if (!result.success) {
|
|
204
|
+
return { Group: group, Sample: sample, Computed: computed, BelowFloor: this.belowFloor(computed) };
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Finishes a computed sample: a driver failure fails it, a below-floor decision takes its escalation's
|
|
208
|
+
* outcome, and any other answer is validated, cached and recorded.
|
|
209
|
+
*/
|
|
210
|
+
async finalizeSample(sample, outcomes, context, run) {
|
|
211
|
+
const computed = sample.Computed;
|
|
212
|
+
if ('ErrorMessage' in computed) {
|
|
118
213
|
return {
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
214
|
+
Result: {
|
|
215
|
+
Status: 'Failed',
|
|
216
|
+
ErrorMessage: computed.ErrorMessage,
|
|
217
|
+
AIPromptRunID: computed.AIPromptRunID,
|
|
218
|
+
},
|
|
122
219
|
};
|
|
123
220
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
if (typeof rawResult === 'string') {
|
|
127
|
-
try {
|
|
128
|
-
rawResult = JSON.parse(rawResult);
|
|
129
|
-
}
|
|
130
|
-
catch {
|
|
131
|
-
// leave as raw string if not JSON
|
|
132
|
-
}
|
|
221
|
+
if (sample.BelowFloor.length > 0) {
|
|
222
|
+
return this.finalizeEscalated(sample, computed, outcomes.get(sample.Sample.RecordID), context, run);
|
|
133
223
|
}
|
|
224
|
+
const result = await this.finalizeComputed(sample.Sample, context, run, sample.Group.keyInfo, computed);
|
|
225
|
+
return { Result: result, History: this.missFanOutHistory(result, context, run) };
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Validates a driver's outputs against the constraints (applying each OnViolation policy), stores
|
|
229
|
+
* them in the Dedup Cache, and records their history.
|
|
230
|
+
*/
|
|
231
|
+
async finalizeComputed(record, context, run, keyInfo, computed) {
|
|
232
|
+
const { Prompt: prompt, PromptVersionHash: promptVersionHash, ConstraintHash: constraintHash } = run;
|
|
233
|
+
const aiPromptRunID = computed.AIPromptRunID;
|
|
234
|
+
const rawResult = computed.RawResult;
|
|
134
235
|
// Layer 2: Validate outputs against constraints and apply OnViolation policy
|
|
135
236
|
const validationOutcome = await this.validateOutputs(this.spec?.Outputs ?? [], rawResult, record, context);
|
|
136
237
|
if (!validationOutcome.valid) {
|
|
@@ -140,10 +241,11 @@ export class InferProcessor {
|
|
|
140
241
|
AIPromptRunID: aiPromptRunID,
|
|
141
242
|
};
|
|
142
243
|
}
|
|
244
|
+
const confidence = this.confidenceOfKeptValues(computed.Confidence, validationOutcome.replacedOutputs);
|
|
143
245
|
let featureValueCacheID;
|
|
144
246
|
const reasoning = typeof rawResult === 'object' && rawResult !== null ? rawResult.reasoning : undefined;
|
|
145
247
|
// P1-7c Dedup Cache store
|
|
146
|
-
if (
|
|
248
|
+
if (run.IsCacheable && keyInfo) {
|
|
147
249
|
try {
|
|
148
250
|
const stored = await FeatureValueCacheService.Instance.Store({
|
|
149
251
|
recordProcessID: context.recordProcessID,
|
|
@@ -178,6 +280,7 @@ export class InferProcessor {
|
|
|
178
280
|
constraintHash,
|
|
179
281
|
aiPromptRunID,
|
|
180
282
|
featureValueCacheID,
|
|
283
|
+
...(confidence ? { outputConfidence: confidence } : {}),
|
|
181
284
|
});
|
|
182
285
|
return {
|
|
183
286
|
Status: 'Succeeded',
|
|
@@ -185,6 +288,7 @@ export class InferProcessor {
|
|
|
185
288
|
AIPromptRunID: aiPromptRunID,
|
|
186
289
|
PromptVersionHash: promptVersionHash,
|
|
187
290
|
FeatureValueCacheID: featureValueCacheID,
|
|
291
|
+
...(confidence ? { Confidence: confidence } : {}),
|
|
188
292
|
};
|
|
189
293
|
}
|
|
190
294
|
/**
|
|
@@ -196,21 +300,20 @@ export class InferProcessor {
|
|
|
196
300
|
await this.ensureRecordsLoaded(records, context);
|
|
197
301
|
const results = new Map();
|
|
198
302
|
if (!this.spec?.Caching?.Cacheable || records.length === 0) {
|
|
303
|
+
if (this.escalator && records.length > 0) {
|
|
304
|
+
return this.processUncachedBatchWithEscalation(records, context);
|
|
305
|
+
}
|
|
199
306
|
for (const r of records) {
|
|
200
307
|
results.set(r.RecordID, await this.ProcessRecord(r, context));
|
|
201
308
|
}
|
|
202
309
|
return results;
|
|
203
310
|
}
|
|
204
|
-
|
|
205
|
-
const
|
|
206
|
-
if (
|
|
207
|
-
|
|
208
|
-
results.set(r.RecordID, { Status: 'Failed', ErrorMessage: `AI Prompt '${this.promptID}' not found` });
|
|
209
|
-
}
|
|
210
|
-
return results;
|
|
311
|
+
// Resolve before the cache phases, so a type that cannot run fails every record rather than serving cache hits
|
|
312
|
+
const run = await this.resolveRunState(context);
|
|
313
|
+
if ('ErrorMessage' in run) {
|
|
314
|
+
return this.failEvery(records, run.ErrorMessage, results);
|
|
211
315
|
}
|
|
212
|
-
const
|
|
213
|
-
const constraintHash = this.computeConstraintHash(this.spec);
|
|
316
|
+
const { Prompt: prompt, PromptVersionHash: promptVersionHash, ConstraintHash: constraintHash } = run;
|
|
214
317
|
// Phase 1: Compute distinct cache keys across the batch
|
|
215
318
|
const keyGroupMap = new Map();
|
|
216
319
|
for (const record of records) {
|
|
@@ -239,6 +342,7 @@ export class InferProcessor {
|
|
|
239
342
|
provider: context.provider,
|
|
240
343
|
});
|
|
241
344
|
// Phase 3: Fan out hits; execute misses ONCE per distinct key and fan out
|
|
345
|
+
const escalatingMisses = [];
|
|
242
346
|
for (const [keyHash, group] of keyGroupMap.entries()) {
|
|
243
347
|
const cached = cacheMap.get(keyHash);
|
|
244
348
|
if (cached) {
|
|
@@ -273,6 +377,10 @@ export class InferProcessor {
|
|
|
273
377
|
});
|
|
274
378
|
}
|
|
275
379
|
}
|
|
380
|
+
else if (this.escalator) {
|
|
381
|
+
// CACHE MISS, escalating pipeline: computed together below, so the below-floor records escalate together
|
|
382
|
+
escalatingMisses.push(group);
|
|
383
|
+
}
|
|
276
384
|
else {
|
|
277
385
|
// CACHE MISS: Execute prompt ONCE for the distinct key (using the first record in the group)
|
|
278
386
|
const sampleRecord = group.records[0];
|
|
@@ -281,38 +389,314 @@ export class InferProcessor {
|
|
|
281
389
|
keyInfo: group.keyInfo,
|
|
282
390
|
});
|
|
283
391
|
// Fan out result to all records in this group
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
392
|
+
await this.fanOutGroupResult(group, sampleRecord, singleResult, this.missFanOutHistory(singleResult, context, run), results);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
await this.computeGroupsWithEscalation(escalatingMisses, context, run, results);
|
|
396
|
+
return results;
|
|
397
|
+
}
|
|
398
|
+
/** Fails every record with one message. */
|
|
399
|
+
failEvery(records, errorMessage, results) {
|
|
400
|
+
for (const r of records) {
|
|
401
|
+
results.set(r.RecordID, { Status: 'Failed', ErrorMessage: errorMessage });
|
|
402
|
+
}
|
|
403
|
+
return results;
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Resolves what one processing pass needs: the prompt, the driver, and the hashes that version the
|
|
407
|
+
* pipeline's answers. Returns why the pipeline cannot run instead, when the prompt is missing or the
|
|
408
|
+
* driver cannot be resolved.
|
|
409
|
+
*/
|
|
410
|
+
async resolveRunState(context) {
|
|
411
|
+
await AIEngine.Instance.Config(false, context.contextUser);
|
|
412
|
+
const prompt = AIEngine.Instance.Prompts.find((p) => UUIDsEqual(p.ID, this.promptID));
|
|
413
|
+
if (!prompt) {
|
|
414
|
+
return { ErrorMessage: `AI Prompt '${this.promptID}' not found` };
|
|
415
|
+
}
|
|
416
|
+
const resolution = await this.resolveDriverOrError(context);
|
|
417
|
+
if ('ErrorMessage' in resolution) {
|
|
418
|
+
return { ErrorMessage: resolution.ErrorMessage };
|
|
419
|
+
}
|
|
420
|
+
return {
|
|
421
|
+
Prompt: prompt,
|
|
422
|
+
Driver: resolution.Driver,
|
|
423
|
+
IsCacheable: this.spec?.Caching?.Cacheable === true,
|
|
424
|
+
PromptVersionHash: this.computePromptVersionHash(prompt, this.spec),
|
|
425
|
+
ConstraintHash: this.computeConstraintHash(this.spec),
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Gives every record in a key group its sample's result. The other records get a copy of it, and their
|
|
430
|
+
* own history row from `history` (which is absent when the sample failed).
|
|
431
|
+
*/
|
|
432
|
+
async fanOutGroupResult(group, sample, result, history, results) {
|
|
433
|
+
for (const rec of group.records) {
|
|
434
|
+
if (rec.RecordID === sample.RecordID) {
|
|
435
|
+
results.set(rec.RecordID, result);
|
|
436
|
+
}
|
|
437
|
+
else {
|
|
438
|
+
if (history) {
|
|
439
|
+
await this.recordFeatureValuesHistory({ ...history, record: rec });
|
|
303
440
|
}
|
|
441
|
+
results.set(rec.RecordID, { ...result });
|
|
304
442
|
}
|
|
305
443
|
}
|
|
444
|
+
}
|
|
445
|
+
/** The history a key group's other records get from its sample's computed result: none when it failed. */
|
|
446
|
+
missFanOutHistory(result, context, run) {
|
|
447
|
+
if (result.Status !== 'Succeeded') {
|
|
448
|
+
return undefined;
|
|
449
|
+
}
|
|
450
|
+
return {
|
|
451
|
+
context,
|
|
452
|
+
payload: result.ResultPayload,
|
|
453
|
+
promptID: run.Prompt.ID,
|
|
454
|
+
promptVersionHash: run.PromptVersionHash,
|
|
455
|
+
constraintHash: run.ConstraintHash,
|
|
456
|
+
aiPromptRunID: result.AIPromptRunID,
|
|
457
|
+
featureValueCacheID: result.FeatureValueCacheID,
|
|
458
|
+
...(result.Confidence ? { outputConfidence: result.Confidence } : {}),
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
// -------------------------------------------------------------------------------------------------
|
|
462
|
+
// Escalation (DataFeatureSpec.Escalation): below-floor decisions re-run through an LLM pipeline
|
|
463
|
+
// -------------------------------------------------------------------------------------------------
|
|
464
|
+
/**
|
|
465
|
+
* The escalation of below-floor decisions, when the spec is a Decision pipeline's and has `Escalation`;
|
|
466
|
+
* created once. `ValidateSpec` already refuses `Escalation` on any other type, but a processor built
|
|
467
|
+
* directly from a spec skips it, and an LLM pipeline returns no confidence, so every record would escalate.
|
|
468
|
+
*/
|
|
469
|
+
get escalator() {
|
|
470
|
+
if (!this.spec?.Escalation || !IsDecisionPipelineType(this.spec.PipelineType)) {
|
|
471
|
+
return undefined;
|
|
472
|
+
}
|
|
473
|
+
this._escalator ??= new FeaturePipelineEscalator(this.spec.Escalation, this.spec.Outputs ?? [], (pipeline, provider) => InferProcessor.FromRecordProcess(pipeline, provider));
|
|
474
|
+
return this._escalator;
|
|
475
|
+
}
|
|
476
|
+
/** A successful decision's outputs below the escalation floor; empty when the pipeline does not escalate. */
|
|
477
|
+
belowFloor(computed) {
|
|
478
|
+
const escalator = this.escalator;
|
|
479
|
+
if (!escalator || 'ErrorMessage' in computed) {
|
|
480
|
+
return [];
|
|
481
|
+
}
|
|
482
|
+
return escalator.BelowFloor(computed.Confidence);
|
|
483
|
+
}
|
|
484
|
+
/** An uncached batch of a pipeline that escalates: every record is its own group, computed together. */
|
|
485
|
+
async processUncachedBatchWithEscalation(records, context) {
|
|
486
|
+
const results = new Map();
|
|
487
|
+
const run = await this.resolveRunState(context);
|
|
488
|
+
if ('ErrorMessage' in run) {
|
|
489
|
+
return this.failEvery(records, run.ErrorMessage, results);
|
|
490
|
+
}
|
|
491
|
+
await this.computeGroupsWithEscalation(records.map((r) => ({ records: [r] })), context, run, results);
|
|
306
492
|
return results;
|
|
307
493
|
}
|
|
308
|
-
/**
|
|
494
|
+
/**
|
|
495
|
+
* Computes key groups for a pipeline that escalates. The driver answers each group's first record; the
|
|
496
|
+
* below-floor answers escalate together, in one pass through the target; then each group's final
|
|
497
|
+
* answer is recorded once and fanned out to its records.
|
|
498
|
+
*/
|
|
499
|
+
async computeGroupsWithEscalation(groups, context, run, results) {
|
|
500
|
+
const samples = [];
|
|
501
|
+
for (const group of groups) {
|
|
502
|
+
samples.push(await this.computeSample(group, context, run));
|
|
503
|
+
}
|
|
504
|
+
const finalized = await this.finalizeSamples(samples, context, run);
|
|
505
|
+
for (let i = 0; i < samples.length; i++) {
|
|
506
|
+
await this.fanOutGroupResult(samples[i].Group, samples[i].Sample, finalized[i].Result, finalized[i].History, results);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Escalates the below-floor samples together, then finalizes every sample, in order. The escalations are
|
|
511
|
+
* counted and logged by each escalated sample's final result, so an escalated answer that fails this
|
|
512
|
+
* pipeline's own constraints counts as failed.
|
|
513
|
+
*/
|
|
514
|
+
async finalizeSamples(samples, context, run) {
|
|
515
|
+
const outcomes = await this.escalateBelowFloor(samples, context);
|
|
516
|
+
const finalized = [];
|
|
517
|
+
for (const sample of samples) {
|
|
518
|
+
finalized.push(await this.finalizeSample(sample, outcomes, context, run));
|
|
519
|
+
}
|
|
520
|
+
this.countEscalations(samples, finalized);
|
|
521
|
+
return finalized;
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Escalates, together, the samples whose decision was below the floor. Returns each escalated sample's
|
|
525
|
+
* outcome by record ID; empty when none escalated.
|
|
526
|
+
*/
|
|
527
|
+
async escalateBelowFloor(samples, context) {
|
|
528
|
+
const escalator = this.escalator;
|
|
529
|
+
const escalating = samples.filter((s) => s.BelowFloor.length > 0);
|
|
530
|
+
if (!escalator || escalating.length === 0) {
|
|
531
|
+
return new Map();
|
|
532
|
+
}
|
|
533
|
+
return escalator.Escalate(escalating.map((s) => ({ Record: s.Sample, BelowFloor: s.BelowFloor })), context);
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* Adds a pass's escalated records (each group's records, fan-out included) to the run's count, and logs
|
|
537
|
+
* it, counting as failed each escalated group whose final result failed.
|
|
538
|
+
*/
|
|
539
|
+
countEscalations(samples, finalized) {
|
|
540
|
+
const escalator = this.escalator;
|
|
541
|
+
let escalated = 0;
|
|
542
|
+
let failed = 0;
|
|
543
|
+
samples.forEach((sample, i) => {
|
|
544
|
+
if (sample.BelowFloor.length === 0) {
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
escalated += sample.Group.records.length;
|
|
548
|
+
if (finalized[i].Result.Status !== 'Succeeded') {
|
|
549
|
+
failed += sample.Group.records.length;
|
|
550
|
+
}
|
|
551
|
+
});
|
|
552
|
+
if (!escalator || escalated === 0) {
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
this.escalatedRecordCount += escalated;
|
|
556
|
+
LogStatus(`InferProcessor: escalated ${escalated} record(s) whose decision confidence was below ${escalator.BelowConfidence} ` +
|
|
557
|
+
`to Feature Pipeline '${escalator.PipelineID}' (${failed} failed); ${this.escalatedRecordCount} escalated in this run.`);
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Finishes a record whose decision was below the escalation floor. A failed escalation fails the record
|
|
561
|
+
* with both reasons, and the low-confidence decision is never cached, recorded or returned. A successful
|
|
562
|
+
* one replaces the decision: the target's validated payload, in this pipeline's shape, is recorded in
|
|
563
|
+
* history under the target's prompt, prompt run, hashes and cache entry, with the escalation note as the
|
|
564
|
+
* history row's reasoning, and the record's result names the target's prompt with that prompt run and
|
|
565
|
+
* hash, so write-back's `$run` provenance describes one run. It is not written to this pipeline's Dedup
|
|
566
|
+
* Cache, which holds only answers the decision model gave with confidence; the target caches its own answers.
|
|
567
|
+
*
|
|
568
|
+
* The target validated its answer against its own constraints only, and those may be looser than this
|
|
569
|
+
* pipeline's (a wider enum, or none). So the answer, in this pipeline's shape, is validated again against
|
|
570
|
+
* this pipeline's own output constraints, with each output's OnViolation policy, exactly as a decision's
|
|
571
|
+
* answer is: `fail` fails the record with both reasons, `null` and `coerce-to-other` apply. A value
|
|
572
|
+
* outside the Decision pipeline's domain is never recorded or written back.
|
|
573
|
+
*
|
|
574
|
+
* The record paid for two model calls, and `MJ: Feature Values` is what links a prompt run to the process
|
|
575
|
+
* run. So before the answer's row, one more history row records the superseded decision: its prompt run,
|
|
576
|
+
* prompt, hashes and confidence, with no values (the low-confidence answer is never recorded as a value)
|
|
577
|
+
* and a reasoning that says it was superseded. It is written once per decision call: a key group's other
|
|
578
|
+
* records get only the answer's row.
|
|
579
|
+
*/
|
|
580
|
+
async finalizeEscalated(sample, decision, outcome, context, run) {
|
|
581
|
+
const record = sample.Sample;
|
|
582
|
+
const decisionRunID = decision.AIPromptRunID;
|
|
583
|
+
if (!outcome) {
|
|
584
|
+
const message = `Escalation to Feature Pipeline '${this.spec?.Escalation?.PipelineID}' returned no outcome`;
|
|
585
|
+
return { Result: { Status: 'Failed', ErrorMessage: message, AIPromptRunID: decisionRunID } };
|
|
586
|
+
}
|
|
587
|
+
if ('ErrorMessage' in outcome) {
|
|
588
|
+
return { Result: { Status: 'Failed', ErrorMessage: outcome.ErrorMessage, AIPromptRunID: outcome.AIPromptRunID ?? decisionRunID } };
|
|
589
|
+
}
|
|
590
|
+
const checked = await this.validateOutputs(this.spec?.Outputs ?? [], this.projectEscalatedPayload(outcome), record, context);
|
|
591
|
+
if (!checked.valid) {
|
|
592
|
+
const reason = `its answer is outside this Decision pipeline's own constraints: ${checked.errorMessage ?? 'Constraint violation'}`;
|
|
593
|
+
const message = DescribeEscalationFailure(outcome.EscalationReason, outcome.PipelineName, reason);
|
|
594
|
+
return { Result: { Status: 'Failed', ErrorMessage: message, AIPromptRunID: outcome.AIPromptRunID ?? decisionRunID } };
|
|
595
|
+
}
|
|
596
|
+
const payload = checked.payload;
|
|
597
|
+
await this.recordSupersededDecision(record, decision, outcome, context, run);
|
|
598
|
+
const history = {
|
|
599
|
+
context,
|
|
600
|
+
payload,
|
|
601
|
+
reasoning: outcome.Note,
|
|
602
|
+
promptID: outcome.PromptID,
|
|
603
|
+
promptVersionHash: outcome.PromptVersionHash,
|
|
604
|
+
constraintHash: outcome.ConstraintHash,
|
|
605
|
+
aiPromptRunID: outcome.AIPromptRunID,
|
|
606
|
+
featureValueCacheID: outcome.FeatureValueCacheID,
|
|
607
|
+
};
|
|
608
|
+
await this.recordFeatureValuesHistory({ ...history, record });
|
|
609
|
+
return {
|
|
610
|
+
Result: {
|
|
611
|
+
Status: 'Succeeded',
|
|
612
|
+
ResultPayload: payload,
|
|
613
|
+
PromptID: outcome.PromptID,
|
|
614
|
+
AIPromptRunID: outcome.AIPromptRunID,
|
|
615
|
+
PromptVersionHash: outcome.PromptVersionHash,
|
|
616
|
+
FeatureValueCacheID: outcome.FeatureValueCacheID,
|
|
617
|
+
},
|
|
618
|
+
History: history,
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Records the history row of a decision an escalation superseded: the decision model's prompt run and
|
|
623
|
+
* confidence under this pipeline's prompt and hashes, no values, and a reasoning saying it was superseded.
|
|
624
|
+
* Nothing is recorded when the decision has no prompt run to link.
|
|
625
|
+
*/
|
|
626
|
+
async recordSupersededDecision(record, decision, outcome, context, run) {
|
|
627
|
+
if (!decision.AIPromptRunID) {
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
await this.recordFeatureValuesHistory({
|
|
631
|
+
record,
|
|
632
|
+
context,
|
|
633
|
+
payload: null,
|
|
634
|
+
omitValues: true,
|
|
635
|
+
reasoning: outcome.SupersededNote,
|
|
636
|
+
promptID: run.Prompt.ID,
|
|
637
|
+
promptVersionHash: run.PromptVersionHash,
|
|
638
|
+
constraintHash: run.ConstraintHash,
|
|
639
|
+
aiPromptRunID: decision.AIPromptRunID,
|
|
640
|
+
...(decision.Confidence ? { outputConfidence: decision.Confidence } : {}),
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* The escalated payload in this pipeline's shape: the target's validated payload, with each output's
|
|
645
|
+
* value also placed at this pipeline's Ref for it, so write-back and history (which read this
|
|
646
|
+
* pipeline's Refs) find the escalated values. When both pipelines use the same Refs, it is the target's
|
|
647
|
+
* payload as is.
|
|
648
|
+
*/
|
|
649
|
+
projectEscalatedPayload(outcome) {
|
|
650
|
+
let projected = isPlainRecord(outcome.Payload) ? structuredClone(outcome.Payload) : outcome.Payload;
|
|
651
|
+
for (const output of this.spec?.Outputs ?? []) {
|
|
652
|
+
const source = FindOutputByName(outcome.TargetOutputs, output.Name);
|
|
653
|
+
if (!source || source.Ref === output.Ref) {
|
|
654
|
+
continue;
|
|
655
|
+
}
|
|
656
|
+
const value = ResolveMappingRef(source.Ref, { $: outcome.Payload });
|
|
657
|
+
if (output.Ref === '$') {
|
|
658
|
+
projected = value;
|
|
659
|
+
}
|
|
660
|
+
else if (output.Ref.startsWith('$.')) {
|
|
661
|
+
const target = isPlainRecord(projected) ? projected : {};
|
|
662
|
+
SetNestedValue(target, output.Ref.substring(2), value);
|
|
663
|
+
projected = target;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
return projected;
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Computes a deterministic SHA-256 hash representing the prompt version and constraint instructions.
|
|
670
|
+
* A pipeline type other than `LLM` is part of the hash, so switching a pipeline's type never serves
|
|
671
|
+
* the old type's cached values. An LLM pipeline's hash is unchanged by the type's introduction.
|
|
672
|
+
* So are the `Escalation` settings: the floor decides which decision answers are confident enough to
|
|
673
|
+
* keep, so changing it (or the target) invalidates the answers cached under the old settings. A
|
|
674
|
+
* pipeline without `Escalation` keeps its hash.
|
|
675
|
+
*/
|
|
309
676
|
computePromptVersionHash(prompt, spec) {
|
|
310
677
|
const promptText = prompt.TemplateText ?? prompt.Description ?? prompt.Name ?? '';
|
|
311
678
|
const outputsStr = spec?.Outputs ? JSON.stringify(spec.Outputs) : '';
|
|
312
679
|
const constraintBlock = spec?.Outputs ? renderConstraintBlock(spec.Outputs) : '';
|
|
313
|
-
const hashBasis = `${prompt.ID}::${promptText}::${outputsStr}::${constraintBlock}`;
|
|
680
|
+
const hashBasis = `${prompt.ID}::${promptText}::${outputsStr}::${constraintBlock}${this.pipelineTypeHashSuffix(spec)}${this.escalationHashSuffix(spec)}`;
|
|
314
681
|
return createHash('sha256').update(hashBasis).digest('hex');
|
|
315
682
|
}
|
|
683
|
+
/** The pipeline type's part of the prompt version hash: empty when the type is absent or `LLM`. */
|
|
684
|
+
pipelineTypeHashSuffix(spec) {
|
|
685
|
+
const pipelineType = spec?.PipelineType?.trim();
|
|
686
|
+
if (!pipelineType || IsLLMPipelineType(pipelineType)) {
|
|
687
|
+
return '';
|
|
688
|
+
}
|
|
689
|
+
return `::PipelineType=${pipelineType.toLowerCase()}`;
|
|
690
|
+
}
|
|
691
|
+
/** The escalation settings' part of the prompt version hash: empty without `Escalation`. */
|
|
692
|
+
escalationHashSuffix(spec) {
|
|
693
|
+
const escalation = spec?.Escalation;
|
|
694
|
+
if (!escalation) {
|
|
695
|
+
return '';
|
|
696
|
+
}
|
|
697
|
+
const settings = { PipelineID: escalation.PipelineID?.trim().toLowerCase(), BelowConfidence: escalation.BelowConfidence };
|
|
698
|
+
return `::Escalation=${Canonicalize(settings)}`;
|
|
699
|
+
}
|
|
316
700
|
/** Computes a deterministic SHA-256 hash representing the output constraints. */
|
|
317
701
|
computeConstraintHash(spec) {
|
|
318
702
|
if (!spec?.Outputs || spec.Outputs.length === 0) {
|
|
@@ -327,21 +711,24 @@ export class InferProcessor {
|
|
|
327
711
|
}
|
|
328
712
|
/**
|
|
329
713
|
* Records historical audit rows in MJ: Feature Values for all outputs on a record.
|
|
714
|
+
* `outputConfidence` (from a driver that produces confidence) sets each output's confidence by
|
|
715
|
+
* output name, ahead of the single `confidence`. `omitValues` records every output's value as null,
|
|
716
|
+
* whatever the payload holds (a superseded decision's row). Records nothing when {@link WritesHistory} is off.
|
|
330
717
|
*/
|
|
331
718
|
async recordFeatureValuesHistory(params) {
|
|
332
|
-
if (!this.spec?.Outputs || this.spec.Outputs.length === 0 || !params.context.recordProcessID || !params.context.entityID) {
|
|
719
|
+
if (!this.WritesHistory || !this.spec?.Outputs || this.spec.Outputs.length === 0 || !params.context.recordProcessID || !params.context.entityID) {
|
|
333
720
|
return;
|
|
334
721
|
}
|
|
335
722
|
const outputsList = [];
|
|
336
723
|
const rawPayload = params.payload;
|
|
337
724
|
const sources = { $: rawPayload };
|
|
338
725
|
for (const output of this.spec.Outputs) {
|
|
339
|
-
const val = resolveMappingRef(output.Ref, sources);
|
|
726
|
+
const val = params.omitValues ? null : resolveMappingRef(output.Ref, sources);
|
|
340
727
|
outputsList.push({
|
|
341
728
|
featureName: output.Name,
|
|
342
729
|
value: val !== undefined ? val : null,
|
|
343
730
|
reasoning: params.reasoning,
|
|
344
|
-
confidence: params.confidence,
|
|
731
|
+
confidence: params.outputConfidence?.[output.Name] ?? params.confidence,
|
|
345
732
|
});
|
|
346
733
|
}
|
|
347
734
|
try {
|
|
@@ -380,6 +767,112 @@ export class InferProcessor {
|
|
|
380
767
|
});
|
|
381
768
|
}
|
|
382
769
|
// -------------------------------------------------------------------------------------------------
|
|
770
|
+
// Feature Pipeline driver (resolved from MJ: Feature Pipeline Types by DataFeatureSpec.PipelineType)
|
|
771
|
+
// -------------------------------------------------------------------------------------------------
|
|
772
|
+
/**
|
|
773
|
+
* Resolves the driver for this pipeline's type, once per processor instance.
|
|
774
|
+
*
|
|
775
|
+
* The type is `DataFeatureSpec.PipelineType`, or `LLM` when absent. It is matched by name
|
|
776
|
+
* (case-insensitive, trimmed) against the `MJ: Feature Pipeline Types` catalog cached by
|
|
777
|
+
* `KnowledgeHubMetadataEngine`, and its `DriverClass` is created through the ClassFactory. `LLM`
|
|
778
|
+
* resolves to {@link LLMFeaturePipelineDriver} when the catalog has no `LLM` row, or cannot be read,
|
|
779
|
+
* so a database without the seed row keeps working. The driver's `ValidateOutputs` then runs once.
|
|
780
|
+
*
|
|
781
|
+
* @throws Error when the type is not in the catalog (and is not `LLM`), is not Active, names a
|
|
782
|
+
* DriverClass that is not registered, or cannot produce every output (naming each one).
|
|
783
|
+
*/
|
|
784
|
+
async ResolveDriver(context) {
|
|
785
|
+
this.driverResolution ??= this.resolveDriverFromCatalog(context);
|
|
786
|
+
return this.driverResolution;
|
|
787
|
+
}
|
|
788
|
+
/** Runs {@link ResolveDriver}, turning a resolution error into a message the caller fails the record with. */
|
|
789
|
+
async resolveDriverOrError(context) {
|
|
790
|
+
try {
|
|
791
|
+
return { Driver: await this.ResolveDriver(context) };
|
|
792
|
+
}
|
|
793
|
+
catch (e) {
|
|
794
|
+
return { ErrorMessage: e instanceof Error ? e.message : String(e) };
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
/** Finds the pipeline's type in the catalog, creates its driver, and checks it can produce every output. */
|
|
798
|
+
async resolveDriverFromCatalog(context) {
|
|
799
|
+
const typeName = this.spec?.PipelineType ?? LLM_PIPELINE_TYPE;
|
|
800
|
+
const pipelineType = await this.findPipelineType(typeName, context);
|
|
801
|
+
const driver = pipelineType ? this.createDriver(pipelineType) : this.createDriverWithoutCatalogRow(typeName);
|
|
802
|
+
if (this.spec) {
|
|
803
|
+
this.assertDriverProducesOutputs(driver, typeName, this.spec, context);
|
|
804
|
+
}
|
|
805
|
+
return driver;
|
|
806
|
+
}
|
|
807
|
+
/**
|
|
808
|
+
* Looks the type up by name in the catalog. If the catalog cannot be read, `LLM` is treated as not
|
|
809
|
+
* found (and so still resolves); any other type fails, because only the catalog names its driver.
|
|
810
|
+
*/
|
|
811
|
+
async findPipelineType(typeName, context) {
|
|
812
|
+
try {
|
|
813
|
+
await KnowledgeHubMetadataEngine.Instance.Config(false, context.contextUser, context.provider);
|
|
814
|
+
const wanted = typeName.trim().toLowerCase();
|
|
815
|
+
return KnowledgeHubMetadataEngine.Instance.FeaturePipelineTypes.find((t) => t.Name?.trim().toLowerCase() === wanted);
|
|
816
|
+
}
|
|
817
|
+
catch (e) {
|
|
818
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
819
|
+
if (!IsLLMPipelineType(typeName)) {
|
|
820
|
+
throw new Error(`Feature Pipeline type '${typeName}' could not be resolved: MJ: Feature Pipeline Types could not be read: ${reason}`);
|
|
821
|
+
}
|
|
822
|
+
LogError(`InferProcessor: MJ: Feature Pipeline Types could not be read (${reason}); running as LLM`);
|
|
823
|
+
return undefined;
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
/** The driver for a type with no catalog row: `LLM` still runs; any other name is an error. */
|
|
827
|
+
createDriverWithoutCatalogRow(typeName) {
|
|
828
|
+
if (IsLLMPipelineType(typeName)) {
|
|
829
|
+
return new LLMFeaturePipelineDriver();
|
|
830
|
+
}
|
|
831
|
+
throw new Error(`Feature Pipeline type '${typeName}' was not found in MJ: Feature Pipeline Types.`);
|
|
832
|
+
}
|
|
833
|
+
/** Creates an Active type's driver from its registered `DriverClass`. */
|
|
834
|
+
createDriver(pipelineType) {
|
|
835
|
+
if (pipelineType.Status !== 'Active') {
|
|
836
|
+
throw new Error(`Feature Pipeline type '${pipelineType.Name}' is ${pipelineType.Status}; only an Active type can run.`);
|
|
837
|
+
}
|
|
838
|
+
const driverClass = pipelineType.DriverClass;
|
|
839
|
+
const driver = MJGlobal.Instance.ClassFactory.CreateInstance(BaseFeaturePipelineDriver, driverClass);
|
|
840
|
+
if (!driver || driver.constructor === BaseFeaturePipelineDriver) {
|
|
841
|
+
throw new Error(`Feature Pipeline type '${pipelineType.Name}' names DriverClass '${driverClass}', which is not registered ` +
|
|
842
|
+
`with @RegisterClass(BaseFeaturePipelineDriver, '${driverClass}').`);
|
|
843
|
+
}
|
|
844
|
+
return driver;
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* The value lists of the pipeline's own entity (`context.entityID`), for the output check and the
|
|
848
|
+
* driver. Consults only that entity's fields, so a same-named field elsewhere is never read; undefined
|
|
849
|
+
* when the run names no entity or the provider does not know it.
|
|
850
|
+
*/
|
|
851
|
+
buildFieldValuesLookup(context) {
|
|
852
|
+
if (!context.entityID) {
|
|
853
|
+
return undefined;
|
|
854
|
+
}
|
|
855
|
+
const provider = context.provider ?? Metadata.Provider; // global-provider-ok: last-resort fallback for a context built without its provider
|
|
856
|
+
return typeof provider?.EntityByID === 'function' ? BuildEntityFieldValueLookup(provider.EntityByID(context.entityID)) : undefined;
|
|
857
|
+
}
|
|
858
|
+
/** Fails when the driver cannot produce one or more of the spec's outputs, naming every one. */
|
|
859
|
+
assertDriverProducesOutputs(driver, typeName, spec, context) {
|
|
860
|
+
const fieldValues = this.buildFieldValuesLookup(context);
|
|
861
|
+
const messages = driver.ValidateOutputs(spec, fieldValues);
|
|
862
|
+
if (messages.length > 0) {
|
|
863
|
+
throw new Error(`Feature Pipeline type '${typeName}' cannot produce every output: ${messages.join(' ')}`);
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
/** The driver's callbacks into this processor's overridable steps, so extensions keep working. */
|
|
867
|
+
buildComputeHooks() {
|
|
868
|
+
return {
|
|
869
|
+
BuildPromptData: (record, ctx) => this.buildPromptData(record, ctx),
|
|
870
|
+
BeforeBuildContext: (record, ctx) => this.beforeBuildContext(record, ctx),
|
|
871
|
+
BeforePromptExecute: (params, record, ctx) => this.beforePromptExecute(params, record, ctx),
|
|
872
|
+
AfterPromptExecute: (result, record, ctx) => this.afterPromptExecute(result, record, ctx),
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
// -------------------------------------------------------------------------------------------------
|
|
383
876
|
// P1-6 Lifecycle Hooks (overridable by subclasses registered under DataFeatureSpec.ProcessorExtensionKey)
|
|
384
877
|
// -------------------------------------------------------------------------------------------------
|
|
385
878
|
/** Lifecycle hook called before prompt data context is constructed. */
|
|
@@ -392,7 +885,8 @@ export class InferProcessor {
|
|
|
392
885
|
}
|
|
393
886
|
/**
|
|
394
887
|
* Layer 2 output validation hook. Evaluates outputs against declared constraints, applies OnViolation
|
|
395
|
-
* policies (fail, null, coerce-to-other), and builds the processed payload.
|
|
888
|
+
* policies (fail, null, coerce-to-other), and builds the processed payload. `replacedOutputs` names
|
|
889
|
+
* the outputs whose value a `null` or `coerce-to-other` policy replaced.
|
|
396
890
|
*/
|
|
397
891
|
async validateOutputs(outputs, rawResult, record, ctx) {
|
|
398
892
|
if (!outputs || !Array.isArray(outputs) || outputs.length === 0) {
|
|
@@ -408,15 +902,15 @@ export class InferProcessor {
|
|
|
408
902
|
}
|
|
409
903
|
const sources = { $: rawResult };
|
|
410
904
|
const rawVal = resolveMappingRef(output.Ref, sources);
|
|
411
|
-
let targetTSType;
|
|
412
905
|
const target = output.Target;
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
906
|
+
const field = target.Mode === 'field'
|
|
907
|
+
? ctx.provider?.EntityByID(record.EntityID)?.Fields?.find((f) => f.Name.toLowerCase() === target.EntityFieldName.toLowerCase())
|
|
908
|
+
: undefined;
|
|
909
|
+
// The resolved constraint carries the field's value list for an enum with FromFieldMetadata;
|
|
910
|
+
// without it the check sees only the spec's own Values
|
|
418
911
|
const validation = validateOutputValue(rawVal, output.Constraint, {
|
|
419
|
-
targetFieldTSType:
|
|
912
|
+
targetFieldTSType: field?.TSType,
|
|
913
|
+
resolved: ResolveConstraint(output, field),
|
|
420
914
|
});
|
|
421
915
|
if (!validation.valid) {
|
|
422
916
|
return {
|
|
@@ -444,7 +938,20 @@ export class InferProcessor {
|
|
|
444
938
|
if (typeof payloadCopy === 'object' && payloadCopy !== null && violations.length > 0) {
|
|
445
939
|
payloadCopy._violations = violations;
|
|
446
940
|
}
|
|
447
|
-
return { valid: true, payload: payloadCopy };
|
|
941
|
+
return { valid: true, payload: payloadCopy, replacedOutputs: violations.map((v) => v.outputName) };
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* The driver's per-output confidences, less those of outputs whose value the constraint check replaced:
|
|
945
|
+
* a confidence belongs to the value the model gave, not to a null or 'Other' written in its place.
|
|
946
|
+
* Undefined when none remain.
|
|
947
|
+
*/
|
|
948
|
+
confidenceOfKeptValues(confidence, replacedOutputs) {
|
|
949
|
+
if (!confidence) {
|
|
950
|
+
return undefined;
|
|
951
|
+
}
|
|
952
|
+
const replaced = new Set(replacedOutputs ?? []);
|
|
953
|
+
const kept = Object.entries(confidence).filter(([outputName]) => !replaced.has(outputName));
|
|
954
|
+
return kept.length > 0 ? Object.fromEntries(kept) : undefined;
|
|
448
955
|
}
|
|
449
956
|
/** Lifecycle hook to resolve a dedup cache key for this record. Default returns null (computed by cache service). */
|
|
450
957
|
async resolveCacheKey(record, spec, ctx) {
|