@valerypopoff/rivet2-core 2.13.0 → 2.17.0
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/cjs/bundle.cjs +28167 -23834
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/interpolationRuntime.cjs +22 -3
- package/dist/cjs/interpolationRuntime.cjs.map +3 -3
- package/dist/cjs/interpolationSyntax.cjs +9 -5
- package/dist/cjs/interpolationSyntax.cjs.map +2 -2
- package/dist/esm/api/createProcessor.js +10 -2
- package/dist/esm/api/processSettings.js +1 -0
- package/dist/esm/exports.js +6 -0
- package/dist/esm/model/GraphBoundaryCache.js +2 -1
- package/dist/esm/model/GraphProcessor.js +278 -22
- package/dist/esm/model/MarkdownSanitizationPolicy.js +2 -0
- package/dist/esm/model/NodeImpl.js +1 -1
- package/dist/esm/model/Nodes.js +16 -0
- package/dist/esm/model/ProjectBundle.js +235 -0
- package/dist/esm/model/SplitRunProcessor.js +28 -7
- package/dist/esm/model/StreamingWatchTopology.js +211 -64
- package/dist/esm/model/SubgraphProjectTarget.js +7 -0
- package/dist/esm/model/chat-v2/aiSdkBridge.js +7 -5
- package/dist/esm/model/chat-v2/chatV2Pipeline.js +13 -8
- package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +19 -1
- package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
- package/dist/esm/model/chat-v2/llmChatV2Body.js +11 -8
- package/dist/esm/model/chat-v2/llmChatV2NodeData.js +2 -0
- package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +15 -1
- package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +22 -2
- package/dist/esm/model/chat-v2/llmProfile.js +3 -0
- package/dist/esm/model/chat-v2/llmProfileBody.js +2 -2
- package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -1
- package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +1 -1
- package/dist/esm/model/chat-v2/temperature.js +9 -0
- package/dist/esm/model/classifier/credentials.js +107 -0
- package/dist/esm/model/classifier/images.js +176 -0
- package/dist/esm/model/classifier/json.js +57 -0
- package/dist/esm/model/classifier/limits.js +270 -0
- package/dist/esm/model/classifier/migration.js +97 -0
- package/dist/esm/model/classifier/openai.js +118 -0
- package/dist/esm/model/classifier/preparation.js +74 -0
- package/dist/esm/model/classifier/providers.js +422 -0
- package/dist/esm/model/classifier/questionHelpers.js +109 -0
- package/dist/esm/model/classifier/questions.js +53 -0
- package/dist/esm/model/classifier/response.js +75 -0
- package/dist/esm/model/classifier/state.js +204 -0
- package/dist/esm/model/classifier/types.js +1 -0
- package/dist/esm/model/nodeBodyMarkdown.js +37 -0
- package/dist/esm/model/nodeRunFailure.js +47 -0
- package/dist/esm/model/nodes/CatchStreamingChunksNode.js +42 -0
- package/dist/esm/model/nodes/ClassifierEvaluateNode.js +432 -0
- package/dist/esm/model/nodes/ClassifierQuestionNode.js +613 -0
- package/dist/esm/model/nodes/CodeNewNode.js +33 -9
- package/dist/esm/model/nodes/GetGlobalNode.js +2 -2
- package/dist/esm/model/nodes/HttpCallNode.js +44 -75
- package/dist/esm/model/nodes/ImageNode.js +44 -3
- package/dist/esm/model/nodes/LLMChatV2Node.js +27 -15
- package/dist/esm/model/nodes/LLMProfileNode.js +6 -12
- package/dist/esm/model/nodes/MatchCaseNode.js +76 -1
- package/dist/esm/model/nodes/MatchCaseNodeBase.js +24 -2
- package/dist/esm/model/nodes/ObjectNode.js +68 -50
- package/dist/esm/model/nodes/PassthroughNode.js +1 -1
- package/dist/esm/model/nodes/PromptNode.js +2 -1
- package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +4 -1
- package/dist/esm/model/nodes/SetGlobalNode.js +5 -3
- package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +8 -8
- package/dist/esm/model/nodes/StreamValueNode.js +38 -0
- package/dist/esm/model/nodes/SubGraphNode.js +196 -35
- package/dist/esm/model/nodes/ToBase64Node.js +106 -0
- package/dist/esm/model/nodes/WatchStreamingOutputNode.js +7 -7
- package/dist/esm/model/nodes/codeOutputInference.js +292 -0
- package/dist/esm/recording/ExecutionRecorder.js +26 -0
- package/dist/esm/utils/base64.js +18 -15
- package/dist/esm/utils/errors.js +41 -0
- package/dist/esm/utils/interpolation.js +44 -22
- package/dist/esm/utils/interpolationSyntax.js +15 -6
- package/dist/esm/utils/serialization/serialization.js +7 -2
- package/dist/esm/utils/serialization/serializationUtils.js +6 -0
- package/dist/esm/utils/serialization/serialization_v4.js +15 -3
- package/dist/types/api/createProcessor.d.ts +7 -1
- package/dist/types/exports.d.ts +6 -0
- package/dist/types/model/CycleDetector.d.ts +1 -2
- package/dist/types/model/EditorDefinition.d.ts +24 -0
- package/dist/types/model/ExecutorProtocol.d.ts +2 -0
- package/dist/types/model/GraphBoundaryCache.d.ts +2 -0
- package/dist/types/model/GraphProcessor.d.ts +1 -0
- package/dist/types/model/MarkdownSanitizationPolicy.d.ts +1 -1
- package/dist/types/model/NodeImpl.d.ts +3 -1
- package/dist/types/model/Nodes.d.ts +10 -4
- package/dist/types/model/ProcessContext.d.ts +12 -0
- package/dist/types/model/ProjectBundle.d.ts +54 -0
- package/dist/types/model/ProjectReferenceLoader.d.ts +3 -0
- package/dist/types/model/Settings.d.ts +4 -0
- package/dist/types/model/StreamingWatchTopology.d.ts +17 -1
- package/dist/types/model/SubgraphProjectTarget.d.ts +38 -0
- package/dist/types/model/chat-v2/chatV2Shared.d.ts +1 -1
- package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +3 -1
- package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +3 -1
- package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +6 -6
- package/dist/types/model/chat-v2/temperature.d.ts +2 -0
- package/dist/types/model/classifier/credentials.d.ts +26 -0
- package/dist/types/model/classifier/images.d.ts +18 -0
- package/dist/types/model/classifier/json.d.ts +19 -0
- package/dist/types/model/classifier/limits.d.ts +42 -0
- package/dist/types/model/classifier/migration.d.ts +18 -0
- package/dist/types/model/classifier/openai.d.ts +5 -0
- package/dist/types/model/classifier/preparation.d.ts +16 -0
- package/dist/types/model/classifier/providers.d.ts +136 -0
- package/dist/types/model/classifier/questionHelpers.d.ts +33 -0
- package/dist/types/model/classifier/questions.d.ts +4 -0
- package/dist/types/model/classifier/response.d.ts +4 -0
- package/dist/types/model/classifier/state.d.ts +37 -0
- package/dist/types/model/classifier/types.d.ts +60 -0
- package/dist/types/model/nodeBodyMarkdown.d.ts +19 -0
- package/dist/types/model/nodeRunFailure.d.ts +13 -0
- package/dist/types/model/nodes/CatchStreamingChunksNode.d.ts +20 -0
- package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +50 -0
- package/dist/types/model/nodes/ClassifierQuestionNode.d.ts +60 -0
- package/dist/types/model/nodes/CodeNewNode.d.ts +6 -0
- package/dist/types/model/nodes/GetGlobalNode.d.ts +7 -0
- package/dist/types/model/nodes/ImageNode.d.ts +4 -0
- package/dist/types/model/nodes/LLMChatV2Node.d.ts +1 -0
- package/dist/types/model/nodes/MatchCaseNode.d.ts +8 -1
- package/dist/types/model/nodes/MatchCaseNodeBase.d.ts +13 -1
- package/dist/types/model/nodes/ObjectNode.d.ts +6 -0
- package/dist/types/model/nodes/StreamValueNode.d.ts +14 -0
- package/dist/types/model/nodes/SubGraphNode.d.ts +21 -2
- package/dist/types/model/nodes/ToBase64Node.d.ts +12 -0
- package/dist/types/model/nodes/codeOutputInference.d.ts +31 -0
- package/dist/types/recording/ExecutionRecorder.d.ts +8 -2
- package/dist/types/utils/base64.d.ts +1 -1
- package/dist/types/utils/errors.d.ts +4 -0
- package/dist/types/utils/interpolation.d.ts +13 -2
- package/dist/types/utils/interpolationSyntax.d.ts +1 -1
- package/dist/types/utils/serialization/serialization.d.ts +3 -1
- package/dist/types/utils/serialization/serializationUtils.d.ts +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
import { JEV_DEFAULT_CREDENTIAL_NAMES, LIQUID_DEFAULT_CREDENTIAL_NAMES, OPENAI_DEFAULT_CREDENTIAL_NAMES, } from './credentials.js';
|
|
2
|
+
import { assertLiquidImageLimits } from './images.js';
|
|
3
|
+
import { prepareClassifierState, systemOneState, } from './state.js';
|
|
4
|
+
import { validateClassifierEvaluationResponse } from './response.js';
|
|
5
|
+
import { createOpenAIDecisionRequest, validateOpenAIDecisionResponse } from './openai.js';
|
|
6
|
+
import { prepareClassifierQuestion } from './questions.js';
|
|
7
|
+
import { classifierArrayValues } from './json.js';
|
|
8
|
+
import { assertClassifierResourceLimits, ClassifierValueBudget, CLASSIFIER_LIMITS, ClassifierResourceLimitError, readClassifierResponse, } from './limits.js';
|
|
9
|
+
export { validateApiCompatibleClassifierResponse } from './response.js';
|
|
10
|
+
export const JEV_SYSTEM_ONE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone';
|
|
11
|
+
export const LIQUID_SYSTEM_ONE_ENDPOINT = 'https://api.liquid.ai/decisions/v1/systemone';
|
|
12
|
+
export const OPENAI_DECISIONS_ENDPOINT = 'https://api.openai.com/v1/decisions';
|
|
13
|
+
/** Jev's published USD rates. Keep this Core-owned rather than graph-authored. */
|
|
14
|
+
export const JEV_TOKEN_PRICING = {
|
|
15
|
+
inputPerMillionTokens: 0.042,
|
|
16
|
+
outputPerMillionTokens: 0,
|
|
17
|
+
};
|
|
18
|
+
/** Liquid d1's published USD rates: https://www.liquid.ai/blog/d1-decision-model */
|
|
19
|
+
export const LIQUID_TOKEN_PRICING = {
|
|
20
|
+
inputPerMillionTokens: 0.04,
|
|
21
|
+
outputPerMillionTokens: 0,
|
|
22
|
+
};
|
|
23
|
+
const TOKENS_PER_MILLION = 1_000_000;
|
|
24
|
+
const MAX_AUTOMATIC_ATTEMPTS = 3;
|
|
25
|
+
const MAX_TIMER_DELAY_MS = 2_147_483_647;
|
|
26
|
+
const RETRYABLE_STATUSES = new Set([429, 529]);
|
|
27
|
+
export const DEFAULT_CLASSIFIER_RETRY_ON_NON_200_REPEAT_TIMES = 1;
|
|
28
|
+
export const DEFAULT_CLASSIFIER_RETRY_ON_NON_200_COOLDOWN_MS = 0;
|
|
29
|
+
/**
|
|
30
|
+
* Builds a provider for the shared System One-compatible protocol. Provider
|
|
31
|
+
* descriptors remain static Core code, while the Evaluate node stays agnostic
|
|
32
|
+
* to which compatible provider is selected.
|
|
33
|
+
*/
|
|
34
|
+
export function createApiCompatibleClassifierProvider(config) {
|
|
35
|
+
return createClassifierProvider({
|
|
36
|
+
...config,
|
|
37
|
+
browserExecutionSupported: config.browserExecutionSupported ?? false,
|
|
38
|
+
buildRequest: ({ model, questions, state }) => ({
|
|
39
|
+
...systemOneState(state.kind === 'json' ? { state: state.value } : { state: '', stateMessages: state.messages }),
|
|
40
|
+
model,
|
|
41
|
+
questions: createQuestionMap(questions),
|
|
42
|
+
}),
|
|
43
|
+
validateResponse: validateClassifierEvaluationResponse,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
export const jevClassifierProvider = createApiCompatibleClassifierProvider({
|
|
47
|
+
id: 'jev',
|
|
48
|
+
label: 'Jev',
|
|
49
|
+
defaultModel: 'jev-latest',
|
|
50
|
+
credentialNames: JEV_DEFAULT_CREDENTIAL_NAMES,
|
|
51
|
+
endpoint: JEV_SYSTEM_ONE_ENDPOINT,
|
|
52
|
+
modelPricing: [{ models: ['jev-latest', 'jev-preview', 'jev-1.13.0'], pricing: JEV_TOKEN_PRICING }],
|
|
53
|
+
});
|
|
54
|
+
export const liquidClassifierProvider = createApiCompatibleClassifierProvider({
|
|
55
|
+
id: 'liquid',
|
|
56
|
+
label: 'Liquid AI',
|
|
57
|
+
defaultModel: 'd1',
|
|
58
|
+
credentialNames: LIQUID_DEFAULT_CREDENTIAL_NAMES,
|
|
59
|
+
endpoint: LIQUID_SYSTEM_ONE_ENDPOINT,
|
|
60
|
+
modelPricing: [{ models: ['d1'], pricing: LIQUID_TOKEN_PRICING }],
|
|
61
|
+
supportsImages: (model) => model === 'd1',
|
|
62
|
+
maxRequestBytes: 4_500_000,
|
|
63
|
+
checkState: (state, check) => {
|
|
64
|
+
if (state.kind === 'messages')
|
|
65
|
+
assertLiquidImageLimits(state.images, check);
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
/** Decisions-specific rates, not GPT-6 Luna's Chat/Responses cache/output rates.
|
|
69
|
+
* https://developers.openai.com/api/docs/guides/decisions#pricing-and-availability
|
|
70
|
+
*/
|
|
71
|
+
export const openaiClassifierProvider = createClassifierProvider({
|
|
72
|
+
id: 'openai',
|
|
73
|
+
label: 'OpenAI',
|
|
74
|
+
defaultModel: 'gpt-6-luna',
|
|
75
|
+
credentialNames: OPENAI_DEFAULT_CREDENTIAL_NAMES,
|
|
76
|
+
browserExecutionSupported: false,
|
|
77
|
+
endpoint: OPENAI_DECISIONS_ENDPOINT,
|
|
78
|
+
supportsImages: (model) => model === 'gpt-6-luna',
|
|
79
|
+
modelPricing: [
|
|
80
|
+
{
|
|
81
|
+
models: ['gpt-6-luna'],
|
|
82
|
+
pricing: {
|
|
83
|
+
inputPerMillionTokens: 0.1,
|
|
84
|
+
outputPerMillionTokens: 0,
|
|
85
|
+
longContext: { aboveInputTokens: 272_000, inputPerMillionTokens: 0.2, outputPerMillionTokens: 0 },
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
],
|
|
89
|
+
buildRequest: createOpenAIDecisionRequest,
|
|
90
|
+
validateResponse: validateOpenAIDecisionResponse,
|
|
91
|
+
});
|
|
92
|
+
/** Ordered so adding compatible providers does not alter authored IDs. */
|
|
93
|
+
export const classifierProviders = [
|
|
94
|
+
jevClassifierProvider,
|
|
95
|
+
liquidClassifierProvider,
|
|
96
|
+
openaiClassifierProvider,
|
|
97
|
+
];
|
|
98
|
+
function createOperation(args, label) {
|
|
99
|
+
if (!Number.isFinite(args.timeoutMs) ||
|
|
100
|
+
args.timeoutMs <= 0 ||
|
|
101
|
+
(args.deadline !== undefined && !Number.isFinite(args.deadline)))
|
|
102
|
+
throw new Error('Classifier timeout and deadline must be finite, with a positive timeout.');
|
|
103
|
+
const now = Date.now();
|
|
104
|
+
const deadline = Math.min(now + args.timeoutMs, args.deadline ?? Infinity);
|
|
105
|
+
// Node turns overflowing setTimeout delays into 1 ms, not a long timeout.
|
|
106
|
+
if (deadline - now > MAX_TIMER_DELAY_MS)
|
|
107
|
+
throw new Error(`Classifier effective timeout must not exceed ${MAX_TIMER_DELAY_MS} ms.`);
|
|
108
|
+
const timeoutError = () => new Error(`${label} request timed out after ${args.timeoutMs} ms.`);
|
|
109
|
+
return {
|
|
110
|
+
signal: args.signal,
|
|
111
|
+
deadline,
|
|
112
|
+
check(attemptSignal) {
|
|
113
|
+
throwIfAborted(args.signal, label);
|
|
114
|
+
if (Date.now() >= deadline || attemptSignal?.aborted)
|
|
115
|
+
throw timeoutError();
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/** A plain specification and one runner for both graph and direct provider inputs. */
|
|
120
|
+
function createClassifierProvider(spec) {
|
|
121
|
+
const { endpoint, buildRequest, validateResponse, checkState, ...provider } = spec;
|
|
122
|
+
const evaluate = async (input) => {
|
|
123
|
+
// Reject removed evidence fields before object spread can read a getter or
|
|
124
|
+
// discard non-enumerable/inherited content.
|
|
125
|
+
if ('images' in input)
|
|
126
|
+
throw new Error('Pass image evidence through State, not a separate images field.');
|
|
127
|
+
const args = { ...input, fetchImplementation: input.fetchImplementation ?? fetch };
|
|
128
|
+
const operation = createOperation(args, provider.label);
|
|
129
|
+
operation.check();
|
|
130
|
+
if (typeof args.model !== 'string')
|
|
131
|
+
throw new Error('Classifier model must be a nonblank string.');
|
|
132
|
+
const budget = new ClassifierValueBudget(operation.check, provider.maxRequestBytes);
|
|
133
|
+
budget.inspect(args.model);
|
|
134
|
+
if (args.model.trim() === '')
|
|
135
|
+
throw new Error('Classifier model must be a nonblank string.');
|
|
136
|
+
if (typeof args.apiKey !== 'string' || args.apiKey.trim() === '' || /[\r\n]/.test(args.apiKey))
|
|
137
|
+
throw new Error('Classifier API key must be a nonblank string without line breaks.');
|
|
138
|
+
if (!Array.isArray(args.questions) || args.questions.length === 0)
|
|
139
|
+
throw new Error('Classifier Evaluate requires at least one question.');
|
|
140
|
+
if (args.questions.length > CLASSIFIER_LIMITS.questions)
|
|
141
|
+
throw new Error('Classifier Evaluate supports at most 1000 questions.');
|
|
142
|
+
const state = prepareClassifierState(args, budget);
|
|
143
|
+
const questions = [];
|
|
144
|
+
const ids = new Set();
|
|
145
|
+
for (const value of classifierArrayValues(args.questions, 'Questions')) {
|
|
146
|
+
const question = prepareClassifierQuestion(value, budget);
|
|
147
|
+
if (ids.has(question.questionId))
|
|
148
|
+
throw new Error(`Question ID '${question.questionId}' is duplicated in this evaluation.`);
|
|
149
|
+
ids.add(question.questionId);
|
|
150
|
+
questions.push(question);
|
|
151
|
+
}
|
|
152
|
+
if (state.kind === 'messages' && state.images.length && !provider.supportsImages?.(args.model))
|
|
153
|
+
throw new Error(`${provider.label} model '${args.model}' does not support classifier images.`);
|
|
154
|
+
checkState?.(state, operation.check);
|
|
155
|
+
operation.check();
|
|
156
|
+
const result = await callClassifierHttp(args, { endpoint, validateResponse, label: provider.label, maxRequestBytes: provider.maxRequestBytes }, { model: args.model, state, questions }, buildRequest, operation);
|
|
157
|
+
operation.check();
|
|
158
|
+
return result;
|
|
159
|
+
};
|
|
160
|
+
return { ...provider, evaluate, evaluateInput: evaluate };
|
|
161
|
+
}
|
|
162
|
+
function normalizeModelPricing(provider) {
|
|
163
|
+
return (provider.modelPricing ??
|
|
164
|
+
(provider.pricing && provider.defaultModel ? [{ models: [provider.defaultModel], pricing: provider.pricing }] : []));
|
|
165
|
+
}
|
|
166
|
+
export function getClassifierProvider(id) {
|
|
167
|
+
const provider = classifierProviders.find((candidate) => candidate.id === (id || jevClassifierProvider.id));
|
|
168
|
+
if (!provider)
|
|
169
|
+
throw new Error(`Unknown classifier provider '${id}'.`);
|
|
170
|
+
return provider;
|
|
171
|
+
}
|
|
172
|
+
export function getClassifierProviderEnvironmentVariableNames() {
|
|
173
|
+
return [...new Set(classifierProviders.map((provider) => provider.credentialNames.environmentVariableName))];
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Returns a USD cost only for a recognized requested/returned model pair and
|
|
177
|
+
* the token counts are safe non-negative integers. Provider input_tokens already
|
|
178
|
+
* includes billed text/image work across questions; never multiply by question
|
|
179
|
+
* count or add image tokens again. Decisions has no separate cache charges.
|
|
180
|
+
* Callers must not treat an unpriced provider as free.
|
|
181
|
+
*/
|
|
182
|
+
export function calculateClassifierUsageCost(provider, usage, models) {
|
|
183
|
+
if (!models)
|
|
184
|
+
return undefined;
|
|
185
|
+
const entries = normalizeModelPricing(provider);
|
|
186
|
+
const entry = entries.find(({ models: names }) => names.includes(models.requestedModel) && names.includes(models.responseModel));
|
|
187
|
+
const base = entry?.pricing;
|
|
188
|
+
const tier = base?.longContext;
|
|
189
|
+
const validRates = (rates) => Number.isFinite(rates.inputPerMillionTokens) &&
|
|
190
|
+
rates.inputPerMillionTokens >= 0 &&
|
|
191
|
+
Number.isFinite(rates.outputPerMillionTokens) &&
|
|
192
|
+
rates.outputPerMillionTokens >= 0;
|
|
193
|
+
if (base == null ||
|
|
194
|
+
!validRates(base) ||
|
|
195
|
+
(tier != null &&
|
|
196
|
+
(!Number.isSafeInteger(tier.aboveInputTokens) || tier.aboveInputTokens < 0 || !validRates(tier))) ||
|
|
197
|
+
!Number.isSafeInteger(usage.input_tokens) ||
|
|
198
|
+
usage.input_tokens < 0 ||
|
|
199
|
+
!Number.isSafeInteger(usage.output_tokens) ||
|
|
200
|
+
usage.output_tokens < 0) {
|
|
201
|
+
return undefined;
|
|
202
|
+
}
|
|
203
|
+
const pricing = tier && usage.input_tokens > tier.aboveInputTokens ? tier : base;
|
|
204
|
+
const totalCost = (usage.input_tokens * pricing.inputPerMillionTokens + usage.output_tokens * pricing.outputPerMillionTokens) /
|
|
205
|
+
TOKENS_PER_MILLION;
|
|
206
|
+
return Number.isFinite(totalCost) && totalCost >= 0 ? totalCost : undefined;
|
|
207
|
+
}
|
|
208
|
+
function createQuestionMap(questions) {
|
|
209
|
+
const result = Object.create(null);
|
|
210
|
+
for (const question of questions) {
|
|
211
|
+
const providerQuestion = question.type === 'noul' && question.criteria === undefined
|
|
212
|
+
? { type: question.type, instructions: question.instructions }
|
|
213
|
+
: { type: question.type, instructions: question.instructions, criteria: question.criteria };
|
|
214
|
+
Object.defineProperty(result, question.questionId, { enumerable: true, value: providerQuestion });
|
|
215
|
+
}
|
|
216
|
+
return result;
|
|
217
|
+
}
|
|
218
|
+
async function callClassifierHttp(args, spec, prepared, buildRequest, operation) {
|
|
219
|
+
const { apiKey, fetchImplementation, retryOnNon200, retryOnNon200CooldownMs, retryOnNon200RepeatTimes } = args;
|
|
220
|
+
const { endpoint, label: providerLabel, validateResponse, maxRequestBytes } = spec;
|
|
221
|
+
const { signal, deadline } = operation;
|
|
222
|
+
const request = buildRequest(prepared);
|
|
223
|
+
const configuredRetryCount = retryOnNon200 ? normalizeClassifierNon200RetryCount(retryOnNon200RepeatTimes) : 0;
|
|
224
|
+
const configuredCooldownMs = normalizeClassifierNon200RetryCooldownMs(retryOnNon200CooldownMs);
|
|
225
|
+
let automaticRetryCount = 0;
|
|
226
|
+
let configuredRetryCountUsed = 0;
|
|
227
|
+
// The transformed protocol can expand content (notably escaped JSON in OpenAI).
|
|
228
|
+
// This final wire check is distinct from validating/detaching untrusted inputs.
|
|
229
|
+
assertClassifierResourceLimits(request, operation.check);
|
|
230
|
+
const requestJson = JSON.stringify(request);
|
|
231
|
+
if (maxRequestBytes !== undefined && new TextEncoder().encode(requestJson).byteLength >= maxRequestBytes) {
|
|
232
|
+
throw new Error(`${providerLabel} request must be smaller than ${maxRequestBytes / 1_000_000} MB, including State, images, and questions. Resize images or reduce input content.`);
|
|
233
|
+
}
|
|
234
|
+
let requestBody;
|
|
235
|
+
operation.check();
|
|
236
|
+
for (;;) {
|
|
237
|
+
operation.check();
|
|
238
|
+
const remainingMs = deadline - Date.now();
|
|
239
|
+
const controller = new AbortController();
|
|
240
|
+
const onAbort = () => controller.abort(signal.reason);
|
|
241
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
242
|
+
const timer = setTimeout(() => controller.abort(new Error(`${providerLabel} request timeout`)), remainingMs);
|
|
243
|
+
const cleanupAttempt = () => {
|
|
244
|
+
clearTimeout(timer);
|
|
245
|
+
signal.removeEventListener('abort', onAbort);
|
|
246
|
+
};
|
|
247
|
+
const assertAttemptActive = () => operation.check(controller.signal);
|
|
248
|
+
let response;
|
|
249
|
+
try {
|
|
250
|
+
response = await waitForAttempt(fetchImplementation(endpoint, {
|
|
251
|
+
method: 'POST',
|
|
252
|
+
redirect: 'error',
|
|
253
|
+
headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
|
|
254
|
+
body: requestJson,
|
|
255
|
+
signal: controller.signal,
|
|
256
|
+
}), controller.signal, discardResponseBody);
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
cleanupAttempt();
|
|
260
|
+
operation.check(controller.signal);
|
|
261
|
+
if (automaticRetryCount >= MAX_AUTOMATIC_ATTEMPTS - 1) {
|
|
262
|
+
throw new Error(`${providerLabel} request failed after ${MAX_AUTOMATIC_ATTEMPTS} attempts due to a transport error.`, { cause: error });
|
|
263
|
+
}
|
|
264
|
+
automaticRetryCount += 1;
|
|
265
|
+
await waitForRetry(Math.min(250 * 2 ** (automaticRetryCount - 1), deadline - Date.now()), signal, providerLabel);
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
try {
|
|
269
|
+
assertAttemptActive();
|
|
270
|
+
}
|
|
271
|
+
catch (error) {
|
|
272
|
+
cleanupAttempt();
|
|
273
|
+
discardResponseBody(response);
|
|
274
|
+
throw error;
|
|
275
|
+
}
|
|
276
|
+
if (!response.ok) {
|
|
277
|
+
cleanupAttempt();
|
|
278
|
+
// Rejected bodies are not answer outputs. Release every response, not just
|
|
279
|
+
// retries, so caught terminal failures cannot leave connections occupied.
|
|
280
|
+
// Initiate cancellation without awaiting a hostile stream's cleanup;
|
|
281
|
+
// neither the final error nor the next bounded retry may depend on it.
|
|
282
|
+
discardResponseBody(response);
|
|
283
|
+
if (RETRYABLE_STATUSES.has(response.status) && automaticRetryCount < MAX_AUTOMATIC_ATTEMPTS - 1) {
|
|
284
|
+
automaticRetryCount += 1;
|
|
285
|
+
const delayMs = getRetryDelayMs(response.headers.get('retry-after'), automaticRetryCount, deadline);
|
|
286
|
+
await waitForRetry(delayMs, signal, providerLabel);
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
if (response.status === 401 || response.status === 403) {
|
|
290
|
+
throw Object.assign(new Error(`${providerLabel} authentication failed. Check the ${providerLabel} API key.`), {
|
|
291
|
+
statusCode: response.status,
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
if (response.status === 422 || response.status === 400) {
|
|
295
|
+
throw Object.assign(new Error(`${providerLabel} rejected the request (HTTP ${response.status}).`), {
|
|
296
|
+
statusCode: response.status,
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
if (configuredRetryCountUsed < configuredRetryCount && !RETRYABLE_STATUSES.has(response.status)) {
|
|
300
|
+
configuredRetryCountUsed += 1;
|
|
301
|
+
await waitForRetry(Math.min(configuredCooldownMs, deadline - Date.now()), signal, providerLabel);
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
throw Object.assign(new Error(`${providerLabel} request failed (HTTP ${response.status}).`), {
|
|
305
|
+
statusCode: response.status,
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
let body;
|
|
309
|
+
try {
|
|
310
|
+
body = await waitForAttempt(readClassifierResponse(response, controller.signal, assertAttemptActive), controller.signal);
|
|
311
|
+
assertAttemptActive();
|
|
312
|
+
}
|
|
313
|
+
catch (error) {
|
|
314
|
+
discardResponseBody(response);
|
|
315
|
+
operation.check(controller.signal);
|
|
316
|
+
if (error instanceof ClassifierResourceLimitError)
|
|
317
|
+
throw error;
|
|
318
|
+
throw new Error(`${providerLabel} returned an invalid JSON response.`, { cause: error });
|
|
319
|
+
}
|
|
320
|
+
finally {
|
|
321
|
+
cleanupAttempt();
|
|
322
|
+
}
|
|
323
|
+
const validatedResponse = validateResponse(body, prepared.questions, providerLabel);
|
|
324
|
+
return {
|
|
325
|
+
// Preserve the direct-provider result contract, but graph runs with the
|
|
326
|
+
// diagnostic disabled never allocate this second representation.
|
|
327
|
+
get requestBody() {
|
|
328
|
+
return (requestBody ??= JSON.parse(requestJson));
|
|
329
|
+
},
|
|
330
|
+
set requestBody(value) {
|
|
331
|
+
requestBody = value;
|
|
332
|
+
},
|
|
333
|
+
response: validatedResponse,
|
|
334
|
+
// Expose native JSON, not the adapter's Rivet answer projection. The
|
|
335
|
+
// validators accept only object-shaped provider envelopes.
|
|
336
|
+
responseBody: body,
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
/** Bound awaiting even when a custom transport ignores its abort signal. */
|
|
341
|
+
function waitForAttempt(promise, signal, onLateResult) {
|
|
342
|
+
return new Promise((resolve, reject) => {
|
|
343
|
+
let aborted = false;
|
|
344
|
+
const cleanup = () => signal.removeEventListener('abort', onAbort);
|
|
345
|
+
const onAbort = () => {
|
|
346
|
+
aborted = true;
|
|
347
|
+
cleanup();
|
|
348
|
+
reject(signal.reason);
|
|
349
|
+
};
|
|
350
|
+
// Attach both handlers even after cancellation: late errors are consumed
|
|
351
|
+
// and a late HTTP response is disposed, never accepted by another attempt.
|
|
352
|
+
promise.then((value) => {
|
|
353
|
+
cleanup();
|
|
354
|
+
if (aborted)
|
|
355
|
+
onLateResult?.(value);
|
|
356
|
+
else
|
|
357
|
+
resolve(value);
|
|
358
|
+
}, (error) => {
|
|
359
|
+
cleanup();
|
|
360
|
+
reject(error);
|
|
361
|
+
});
|
|
362
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
363
|
+
if (signal.aborted)
|
|
364
|
+
onAbort();
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
function discardResponseBody(response) {
|
|
368
|
+
try {
|
|
369
|
+
void response.body?.cancel().catch(() => undefined);
|
|
370
|
+
}
|
|
371
|
+
catch {
|
|
372
|
+
// Cleanup is observational, including custom fetch/body implementations.
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
export function normalizeClassifierNon200RetryCount(value) {
|
|
376
|
+
const retryCount = typeof value === 'number' && Number.isFinite(value) ? value : DEFAULT_CLASSIFIER_RETRY_ON_NON_200_REPEAT_TIMES;
|
|
377
|
+
return Math.max(1, Math.floor(retryCount));
|
|
378
|
+
}
|
|
379
|
+
export function normalizeClassifierNon200RetryCooldownMs(value) {
|
|
380
|
+
const cooldownMs = typeof value === 'number' && Number.isFinite(value) ? value : DEFAULT_CLASSIFIER_RETRY_ON_NON_200_COOLDOWN_MS;
|
|
381
|
+
return Math.max(0, Math.floor(cooldownMs));
|
|
382
|
+
}
|
|
383
|
+
function throwIfAborted(signal, providerLabel) {
|
|
384
|
+
if (signal.aborted)
|
|
385
|
+
throwAbort(signal, providerLabel);
|
|
386
|
+
}
|
|
387
|
+
function throwAbort(signal, providerLabel) {
|
|
388
|
+
throw signal.reason instanceof Error ? signal.reason : new Error(`${providerLabel} request aborted.`);
|
|
389
|
+
}
|
|
390
|
+
function waitForRetry(delayMs, signal, providerLabel) {
|
|
391
|
+
throwIfAborted(signal, providerLabel);
|
|
392
|
+
if (delayMs <= 0)
|
|
393
|
+
return Promise.resolve();
|
|
394
|
+
return new Promise((resolve, reject) => {
|
|
395
|
+
const onAbort = () => {
|
|
396
|
+
clearTimeout(timer);
|
|
397
|
+
signal.removeEventListener('abort', onAbort);
|
|
398
|
+
reject(signal.reason instanceof Error ? signal.reason : new Error(`${providerLabel} request aborted.`));
|
|
399
|
+
};
|
|
400
|
+
const timer = setTimeout(() => {
|
|
401
|
+
signal.removeEventListener('abort', onAbort);
|
|
402
|
+
resolve();
|
|
403
|
+
}, delayMs);
|
|
404
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
405
|
+
if (signal.aborted)
|
|
406
|
+
onAbort();
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
function getRetryDelayMs(retryAfter, attempt, deadline) {
|
|
410
|
+
let requestedMs;
|
|
411
|
+
if (retryAfter != null) {
|
|
412
|
+
const seconds = Number(retryAfter);
|
|
413
|
+
if (Number.isFinite(seconds) && seconds >= 0)
|
|
414
|
+
requestedMs = seconds * 1000;
|
|
415
|
+
else {
|
|
416
|
+
const date = Date.parse(retryAfter);
|
|
417
|
+
if (Number.isFinite(date))
|
|
418
|
+
requestedMs = Math.max(0, date - Date.now());
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return Math.max(0, Math.min(requestedMs ?? 250 * 2 ** (attempt - 1), deadline - Date.now()));
|
|
422
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { createInterpolationInputDefinition } from '../interpolationInputDefinition.js';
|
|
2
|
+
import { extractInterpolationVariableReferences, getInterpolationGlobalValues, interpolate, } from '../../utils/interpolation.js';
|
|
3
|
+
import { interpolateJsonTemplate } from '../nodes/ObjectNode.js';
|
|
4
|
+
import { assertClassifierEntry, classifierDataProperty } from './json.js';
|
|
5
|
+
import { checkClassifierJsonWork } from './limits.js';
|
|
6
|
+
export { assertClassifierEntry, assertClassifierInstructions } from './json.js';
|
|
7
|
+
const STRUCTURED_ENTRY_TYPES = ['string', 'object', 'object[]', 'any', 'any[]'];
|
|
8
|
+
export function getInstructionsInputDefinition() {
|
|
9
|
+
return {
|
|
10
|
+
id: 'instructions',
|
|
11
|
+
title: 'Instructions',
|
|
12
|
+
dataType: STRUCTURED_ENTRY_TYPES,
|
|
13
|
+
required: true,
|
|
14
|
+
splitRunBehavior: 'preserve-array',
|
|
15
|
+
description: 'String or JSON structure describing the independent question.',
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export function getCriteriaInputDefinition(dataTypes) {
|
|
19
|
+
return {
|
|
20
|
+
id: 'criteria',
|
|
21
|
+
title: 'Criteria',
|
|
22
|
+
dataType: dataTypes,
|
|
23
|
+
required: true,
|
|
24
|
+
splitRunBehavior: 'preserve-array',
|
|
25
|
+
description: 'Complete criteria for this question.',
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export function getInterpolationInputDefinitions(templates, reserved) {
|
|
29
|
+
const names = new Set();
|
|
30
|
+
for (const template of templates) {
|
|
31
|
+
for (const { baseName } of extractInterpolationVariableReferences(template)) {
|
|
32
|
+
if (!reserved.has(baseName))
|
|
33
|
+
names.add(baseName);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return [...names].map((interpolationName) => createInterpolationInputDefinition({
|
|
37
|
+
interpolationName,
|
|
38
|
+
dataType: 'any',
|
|
39
|
+
required: false,
|
|
40
|
+
description: `Interpolated value named '${interpolationName}'.`,
|
|
41
|
+
}));
|
|
42
|
+
}
|
|
43
|
+
export function interpolateQuestionText(template, inputs, context, preparation) {
|
|
44
|
+
preparation?.capture(template);
|
|
45
|
+
const result = interpolate(template, inputs, context.graphInputNodeValues, context.contextValues, {
|
|
46
|
+
globalValues: getInterpolationGlobalValues(template, context.getGlobal, preparation?.check, preparation?.tokenLimit),
|
|
47
|
+
guard: preparation,
|
|
48
|
+
});
|
|
49
|
+
preparation?.capture(result);
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
52
|
+
export function resolveAuthoredClassifierEntry({ type, text, lines, objectTemplate, inputs, context, label, preparation, }) {
|
|
53
|
+
if (type === 'lines') {
|
|
54
|
+
preparation?.capture(lines ?? []);
|
|
55
|
+
const resolved = [];
|
|
56
|
+
for (let index = 0; index < (lines?.length ?? 0); index++) {
|
|
57
|
+
resolved.push(interpolateQuestionText(lines[index], inputs, context, preparation));
|
|
58
|
+
}
|
|
59
|
+
if (resolved.length === 0)
|
|
60
|
+
throw new Error(`${label} require at least one line.`);
|
|
61
|
+
return resolved;
|
|
62
|
+
}
|
|
63
|
+
if (type === 'object') {
|
|
64
|
+
preparation?.capture(objectTemplate ?? '{}');
|
|
65
|
+
const template = objectTemplate?.trim() ? objectTemplate : '{}';
|
|
66
|
+
let parsed;
|
|
67
|
+
try {
|
|
68
|
+
const json = interpolateJsonTemplate(template, inputs, context.graphInputNodeValues, context.contextValues, getInterpolationGlobalValues(template, context.getGlobal, preparation?.check, preparation?.tokenLimit), preparation, true);
|
|
69
|
+
preparation?.capture(json);
|
|
70
|
+
checkClassifierJsonWork(json, preparation?.check ?? (() => { }), 'question template');
|
|
71
|
+
parsed = JSON.parse(json);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
throw new Error(`${label} JSON template is invalid: ${error.message}`);
|
|
75
|
+
}
|
|
76
|
+
if (parsed === null || Array.isArray(parsed) || typeof parsed !== 'object') {
|
|
77
|
+
throw new Error(`${label} JSON template must produce an object.`);
|
|
78
|
+
}
|
|
79
|
+
assertClassifierEntry(parsed, label);
|
|
80
|
+
return parsed;
|
|
81
|
+
}
|
|
82
|
+
return interpolateQuestionText(text ?? '', inputs, context, preparation);
|
|
83
|
+
}
|
|
84
|
+
export function getQuestionInputValue(inputs, portId, label) {
|
|
85
|
+
const input = classifierDataProperty(inputs, portId, label);
|
|
86
|
+
return input && typeof input === 'object' ? classifierDataProperty(input, 'value', label) : undefined;
|
|
87
|
+
}
|
|
88
|
+
export function getStringInput(inputs, portId, label) {
|
|
89
|
+
const value = getQuestionInputValue(inputs, portId, label);
|
|
90
|
+
if (typeof value !== 'string')
|
|
91
|
+
throw new Error(`${label} input must be a string.`);
|
|
92
|
+
return value;
|
|
93
|
+
}
|
|
94
|
+
export function requireQuestionId(questionId) {
|
|
95
|
+
if (questionId.trim().length === 0)
|
|
96
|
+
throw new Error('Question ID is required.');
|
|
97
|
+
return questionId;
|
|
98
|
+
}
|
|
99
|
+
export function getStructuredInput(inputs, portId, label) {
|
|
100
|
+
const value = getQuestionInputValue(inputs, portId, label);
|
|
101
|
+
if (value === undefined)
|
|
102
|
+
throw new Error(`${label} input is required.`);
|
|
103
|
+
assertClassifierEntry(value, label);
|
|
104
|
+
return value;
|
|
105
|
+
}
|
|
106
|
+
export function abbreviate(value, maximum = 72) {
|
|
107
|
+
const compact = value.replace(/\s+/g, ' ').trim();
|
|
108
|
+
return compact.length <= maximum ? compact : `${compact.slice(0, maximum - 3)}...`;
|
|
109
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { assertClassifierEntryKind, assertClassifierInstructionsKind, snapshotClassifierJson, classifierArrayValues, } from './json.js';
|
|
2
|
+
/** Shared by node execution and direct provider calls, before taking the request snapshot. */
|
|
3
|
+
export function prepareClassifierQuestion(value, budget) {
|
|
4
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
5
|
+
throw new Error('Question inputs must contain question definition objects.');
|
|
6
|
+
if ('images' in value)
|
|
7
|
+
throw new Error("Question-level images are not supported. Connect images to Classifier Evaluate's State input.");
|
|
8
|
+
for (const key of ['questionId', 'type', 'instructions']) {
|
|
9
|
+
if (!Object.prototype.propertyIsEnumerable.call(value, key))
|
|
10
|
+
throw new Error(`Every classifier question must have an own, enumerable '${key}' field.`);
|
|
11
|
+
}
|
|
12
|
+
const criteriaProperty = Object.getOwnPropertyDescriptor(value, 'criteria');
|
|
13
|
+
if (criteriaProperty && (!criteriaProperty.enumerable || !('value' in criteriaProperty)))
|
|
14
|
+
throw new Error('Classifier question criteria must be an own, enumerable field.');
|
|
15
|
+
// Optional envelope properties may be undefined; structured entries themselves must be exact JSON.
|
|
16
|
+
const question = snapshotClassifierJson(value, 'Question', budget, true);
|
|
17
|
+
if (typeof question.questionId !== 'string' || question.questionId.trim() === '')
|
|
18
|
+
throw new Error('Every classifier question must have a non-empty Question ID.');
|
|
19
|
+
if (!['choice', 'score', 'noul'].includes(question.type))
|
|
20
|
+
throw new Error(`Question '${question.questionId}' has an unsupported type.`);
|
|
21
|
+
// The whole question has already passed recursive JSON/resource validation.
|
|
22
|
+
// Check only entry kinds here; do not scan each structured entry again.
|
|
23
|
+
assertClassifierInstructionsKind(question.instructions, `Question '${question.questionId}' instructions`);
|
|
24
|
+
const criteria = question.criteria;
|
|
25
|
+
if (question.type === 'choice') {
|
|
26
|
+
if (typeof criteria !== 'object' || criteria === null || Array.isArray(criteria))
|
|
27
|
+
throw new Error(`Choice question '${question.questionId}' requires object criteria.`);
|
|
28
|
+
const keys = Object.keys(criteria);
|
|
29
|
+
if (keys.length < 2 || keys.length > 255)
|
|
30
|
+
throw new Error(`Choice question '${question.questionId}' requires 2 to 255 options.`);
|
|
31
|
+
for (const key of keys)
|
|
32
|
+
assertClassifierEntryKind(criteria[key], `Question '${question.questionId}' criteria.${key}`);
|
|
33
|
+
}
|
|
34
|
+
else if (question.type === 'score') {
|
|
35
|
+
if (!Array.isArray(criteria) || criteria.length < 2 || criteria.length > 10)
|
|
36
|
+
throw new Error(`Score question '${question.questionId}' requires 2 to 10 levels.`);
|
|
37
|
+
let index = 0;
|
|
38
|
+
for (const entry of classifierArrayValues(criteria, 'Criteria'))
|
|
39
|
+
assertClassifierEntryKind(entry, `Question '${question.questionId}' criteria[${index++}]`);
|
|
40
|
+
}
|
|
41
|
+
else if (criteria !== undefined) {
|
|
42
|
+
if (typeof criteria !== 'object' ||
|
|
43
|
+
criteria === null ||
|
|
44
|
+
Array.isArray(criteria) ||
|
|
45
|
+
!Object.prototype.propertyIsEnumerable.call(criteria, 'true') ||
|
|
46
|
+
!Object.prototype.propertyIsEnumerable.call(criteria, 'false'))
|
|
47
|
+
throw new Error(`Noul question '${question.questionId}' criteria must contain true and false entries.`);
|
|
48
|
+
const entries = criteria;
|
|
49
|
+
assertClassifierEntryKind(entries.true, `Question '${question.questionId}' criteria.true`);
|
|
50
|
+
assertClassifierEntryKind(entries.false, `Question '${question.questionId}' criteria.false`);
|
|
51
|
+
}
|
|
52
|
+
return question;
|
|
53
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
function isRecord(value) {
|
|
2
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
3
|
+
}
|
|
4
|
+
/** Inherited values are not fields of the provider's JSON response. */
|
|
5
|
+
function responseField(record, key) {
|
|
6
|
+
return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined;
|
|
7
|
+
}
|
|
8
|
+
function requireResponseNumber(value, label, providerLabel) {
|
|
9
|
+
// Check JSON-compatible representation only, never the provider's numeric
|
|
10
|
+
// range, normalization, precision or derived relationships.
|
|
11
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
12
|
+
throw new Error(`${providerLabel} response has invalid ${label}.`);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function requireResponseMap(value, expectedKeys, label, providerLabel) {
|
|
16
|
+
if (!isRecord(value))
|
|
17
|
+
throw new Error(`${providerLabel} response has invalid ${label}.`);
|
|
18
|
+
const actualKeys = Object.keys(value);
|
|
19
|
+
if (actualKeys.length !== expectedKeys.length ||
|
|
20
|
+
expectedKeys.some((key) => !Object.prototype.hasOwnProperty.call(value, key))) {
|
|
21
|
+
throw new Error(`${providerLabel} response has inconsistent ${label} keys.`);
|
|
22
|
+
}
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
function requireProbabilityMap(value, keys, label, providerLabel) {
|
|
26
|
+
const probabilities = requireResponseMap(value, keys, label, providerLabel);
|
|
27
|
+
for (const key of keys)
|
|
28
|
+
requireResponseNumber(probabilities[key], `${label}.${key}`, providerLabel);
|
|
29
|
+
}
|
|
30
|
+
export function validateApiCompatibleClassifierResponse(body, questions, providerLabel = 'Classifier provider') {
|
|
31
|
+
return validateClassifierEvaluationResponse(body, questions, providerLabel);
|
|
32
|
+
}
|
|
33
|
+
/** Validate the common Rivet result, independently of the provider's wire protocol. */
|
|
34
|
+
export function validateClassifierEvaluationResponse(body, questions, providerLabel = 'Classifier provider') {
|
|
35
|
+
const model = isRecord(body) ? responseField(body, 'model') : undefined;
|
|
36
|
+
const answers = isRecord(body) ? responseField(body, 'answers') : undefined;
|
|
37
|
+
const usage = isRecord(body) ? responseField(body, 'usage') : undefined;
|
|
38
|
+
if (!isRecord(body) || typeof model !== 'string' || model.trim() === '' || !isRecord(answers) || !isRecord(usage)) {
|
|
39
|
+
throw new Error(`${providerLabel} returned an invalid response shape.`);
|
|
40
|
+
}
|
|
41
|
+
const expectedIds = questions.map((question) => question.questionId);
|
|
42
|
+
const answerIds = Object.keys(answers);
|
|
43
|
+
if (answerIds.length !== expectedIds.length ||
|
|
44
|
+
expectedIds.some((id) => !Object.prototype.hasOwnProperty.call(answers, id))) {
|
|
45
|
+
throw new Error(`${providerLabel} response does not match the submitted question IDs.`);
|
|
46
|
+
}
|
|
47
|
+
for (const question of questions) {
|
|
48
|
+
const answer = answers[question.questionId];
|
|
49
|
+
if (!isRecord(answer) || responseField(answer, 'type') !== question.type) {
|
|
50
|
+
throw new Error(`${providerLabel} response type does not match question '${question.questionId}'.`);
|
|
51
|
+
}
|
|
52
|
+
if (question.type === 'choice') {
|
|
53
|
+
const keys = Object.keys(question.criteria);
|
|
54
|
+
const choice = responseField(answer, 'choice');
|
|
55
|
+
if (typeof choice !== 'string' || !Object.prototype.hasOwnProperty.call(question.criteria, choice)) {
|
|
56
|
+
throw new Error(`${providerLabel} response chose an unknown option for '${question.questionId}'.`);
|
|
57
|
+
}
|
|
58
|
+
requireResponseNumber(responseField(answer, 'confidence'), `${question.questionId}.confidence`, providerLabel);
|
|
59
|
+
requireProbabilityMap(responseField(answer, 'probabilities'), keys, `${question.questionId}.probabilities`, providerLabel);
|
|
60
|
+
}
|
|
61
|
+
else if (question.type === 'score') {
|
|
62
|
+
requireResponseNumber(responseField(answer, 'score'), `${question.questionId}.score`, providerLabel);
|
|
63
|
+
requireResponseNumber(responseField(answer, 'confidence'), `${question.questionId}.confidence`, providerLabel);
|
|
64
|
+
const keys = question.criteria.map((_, index) => String(index));
|
|
65
|
+
requireProbabilityMap(responseField(answer, 'probabilities'), keys, `${question.questionId}.probabilities`, providerLabel);
|
|
66
|
+
requireResponseMap(responseField(answer, 'legend'), keys, `${question.questionId}.legend`, providerLabel);
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
requireResponseNumber(responseField(answer, 'noul'), `${question.questionId}.noul`, providerLabel);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
requireResponseNumber(responseField(usage, 'input_tokens'), 'usage.input_tokens', providerLabel);
|
|
73
|
+
requireResponseNumber(responseField(usage, 'output_tokens'), 'usage.output_tokens', providerLabel);
|
|
74
|
+
return body;
|
|
75
|
+
}
|