@valerypopoff/rivet2-core 2.15.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 +4350 -2077
- 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 +5 -2
- package/dist/esm/exports.js +2 -0
- package/dist/esm/model/GraphBoundaryCache.js +2 -1
- package/dist/esm/model/GraphProcessor.js +268 -6
- package/dist/esm/model/Nodes.js +10 -0
- package/dist/esm/model/ProjectBundle.js +235 -0
- package/dist/esm/model/SplitRunProcessor.js +28 -7
- package/dist/esm/model/StreamingWatchTopology.js +118 -8
- 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 +30 -4
- 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/openai.js +118 -0
- package/dist/esm/model/classifier/preparation.js +74 -0
- package/dist/esm/model/classifier/providers.js +260 -185
- package/dist/esm/model/classifier/questionHelpers.js +29 -45
- 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/nodeRunFailure.js +47 -0
- package/dist/esm/model/nodes/CatchStreamingChunksNode.js +42 -0
- package/dist/esm/model/nodes/ClassifierEvaluateNode.js +178 -138
- package/dist/esm/model/nodes/ClassifierQuestionNode.js +59 -15
- 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 +24 -3
- package/dist/esm/model/nodes/ObjectNode.js +29 -18
- 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/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 +3 -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 +2 -0
- package/dist/types/model/CycleDetector.d.ts +1 -2
- 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/Nodes.d.ts +6 -2
- 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/StreamingWatchTopology.d.ts +11 -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 +3 -1
- 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/openai.d.ts +5 -0
- package/dist/types/model/classifier/preparation.d.ts +16 -0
- package/dist/types/model/classifier/providers.d.ts +67 -9
- package/dist/types/model/classifier/questionHelpers.d.ts +6 -4
- 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 +2 -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 +3 -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/ObjectNode.d.ts +2 -1
- 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/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
|
@@ -1,12 +1,28 @@
|
|
|
1
|
-
import { JEV_DEFAULT_CREDENTIAL_NAMES } from './credentials.js';
|
|
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';
|
|
2
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';
|
|
3
13
|
/** Jev's published USD rates. Keep this Core-owned rather than graph-authored. */
|
|
4
14
|
export const JEV_TOKEN_PRICING = {
|
|
5
15
|
inputPerMillionTokens: 0.042,
|
|
6
16
|
outputPerMillionTokens: 0,
|
|
7
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
|
+
};
|
|
8
23
|
const TOKENS_PER_MILLION = 1_000_000;
|
|
9
24
|
const MAX_AUTOMATIC_ATTEMPTS = 3;
|
|
25
|
+
const MAX_TIMER_DELAY_MS = 2_147_483_647;
|
|
10
26
|
const RETRYABLE_STATUSES = new Set([429, 529]);
|
|
11
27
|
export const DEFAULT_CLASSIFIER_RETRY_ON_NON_200_REPEAT_TIMES = 1;
|
|
12
28
|
export const DEFAULT_CLASSIFIER_RETRY_ON_NON_200_COOLDOWN_MS = 0;
|
|
@@ -16,34 +32,16 @@ export const DEFAULT_CLASSIFIER_RETRY_ON_NON_200_COOLDOWN_MS = 0;
|
|
|
16
32
|
* to which compatible provider is selected.
|
|
17
33
|
*/
|
|
18
34
|
export function createApiCompatibleClassifierProvider(config) {
|
|
19
|
-
return {
|
|
20
|
-
|
|
21
|
-
label: config.label,
|
|
22
|
-
defaultModel: config.defaultModel,
|
|
23
|
-
credentialNames: config.credentialNames,
|
|
35
|
+
return createClassifierProvider({
|
|
36
|
+
...config,
|
|
24
37
|
browserExecutionSupported: config.browserExecutionSupported ?? false,
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
return await callApiCompatibleClassifier({
|
|
33
|
-
apiKey,
|
|
34
|
-
endpoint: config.endpoint,
|
|
35
|
-
fetchImplementation,
|
|
36
|
-
providerLabel: config.label,
|
|
37
|
-
questions,
|
|
38
|
-
request,
|
|
39
|
-
retryOnNon200,
|
|
40
|
-
retryOnNon200CooldownMs,
|
|
41
|
-
retryOnNon200RepeatTimes,
|
|
42
|
-
signal,
|
|
43
|
-
timeoutMs,
|
|
44
|
-
});
|
|
45
|
-
},
|
|
46
|
-
};
|
|
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
|
+
});
|
|
47
45
|
}
|
|
48
46
|
export const jevClassifierProvider = createApiCompatibleClassifierProvider({
|
|
49
47
|
id: 'jev',
|
|
@@ -51,10 +49,120 @@ export const jevClassifierProvider = createApiCompatibleClassifierProvider({
|
|
|
51
49
|
defaultModel: 'jev-latest',
|
|
52
50
|
credentialNames: JEV_DEFAULT_CREDENTIAL_NAMES,
|
|
53
51
|
endpoint: JEV_SYSTEM_ONE_ENDPOINT,
|
|
54
|
-
pricing: JEV_TOKEN_PRICING,
|
|
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
|
+
},
|
|
55
67
|
});
|
|
56
|
-
/**
|
|
57
|
-
|
|
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
|
+
}
|
|
58
166
|
export function getClassifierProvider(id) {
|
|
59
167
|
const provider = classifierProviders.find((candidate) => candidate.id === (id || jevClassifierProvider.id));
|
|
60
168
|
if (!provider)
|
|
@@ -65,23 +173,34 @@ export function getClassifierProviderEnvironmentVariableNames() {
|
|
|
65
173
|
return [...new Set(classifierProviders.map((provider) => provider.credentialNames.environmentVariableName))];
|
|
66
174
|
}
|
|
67
175
|
/**
|
|
68
|
-
* Returns a USD cost only
|
|
69
|
-
* the token counts are safe non-negative integers.
|
|
70
|
-
*
|
|
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.
|
|
71
181
|
*/
|
|
72
|
-
export function calculateClassifierUsageCost(provider, usage) {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
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))) ||
|
|
79
197
|
!Number.isSafeInteger(usage.input_tokens) ||
|
|
80
198
|
usage.input_tokens < 0 ||
|
|
81
199
|
!Number.isSafeInteger(usage.output_tokens) ||
|
|
82
200
|
usage.output_tokens < 0) {
|
|
83
201
|
return undefined;
|
|
84
202
|
}
|
|
203
|
+
const pricing = tier && usage.input_tokens > tier.aboveInputTokens ? tier : base;
|
|
85
204
|
const totalCost = (usage.input_tokens * pricing.inputPerMillionTokens + usage.output_tokens * pricing.outputPerMillionTokens) /
|
|
86
205
|
TOKENS_PER_MILLION;
|
|
87
206
|
return Number.isFinite(totalCost) && totalCost >= 0 ? totalCost : undefined;
|
|
@@ -96,25 +215,27 @@ function createQuestionMap(questions) {
|
|
|
96
215
|
}
|
|
97
216
|
return result;
|
|
98
217
|
}
|
|
99
|
-
async function
|
|
100
|
-
const
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
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;
|
|
104
224
|
const configuredCooldownMs = normalizeClassifierNon200RetryCooldownMs(retryOnNon200CooldownMs);
|
|
105
225
|
let automaticRetryCount = 0;
|
|
106
226
|
let configuredRetryCountUsed = 0;
|
|
107
|
-
//
|
|
108
|
-
//
|
|
109
|
-
|
|
110
|
-
// retries and make the diagnostic disagree with the wire payload.
|
|
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);
|
|
111
230
|
const requestJson = JSON.stringify(request);
|
|
112
|
-
|
|
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();
|
|
113
236
|
for (;;) {
|
|
114
|
-
|
|
237
|
+
operation.check();
|
|
115
238
|
const remainingMs = deadline - Date.now();
|
|
116
|
-
if (remainingMs <= 0)
|
|
117
|
-
throw new Error(`${providerLabel} request timed out after ${timeoutMs} ms.`);
|
|
118
239
|
const controller = new AbortController();
|
|
119
240
|
const onAbort = () => controller.abort(signal.reason);
|
|
120
241
|
signal.addEventListener('abort', onAbort, { once: true });
|
|
@@ -123,82 +244,136 @@ async function callApiCompatibleClassifier({ apiKey, endpoint, fetchImplementati
|
|
|
123
244
|
clearTimeout(timer);
|
|
124
245
|
signal.removeEventListener('abort', onAbort);
|
|
125
246
|
};
|
|
247
|
+
const assertAttemptActive = () => operation.check(controller.signal);
|
|
126
248
|
let response;
|
|
127
249
|
try {
|
|
128
|
-
response = await fetchImplementation(endpoint, {
|
|
250
|
+
response = await waitForAttempt(fetchImplementation(endpoint, {
|
|
129
251
|
method: 'POST',
|
|
252
|
+
redirect: 'error',
|
|
130
253
|
headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
|
|
131
254
|
body: requestJson,
|
|
132
255
|
signal: controller.signal,
|
|
133
|
-
});
|
|
256
|
+
}), controller.signal, discardResponseBody);
|
|
134
257
|
}
|
|
135
|
-
catch {
|
|
258
|
+
catch (error) {
|
|
136
259
|
cleanupAttempt();
|
|
137
|
-
|
|
138
|
-
throwAbort(signal, providerLabel);
|
|
139
|
-
if (Date.now() >= deadline || controller.signal.aborted) {
|
|
140
|
-
throw new Error(`${providerLabel} request timed out after ${timeoutMs} ms.`);
|
|
141
|
-
}
|
|
260
|
+
operation.check(controller.signal);
|
|
142
261
|
if (automaticRetryCount >= MAX_AUTOMATIC_ATTEMPTS - 1) {
|
|
143
|
-
throw new Error(`${providerLabel} request failed after ${MAX_AUTOMATIC_ATTEMPTS} attempts due to a transport error
|
|
262
|
+
throw new Error(`${providerLabel} request failed after ${MAX_AUTOMATIC_ATTEMPTS} attempts due to a transport error.`, { cause: error });
|
|
144
263
|
}
|
|
145
264
|
automaticRetryCount += 1;
|
|
146
265
|
await waitForRetry(Math.min(250 * 2 ** (automaticRetryCount - 1), deadline - Date.now()), signal, providerLabel);
|
|
147
266
|
continue;
|
|
148
267
|
}
|
|
268
|
+
try {
|
|
269
|
+
assertAttemptActive();
|
|
270
|
+
}
|
|
271
|
+
catch (error) {
|
|
272
|
+
cleanupAttempt();
|
|
273
|
+
discardResponseBody(response);
|
|
274
|
+
throw error;
|
|
275
|
+
}
|
|
149
276
|
if (!response.ok) {
|
|
150
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);
|
|
151
283
|
if (RETRYABLE_STATUSES.has(response.status) && automaticRetryCount < MAX_AUTOMATIC_ATTEMPTS - 1) {
|
|
152
284
|
automaticRetryCount += 1;
|
|
153
285
|
const delayMs = getRetryDelayMs(response.headers.get('retry-after'), automaticRetryCount, deadline);
|
|
154
|
-
await response.body?.cancel().catch(() => undefined);
|
|
155
286
|
await waitForRetry(delayMs, signal, providerLabel);
|
|
156
287
|
continue;
|
|
157
288
|
}
|
|
158
289
|
if (response.status === 401 || response.status === 403) {
|
|
159
|
-
throw new Error(`${providerLabel} authentication failed. Check the ${providerLabel} API key.`)
|
|
290
|
+
throw Object.assign(new Error(`${providerLabel} authentication failed. Check the ${providerLabel} API key.`), {
|
|
291
|
+
statusCode: response.status,
|
|
292
|
+
});
|
|
160
293
|
}
|
|
161
294
|
if (response.status === 422 || response.status === 400) {
|
|
162
|
-
throw new Error(`${providerLabel} rejected the request (HTTP ${response.status}).`)
|
|
295
|
+
throw Object.assign(new Error(`${providerLabel} rejected the request (HTTP ${response.status}).`), {
|
|
296
|
+
statusCode: response.status,
|
|
297
|
+
});
|
|
163
298
|
}
|
|
164
299
|
if (configuredRetryCountUsed < configuredRetryCount && !RETRYABLE_STATUSES.has(response.status)) {
|
|
165
300
|
configuredRetryCountUsed += 1;
|
|
166
|
-
await response.body?.cancel().catch(() => undefined);
|
|
167
301
|
await waitForRetry(Math.min(configuredCooldownMs, deadline - Date.now()), signal, providerLabel);
|
|
168
302
|
continue;
|
|
169
303
|
}
|
|
170
|
-
throw new Error(`${providerLabel} request failed (HTTP ${response.status}).`)
|
|
304
|
+
throw Object.assign(new Error(`${providerLabel} request failed (HTTP ${response.status}).`), {
|
|
305
|
+
statusCode: response.status,
|
|
306
|
+
});
|
|
171
307
|
}
|
|
172
308
|
let body;
|
|
173
309
|
try {
|
|
174
|
-
body = await response.
|
|
310
|
+
body = await waitForAttempt(readClassifierResponse(response, controller.signal, assertAttemptActive), controller.signal);
|
|
311
|
+
assertAttemptActive();
|
|
175
312
|
}
|
|
176
|
-
catch {
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
if (
|
|
180
|
-
throw
|
|
181
|
-
}
|
|
182
|
-
throw new Error(`${providerLabel} returned an invalid JSON response.`);
|
|
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 });
|
|
183
319
|
}
|
|
184
320
|
finally {
|
|
185
321
|
cleanupAttempt();
|
|
186
322
|
}
|
|
187
|
-
const validatedResponse =
|
|
323
|
+
const validatedResponse = validateResponse(body, prepared.questions, providerLabel);
|
|
188
324
|
return {
|
|
189
|
-
|
|
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
|
+
},
|
|
190
333
|
response: validatedResponse,
|
|
191
|
-
//
|
|
192
|
-
//
|
|
193
|
-
|
|
194
|
-
responseBody: validatedResponse,
|
|
334
|
+
// Expose native JSON, not the adapter's Rivet answer projection. The
|
|
335
|
+
// validators accept only object-shaped provider envelopes.
|
|
336
|
+
responseBody: body,
|
|
195
337
|
};
|
|
196
338
|
}
|
|
197
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
|
+
}
|
|
198
375
|
export function normalizeClassifierNon200RetryCount(value) {
|
|
199
|
-
const retryCount = typeof value === 'number' && Number.isFinite(value)
|
|
200
|
-
? value
|
|
201
|
-
: DEFAULT_CLASSIFIER_RETRY_ON_NON_200_REPEAT_TIMES;
|
|
376
|
+
const retryCount = typeof value === 'number' && Number.isFinite(value) ? value : DEFAULT_CLASSIFIER_RETRY_ON_NON_200_REPEAT_TIMES;
|
|
202
377
|
return Math.max(1, Math.floor(retryCount));
|
|
203
378
|
}
|
|
204
379
|
export function normalizeClassifierNon200RetryCooldownMs(value) {
|
|
@@ -245,103 +420,3 @@ function getRetryDelayMs(retryAfter, attempt, deadline) {
|
|
|
245
420
|
}
|
|
246
421
|
return Math.max(0, Math.min(requestedMs ?? 250 * 2 ** (attempt - 1), deadline - Date.now()));
|
|
247
422
|
}
|
|
248
|
-
function isRecord(value) {
|
|
249
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
250
|
-
}
|
|
251
|
-
function requireFiniteUnit(value, label, providerLabel) {
|
|
252
|
-
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {
|
|
253
|
-
throw new Error(`${providerLabel} response has invalid ${label}.`);
|
|
254
|
-
}
|
|
255
|
-
return value;
|
|
256
|
-
}
|
|
257
|
-
function requireProbabilityMap(value, expectedKeys, label, providerLabel) {
|
|
258
|
-
if (!isRecord(value))
|
|
259
|
-
throw new Error(`${providerLabel} response has invalid ${label}.`);
|
|
260
|
-
const actualKeys = Object.keys(value);
|
|
261
|
-
if (actualKeys.length !== expectedKeys.length ||
|
|
262
|
-
expectedKeys.some((key) => !Object.prototype.hasOwnProperty.call(value, key))) {
|
|
263
|
-
throw new Error(`${providerLabel} response has inconsistent ${label} keys.`);
|
|
264
|
-
}
|
|
265
|
-
let total = 0;
|
|
266
|
-
for (const key of expectedKeys)
|
|
267
|
-
total += requireFiniteUnit(value[key], `${label}.${key}`, providerLabel);
|
|
268
|
-
if (Math.abs(total - 1) > 0.001)
|
|
269
|
-
throw new Error(`${providerLabel} response ${label} must sum to 1.`);
|
|
270
|
-
return value;
|
|
271
|
-
}
|
|
272
|
-
function structurallyEqual(left, right) {
|
|
273
|
-
if (Object.is(left, right))
|
|
274
|
-
return true;
|
|
275
|
-
if (Array.isArray(left) || Array.isArray(right)) {
|
|
276
|
-
return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((item, index) => structurallyEqual(item, right[index]));
|
|
277
|
-
}
|
|
278
|
-
if (!isRecord(left) || !isRecord(right))
|
|
279
|
-
return false;
|
|
280
|
-
const leftKeys = Object.keys(left);
|
|
281
|
-
const rightKeys = Object.keys(right);
|
|
282
|
-
return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && structurallyEqual(left[key], right[key]));
|
|
283
|
-
}
|
|
284
|
-
export function validateApiCompatibleClassifierResponse(body, questions, providerLabel = 'Classifier provider') {
|
|
285
|
-
if (!isRecord(body) ||
|
|
286
|
-
typeof body.model !== 'string' ||
|
|
287
|
-
body.model.trim() === '' ||
|
|
288
|
-
!isRecord(body.answers) ||
|
|
289
|
-
!isRecord(body.usage)) {
|
|
290
|
-
throw new Error(`${providerLabel} returned an invalid response shape.`);
|
|
291
|
-
}
|
|
292
|
-
const expectedIds = questions.map((question) => question.questionId);
|
|
293
|
-
const answerIds = Object.keys(body.answers);
|
|
294
|
-
if (answerIds.length !== expectedIds.length ||
|
|
295
|
-
expectedIds.some((id) => !Object.prototype.hasOwnProperty.call(body.answers, id))) {
|
|
296
|
-
throw new Error(`${providerLabel} response does not match the submitted question IDs.`);
|
|
297
|
-
}
|
|
298
|
-
for (const question of questions) {
|
|
299
|
-
const answer = body.answers[question.questionId];
|
|
300
|
-
if (!isRecord(answer) || answer.type !== question.type) {
|
|
301
|
-
throw new Error(`${providerLabel} response type does not match question '${question.questionId}'.`);
|
|
302
|
-
}
|
|
303
|
-
if (question.type === 'choice') {
|
|
304
|
-
const choiceQuestion = question;
|
|
305
|
-
const keys = Object.keys(choiceQuestion.criteria);
|
|
306
|
-
if (typeof answer.choice !== 'string' ||
|
|
307
|
-
!Object.prototype.hasOwnProperty.call(choiceQuestion.criteria, answer.choice)) {
|
|
308
|
-
throw new Error(`${providerLabel} response chose an unknown option for '${question.questionId}'.`);
|
|
309
|
-
}
|
|
310
|
-
requireFiniteUnit(answer.confidence, `${question.questionId}.confidence`, providerLabel);
|
|
311
|
-
requireProbabilityMap(answer.probabilities, keys, `${question.questionId}.probabilities`, providerLabel);
|
|
312
|
-
}
|
|
313
|
-
else if (question.type === 'score') {
|
|
314
|
-
const scoreQuestion = question;
|
|
315
|
-
if (typeof answer.score !== 'number' ||
|
|
316
|
-
!Number.isFinite(answer.score) ||
|
|
317
|
-
answer.score < 0 ||
|
|
318
|
-
answer.score > scoreQuestion.criteria.length - 1) {
|
|
319
|
-
throw new Error(`${providerLabel} response has invalid score for '${question.questionId}'.`);
|
|
320
|
-
}
|
|
321
|
-
requireFiniteUnit(answer.confidence, `${question.questionId}.confidence`, providerLabel);
|
|
322
|
-
const keys = scoreQuestion.criteria.map((_, index) => String(index));
|
|
323
|
-
requireProbabilityMap(answer.probabilities, keys, `${question.questionId}.probabilities`, providerLabel);
|
|
324
|
-
const legend = answer.legend;
|
|
325
|
-
if (!isRecord(legend) ||
|
|
326
|
-
Object.keys(legend).length !== keys.length ||
|
|
327
|
-
keys.some((key, index) => !Object.prototype.hasOwnProperty.call(legend, key) ||
|
|
328
|
-
!structurallyEqual(legend[key], scoreQuestion.criteria[index]))) {
|
|
329
|
-
throw new Error(`${providerLabel} response has inconsistent legend for '${question.questionId}'.`);
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
else {
|
|
333
|
-
requireFiniteUnit(answer.noul, `${question.questionId}.noul`, providerLabel);
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
const inputTokens = body.usage.input_tokens;
|
|
337
|
-
const outputTokens = body.usage.output_tokens;
|
|
338
|
-
if (typeof inputTokens !== 'number' ||
|
|
339
|
-
!Number.isSafeInteger(inputTokens) ||
|
|
340
|
-
inputTokens < 0 ||
|
|
341
|
-
typeof outputTokens !== 'number' ||
|
|
342
|
-
!Number.isSafeInteger(outputTokens) ||
|
|
343
|
-
outputTokens < 0) {
|
|
344
|
-
throw new Error(`${providerLabel} response has invalid usage values.`);
|
|
345
|
-
}
|
|
346
|
-
return body;
|
|
347
|
-
}
|