@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
|
@@ -2,6 +2,7 @@ import { generateText, NoObjectGeneratedError, streamText } from 'ai';
|
|
|
2
2
|
import { consumeAiSdkStream } from '../chat/aiSdkStreaming.js';
|
|
3
3
|
import { ChatV2ProviderTimeoutError } from './chatV2Types.js';
|
|
4
4
|
import { isChatV2StructuredResponseFormat } from './chatV2ResponseFormat.js';
|
|
5
|
+
import { normalizeTemperature } from './temperature.js';
|
|
5
6
|
function keepPromiseHandled(value) {
|
|
6
7
|
const promise = Promise.resolve(value);
|
|
7
8
|
void promise.catch(() => undefined);
|
|
@@ -130,8 +131,9 @@ function buildTextArgs(options) {
|
|
|
130
131
|
args.tools = options.tools;
|
|
131
132
|
if (options.maxTokens !== undefined)
|
|
132
133
|
args.maxOutputTokens = options.maxTokens;
|
|
133
|
-
|
|
134
|
-
|
|
134
|
+
const temperature = normalizeTemperature(options.temperature);
|
|
135
|
+
if (temperature !== undefined)
|
|
136
|
+
args.temperature = temperature;
|
|
135
137
|
if (options.topP !== undefined)
|
|
136
138
|
args.topP = options.topP;
|
|
137
139
|
if (options.topK !== undefined)
|
|
@@ -196,10 +198,10 @@ async function* streamWithDeadlines(stream, options, firstOutputStartedAt) {
|
|
|
196
198
|
for (;;) {
|
|
197
199
|
const kind = hasUsefulOutput ? 'stream-inactivity' : 'first-output';
|
|
198
200
|
const configuredTimeout = hasUsefulOutput ? options.streamInactivityTimeoutMs : options.firstOutputTimeoutMs;
|
|
199
|
-
const timeoutMs = configuredTimeout == null
|
|
201
|
+
const timeoutMs = configuredTimeout == null ? undefined : Math.max(1, configuredTimeout - (Date.now() - lastUsefulOutputAt));
|
|
202
|
+
const timeout = timeoutMs == null
|
|
200
203
|
? undefined
|
|
201
|
-
:
|
|
202
|
-
const timeout = timeoutMs == null ? undefined : timeoutPromise(timeoutMs, kind, options.onTimeout);
|
|
204
|
+
: timeoutPromise(timeoutMs, kind, options.onTimeout);
|
|
203
205
|
let next;
|
|
204
206
|
try {
|
|
205
207
|
next = await (timeout == null ? iterator.next() : Promise.race([iterator.next(), timeout.promise]));
|
|
@@ -5,9 +5,9 @@ import { chatMessagesToModelMessages } from './messageConverter.js';
|
|
|
5
5
|
import { isChatV2ProviderTimeoutError } from './chatV2Types.js';
|
|
6
6
|
import { chatV2ToolsToAiSdk } from './toolConverter.js';
|
|
7
7
|
import { buildChatV2RequestPlan } from './chatV2RequestPlan.js';
|
|
8
|
-
import { getChatV2ProviderErrorStatusCode, normalizeChatV2ProviderError
|
|
8
|
+
import { getChatV2ProviderErrorStatusCode, normalizeChatV2ProviderError } from './chatV2Errors.js';
|
|
9
9
|
import { createLLMChatV2RetryAbortError, waitForLLMChatV2RetryCooldown } from './chatV2Retry.js';
|
|
10
|
-
import { createChatV2CommonOutputs, normalizeChatV2Usage
|
|
10
|
+
import { createChatV2CommonOutputs, normalizeChatV2Usage } from './chatV2Outputs.js';
|
|
11
11
|
import { materializeLLMResponse } from './llmResponseMaterializer.js';
|
|
12
12
|
/** Identifies legacy pipeline results that represent a terminal provider failure. */
|
|
13
13
|
export function isChatV2PipelineProviderFailureResult(result) {
|
|
@@ -64,6 +64,7 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
|
|
|
64
64
|
}
|
|
65
65
|
};
|
|
66
66
|
for (let attempt = 0;; attempt++) {
|
|
67
|
+
signal.throwIfAborted();
|
|
67
68
|
const callId = createObservedChatV2CallId(options);
|
|
68
69
|
const callStartedAt = Date.now();
|
|
69
70
|
let callWasObserved = false;
|
|
@@ -115,13 +116,16 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
|
|
|
115
116
|
const result = transportMode === 'generate'
|
|
116
117
|
? await generateChatV2(attemptChatOptions)
|
|
117
118
|
: await streamChatV2(attemptChatOptions);
|
|
119
|
+
signal.throwIfAborted();
|
|
118
120
|
await options.responseBodyCapture?.flush();
|
|
121
|
+
signal.throwIfAborted();
|
|
119
122
|
publishAndRetireResponseEvidence();
|
|
120
123
|
const statusCode = result.requestStatus ?? 200;
|
|
124
|
+
const statusSucceeded = statusCode >= 200 && statusCode < 300;
|
|
121
125
|
notifyChatV2CallFinished(options, {
|
|
122
126
|
callId,
|
|
123
127
|
attemptIndex: attempt,
|
|
124
|
-
outcome:
|
|
128
|
+
outcome: statusSucceeded ? 'success' : 'provider-failure',
|
|
125
129
|
result,
|
|
126
130
|
startedAt: callStartedAt,
|
|
127
131
|
durationMs: Math.max(0, Date.now() - callStartedAt),
|
|
@@ -129,16 +133,16 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
|
|
|
129
133
|
callWasObserved = true;
|
|
130
134
|
notifyProviderAttempt(options, {
|
|
131
135
|
attemptIndex: attempt,
|
|
132
|
-
outcome:
|
|
136
|
+
outcome: statusSucceeded ? 'success' : 'provider-failure',
|
|
133
137
|
status: statusCode,
|
|
134
|
-
...(
|
|
138
|
+
...(statusSucceeded ? {} : { error: buildNon200StatusError(statusCode) }),
|
|
135
139
|
});
|
|
136
140
|
if (!retryPlan.enabled || statusCode === 200) {
|
|
137
141
|
return { result };
|
|
138
142
|
}
|
|
139
143
|
const responseError = buildNon200StatusError(statusCode);
|
|
140
144
|
if (attempt >= retryPlan.repeatTimes) {
|
|
141
|
-
return { result, responseError };
|
|
145
|
+
return { result, ...(statusSucceeded ? {} : { responseError }) };
|
|
142
146
|
}
|
|
143
147
|
await prepareProviderRetry();
|
|
144
148
|
await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
|
|
@@ -172,7 +176,7 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
|
|
|
172
176
|
// The provider may reject concurrently with graph cancellation. The
|
|
173
177
|
// cancellation wins: it must neither retry nor masquerade as a
|
|
174
178
|
// provider failure to profile fallback and run activity.
|
|
175
|
-
throw createLLMChatV2RetryAbortError();
|
|
179
|
+
throw signal.reason ?? createLLMChatV2RetryAbortError();
|
|
176
180
|
}
|
|
177
181
|
if (isChatV2ProviderTimeoutError(error) || !retryPlan.enabled || statusCode == null || statusCode === 200) {
|
|
178
182
|
throw error;
|
|
@@ -322,7 +326,8 @@ export async function runChatV2PipelineExecution(options) {
|
|
|
322
326
|
providerMetadata: chatResponse.result.providerMetadata,
|
|
323
327
|
requestStatus,
|
|
324
328
|
};
|
|
325
|
-
const providerRoundFailure = chatResponse.responseError ??
|
|
329
|
+
const providerRoundFailure = chatResponse.responseError ??
|
|
330
|
+
(requestStatus >= 200 && requestStatus < 300 ? undefined : buildNon200StatusError(requestStatus));
|
|
326
331
|
if (providerRoundFailure != null) {
|
|
327
332
|
const rawError = providerRoundFailure;
|
|
328
333
|
return {
|
|
@@ -5,6 +5,7 @@ import { cleanHeaders, getInputOrData } from '../../utils/inputs.js';
|
|
|
5
5
|
import { cloneRivetStoredValue } from '../StoredValueStore.js';
|
|
6
6
|
import { resolveChatV2Credential } from './chatV2ProviderProfile.js';
|
|
7
7
|
import { applyLLMChatV2ParallelToolCallProviderOptions } from './parallelToolCalls.js';
|
|
8
|
+
import { normalizeTemperature } from './temperature.js';
|
|
8
9
|
export function resolveLLMChatV2Headers(data, inputs) {
|
|
9
10
|
const resolvedHeaders = data.useHeadersInput && inputs['headers'] != null
|
|
10
11
|
? coerceTypeOptional(inputs['headers'], 'object')
|
|
@@ -159,9 +160,26 @@ function resolveStopSequences(data, inputs) {
|
|
|
159
160
|
return normalizeStopSequences(stopSequences);
|
|
160
161
|
}
|
|
161
162
|
export function resolveLLMChatV2GenerationParameters(data, inputs) {
|
|
163
|
+
const temperatureInput = data.useTemperatureInput ? inputs['temperature'] : undefined;
|
|
164
|
+
let temperature;
|
|
165
|
+
if (temperatureInput != null) {
|
|
166
|
+
const resolved = temperatureInput.type === 'string'
|
|
167
|
+
? temperatureInput.value.trim() === ''
|
|
168
|
+
? undefined
|
|
169
|
+
: Number(temperatureInput.value)
|
|
170
|
+
: coerceTypeOptional(temperatureInput, 'number');
|
|
171
|
+
// A connected malformed input must not silently fall back to node data.
|
|
172
|
+
if (typeof resolved !== 'number' || !Number.isFinite(resolved)) {
|
|
173
|
+
throw new Error('Temperature input must be a finite number.');
|
|
174
|
+
}
|
|
175
|
+
temperature = resolved;
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
temperature = normalizeTemperature(data.temperature);
|
|
179
|
+
}
|
|
162
180
|
return {
|
|
163
181
|
maxTokens: getInputOrData(data, inputs, 'maxTokens', 'number'),
|
|
164
|
-
temperature
|
|
182
|
+
temperature,
|
|
165
183
|
topP: getInputOrData(data, inputs, 'topP', 'number'),
|
|
166
184
|
topK: getInputOrData(data, inputs, 'topK', 'number'),
|
|
167
185
|
presencePenalty: getInputOrData(data, inputs, 'presencePenalty', 'number'),
|
|
@@ -179,9 +179,10 @@ export function getCommonChatV2Editors(modelOptions) {
|
|
|
179
179
|
{
|
|
180
180
|
type: 'number',
|
|
181
181
|
label: 'Temperature',
|
|
182
|
-
helperMessage: '
|
|
182
|
+
helperMessage: 'Leave blank to use the provider default. Some reasoning models may ignore this setting.',
|
|
183
183
|
dataKey: 'temperature',
|
|
184
184
|
useInputToggleDataKey: 'useTemperatureInput',
|
|
185
|
+
allowEmpty: true,
|
|
185
186
|
min: 0,
|
|
186
187
|
max: 2,
|
|
187
188
|
step: 0.1,
|
|
@@ -47,7 +47,7 @@ function getOptionalNumberBodyField(label, value, usesInput) {
|
|
|
47
47
|
if (usesInput) {
|
|
48
48
|
return { label, value: '(Using Input)' };
|
|
49
49
|
}
|
|
50
|
-
return value
|
|
50
|
+
return value == null || !Number.isFinite(value) ? undefined : { label, value: `${value}` };
|
|
51
51
|
}
|
|
52
52
|
function getOptionalStringBodyField(label, value, usesInput) {
|
|
53
53
|
if (usesInput) {
|
|
@@ -177,15 +177,18 @@ function getBehaviorBodyFields(data) {
|
|
|
177
177
|
];
|
|
178
178
|
}
|
|
179
179
|
function getErrorBodyFields(data) {
|
|
180
|
-
if (!data.retryOnNon200) {
|
|
181
|
-
return [];
|
|
182
|
-
}
|
|
183
180
|
const repeatTimes = data.retryOnNon200RepeatTimes ?? DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES;
|
|
184
181
|
const cooldownMs = data.retryOnNon200CooldownMs ?? DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS;
|
|
185
182
|
return [
|
|
186
|
-
{ label: '
|
|
187
|
-
{ label: '
|
|
188
|
-
|
|
183
|
+
...(data.errorOnNon200 !== false ? [{ label: 'Throw on non-2XX', value: 'Enabled' }] : []),
|
|
184
|
+
...(data.catchRequestFailed ? [{ label: 'Catch all failures', value: 'Enabled' }] : []),
|
|
185
|
+
...(data.retryOnNon200
|
|
186
|
+
? [
|
|
187
|
+
{ label: 'Retry on non-200', value: 'Enabled' },
|
|
188
|
+
{ label: 'Repeat times', value: `${repeatTimes}` },
|
|
189
|
+
{ label: 'Cooldown, ms', value: `${cooldownMs}` },
|
|
190
|
+
]
|
|
191
|
+
: []),
|
|
189
192
|
];
|
|
190
193
|
}
|
|
191
194
|
function getAdvancedBodySection(data) {
|
|
@@ -241,7 +244,7 @@ function getParameterBodyFields(data) {
|
|
|
241
244
|
: undefined;
|
|
242
245
|
return [
|
|
243
246
|
...(reasoningEffort ? [{ label: 'Reasoning effort', value: reasoningEffort }] : []),
|
|
244
|
-
|
|
247
|
+
getOptionalNumberBodyField('Temperature', data.temperature, data.useTemperatureInput),
|
|
245
248
|
{ label: 'Max output tokens', value: data.useMaxTokensInput ? '(Using Input)' : `${data.maxTokens}` },
|
|
246
249
|
getOptionalNumberBodyField('Top P', data.topP, data.useTopPInput),
|
|
247
250
|
getOptionalNumberBodyField('Top K', data.topK, data.useTopKInput),
|
|
@@ -58,6 +58,8 @@ export function createLLMChatV2NodeData() {
|
|
|
58
58
|
autoContinueToolCalls: false,
|
|
59
59
|
maxToolRounds: 3,
|
|
60
60
|
retryOnNon200: false,
|
|
61
|
+
errorOnNon200: true,
|
|
62
|
+
catchRequestFailed: false,
|
|
61
63
|
retryOnNon200RepeatTimes: DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES,
|
|
62
64
|
retryOnNon200CooldownMs: DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS,
|
|
63
65
|
outputLLMAttempts: false,
|
|
@@ -252,9 +252,10 @@ function getParameterEditors() {
|
|
|
252
252
|
{
|
|
253
253
|
type: 'number',
|
|
254
254
|
label: 'Temperature',
|
|
255
|
-
helperMessage: '
|
|
255
|
+
helperMessage: 'Leave blank to use the provider default. Some reasoning models may ignore this setting.',
|
|
256
256
|
dataKey: 'temperature',
|
|
257
257
|
useInputToggleDataKey: 'useTemperatureInput',
|
|
258
|
+
allowEmpty: true,
|
|
258
259
|
min: 0,
|
|
259
260
|
max: 2,
|
|
260
261
|
step: 0.1,
|
|
@@ -559,6 +560,19 @@ function getProviderAdvancedEditors() {
|
|
|
559
560
|
}
|
|
560
561
|
function getErrorBehaviorEditors() {
|
|
561
562
|
return group('Error behavior', [
|
|
563
|
+
{
|
|
564
|
+
type: 'toggle',
|
|
565
|
+
label: 'Fail on non-2XX status code',
|
|
566
|
+
dataKey: 'errorOnNon200',
|
|
567
|
+
defaultValue: true,
|
|
568
|
+
helperMessage: 'After retries and profile fallback, throw on a rejected HTTP request. When disabled, return Run failed and Run error; unavailable response outputs are excluded.',
|
|
569
|
+
},
|
|
570
|
+
{
|
|
571
|
+
type: 'toggle',
|
|
572
|
+
label: 'Catch all failures',
|
|
573
|
+
dataKey: 'catchRequestFailed',
|
|
574
|
+
helperMessage: 'Return any node execution failure through Run failed and Run error instead of stopping the graph. Explicit graph cancellation is never caught.',
|
|
575
|
+
},
|
|
562
576
|
{
|
|
563
577
|
type: 'toggle',
|
|
564
578
|
label: 'Retry on non-200',
|
|
@@ -1,14 +1,34 @@
|
|
|
1
|
+
/** Repair legacy payloads on read or Save without mutating the supplied data. */
|
|
2
|
+
export function normalizeSerializedLLMTemperatureData(nodeType, data) {
|
|
3
|
+
if (!['llmChatV2', 'llmProfile'].includes(nodeType) || data == null || typeof data !== 'object')
|
|
4
|
+
return data;
|
|
5
|
+
const record = data;
|
|
6
|
+
if (!Object.hasOwn(record, 'temperature'))
|
|
7
|
+
return data;
|
|
8
|
+
if (record.temperature != null && !(typeof record.temperature === 'number' && Number.isNaN(record.temperature)))
|
|
9
|
+
return data;
|
|
10
|
+
const copy = { ...record };
|
|
11
|
+
delete copy.temperature;
|
|
12
|
+
return copy;
|
|
13
|
+
}
|
|
1
14
|
/**
|
|
2
|
-
* Serialized LLM Chat migrations live beside the node contract, rather than
|
|
15
|
+
* Serialized LLM Chat/Profile migrations live beside the node contract, rather than
|
|
3
16
|
* making generic project serialization understand LLM-specific settings.
|
|
4
17
|
* This is deliberately idempotent because deserialization can normalize a
|
|
5
18
|
* graph more than once while it is imported or embedded in a prefab.
|
|
6
19
|
*/
|
|
7
20
|
export function normalizeSerializedLLMChatV2Node(node) {
|
|
8
|
-
if (
|
|
21
|
+
if (!['llmChatV2', 'llmProfile'].includes(node.type))
|
|
9
22
|
return;
|
|
23
|
+
for (const variant of node.variants ?? []) {
|
|
24
|
+
variant.data = normalizeSerializedLLMTemperatureData(node.type, variant.data);
|
|
10
25
|
}
|
|
26
|
+
node.data = normalizeSerializedLLMTemperatureData(node.type, node.data);
|
|
27
|
+
if (node.data == null || typeof node.data !== 'object')
|
|
28
|
+
return;
|
|
11
29
|
const data = node.data;
|
|
30
|
+
if (node.type !== 'llmChatV2')
|
|
31
|
+
return;
|
|
12
32
|
const hadLegacyRequestDiagnostics = data.outputRequestStatus === true || data.outputRequestError === true;
|
|
13
33
|
if (hadLegacyRequestDiagnostics && !Object.hasOwn(data, 'outputLLMAttempts')) {
|
|
14
34
|
data.outputLLMAttempts = true;
|
|
@@ -4,6 +4,7 @@ import { llmProfileBooleanDataKeys, llmProfileOptionalNumberDataKeys, llmProfile
|
|
|
4
4
|
import { LLM_PROFILE_VALUE_VERSION, pickLLMChatV2ProfileData } from './llmProfileTypes.js';
|
|
5
5
|
import { createRivetLLMProfileHealthIdentity } from './llmProfileHealthStore.js';
|
|
6
6
|
import { normalizeChatV2CredentialNamesByProvider } from './chatV2CredentialNames.js';
|
|
7
|
+
import { normalizeTemperature } from './temperature.js';
|
|
7
8
|
export { applyLLMProfileToNodeData, createDefaultLLMProfileValue, createLLMProfileNodeData, LLM_PROFILE_VALUE_VERSION, pickLLMChatV2ProfileData, } from './llmProfileTypes.js';
|
|
8
9
|
const credentialSources = new Set([
|
|
9
10
|
'input',
|
|
@@ -34,6 +35,8 @@ export function normalizeLLMProfileValue(value) {
|
|
|
34
35
|
const configuration = normalizeConfiguration({
|
|
35
36
|
...defaults,
|
|
36
37
|
...value.configuration,
|
|
38
|
+
// Defaults seed new nodes, not missing values in an existing profile.
|
|
39
|
+
temperature: normalizeTemperature(value.configuration.temperature, 'LLM Profile temperature'),
|
|
37
40
|
provider,
|
|
38
41
|
model: model.trim(),
|
|
39
42
|
});
|
|
@@ -9,7 +9,7 @@ function getOptionalNumberBodyField(label, value, usesInput) {
|
|
|
9
9
|
if (usesInput) {
|
|
10
10
|
return { label, value: '(Using Input)' };
|
|
11
11
|
}
|
|
12
|
-
return value
|
|
12
|
+
return value == null || !Number.isFinite(value) ? undefined : { label, value: `${value}` };
|
|
13
13
|
}
|
|
14
14
|
function getOptionalStringBodyField(label, value, usesInput) {
|
|
15
15
|
if (usesInput) {
|
|
@@ -159,7 +159,7 @@ export function getLLMProfileBodySections(data) {
|
|
|
159
159
|
: []),
|
|
160
160
|
];
|
|
161
161
|
const parameterFields = [
|
|
162
|
-
|
|
162
|
+
getOptionalNumberBodyField('Temperature', data.temperature, data.useTemperatureInput),
|
|
163
163
|
{ label: 'Max output tokens', value: data.useMaxTokensInput ? '(Using Input)' : `${data.maxTokens}` },
|
|
164
164
|
getOptionalNumberBodyField('Top P', data.topP, data.useTopPInput),
|
|
165
165
|
getOptionalNumberBodyField('Top K', data.topK, data.useTopKInput),
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export const llmProfileFieldSpecs = [
|
|
2
2
|
{ key: 'model', inputId: 'model', valueKind: 'string' },
|
|
3
3
|
{ key: 'useModelInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
4
|
-
{ key: 'temperature', inputId: 'temperature', valueKind: '
|
|
4
|
+
{ key: 'temperature', inputId: 'temperature', valueKind: 'optional-number' },
|
|
5
5
|
{ key: 'useTemperatureInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
6
6
|
{ key: 'topP', inputId: 'topP', valueKind: 'optional-number' },
|
|
7
7
|
{ key: 'useTopPInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
@@ -41,7 +41,7 @@ export function resolveLLMProfileNodeValue(params) {
|
|
|
41
41
|
...data,
|
|
42
42
|
model,
|
|
43
43
|
useModelInput: false,
|
|
44
|
-
temperature: generation.temperature
|
|
44
|
+
temperature: generation.temperature,
|
|
45
45
|
useTemperatureInput: false,
|
|
46
46
|
maxTokens: generation.maxTokens ?? data.maxTokens,
|
|
47
47
|
useMaxTokensInput: false,
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Empty historical editor values are unset, never the provider's explicit zero. */
|
|
2
|
+
export function normalizeTemperature(value, label = 'Temperature') {
|
|
3
|
+
if (value == null || (typeof value === 'number' && Number.isNaN(value)))
|
|
4
|
+
return undefined;
|
|
5
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
6
|
+
throw new Error(`${label} must be a finite number when provided.`);
|
|
7
|
+
}
|
|
8
|
+
return value;
|
|
9
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { coerceTypeOptional } from '../../utils/coerceType.js';
|
|
2
|
+
import { classifierDataProperty, classifierInputDataValue } from './json.js';
|
|
3
|
+
export const JEV_DEFAULT_CREDENTIAL_NAMES = {
|
|
4
|
+
programmaticName: 'typesafeApiKey',
|
|
5
|
+
environmentVariableName: 'TYPESAFE_API_KEY',
|
|
6
|
+
};
|
|
7
|
+
export const LIQUID_DEFAULT_CREDENTIAL_NAMES = {
|
|
8
|
+
programmaticName: 'liquidApiKey',
|
|
9
|
+
environmentVariableName: 'LIQUID_API_KEY',
|
|
10
|
+
};
|
|
11
|
+
export const OPENAI_DEFAULT_CREDENTIAL_NAMES = {
|
|
12
|
+
programmaticName: 'openAiApiKey',
|
|
13
|
+
environmentVariableName: 'OPENAI_API_KEY',
|
|
14
|
+
};
|
|
15
|
+
const programmaticNamePattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
16
|
+
const environmentVariableNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
17
|
+
export function isValidClassifierProgrammaticCredentialName(name) {
|
|
18
|
+
return programmaticNamePattern.test(name);
|
|
19
|
+
}
|
|
20
|
+
export function isValidClassifierEnvironmentCredentialName(name) {
|
|
21
|
+
return environmentVariableNamePattern.test(name);
|
|
22
|
+
}
|
|
23
|
+
export function normalizeClassifierCredentialNames(value, defaults = JEV_DEFAULT_CREDENTIAL_NAMES) {
|
|
24
|
+
if (value != null && (typeof value !== 'object' || Array.isArray(value))) {
|
|
25
|
+
throw new Error('Classifier API key names must be an object.');
|
|
26
|
+
}
|
|
27
|
+
const raw = value;
|
|
28
|
+
if (raw?.programmaticName != null && typeof raw.programmaticName !== 'string') {
|
|
29
|
+
throw new Error('Classifier programmatic API key name must be a string.');
|
|
30
|
+
}
|
|
31
|
+
if (raw?.environmentVariableName != null && typeof raw.environmentVariableName !== 'string') {
|
|
32
|
+
throw new Error('Classifier API key environment variable must be a string.');
|
|
33
|
+
}
|
|
34
|
+
const programmaticName = raw?.programmaticName?.trim() || defaults.programmaticName;
|
|
35
|
+
const environmentVariableName = raw?.environmentVariableName?.trim() || defaults.environmentVariableName;
|
|
36
|
+
if (!isValidClassifierProgrammaticCredentialName(programmaticName)) {
|
|
37
|
+
throw new Error('Classifier programmatic API key name must be a JavaScript-style identifier without a leading digit.');
|
|
38
|
+
}
|
|
39
|
+
if (!isValidClassifierEnvironmentCredentialName(environmentVariableName)) {
|
|
40
|
+
throw new Error('Classifier API key environment variable must contain letters, digits, and _ without a leading digit.');
|
|
41
|
+
}
|
|
42
|
+
return { programmaticName, environmentVariableName };
|
|
43
|
+
}
|
|
44
|
+
export function getClassifierCredentialNamesForDisplay(value, defaults = JEV_DEFAULT_CREDENTIAL_NAMES) {
|
|
45
|
+
try {
|
|
46
|
+
return normalizeClassifierCredentialNames(value, defaults);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return { ...defaults };
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export function isDefaultClassifierCredentialNames(names, defaults = JEV_DEFAULT_CREDENTIAL_NAMES) {
|
|
53
|
+
return (names.programmaticName === defaults.programmaticName &&
|
|
54
|
+
names.environmentVariableName === defaults.environmentVariableName);
|
|
55
|
+
}
|
|
56
|
+
export function resolveClassifierApiKey({ apiKeyNames, apiKeySource, context, defaults, inputs, providerId, }) {
|
|
57
|
+
if (apiKeySource === 'classifier-settings') {
|
|
58
|
+
const read = (value, key) => value !== null && typeof value === 'object'
|
|
59
|
+
? classifierDataProperty(value, key, 'Classifier settings credentials')
|
|
60
|
+
: undefined;
|
|
61
|
+
const saved = getNonEmptyString(read(read(read(context.settings, 'classifierProviders'), providerId), 'apiKey'));
|
|
62
|
+
if (!saved)
|
|
63
|
+
throw new Error(`Classifier settings API key for ${providerId} is not set. No automatic fallback is used.`);
|
|
64
|
+
return saved;
|
|
65
|
+
}
|
|
66
|
+
if (apiKeySource === 'input') {
|
|
67
|
+
const value = coerceTypeOptional(classifierInputDataValue(inputs, 'apiKey'), 'string')?.trim();
|
|
68
|
+
if (!value)
|
|
69
|
+
throw new Error('API Key input is required when API key source is Input port.');
|
|
70
|
+
return value;
|
|
71
|
+
}
|
|
72
|
+
if (apiKeySource !== undefined && apiKeySource !== 'configured')
|
|
73
|
+
throw new Error('Unknown classifier API key source.');
|
|
74
|
+
const names = normalizeClassifierCredentialNames(apiKeyNames, defaults);
|
|
75
|
+
const namedValue = resolveNamedClassifierApiKey(context, names, providerId === 'openai' && isDefaultClassifierCredentialNames(names, defaults));
|
|
76
|
+
if (namedValue)
|
|
77
|
+
return namedValue;
|
|
78
|
+
if (isDefaultClassifierCredentialNames(names, defaults)) {
|
|
79
|
+
const firstPartyValue = getNonEmptyString(context.settings.classifierProviders?.[providerId]?.apiKey);
|
|
80
|
+
if (firstPartyValue)
|
|
81
|
+
return firstPartyValue;
|
|
82
|
+
// Compatibility only: old applications stored the key under the removed plugin.
|
|
83
|
+
if (providerId === 'jev') {
|
|
84
|
+
const legacyValue = getNonEmptyString(context.settings.pluginSettings?.typesafe?.typesafeApiKey);
|
|
85
|
+
if (legacyValue)
|
|
86
|
+
return legacyValue;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
throw new Error(`${providerId === 'jev' ? 'Jev' : 'Classifier'} API key is not set. Pass ${names.programmaticName}, configure ${names.environmentVariableName}, or set the configured key in Settings > Classifier.`);
|
|
90
|
+
}
|
|
91
|
+
function resolveNamedClassifierApiKey(context, names, useLegacyOpenAIKey = false) {
|
|
92
|
+
const programmaticValue = getNonEmptyString(context.settings?.[names.programmaticName]);
|
|
93
|
+
if (programmaticValue)
|
|
94
|
+
return programmaticValue;
|
|
95
|
+
if (useLegacyOpenAIKey) {
|
|
96
|
+
const legacy = getNonEmptyString(context.settings.openAiKey);
|
|
97
|
+
if (legacy)
|
|
98
|
+
return legacy;
|
|
99
|
+
}
|
|
100
|
+
const environmentValue = getNonEmptyString(context.settings?.pluginEnv?.[names.environmentVariableName]);
|
|
101
|
+
if (environmentValue)
|
|
102
|
+
return environmentValue;
|
|
103
|
+
return getNonEmptyString(globalThis.process?.env?.[names.environmentVariableName]);
|
|
104
|
+
}
|
|
105
|
+
function getNonEmptyString(value) {
|
|
106
|
+
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
|
|
107
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { base64ToUint8Array, uint8ArrayToBase64Sync } from '../../utils/base64.js';
|
|
2
|
+
import { classifierDataProperty } from './json.js';
|
|
3
|
+
import { assertClassifierResourceLimits, classifierByteView, CLASSIFIER_LIMITS, } from './limits.js';
|
|
4
|
+
class InvalidClassifierImageError extends Error {
|
|
5
|
+
}
|
|
6
|
+
const invalidImage = () => new InvalidClassifierImageError('State images must contain inline base64 PNG, JPEG, GIF or WebP image data with valid headers and matching media type.');
|
|
7
|
+
function isBase64(value) {
|
|
8
|
+
// Avoid repeated regexp groups: they overflow the regexp stack on large images.
|
|
9
|
+
return value.length > 0 && value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value);
|
|
10
|
+
}
|
|
11
|
+
function jpegInfo(size, read, check) {
|
|
12
|
+
const byte = (offset) => read(offset, 1)[0];
|
|
13
|
+
const uint16 = (offset) => {
|
|
14
|
+
const bytes = read(offset, 2);
|
|
15
|
+
return (bytes[0] << 8) + bytes[1];
|
|
16
|
+
};
|
|
17
|
+
let offset = 2;
|
|
18
|
+
while (offset + 4 <= size) {
|
|
19
|
+
check?.();
|
|
20
|
+
if (byte(offset++) !== 0xff)
|
|
21
|
+
break;
|
|
22
|
+
while (byte(offset) === 0xff) {
|
|
23
|
+
if ((offset & 4095) === 0)
|
|
24
|
+
check?.();
|
|
25
|
+
offset++;
|
|
26
|
+
}
|
|
27
|
+
const marker = byte(offset++);
|
|
28
|
+
if (marker === undefined || marker === 0xda || marker === 0xd9)
|
|
29
|
+
break;
|
|
30
|
+
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7))
|
|
31
|
+
continue;
|
|
32
|
+
if (offset + 2 > size)
|
|
33
|
+
break;
|
|
34
|
+
const length = uint16(offset);
|
|
35
|
+
if (length < 2 || offset + length > size)
|
|
36
|
+
break;
|
|
37
|
+
if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker) && length >= 8)
|
|
38
|
+
return { mediaType: 'image/jpeg', width: uint16(offset + 5), height: uint16(offset + 3) };
|
|
39
|
+
offset += length;
|
|
40
|
+
}
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
/** Read image headers without a browser, filesystem access, or a decoder dependency. */
|
|
44
|
+
function imageInfo(bytes, check) {
|
|
45
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
46
|
+
const ascii = (offset, length) => String.fromCharCode(...bytes.subarray(offset, offset + length));
|
|
47
|
+
let info;
|
|
48
|
+
if (bytes.length >= 33 &&
|
|
49
|
+
ascii(0, 8) === '\x89PNG\r\n\x1a\n' &&
|
|
50
|
+
view.getUint32(8) === 13 &&
|
|
51
|
+
ascii(12, 4) === 'IHDR') {
|
|
52
|
+
info = { mediaType: 'image/png', width: view.getUint32(16), height: view.getUint32(20) };
|
|
53
|
+
}
|
|
54
|
+
else if (bytes.length >= 13 && ['GIF87a', 'GIF89a'].includes(ascii(0, 6))) {
|
|
55
|
+
info = { mediaType: 'image/gif', width: view.getUint16(6, true), height: view.getUint16(8, true) };
|
|
56
|
+
}
|
|
57
|
+
else if (bytes.length >= 25 && ascii(0, 4) === 'RIFF' && ascii(8, 4) === 'WEBP') {
|
|
58
|
+
const chunk = ascii(12, 4);
|
|
59
|
+
const uint24 = (offset) => bytes[offset] + (bytes[offset + 1] << 8) + (bytes[offset + 2] << 16);
|
|
60
|
+
if (chunk === 'VP8X' && bytes.length >= 30)
|
|
61
|
+
info = { mediaType: 'image/webp', width: uint24(24) + 1, height: uint24(27) + 1 };
|
|
62
|
+
else if (chunk === 'VP8 ' && bytes.length >= 30 && ascii(23, 3) === '\x9d\x01\x2a')
|
|
63
|
+
info = {
|
|
64
|
+
mediaType: 'image/webp',
|
|
65
|
+
width: view.getUint16(26, true) & 0x3fff,
|
|
66
|
+
height: view.getUint16(28, true) & 0x3fff,
|
|
67
|
+
};
|
|
68
|
+
else if (chunk === 'VP8L' && bytes[20] === 0x2f) {
|
|
69
|
+
const bits = view.getUint32(21, true);
|
|
70
|
+
info = { mediaType: 'image/webp', width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
else if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {
|
|
74
|
+
info = jpegInfo(bytes.length, (offset, length) => bytes.subarray(offset, offset + length), check);
|
|
75
|
+
}
|
|
76
|
+
if (!info || info.width === 0 || info.height === 0)
|
|
77
|
+
throw invalidImage();
|
|
78
|
+
return info;
|
|
79
|
+
}
|
|
80
|
+
function base64ImageInfo(payload, check) {
|
|
81
|
+
// JPEG metadata may precede its dimensions. Skip segment bodies and decode
|
|
82
|
+
// only the byte windows needed by the same parser used for native images.
|
|
83
|
+
if (payload.startsWith('/9j/')) {
|
|
84
|
+
const size = (payload.length / 4) * 3 - (payload.endsWith('==') ? 2 : payload.endsWith('=') ? 1 : 0);
|
|
85
|
+
let start = -1;
|
|
86
|
+
let window = new Uint8Array();
|
|
87
|
+
const info = jpegInfo(size, (offset, length) => {
|
|
88
|
+
if (offset < start || offset + length > start + window.length) {
|
|
89
|
+
start = Math.floor(offset / 3) * 3;
|
|
90
|
+
// A small cache also bounds decoder calls for runs of JPEG fill bytes.
|
|
91
|
+
window = base64ToUint8Array(payload.slice((start / 3) * 4, (start / 3) * 4 + 4096));
|
|
92
|
+
}
|
|
93
|
+
return window.subarray(offset - start, offset - start + length);
|
|
94
|
+
}, check);
|
|
95
|
+
if (!info || info.width === 0 || info.height === 0)
|
|
96
|
+
throw invalidImage();
|
|
97
|
+
return info;
|
|
98
|
+
}
|
|
99
|
+
// PNG/GIF/WebP dimensions are in the first 36 bytes.
|
|
100
|
+
return imageInfo(base64ToUint8Array(payload.slice(0, 48)));
|
|
101
|
+
}
|
|
102
|
+
export function prepareNativeClassifierImage(value, check) {
|
|
103
|
+
if (!value || typeof value !== 'object')
|
|
104
|
+
throw invalidImage();
|
|
105
|
+
const data = classifierDataProperty(value, 'data');
|
|
106
|
+
const mediaType = classifierDataProperty(value, 'mediaType');
|
|
107
|
+
if (!(data instanceof Uint8Array))
|
|
108
|
+
throw invalidImage();
|
|
109
|
+
const bytes = classifierByteView(data);
|
|
110
|
+
assertClassifierResourceLimits(bytes, check);
|
|
111
|
+
const info = imageInfo(bytes, check);
|
|
112
|
+
if (info.mediaType !== mediaType)
|
|
113
|
+
throw invalidImage();
|
|
114
|
+
check?.();
|
|
115
|
+
return { ...info, dataUrl: `data:${info.mediaType};base64,${uint8ArrayToBase64Sync(bytes)}` };
|
|
116
|
+
}
|
|
117
|
+
export function nativeClassifierImage(value, check) {
|
|
118
|
+
return prepareNativeClassifierImage(value, check).dataUrl;
|
|
119
|
+
}
|
|
120
|
+
export function inspectClassifierImage(value, check) {
|
|
121
|
+
check?.();
|
|
122
|
+
if (typeof value !== 'string')
|
|
123
|
+
throw invalidImage();
|
|
124
|
+
const prefix = /^data:(image\/(?:png|jpeg|gif|webp));base64,/.exec(value);
|
|
125
|
+
if (!prefix)
|
|
126
|
+
throw invalidImage();
|
|
127
|
+
const payload = value.slice(prefix[0].length);
|
|
128
|
+
if (!isBase64(payload))
|
|
129
|
+
throw invalidImage();
|
|
130
|
+
const info = base64ImageInfo(payload, check);
|
|
131
|
+
if (info.mediaType !== prefix[1])
|
|
132
|
+
throw invalidImage();
|
|
133
|
+
return info;
|
|
134
|
+
}
|
|
135
|
+
/** Recognize image bytes, not merely strings using the base64 alphabet. */
|
|
136
|
+
export function classifierImageFromText(value, check) {
|
|
137
|
+
return prepareClassifierImageText(value, check)?.dataUrl;
|
|
138
|
+
}
|
|
139
|
+
export function prepareClassifierImageText(value, check) {
|
|
140
|
+
check?.();
|
|
141
|
+
if (value.length > CLASSIFIER_LIMITS.requestBytes)
|
|
142
|
+
throw new Error('Classifier image/text exceeds the 32 MiB input limit.');
|
|
143
|
+
if (value.startsWith('data:image/')) {
|
|
144
|
+
return { ...inspectClassifierImage(value, check), dataUrl: value };
|
|
145
|
+
}
|
|
146
|
+
if (!/^(?:iVBOR|\/9j\/|R0lGOD|UklGR)/.test(value) || !isBase64(value))
|
|
147
|
+
return undefined;
|
|
148
|
+
try {
|
|
149
|
+
const info = base64ImageInfo(value, check);
|
|
150
|
+
return { ...info, dataUrl: `data:${info.mediaType};base64,${value}` };
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
if (error instanceof InvalidClassifierImageError)
|
|
154
|
+
return undefined;
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
export function assertClassifierImages(value, check) {
|
|
159
|
+
if (!Array.isArray(value) || value.length > 128)
|
|
160
|
+
throw new Error('State must contain at most 128 images.');
|
|
161
|
+
for (const image of value)
|
|
162
|
+
inspectClassifierImage(image, check);
|
|
163
|
+
}
|
|
164
|
+
export function assertLiquidImageLimits(images, check) {
|
|
165
|
+
if (images.length > 8)
|
|
166
|
+
throw new Error('Liquid d1 State must contain at most 8 images.');
|
|
167
|
+
let patches = 0;
|
|
168
|
+
for (const { width, height } of images) {
|
|
169
|
+
check?.();
|
|
170
|
+
if (Math.max(width, height) / Math.min(width, height) > 100)
|
|
171
|
+
throw new Error('Liquid d1 images must have an aspect ratio at most 100:1.');
|
|
172
|
+
patches += Math.ceil(width / 32) * Math.ceil(height / 32);
|
|
173
|
+
}
|
|
174
|
+
if (patches > 10_000)
|
|
175
|
+
throw new Error('Liquid d1 images must contain at most 10,000 patches of 32 by 32 pixels in total.');
|
|
176
|
+
}
|