@memberjunction/ai-prompts 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.
Files changed (82) hide show
  1. package/README.md +41 -0
  2. package/dist/AIModelRunner.d.ts +9 -88
  3. package/dist/AIModelRunner.d.ts.map +1 -1
  4. package/dist/AIModelRunner.js +11 -283
  5. package/dist/AIModelRunner.js.map +1 -1
  6. package/dist/BaseModelRunner.d.ts +36 -1
  7. package/dist/BaseModelRunner.d.ts.map +1 -1
  8. package/dist/BaseModelRunner.js +82 -3
  9. package/dist/BaseModelRunner.js.map +1 -1
  10. package/dist/audio/AISpeechToTextRunner.d.ts +46 -0
  11. package/dist/audio/AISpeechToTextRunner.d.ts.map +1 -0
  12. package/dist/audio/AISpeechToTextRunner.js +93 -0
  13. package/dist/audio/AISpeechToTextRunner.js.map +1 -0
  14. package/dist/audio/AITextToSpeechRunner.d.ts +43 -0
  15. package/dist/audio/AITextToSpeechRunner.d.ts.map +1 -0
  16. package/dist/audio/AITextToSpeechRunner.js +80 -0
  17. package/dist/audio/AITextToSpeechRunner.js.map +1 -0
  18. package/dist/audio/audio-description.d.ts +22 -0
  19. package/dist/audio/audio-description.d.ts.map +1 -0
  20. package/dist/audio/audio-description.js +52 -0
  21. package/dist/audio/audio-description.js.map +1 -0
  22. package/dist/audio/audio-runner.types.d.ts +46 -0
  23. package/dist/audio/audio-runner.types.d.ts.map +1 -0
  24. package/dist/audio/audio-runner.types.js +7 -0
  25. package/dist/audio/audio-runner.types.js.map +1 -0
  26. package/dist/decision/AIDecisionRunner.d.ts +134 -0
  27. package/dist/decision/AIDecisionRunner.d.ts.map +1 -0
  28. package/dist/decision/AIDecisionRunner.js +498 -0
  29. package/dist/decision/AIDecisionRunner.js.map +1 -0
  30. package/dist/decision/LLMDecision.d.ts +158 -0
  31. package/dist/decision/LLMDecision.d.ts.map +1 -0
  32. package/dist/decision/LLMDecision.js +493 -0
  33. package/dist/decision/LLMDecision.js.map +1 -0
  34. package/dist/decision/decision-questions.d.ts +28 -0
  35. package/dist/decision/decision-questions.d.ts.map +1 -0
  36. package/dist/decision/decision-questions.js +123 -0
  37. package/dist/decision/decision-questions.js.map +1 -0
  38. package/dist/decision/decision-runner.types.d.ts +29 -0
  39. package/dist/decision/decision-runner.types.d.ts.map +1 -0
  40. package/dist/decision/decision-runner.types.js +14 -0
  41. package/dist/decision/decision-runner.types.js.map +1 -0
  42. package/dist/embedding/AIEmbeddingRunner.d.ts +115 -0
  43. package/dist/embedding/AIEmbeddingRunner.d.ts.map +1 -0
  44. package/dist/embedding/AIEmbeddingRunner.js +462 -0
  45. package/dist/embedding/AIEmbeddingRunner.js.map +1 -0
  46. package/dist/embedding/embedding-runner.types.d.ts +72 -0
  47. package/dist/embedding/embedding-runner.types.d.ts.map +1 -0
  48. package/dist/embedding/embedding-runner.types.js +2 -0
  49. package/dist/embedding/embedding-runner.types.js.map +1 -0
  50. package/dist/image/AIImageGenerationRunner.d.ts +101 -0
  51. package/dist/image/AIImageGenerationRunner.d.ts.map +1 -0
  52. package/dist/image/AIImageGenerationRunner.js +355 -0
  53. package/dist/image/AIImageGenerationRunner.js.map +1 -0
  54. package/dist/image/image-runner.types.d.ts +90 -0
  55. package/dist/image/image-runner.types.d.ts.map +1 -0
  56. package/dist/image/image-runner.types.js +7 -0
  57. package/dist/image/image-runner.types.js.map +1 -0
  58. package/dist/index.d.ts +16 -1
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +15 -0
  61. package/dist/index.js.map +1 -1
  62. package/dist/media/BaseMediaRunner.d.ts +143 -0
  63. package/dist/media/BaseMediaRunner.d.ts.map +1 -0
  64. package/dist/media/BaseMediaRunner.js +448 -0
  65. package/dist/media/BaseMediaRunner.js.map +1 -0
  66. package/dist/media/media-runner.types.d.ts +128 -0
  67. package/dist/media/media-runner.types.d.ts.map +1 -0
  68. package/dist/media/media-runner.types.js +8 -0
  69. package/dist/media/media-runner.types.js.map +1 -0
  70. package/dist/media/media-usage.d.ts +13 -0
  71. package/dist/media/media-usage.d.ts.map +1 -0
  72. package/dist/media/media-usage.js +18 -0
  73. package/dist/media/media-usage.js.map +1 -0
  74. package/dist/video/AIVideoRunner.d.ts +46 -0
  75. package/dist/video/AIVideoRunner.d.ts.map +1 -0
  76. package/dist/video/AIVideoRunner.js +88 -0
  77. package/dist/video/AIVideoRunner.js.map +1 -0
  78. package/dist/video/video-runner.types.d.ts +29 -0
  79. package/dist/video/video-runner.types.d.ts.map +1 -0
  80. package/dist/video/video-runner.types.js +7 -0
  81. package/dist/video/video-runner.types.js.map +1 -0
  82. package/package.json +12 -12
@@ -0,0 +1,158 @@
1
+ /**
2
+ * @fileoverview LLM-based Decision Driver for MemberJunction.
3
+ *
4
+ * Executes multi-question decisions by formatting state, questions, and expected output format
5
+ * into template variables, running an AI prompt via AIPromptRunner, and normalizing/mapping
6
+ * the model output into strongly typed DecisionAnswers.
7
+ *
8
+ * @module @memberjunction/ai-prompts
9
+ */
10
+ import { UserInfo } from '@memberjunction/core';
11
+ import { BaseDecision, DecisionParams, DecisionResult } from '@memberjunction/ai';
12
+ /**
13
+ * Driver that answers typed decision questions with a chat LLM through an MJ prompt. It is the
14
+ * fallback `BaseDecision` driver: everything downstream can be written against `BaseDecision`
15
+ * before a native decision model is configured. Unlike a native driver it must parse, because a
16
+ * chat model can return malformed JSON.
17
+ *
18
+ * The prompt receives three template variables:
19
+ * - `state`: the decision state, as-is when it is a string, otherwise as indented JSON;
20
+ * - `questions`: JSON mapping each question key to `{ kind, instructions, options?, levels? }`;
21
+ * - `outputFormat`: the reply's shape as JSON, with every option or level listed and an unquoted
22
+ * placeholder where each number goes.
23
+ *
24
+ * It must reply with one JSON object with the same keys: a number for a Likelihood, and an object
25
+ * mapping every option value (Choice) or level name (Score) to a number. Choice and Score
26
+ * distributions are normalised here, so `BaseDecision.Decide` can validate them strictly. A value
27
+ * that is present but is not a usable number fails the question; it is never read as 0.
28
+ *
29
+ * Registered with ClassFactory under BaseDecision with key 'LLMDecision'.
30
+ */
31
+ export declare class LLMDecision extends BaseDecision {
32
+ private _promptID;
33
+ private _contextUser;
34
+ private _promptRunner;
35
+ private _cachedPrompt;
36
+ /**
37
+ * The `MJ: AI Prompt Runs` row this decision is recorded under. When set, the chat prompt's run
38
+ * is created as its child (`ParentID`), so the chat call's cost rolls up to the decision's run.
39
+ * `AIDecisionRunner` sets it to its own run before it calls the driver.
40
+ */
41
+ ParentPromptRunID?: string;
42
+ /**
43
+ * Creates an instance of LLMDecision.
44
+ *
45
+ * @param apiKey - Optional API key for BaseDecision/BaseModel compatibility.
46
+ * @param promptID - ID of the MJAIPrompt entity to execute.
47
+ * @param contextUser - User context for prompt execution.
48
+ */
49
+ constructor(apiKey: string, promptID: string, contextUser: UserInfo);
50
+ /**
51
+ * Gets the configured prompt ID.
52
+ */
53
+ get PromptID(): string;
54
+ /**
55
+ * Executes the decision by calling the AI prompt and mapping answers.
56
+ *
57
+ * @param params - Parameters for the decision including State and Questions.
58
+ * @returns DecisionResult containing answers or error details.
59
+ */
60
+ protected DoDecide(params: DecisionParams): Promise<DecisionResult>;
61
+ /**
62
+ * Builds a failed result. `BaseDecision.Decide` sets the timings. Usage and the model are
63
+ * recorded whenever the prompt ran, because a failed mapping still cost a model call.
64
+ */
65
+ private failure;
66
+ /**
67
+ * Loads the prompt entity from AIEngine with caching.
68
+ */
69
+ private loadPrompt;
70
+ /**
71
+ * Builds the AIPromptParams instance with template data and cancellation token.
72
+ */
73
+ private buildPromptParams;
74
+ /**
75
+ * Formats state parameter: as-is if string, JSON stringified if object.
76
+ */
77
+ private formatState;
78
+ /**
79
+ * Formats question specifications into JSON string.
80
+ */
81
+ private formatQuestionsSpec;
82
+ /**
83
+ * Formats the reply's shape: JSON laid out as `JSON.stringify(value, null, 1)` would, except that
84
+ * each placeholder is unquoted. A quoted placeholder shows the value as a string, and a chat model
85
+ * copied it, writing `"0.1"` for `0.1`. Keys are still JSON-encoded, so any option value or level
86
+ * name is shown exactly.
87
+ */
88
+ private formatOutputTemplate;
89
+ /**
90
+ * Parses the model reply from the prompt result into an object record.
91
+ */
92
+ private parseReply;
93
+ /**
94
+ * Maps an individual question from the parsed reply to a DecisionAnswer.
95
+ */
96
+ private mapQuestion;
97
+ /**
98
+ * Maps a Likelihood question answer: a finite number within `LIKELIHOOD_CLAMP_TOLERANCE` of
99
+ * [0, 1] is clamped into it; anything else fails.
100
+ */
101
+ private mapLikelihood;
102
+ /**
103
+ * Maps a Choice question answer: normalizes distribution, selects argmax, tie goes to first option.
104
+ */
105
+ private mapChoice;
106
+ /**
107
+ * Maps a Score question answer: normalizes distribution, computes expected level position, max prob confidence.
108
+ */
109
+ private mapScore;
110
+ /**
111
+ * Normalizes a probability distribution for Choice or Score questions.
112
+ * Validates object shape, ignores unexpected keys with LogStatus, counts a missing entry as 0,
113
+ * fails on an entry that is present but not a finite non-negative number, fails if sum <= 0,
114
+ * and divides each by the sum.
115
+ */
116
+ private normalizeDistribution;
117
+ /**
118
+ * Reads a probability as a number. A chat model sometimes copies the quoted placeholder in
119
+ * `outputFormat` and writes `"0.1"` for `0.1`, so a string holding a finite number counts too.
120
+ */
121
+ private toFiniteNumber;
122
+ /**
123
+ * Whether the reply holds a value under `key`. Only an own key counts, so a question or option
124
+ * named after an `Object.prototype` member (`toString`) is not answered by the prototype.
125
+ */
126
+ private isPresent;
127
+ /**
128
+ * Renders a reply value for an error message, quoting a string so `"80%"` reads as the text it was.
129
+ */
130
+ private describeValue;
131
+ /**
132
+ * Populates Usage and ResolvedModel telemetry on DecisionResult from prompt result.
133
+ */
134
+ private recordTelemetry;
135
+ /**
136
+ * The chat call's cost. Once the chat run is saved, its saved cost wins: `TotalCost`, else
137
+ * `Cost`, which the server computes when the run is saved and which is what rolls up to the
138
+ * decision's run. It differs from the runner's reported cost only when the runner reports 0,
139
+ * which the server treats as unpriced and reprices, so reporting the saved cost keeps the
140
+ * decision run's descendant cost equal to the rollup. Before the run is saved, the runner's
141
+ * reported cost wins, then the run's cost as it stands. Unset when none is known.
142
+ */
143
+ private resolveCost;
144
+ /**
145
+ * A saved run's cost: `TotalCost`, else `Cost`. The server writes `TotalCost = 0` for a run it
146
+ * could not price, so `TotalCost` counts only when the run has a `Cost` or a `DescendantCost`.
147
+ */
148
+ private savedRunCost;
149
+ }
150
+ /**
151
+ * Factory function to create an LLMDecision instance.
152
+ *
153
+ * @param promptID - ID of the prompt to execute.
154
+ * @param contextUser - User context for prompt execution.
155
+ * @returns Configured LLMDecision instance.
156
+ */
157
+ export declare function CreateLLMDecision(promptID: string, contextUser: UserInfo): LLMDecision;
158
+ //# sourceMappingURL=LLMDecision.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LLMDecision.d.ts","sourceRoot":"","sources":["../../src/decision/LLMDecision.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,EAAE,QAAQ,EAAuB,MAAM,sBAAsB,CAAC;AAErE,OAAO,EACH,YAAY,EACZ,cAAc,EACd,cAAc,EASjB,MAAM,oBAAoB,CAAC;AAwB5B;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBACa,WAAY,SAAQ,YAAY;IACzC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,YAAY,CAAW;IAC/B,OAAO,CAAC,aAAa,CAAiB;IACtC,OAAO,CAAC,aAAa,CAAyC;IAE9D;;;;OAIG;IACI,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAElC;;;;;;OAMG;gBACS,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ;IAOnE;;OAEG;IACH,IAAW,QAAQ,IAAI,MAAM,CAE5B;IAED;;;;;OAKG;cACa,QAAQ,CAAC,MAAM,EAAE,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC;IAqCzE;;;OAGG;IACH,OAAO,CAAC,OAAO;IASf;;OAEG;IACH,OAAO,CAAC,UAAU;IAelB;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAsBzB;;OAEG;IACH,OAAO,CAAC,WAAW;IAOnB;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAmC3B;;;;;OAKG;IACH,OAAO,CAAC,oBAAoB;IAa5B;;OAEG;IACH,OAAO,CAAC,UAAU;IA2BlB;;OAEG;IACH,OAAO,CAAC,WAAW;IAwBnB;;;OAGG;IACH,OAAO,CAAC,aAAa;IA4BrB;;OAEG;IACH,OAAO,CAAC,SAAS;IAkCjB;;OAEG;IACH,OAAO,CAAC,QAAQ;IAkChB;;;;;OAKG;IACH,OAAO,CAAC,qBAAqB;IA2D7B;;;OAGG;IACH,OAAO,CAAC,cAAc;IAWtB;;;OAGG;IACH,OAAO,CAAC,SAAS;IAIjB;;OAEG;IACH,OAAO,CAAC,aAAa;IAIrB;;OAEG;IACH,OAAO,CAAC,eAAe;IAavB;;;;;;;OAOG;IACH,OAAO,CAAC,WAAW;IAenB;;;OAGG;IACH,OAAO,CAAC,YAAY;CAMvB;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,GAAG,WAAW,CAEtF"}
@@ -0,0 +1,493 @@
1
+ /**
2
+ * @fileoverview LLM-based Decision Driver for MemberJunction.
3
+ *
4
+ * Executes multi-question decisions by formatting state, questions, and expected output format
5
+ * into template variables, running an AI prompt via AIPromptRunner, and normalizing/mapping
6
+ * the model output into strongly typed DecisionAnswers.
7
+ *
8
+ * @module @memberjunction/ai-prompts
9
+ */
10
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
11
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
12
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
13
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
15
+ };
16
+ var __metadata = (this && this.__metadata) || function (k, v) {
17
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
18
+ };
19
+ import { RegisterClass, UUIDsEqual } from '@memberjunction/global';
20
+ import { UserInfo, LogError, LogStatus } from '@memberjunction/core';
21
+ import { AIEngine } from '@memberjunction/aiengine';
22
+ import { BaseDecision, DecisionResult, ModelUsage, } from '@memberjunction/ai';
23
+ import { AIPromptParams, } from '@memberjunction/ai-core-plus';
24
+ import { AIPromptRunner } from '../AIPromptRunner.js';
25
+ /** Longest slice of an unparseable reply quoted in an error message. */
26
+ const MAX_REPLY_IN_ERROR = 500;
27
+ /**
28
+ * How far outside [0, 1] a Likelihood may fall and still be clamped into it: the tolerance
29
+ * `BaseDecision` allows a distribution's sum. A value further out is not a probability (85 is the
30
+ * percent-scale reading of 0.85), so the question fails instead of becoming a certainty.
31
+ */
32
+ const LIKELIHOOD_CLAMP_TOLERANCE = 0.01;
33
+ /** Where `outputFormat` shows the model a Likelihood's number. Written unquoted, like a number. */
34
+ const LIKELIHOOD_PLACEHOLDER = '<probability 0-1>';
35
+ /** Where `outputFormat` shows the model an option's or level's number. Written unquoted, like a number. */
36
+ const DISTRIBUTION_PLACEHOLDER = '<probability>';
37
+ /**
38
+ * Driver that answers typed decision questions with a chat LLM through an MJ prompt. It is the
39
+ * fallback `BaseDecision` driver: everything downstream can be written against `BaseDecision`
40
+ * before a native decision model is configured. Unlike a native driver it must parse, because a
41
+ * chat model can return malformed JSON.
42
+ *
43
+ * The prompt receives three template variables:
44
+ * - `state`: the decision state, as-is when it is a string, otherwise as indented JSON;
45
+ * - `questions`: JSON mapping each question key to `{ kind, instructions, options?, levels? }`;
46
+ * - `outputFormat`: the reply's shape as JSON, with every option or level listed and an unquoted
47
+ * placeholder where each number goes.
48
+ *
49
+ * It must reply with one JSON object with the same keys: a number for a Likelihood, and an object
50
+ * mapping every option value (Choice) or level name (Score) to a number. Choice and Score
51
+ * distributions are normalised here, so `BaseDecision.Decide` can validate them strictly. A value
52
+ * that is present but is not a usable number fails the question; it is never read as 0.
53
+ *
54
+ * Registered with ClassFactory under BaseDecision with key 'LLMDecision'.
55
+ */
56
+ let LLMDecision = class LLMDecision extends BaseDecision {
57
+ /**
58
+ * Creates an instance of LLMDecision.
59
+ *
60
+ * @param apiKey - Optional API key for BaseDecision/BaseModel compatibility.
61
+ * @param promptID - ID of the MJAIPrompt entity to execute.
62
+ * @param contextUser - User context for prompt execution.
63
+ */
64
+ constructor(apiKey, promptID, contextUser) {
65
+ super(apiKey);
66
+ this._cachedPrompt = null;
67
+ this._promptID = promptID;
68
+ this._contextUser = contextUser;
69
+ this._promptRunner = new AIPromptRunner();
70
+ }
71
+ /**
72
+ * Gets the configured prompt ID.
73
+ */
74
+ get PromptID() {
75
+ return this._promptID;
76
+ }
77
+ /**
78
+ * Executes the decision by calling the AI prompt and mapping answers.
79
+ *
80
+ * @param params - Parameters for the decision including State and Questions.
81
+ * @returns DecisionResult containing answers or error details.
82
+ */
83
+ async DoDecide(params) {
84
+ const prompt = this.loadPrompt();
85
+ if (!prompt) {
86
+ LogError(`LLMDecision: Prompt not found with ID: ${this._promptID}`);
87
+ return this.failure(`Prompt not found with ID: ${this._promptID}`);
88
+ }
89
+ const promptParams = this.buildPromptParams(prompt, params);
90
+ const promptResult = await this._promptRunner.ExecutePrompt(promptParams);
91
+ // The chat run's cost is computed when its row is saved, and the runner saves it
92
+ // fire-and-forget. Wait for the save, so recordTelemetry can read the cost, and so the
93
+ // save's cost rollup to the parent run lands before the parent run is finalized.
94
+ await this._promptRunner.WaitForPendingPromptRunSaves();
95
+ if (!promptResult || !promptResult.success) {
96
+ return this.failure(promptResult?.errorMessage || 'Prompt execution failed', promptResult);
97
+ }
98
+ const parsedReply = this.parseReply(promptResult);
99
+ if ('error' in parsedReply) {
100
+ return this.failure(parsedReply.error, promptResult);
101
+ }
102
+ const answers = {};
103
+ for (const [key, question] of Object.entries(params.Questions)) {
104
+ const mapped = this.mapQuestion(key, question, parsedReply.data);
105
+ if ('error' in mapped) {
106
+ return this.failure(mapped.error, promptResult);
107
+ }
108
+ answers[key] = mapped.answer;
109
+ }
110
+ const result = new DecisionResult(true, new Date(), new Date());
111
+ result.Answers = answers;
112
+ this.recordTelemetry(result, promptResult);
113
+ return result;
114
+ }
115
+ /**
116
+ * Builds a failed result. `BaseDecision.Decide` sets the timings. Usage and the model are
117
+ * recorded whenever the prompt ran, because a failed mapping still cost a model call.
118
+ */
119
+ failure(message, promptResult) {
120
+ const failure = new DecisionResult(false, new Date(), new Date());
121
+ failure.errorMessage = message;
122
+ if (promptResult) {
123
+ this.recordTelemetry(failure, promptResult);
124
+ }
125
+ return failure;
126
+ }
127
+ /**
128
+ * Loads the prompt entity from AIEngine with caching.
129
+ */
130
+ loadPrompt() {
131
+ if (this._cachedPrompt) {
132
+ return this._cachedPrompt;
133
+ }
134
+ const prompts = AIEngine.Instance.Prompts;
135
+ const prompt = prompts?.find(p => UUIDsEqual(p.ID, this._promptID));
136
+ if (!prompt) {
137
+ return null;
138
+ }
139
+ this._cachedPrompt = prompt;
140
+ return prompt;
141
+ }
142
+ /**
143
+ * Builds the AIPromptParams instance with template data and cancellation token.
144
+ */
145
+ buildPromptParams(prompt, params) {
146
+ const promptParams = new AIPromptParams();
147
+ promptParams.prompt = prompt;
148
+ promptParams.contextUser = this._contextUser;
149
+ promptParams.attemptJSONRepair = true;
150
+ // The reply's keys are question keys, option values and level names, and level names are
151
+ // often sentences such as "blocked: no workaround". The runner's output validation reads
152
+ // ':', '?' and '*' in keys as OutputExample syntax and strips them, which would rename those
153
+ // keys. This driver maps the reply itself and BaseDecision validates the answers, so skip it.
154
+ promptParams.skipValidation = true;
155
+ promptParams.cancellationToken = params.CancellationToken;
156
+ if (this.ParentPromptRunID) {
157
+ promptParams.parentPromptRunId = this.ParentPromptRunID;
158
+ }
159
+ promptParams.data = {
160
+ state: this.formatState(params.State),
161
+ questions: this.formatQuestionsSpec(params.Questions),
162
+ outputFormat: this.formatOutputTemplate(params.Questions),
163
+ };
164
+ return promptParams;
165
+ }
166
+ /**
167
+ * Formats state parameter: as-is if string, JSON stringified if object.
168
+ */
169
+ formatState(state) {
170
+ if (typeof state === 'string') {
171
+ return state;
172
+ }
173
+ return JSON.stringify(state, null, 1);
174
+ }
175
+ /**
176
+ * Formats question specifications into JSON string.
177
+ */
178
+ formatQuestionsSpec(questions) {
179
+ const spec = {};
180
+ for (const [key, q] of Object.entries(questions)) {
181
+ if (q.Kind === 'Likelihood') {
182
+ spec[key] = {
183
+ kind: 'Likelihood',
184
+ instructions: q.Instructions,
185
+ };
186
+ }
187
+ else if (q.Kind === 'Choice') {
188
+ spec[key] = {
189
+ kind: 'Choice',
190
+ instructions: q.Instructions,
191
+ options: q.Options.map(opt => ({
192
+ value: opt.Value,
193
+ description: opt.Description,
194
+ })),
195
+ };
196
+ }
197
+ else if (q.Kind === 'Score') {
198
+ spec[key] = {
199
+ kind: 'Score',
200
+ instructions: q.Instructions,
201
+ levels: [...q.Levels],
202
+ };
203
+ }
204
+ }
205
+ return JSON.stringify(spec, null, 1);
206
+ }
207
+ /**
208
+ * Formats the reply's shape: JSON laid out as `JSON.stringify(value, null, 1)` would, except that
209
+ * each placeholder is unquoted. A quoted placeholder shows the value as a string, and a chat model
210
+ * copied it, writing `"0.1"` for `0.1`. Keys are still JSON-encoded, so any option value or level
211
+ * name is shown exactly.
212
+ */
213
+ formatOutputTemplate(questions) {
214
+ const entries = Object.entries(questions).map(([key, q]) => {
215
+ if (q.Kind === 'Likelihood') {
216
+ return ` ${JSON.stringify(key)}: ${LIKELIHOOD_PLACEHOLDER}`;
217
+ }
218
+ const names = q.Kind === 'Choice' ? q.Options.map(opt => opt.Value) : q.Levels;
219
+ const lines = names.map(name => ` ${JSON.stringify(name)}: ${DISTRIBUTION_PLACEHOLDER}`);
220
+ return ` ${JSON.stringify(key)}: {\n${lines.join(',\n')}\n }`;
221
+ });
222
+ return `{\n${entries.join(',\n')}\n}`;
223
+ }
224
+ /**
225
+ * Parses the model reply from the prompt result into an object record.
226
+ */
227
+ parseReply(promptResult) {
228
+ let raw = promptResult.result ?? promptResult.rawResult;
229
+ if (typeof raw === 'string') {
230
+ const text = raw;
231
+ try {
232
+ raw = JSON.parse(text);
233
+ }
234
+ catch {
235
+ return {
236
+ success: false,
237
+ error: `Failed to parse model reply as JSON: ${text.slice(0, MAX_REPLY_IN_ERROR)}`,
238
+ };
239
+ }
240
+ }
241
+ if (typeof raw === 'object' && raw !== null && !Array.isArray(raw)) {
242
+ return { success: true, data: raw };
243
+ }
244
+ return {
245
+ success: false,
246
+ error: `Model reply is not a JSON object: ${typeof raw === 'object' && raw !== null ? 'Array' : String(raw)}`,
247
+ };
248
+ }
249
+ /**
250
+ * Maps an individual question from the parsed reply to a DecisionAnswer.
251
+ */
252
+ mapQuestion(key, question, reply) {
253
+ if (!this.isPresent(reply, key)) {
254
+ return { success: false, error: `Question '${key}': Missing answer in model reply` };
255
+ }
256
+ const rawVal = reply[key];
257
+ switch (question.Kind) {
258
+ case 'Likelihood':
259
+ return this.mapLikelihood(key, rawVal);
260
+ case 'Choice':
261
+ return this.mapChoice(key, question, rawVal);
262
+ case 'Score':
263
+ return this.mapScore(key, question, rawVal);
264
+ default: {
265
+ const exhaustiveCheck = question;
266
+ return { success: false, error: `Question '${key}': Unknown Kind '${exhaustiveCheck.Kind}'` };
267
+ }
268
+ }
269
+ }
270
+ /**
271
+ * Maps a Likelihood question answer: a finite number within `LIKELIHOOD_CLAMP_TOLERANCE` of
272
+ * [0, 1] is clamped into it; anything else fails.
273
+ */
274
+ mapLikelihood(key, rawVal) {
275
+ const value = this.toFiniteNumber(rawVal);
276
+ if (value === undefined) {
277
+ return {
278
+ success: false,
279
+ error: `Question '${key}': Likelihood value must be a finite number, got ${this.describeValue(rawVal)}`,
280
+ };
281
+ }
282
+ if (value < -LIKELIHOOD_CLAMP_TOLERANCE || value > 1 + LIKELIHOOD_CLAMP_TOLERANCE) {
283
+ return {
284
+ success: false,
285
+ error: `Question '${key}': Likelihood value must be a probability in [0, 1], got ${this.describeValue(rawVal)}`,
286
+ };
287
+ }
288
+ const probability = Math.max(0, Math.min(1, value));
289
+ return {
290
+ success: true,
291
+ answer: {
292
+ Kind: 'Likelihood',
293
+ Probability: probability,
294
+ },
295
+ };
296
+ }
297
+ /**
298
+ * Maps a Choice question answer: normalizes distribution, selects argmax, tie goes to first option.
299
+ */
300
+ mapChoice(key, question, rawVal) {
301
+ const optionValues = question.Options.map(o => o.Value);
302
+ const normResult = this.normalizeDistribution(key, 'Choice', optionValues, rawVal);
303
+ if ('error' in normResult) {
304
+ return { success: false, error: normResult.error };
305
+ }
306
+ const probabilities = normResult.probabilities;
307
+ let bestOptionValue = question.Options[0].Value;
308
+ let maxProb = -1;
309
+ for (const opt of question.Options) {
310
+ const prob = probabilities[opt.Value];
311
+ if (prob > maxProb) {
312
+ maxProb = prob;
313
+ bestOptionValue = opt.Value;
314
+ }
315
+ }
316
+ return {
317
+ success: true,
318
+ answer: {
319
+ Kind: 'Choice',
320
+ Value: bestOptionValue,
321
+ Confidence: maxProb,
322
+ Probabilities: probabilities,
323
+ },
324
+ };
325
+ }
326
+ /**
327
+ * Maps a Score question answer: normalizes distribution, computes expected level position, max prob confidence.
328
+ */
329
+ mapScore(key, question, rawVal) {
330
+ const normResult = this.normalizeDistribution(key, 'Score', question.Levels, rawVal);
331
+ if ('error' in normResult) {
332
+ return { success: false, error: normResult.error };
333
+ }
334
+ const probabilities = normResult.probabilities;
335
+ let expectedPosition = 0;
336
+ let maxProb = -1;
337
+ for (let i = 0; i < question.Levels.length; i++) {
338
+ const levelName = question.Levels[i];
339
+ const prob = probabilities[levelName];
340
+ expectedPosition += i * prob;
341
+ if (prob > maxProb) {
342
+ maxProb = prob;
343
+ }
344
+ }
345
+ return {
346
+ success: true,
347
+ answer: {
348
+ Kind: 'Score',
349
+ Value: expectedPosition,
350
+ Confidence: maxProb,
351
+ Probabilities: probabilities,
352
+ },
353
+ };
354
+ }
355
+ /**
356
+ * Normalizes a probability distribution for Choice or Score questions.
357
+ * Validates object shape, ignores unexpected keys with LogStatus, counts a missing entry as 0,
358
+ * fails on an entry that is present but not a finite non-negative number, fails if sum <= 0,
359
+ * and divides each by the sum.
360
+ */
361
+ normalizeDistribution(questionKey, kind, expectedKeys, rawVal) {
362
+ if (typeof rawVal !== 'object' || rawVal === null || Array.isArray(rawVal)) {
363
+ return {
364
+ success: false,
365
+ error: `Question '${questionKey}': ${kind} answer must be an object`,
366
+ };
367
+ }
368
+ const rawRecord = rawVal;
369
+ const expectedSet = new Set(expectedKeys);
370
+ for (const actualKey of Object.keys(rawRecord)) {
371
+ if (!expectedSet.has(actualKey)) {
372
+ LogStatus(`LLMDecision: Question '${questionKey}': ignoring unexpected key '${actualKey}' in ${kind} answer`);
373
+ }
374
+ }
375
+ const entityName = kind === 'Choice' ? 'option' : 'level';
376
+ const rawProbs = {};
377
+ let sum = 0;
378
+ for (const expectedKey of expectedKeys) {
379
+ if (!this.isPresent(rawRecord, expectedKey)) {
380
+ rawProbs[expectedKey] = 0;
381
+ continue;
382
+ }
383
+ // Reading a malformed entry such as "80%" as 0 would demote what may be the model's
384
+ // favourite and hand another answer its share, with nothing to show for it.
385
+ const itemVal = rawRecord[expectedKey];
386
+ const parsed = this.toFiniteNumber(itemVal);
387
+ if (parsed === undefined || parsed < 0) {
388
+ return {
389
+ success: false,
390
+ error: `Question '${questionKey}': ${kind} probability for ${entityName} '${expectedKey}' must be a finite non-negative number, got ${this.describeValue(itemVal)}`,
391
+ };
392
+ }
393
+ rawProbs[expectedKey] = parsed;
394
+ sum += parsed;
395
+ }
396
+ if (sum <= 0) {
397
+ return {
398
+ success: false,
399
+ error: `Question '${questionKey}': ${kind} probabilities sum to ${sum}, must be greater than 0`,
400
+ };
401
+ }
402
+ const normalized = {};
403
+ for (const expectedKey of expectedKeys) {
404
+ normalized[expectedKey] = rawProbs[expectedKey] / sum;
405
+ }
406
+ return { success: true, probabilities: normalized };
407
+ }
408
+ /**
409
+ * Reads a probability as a number. A chat model sometimes copies the quoted placeholder in
410
+ * `outputFormat` and writes `"0.1"` for `0.1`, so a string holding a finite number counts too.
411
+ */
412
+ toFiniteNumber(value) {
413
+ if (typeof value === 'number') {
414
+ return Number.isFinite(value) ? value : undefined;
415
+ }
416
+ if (typeof value === 'string' && value.trim() !== '') {
417
+ const parsed = Number(value.trim());
418
+ return Number.isFinite(parsed) ? parsed : undefined;
419
+ }
420
+ return undefined;
421
+ }
422
+ /**
423
+ * Whether the reply holds a value under `key`. Only an own key counts, so a question or option
424
+ * named after an `Object.prototype` member (`toString`) is not answered by the prototype.
425
+ */
426
+ isPresent(record, key) {
427
+ return Object.prototype.hasOwnProperty.call(record, key) && record[key] !== undefined;
428
+ }
429
+ /**
430
+ * Renders a reply value for an error message, quoting a string so `"80%"` reads as the text it was.
431
+ */
432
+ describeValue(value) {
433
+ return typeof value === 'string' ? `"${value}"` : String(value);
434
+ }
435
+ /**
436
+ * Populates Usage and ResolvedModel telemetry on DecisionResult from prompt result.
437
+ */
438
+ recordTelemetry(decisionResult, promptResult) {
439
+ const cost = this.resolveCost(promptResult);
440
+ decisionResult.Usage = new ModelUsage(promptResult.promptTokens ?? 0, promptResult.completionTokens ?? 0, cost.cost, cost.currency);
441
+ if (promptResult.modelInfo?.modelName) {
442
+ decisionResult.ResolvedModel = promptResult.modelInfo.modelName;
443
+ }
444
+ }
445
+ /**
446
+ * The chat call's cost. Once the chat run is saved, its saved cost wins: `TotalCost`, else
447
+ * `Cost`, which the server computes when the run is saved and which is what rolls up to the
448
+ * decision's run. It differs from the runner's reported cost only when the runner reports 0,
449
+ * which the server treats as unpriced and reprices, so reporting the saved cost keeps the
450
+ * decision run's descendant cost equal to the rollup. Before the run is saved, the runner's
451
+ * reported cost wins, then the run's cost as it stands. Unset when none is known.
452
+ */
453
+ resolveCost(promptResult) {
454
+ const run = promptResult.promptRun;
455
+ const runCost = run ? this.savedRunCost(run) : undefined;
456
+ if (run?.IsSaved && runCost !== undefined) {
457
+ return { cost: runCost, currency: run.CostCurrency ?? promptResult.costCurrency };
458
+ }
459
+ if (promptResult.cost !== undefined) {
460
+ return { cost: promptResult.cost, currency: promptResult.costCurrency };
461
+ }
462
+ if (runCost === undefined) {
463
+ return { currency: promptResult.costCurrency };
464
+ }
465
+ return { cost: runCost, currency: run?.CostCurrency ?? promptResult.costCurrency };
466
+ }
467
+ /**
468
+ * A saved run's cost: `TotalCost`, else `Cost`. The server writes `TotalCost = 0` for a run it
469
+ * could not price, so `TotalCost` counts only when the run has a `Cost` or a `DescendantCost`.
470
+ */
471
+ savedRunCost(run) {
472
+ if (run.Cost == null && run.DescendantCost == null) {
473
+ return undefined;
474
+ }
475
+ return run.TotalCost ?? run.Cost ?? undefined;
476
+ }
477
+ };
478
+ LLMDecision = __decorate([
479
+ RegisterClass(BaseDecision, 'LLMDecision'),
480
+ __metadata("design:paramtypes", [String, String, UserInfo])
481
+ ], LLMDecision);
482
+ export { LLMDecision };
483
+ /**
484
+ * Factory function to create an LLMDecision instance.
485
+ *
486
+ * @param promptID - ID of the prompt to execute.
487
+ * @param contextUser - User context for prompt execution.
488
+ * @returns Configured LLMDecision instance.
489
+ */
490
+ export function CreateLLMDecision(promptID, contextUser) {
491
+ return new LLMDecision('', promptID, contextUser);
492
+ }
493
+ //# sourceMappingURL=LLMDecision.js.map