@valerypopoff/rivet2-core 2.1.10 → 2.3.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/README.md +1 -1
- package/dist/cjs/bundle.cjs +2101 -867
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/webAppRuntime.cjs +37 -3
- package/dist/cjs/webAppRuntime.cjs.map +2 -2
- package/dist/esm/api/createProcessor.js +2 -0
- package/dist/esm/integrations/CodeRunner.js +2 -7
- package/dist/esm/integrations/CodeRunnerOptions.js +7 -0
- package/dist/esm/model/AgentResponseTrace.js +121 -11
- package/dist/esm/model/GraphProcessor.js +14 -0
- package/dist/esm/model/RecordingPlayer.js +50 -5
- package/dist/esm/model/SubprocessorBridge.js +1 -0
- package/dist/esm/model/UiGraphActionProtocol.js +1 -0
- package/dist/esm/model/chat-v2/aiSdkBridge.js +146 -14
- package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -0
- package/dist/esm/model/chat-v2/chatV2CredentialNames.js +93 -0
- package/dist/esm/model/chat-v2/chatV2EditorCache.js +6 -5
- package/dist/esm/model/chat-v2/chatV2Pipeline.js +41 -4
- package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +31 -2
- package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +10 -2
- package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -11
- package/dist/esm/model/chat-v2/chatV2Shared.js +1 -1
- package/dist/esm/model/chat-v2/chatV2Types.js +16 -0
- package/dist/esm/model/chat-v2/customProviderApi.js +0 -2
- package/dist/esm/model/chat-v2/index.js +3 -0
- package/dist/esm/model/chat-v2/llmChatV2Body.js +9 -1
- package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +5 -0
- package/dist/esm/model/chat-v2/llmChatV2NodeData.js +7 -0
- package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +95 -14
- package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +32 -9
- package/dist/esm/model/chat-v2/llmModelCandidate.js +5 -1
- package/dist/esm/model/chat-v2/llmProfile.js +42 -0
- package/dist/esm/model/chat-v2/llmProfileBody.js +10 -0
- package/dist/esm/model/chat-v2/llmProfileFallback.js +390 -4
- package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +7 -0
- package/dist/esm/model/chat-v2/llmProfileHealthStore.js +326 -0
- package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +53 -34
- package/dist/esm/model/chat-v2/providerOptions.js +33 -7
- package/dist/esm/model/nodes/CodeNewNode.js +5 -47
- package/dist/esm/model/nodes/CodeNode.js +4 -46
- package/dist/esm/model/nodes/ExpressionNode.js +5 -8
- package/dist/esm/model/nodes/LLMChatV2Node.js +10 -1
- package/dist/esm/model/nodes/MatchNode.js +86 -41
- package/dist/esm/plugins/gentrace/gentraceSdk.js +0 -1
- package/dist/esm/plugins/gentrace/index.js +0 -1
- package/dist/esm/plugins/gentrace/plugin.js +61 -179
- package/dist/esm/plugins.js +1 -2
- package/dist/esm/recording/ExecutionRecorder.js +49 -8
- package/dist/types/api/createProcessor.d.ts +3 -0
- package/dist/types/integrations/CodeRunner.d.ts +10 -7
- package/dist/types/integrations/CodeRunnerOptions.d.ts +15 -0
- package/dist/types/model/AgentResponseTrace.d.ts +14 -1
- package/dist/types/model/EditorDefinition.d.ts +16 -0
- package/dist/types/model/ExecutorProtocol.d.ts +9 -6
- package/dist/types/model/GraphProcessor.d.ts +15 -5
- package/dist/types/model/NodeBase.d.ts +0 -10
- package/dist/types/model/Nodes.d.ts +2 -2
- package/dist/types/model/ProcessContext.d.ts +52 -0
- package/dist/types/model/UiGraphActionProtocol.d.ts +1 -0
- package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +30 -0
- package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +1 -0
- package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +3 -0
- package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +8 -2
- package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +3 -8
- package/dist/types/model/chat-v2/chatV2Types.d.ts +24 -0
- package/dist/types/model/chat-v2/customProviderApi.d.ts +0 -1
- package/dist/types/model/chat-v2/index.d.ts +3 -0
- package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +1 -1
- package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +10 -1
- package/dist/types/model/chat-v2/llmModelCandidate.d.ts +2 -0
- package/dist/types/model/chat-v2/llmProfile.d.ts +14 -0
- package/dist/types/model/chat-v2/llmProfileBody.d.ts +1 -1
- package/dist/types/model/chat-v2/llmProfileFallback.d.ts +21 -2
- package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +26 -6
- package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +111 -0
- package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +1 -1
- package/dist/types/model/chat-v2/llmProfileTypes.d.ts +3 -0
- package/dist/types/model/chat-v2/providerOptions.d.ts +2 -0
- package/dist/types/model/nodes/CodeNewNode.d.ts +0 -5
- package/dist/types/model/nodes/CodeNode.d.ts +0 -5
- package/dist/types/model/nodes/MatchNode.d.ts +6 -0
- package/dist/types/plugins/gentrace/gentraceSdk.d.ts +0 -1
- package/dist/types/plugins/gentrace/plugin.d.ts +55 -9
- package/dist/types/plugins.d.ts +1 -1
- package/dist/types/recording/ExecutionRecorder.d.ts +7 -1
- package/package.json +2 -2
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { generateText, NoObjectGeneratedError, streamText } from 'ai';
|
|
2
2
|
import { consumeAiSdkStream } from '../chat/aiSdkStreaming.js';
|
|
3
|
+
import { ChatV2ProviderTimeoutError } from './chatV2Types.js';
|
|
3
4
|
import { isChatV2StructuredResponseFormat } from './chatV2ResponseFormat.js';
|
|
4
5
|
function keepPromiseHandled(value) {
|
|
5
6
|
const promise = Promise.resolve(value);
|
|
@@ -153,6 +154,109 @@ function buildTextArgs(options) {
|
|
|
153
154
|
args.abortSignal = options.abortSignal;
|
|
154
155
|
return args;
|
|
155
156
|
}
|
|
157
|
+
function isUsefulStreamPart(part) {
|
|
158
|
+
const event = part;
|
|
159
|
+
if (event?.type === 'tool-call')
|
|
160
|
+
return true;
|
|
161
|
+
if (event?.type === 'text-delta' || event?.type === 'reasoning-delta') {
|
|
162
|
+
return typeof event.text === 'string' && event.text.length > 0;
|
|
163
|
+
}
|
|
164
|
+
if (event?.type === 'tool-input-delta') {
|
|
165
|
+
return typeof event.delta === 'string' && event.delta.length > 0;
|
|
166
|
+
}
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
function timeoutPromise(timeoutMs, kind, onTimeout) {
|
|
170
|
+
let timer;
|
|
171
|
+
const promise = new Promise((_resolve, reject) => {
|
|
172
|
+
timer = setTimeout(() => {
|
|
173
|
+
const error = new ChatV2ProviderTimeoutError(kind, timeoutMs);
|
|
174
|
+
reject(error);
|
|
175
|
+
try {
|
|
176
|
+
onTimeout?.(error);
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
// Timeout notification is cleanup-only and cannot replace the deadline.
|
|
180
|
+
}
|
|
181
|
+
}, timeoutMs);
|
|
182
|
+
});
|
|
183
|
+
return {
|
|
184
|
+
promise,
|
|
185
|
+
cancel: () => {
|
|
186
|
+
if (timer != null)
|
|
187
|
+
clearTimeout(timer);
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
async function* streamWithDeadlines(stream, options, firstOutputStartedAt) {
|
|
192
|
+
const iterator = stream[Symbol.asyncIterator]();
|
|
193
|
+
let hasUsefulOutput = false;
|
|
194
|
+
let lastUsefulOutputAt = firstOutputStartedAt;
|
|
195
|
+
try {
|
|
196
|
+
for (;;) {
|
|
197
|
+
const kind = hasUsefulOutput ? 'stream-inactivity' : 'first-output';
|
|
198
|
+
const configuredTimeout = hasUsefulOutput ? options.streamInactivityTimeoutMs : options.firstOutputTimeoutMs;
|
|
199
|
+
const timeoutMs = configuredTimeout == null
|
|
200
|
+
? undefined
|
|
201
|
+
: Math.max(1, configuredTimeout - (Date.now() - lastUsefulOutputAt));
|
|
202
|
+
const timeout = timeoutMs == null ? undefined : timeoutPromise(timeoutMs, kind, options.onTimeout);
|
|
203
|
+
let next;
|
|
204
|
+
try {
|
|
205
|
+
next = await (timeout == null ? iterator.next() : Promise.race([iterator.next(), timeout.promise]));
|
|
206
|
+
}
|
|
207
|
+
finally {
|
|
208
|
+
timeout?.cancel();
|
|
209
|
+
}
|
|
210
|
+
if (next.done)
|
|
211
|
+
return;
|
|
212
|
+
if (isUsefulStreamPart(next.value)) {
|
|
213
|
+
hasUsefulOutput = true;
|
|
214
|
+
lastUsefulOutputAt = Date.now();
|
|
215
|
+
try {
|
|
216
|
+
options.onStreamActivity?.();
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
// Health lease renewal is observational and cannot break the stream.
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
yield next.value;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
finally {
|
|
226
|
+
try {
|
|
227
|
+
const cleanup = iterator.return?.();
|
|
228
|
+
if (cleanup != null) {
|
|
229
|
+
void Promise.resolve(cleanup).catch(() => undefined);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
// The deadline/consumer error remains authoritative over iterator cleanup.
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
async function waitForGeneratedResponse(executorPromise, options) {
|
|
238
|
+
if (options.firstOutputTimeoutMs == null)
|
|
239
|
+
return await executorPromise;
|
|
240
|
+
const timeout = timeoutPromise(options.firstOutputTimeoutMs, 'first-output', options.onTimeout);
|
|
241
|
+
try {
|
|
242
|
+
return await Promise.race([executorPromise, timeout.promise]);
|
|
243
|
+
}
|
|
244
|
+
finally {
|
|
245
|
+
timeout.cancel();
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
async function waitForPostResponseFinalization(finalization, options) {
|
|
249
|
+
const timeoutMs = options.streamInactivityTimeoutMs ?? options.firstOutputTimeoutMs;
|
|
250
|
+
if (timeoutMs == null)
|
|
251
|
+
return await finalization;
|
|
252
|
+
const timeout = timeoutPromise(timeoutMs, options.streamInactivityTimeoutMs == null ? 'first-output' : 'stream-inactivity', options.onTimeout);
|
|
253
|
+
try {
|
|
254
|
+
return await Promise.race([finalization, timeout.promise]);
|
|
255
|
+
}
|
|
256
|
+
finally {
|
|
257
|
+
timeout.cancel();
|
|
258
|
+
}
|
|
259
|
+
}
|
|
156
260
|
function toStreamedFunctionCalls(toolCalls) {
|
|
157
261
|
return (toolCalls ?? []).map((toolCall) => ({
|
|
158
262
|
type: 'function',
|
|
@@ -171,14 +275,25 @@ async function resolveGenerateReasoning(result) {
|
|
|
171
275
|
}
|
|
172
276
|
async function executeStream(options, executor) {
|
|
173
277
|
const args = buildTextArgs(options);
|
|
174
|
-
const
|
|
278
|
+
const firstOutputStartedAt = Date.now();
|
|
279
|
+
const handlePromise = Promise.resolve(executor(args));
|
|
280
|
+
const handleTimeout = options.firstOutputTimeoutMs == null
|
|
281
|
+
? undefined
|
|
282
|
+
: timeoutPromise(options.firstOutputTimeoutMs, 'first-output', options.onTimeout);
|
|
283
|
+
let handle;
|
|
284
|
+
try {
|
|
285
|
+
handle = await (handleTimeout == null ? handlePromise : Promise.race([handlePromise, handleTimeout.promise]));
|
|
286
|
+
}
|
|
287
|
+
finally {
|
|
288
|
+
handleTimeout?.cancel();
|
|
289
|
+
}
|
|
175
290
|
markOptionalPromiseHandled(handle.finishReason);
|
|
176
291
|
markOptionalPromiseHandled(handle.output);
|
|
177
292
|
markOptionalPromiseHandled(handle.providerMetadata);
|
|
178
293
|
markOptionalPromiseHandled(handle.requestStatus);
|
|
179
294
|
markOptionalPromiseHandled(handle.usage);
|
|
180
295
|
const isStructuredOutput = isChatV2StructuredResponseFormat(options.responseFormat);
|
|
181
|
-
const streamed = await consumeAiSdkStream(handle.fullStream, (text, functionCalls) => {
|
|
296
|
+
const streamed = await consumeAiSdkStream(streamWithDeadlines(handle.fullStream, options, firstOutputStartedAt), (text, functionCalls) => {
|
|
182
297
|
options.onPartialOutput?.({
|
|
183
298
|
text: isStructuredOutput ? collapseRepeatedStructuredJsonText(text) : text,
|
|
184
299
|
functionCalls,
|
|
@@ -189,15 +304,22 @@ async function executeStream(options, executor) {
|
|
|
189
304
|
const responseText = isStructuredOutput
|
|
190
305
|
? collapseRepeatedStructuredJsonText(streamed.responseText)
|
|
191
306
|
: streamed.responseText;
|
|
307
|
+
const [structuredOutput, usage, finishReason, providerMetadata, requestStatus] = await waitForPostResponseFinalization(Promise.all([
|
|
308
|
+
options.responseOutput != null ? resolveOptionalStructuredOutput(handle.output) : undefined,
|
|
309
|
+
streamed.usage != null ? streamed.usage : resolveOptionalValue(handle.usage),
|
|
310
|
+
resolveOptionalValue(handle.finishReason),
|
|
311
|
+
resolveOptionalValue(handle.providerMetadata),
|
|
312
|
+
resolveOptionalValue(handle.requestStatus),
|
|
313
|
+
]), options);
|
|
192
314
|
return {
|
|
193
315
|
responseText,
|
|
194
|
-
structuredOutput
|
|
316
|
+
structuredOutput,
|
|
195
317
|
functionCalls: streamed.functionCalls,
|
|
196
|
-
usage
|
|
318
|
+
usage,
|
|
197
319
|
reasoning: streamed.reasoning,
|
|
198
|
-
finishReason
|
|
199
|
-
providerMetadata
|
|
200
|
-
requestStatus
|
|
320
|
+
finishReason,
|
|
321
|
+
providerMetadata,
|
|
322
|
+
requestStatus,
|
|
201
323
|
};
|
|
202
324
|
}
|
|
203
325
|
export async function streamChatV2(options) {
|
|
@@ -208,7 +330,7 @@ export async function generateChatV2(options) {
|
|
|
208
330
|
const stepToolCalls = attachGenerateStepToolCallCollector(args);
|
|
209
331
|
let result;
|
|
210
332
|
try {
|
|
211
|
-
result = await (options.executeGenerate ?? defaultGenerateExecutor)(args);
|
|
333
|
+
result = await waitForGeneratedResponse(Promise.resolve((options.executeGenerate ?? defaultGenerateExecutor)(args)), options);
|
|
212
334
|
}
|
|
213
335
|
catch (error) {
|
|
214
336
|
const recovered = recoverGenerateStructuredOutputError(error, options, stepToolCalls);
|
|
@@ -219,15 +341,25 @@ export async function generateChatV2(options) {
|
|
|
219
341
|
}
|
|
220
342
|
const isStructuredOutput = isChatV2StructuredResponseFormat(options.responseFormat);
|
|
221
343
|
const responseText = isStructuredOutput ? collapseRepeatedStructuredJsonText(result.text) : result.text;
|
|
222
|
-
const finishReason = await
|
|
344
|
+
const [finishReason, structuredOutput, usage, reasoning, providerMetadata, requestStatus] = await waitForPostResponseFinalization((async () => {
|
|
345
|
+
const finishReason = await resolveOptionalValue(result.finishReason);
|
|
346
|
+
const [structuredOutput, usage, reasoning, providerMetadata, requestStatus] = await Promise.all([
|
|
347
|
+
resolveGenerateStructuredOutput(result, options.responseOutput, finishReason),
|
|
348
|
+
(async () => (await resolveOptionalValue(result.totalUsage)) ?? (await resolveOptionalValue(result.usage)))(),
|
|
349
|
+
resolveGenerateReasoning(result),
|
|
350
|
+
resolveOptionalValue(result.providerMetadata),
|
|
351
|
+
resolveOptionalValue(result.requestStatus),
|
|
352
|
+
]);
|
|
353
|
+
return [finishReason, structuredOutput, usage, reasoning, providerMetadata, requestStatus];
|
|
354
|
+
})(), options);
|
|
223
355
|
return {
|
|
224
356
|
responseText,
|
|
225
|
-
structuredOutput
|
|
357
|
+
structuredOutput,
|
|
226
358
|
functionCalls: toStreamedFunctionCalls(result.toolCalls != null && result.toolCalls.length > 0 ? result.toolCalls : stepToolCalls),
|
|
227
|
-
usage
|
|
228
|
-
reasoning
|
|
359
|
+
usage,
|
|
360
|
+
reasoning,
|
|
229
361
|
finishReason,
|
|
230
|
-
providerMetadata
|
|
231
|
-
requestStatus
|
|
362
|
+
providerMetadata,
|
|
363
|
+
requestStatus,
|
|
232
364
|
};
|
|
233
365
|
}
|
|
@@ -120,6 +120,8 @@ export function notifyChatV2CallFinished(options, params) {
|
|
|
120
120
|
callId: params.callId,
|
|
121
121
|
attemptIndex: params.attemptIndex,
|
|
122
122
|
...(options.profileIndex == null ? {} : { profileIndex: options.profileIndex }),
|
|
123
|
+
...(options.profileHealthKey == null ? {} : { profileHealthKey: options.profileHealthKey }),
|
|
124
|
+
...(options.profileHealthState == null ? {} : { profileHealthState: options.profileHealthState }),
|
|
123
125
|
...(options.roundIndex == null ? {} : { roundIndex: options.roundIndex }),
|
|
124
126
|
nodeId,
|
|
125
127
|
processId,
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export const CHAT_V2_DEFAULT_CREDENTIAL_NAMES = {
|
|
2
|
+
openai: {
|
|
3
|
+
programmaticName: 'openAiApiKey',
|
|
4
|
+
environmentVariableName: 'OPENAI_API_KEY',
|
|
5
|
+
},
|
|
6
|
+
anthropic: {
|
|
7
|
+
programmaticName: 'anthropicApiKey',
|
|
8
|
+
environmentVariableName: 'ANTHROPIC_API_KEY',
|
|
9
|
+
},
|
|
10
|
+
google: {
|
|
11
|
+
programmaticName: 'googleApiKey',
|
|
12
|
+
environmentVariableName: 'GOOGLE_GENERATIVE_AI_API_KEY',
|
|
13
|
+
},
|
|
14
|
+
};
|
|
15
|
+
const programmaticNamePattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
16
|
+
const environmentVariableNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
17
|
+
export function isChatV2BuiltInProvider(provider) {
|
|
18
|
+
return Object.hasOwn(CHAT_V2_DEFAULT_CREDENTIAL_NAMES, provider);
|
|
19
|
+
}
|
|
20
|
+
export function isValidChatV2ProgrammaticCredentialName(name) {
|
|
21
|
+
return programmaticNamePattern.test(name);
|
|
22
|
+
}
|
|
23
|
+
export function isValidChatV2EnvironmentCredentialName(name) {
|
|
24
|
+
return environmentVariableNamePattern.test(name);
|
|
25
|
+
}
|
|
26
|
+
export function getChatV2DefaultCredentialNames(provider) {
|
|
27
|
+
return { ...CHAT_V2_DEFAULT_CREDENTIAL_NAMES[provider] };
|
|
28
|
+
}
|
|
29
|
+
export function getChatV2CredentialNamesForDisplay(provider, value) {
|
|
30
|
+
try {
|
|
31
|
+
return normalizeChatV2CredentialNames(provider, value);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return getChatV2DefaultCredentialNames(provider);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export function normalizeChatV2CredentialNames(provider, value) {
|
|
38
|
+
if (value != null && (typeof value !== 'object' || Array.isArray(value))) {
|
|
39
|
+
throw new Error(`${provider} API key names must be an object.`);
|
|
40
|
+
}
|
|
41
|
+
const raw = value;
|
|
42
|
+
if (raw?.programmaticName != null && typeof raw.programmaticName !== 'string') {
|
|
43
|
+
throw new Error(`${provider} programmatic API key name must be a string.`);
|
|
44
|
+
}
|
|
45
|
+
if (raw?.environmentVariableName != null && typeof raw.environmentVariableName !== 'string') {
|
|
46
|
+
throw new Error(`${provider} API key environment variable must be a string.`);
|
|
47
|
+
}
|
|
48
|
+
const defaults = CHAT_V2_DEFAULT_CREDENTIAL_NAMES[provider];
|
|
49
|
+
const programmaticName = raw?.programmaticName?.trim() || defaults.programmaticName;
|
|
50
|
+
const environmentVariableName = raw?.environmentVariableName?.trim() || defaults.environmentVariableName;
|
|
51
|
+
if (!isValidChatV2ProgrammaticCredentialName(programmaticName)) {
|
|
52
|
+
throw new Error(`${provider} programmatic API key name must be a JavaScript-style identifier (letters, digits, _, or $, and not starting with a digit).`);
|
|
53
|
+
}
|
|
54
|
+
if (!isValidChatV2EnvironmentCredentialName(environmentVariableName)) {
|
|
55
|
+
throw new Error(`${provider} API key environment variable must contain only letters, digits, and _, and must not start with a digit.`);
|
|
56
|
+
}
|
|
57
|
+
return { programmaticName, environmentVariableName };
|
|
58
|
+
}
|
|
59
|
+
export function normalizeChatV2CredentialNamesByProvider(value) {
|
|
60
|
+
if (value == null)
|
|
61
|
+
return undefined;
|
|
62
|
+
if (typeof value !== 'object' || Array.isArray(value)) {
|
|
63
|
+
throw new Error('Built-in provider API key names must be an object.');
|
|
64
|
+
}
|
|
65
|
+
const raw = value;
|
|
66
|
+
const unsupportedProvider = Object.keys(raw).find((provider) => !Object.hasOwn(CHAT_V2_DEFAULT_CREDENTIAL_NAMES, provider));
|
|
67
|
+
if (unsupportedProvider) {
|
|
68
|
+
throw new Error(`Unsupported provider API key names entry: ${unsupportedProvider}.`);
|
|
69
|
+
}
|
|
70
|
+
const normalized = {};
|
|
71
|
+
for (const provider of ['openai', 'anthropic', 'google']) {
|
|
72
|
+
if (raw[provider] != null) {
|
|
73
|
+
normalized[provider] = normalizeChatV2CredentialNames(provider, raw[provider]);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return Object.keys(normalized).length === 0 ? undefined : normalized;
|
|
77
|
+
}
|
|
78
|
+
export function isDefaultChatV2CredentialNames(provider, names) {
|
|
79
|
+
const defaults = CHAT_V2_DEFAULT_CREDENTIAL_NAMES[provider];
|
|
80
|
+
return (names.programmaticName === defaults.programmaticName &&
|
|
81
|
+
names.environmentVariableName === defaults.environmentVariableName);
|
|
82
|
+
}
|
|
83
|
+
export function getNonDefaultChatV2CredentialNames(provider, namesByProvider) {
|
|
84
|
+
if (!isChatV2BuiltInProvider(provider) || namesByProvider?.[provider] == null)
|
|
85
|
+
return undefined;
|
|
86
|
+
try {
|
|
87
|
+
const names = normalizeChatV2CredentialNames(provider, namesByProvider[provider]);
|
|
88
|
+
return isDefaultChatV2CredentialNames(provider, names) ? undefined : names;
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
@@ -3,7 +3,7 @@ import CryptoJS from 'crypto-js';
|
|
|
3
3
|
import { normalizeOpenAICompatibleEndpoint } from './providerOptions.js';
|
|
4
4
|
import { parseCustomProviderApi } from './customProviderApi.js';
|
|
5
5
|
export function buildLLMChatV2EditorCacheKey(parts) {
|
|
6
|
-
const { cacheVersion =
|
|
6
|
+
const { cacheVersion = 3, ...keyParts } = parts;
|
|
7
7
|
return stableStringify({ cacheVersion, ...keyParts }) ?? '';
|
|
8
8
|
}
|
|
9
9
|
function cloneEditorCacheValue(value, seen = new WeakMap()) {
|
|
@@ -103,11 +103,11 @@ function fingerprintNodeDataForCache(data) {
|
|
|
103
103
|
})),
|
|
104
104
|
};
|
|
105
105
|
}
|
|
106
|
-
function
|
|
107
|
-
if (
|
|
106
|
+
function fingerprintRuntimeValueForCache(value) {
|
|
107
|
+
if (value == null) {
|
|
108
108
|
return undefined;
|
|
109
109
|
}
|
|
110
|
-
return fingerprintSecret(stableStringify(
|
|
110
|
+
return fingerprintSecret(stableStringify(value) ?? '');
|
|
111
111
|
}
|
|
112
112
|
function fingerprintProfileChainForCache(data, profiles) {
|
|
113
113
|
if (profiles == null) {
|
|
@@ -142,7 +142,8 @@ export function resolveLLMChatV2EditorCache(params) {
|
|
|
142
142
|
functions: params.functions,
|
|
143
143
|
generationParameters: params.generationParameters,
|
|
144
144
|
responseFormatParameters: params.responseFormatParameters,
|
|
145
|
-
providerOptions:
|
|
145
|
+
providerOptions: fingerprintRuntimeValueForCache(params.providerOptions),
|
|
146
|
+
requestBodyOverlay: fingerprintRuntimeValueForCache(params.requestBodyOverlay),
|
|
146
147
|
toolChoice: params.toolChoice,
|
|
147
148
|
profileChain: params.profileChain == null ? undefined : fingerprintProfileChainForCache(params.data, params.profileChain),
|
|
148
149
|
});
|
|
@@ -2,6 +2,7 @@ import { coercePromptToChatMessages, prependSystemPrompt } from '../chat/chatMes
|
|
|
2
2
|
import { generateChatV2, streamChatV2 } from './aiSdkBridge.js';
|
|
3
3
|
import { createObservedChatV2CallId, notifyChatV2CallFinished } from './chatV2CallObserver.js';
|
|
4
4
|
import { chatMessagesToModelMessages } from './messageConverter.js';
|
|
5
|
+
import { isChatV2ProviderTimeoutError } from './chatV2Types.js';
|
|
5
6
|
import { chatV2ToolsToAiSdk } from './toolConverter.js';
|
|
6
7
|
import { buildChatV2RequestPlan } from './chatV2RequestPlan.js';
|
|
7
8
|
import { getChatV2ProviderErrorStatusCode, normalizeChatV2ProviderError, } from './chatV2Errors.js';
|
|
@@ -54,12 +55,38 @@ function notifyProviderAttempt(options, attempt) {
|
|
|
54
55
|
}
|
|
55
56
|
}
|
|
56
57
|
async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, transportMode) {
|
|
58
|
+
const prepareProviderRetry = async () => {
|
|
59
|
+
try {
|
|
60
|
+
await options.onBeforeProviderRetry?.(retryPlan.cooldownMs);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
// Circuit-health persistence is observational and must fail open.
|
|
64
|
+
}
|
|
65
|
+
};
|
|
57
66
|
for (let attempt = 0;; attempt++) {
|
|
58
67
|
const callId = createObservedChatV2CallId(options);
|
|
59
68
|
const callStartedAt = Date.now();
|
|
60
69
|
let callWasObserved = false;
|
|
70
|
+
const attemptController = new AbortController();
|
|
71
|
+
const abortAttemptFromCaller = () => attemptController.abort(signal.reason);
|
|
72
|
+
if (signal.aborted) {
|
|
73
|
+
abortAttemptFromCaller();
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
signal.addEventListener('abort', abortAttemptFromCaller, { once: true });
|
|
77
|
+
}
|
|
61
78
|
try {
|
|
62
|
-
const
|
|
79
|
+
const attemptChatOptions = {
|
|
80
|
+
...chatOptions,
|
|
81
|
+
abortSignal: attemptController.signal,
|
|
82
|
+
firstOutputTimeoutMs: options.firstOutputTimeoutMs,
|
|
83
|
+
streamInactivityTimeoutMs: options.streamInactivityTimeoutMs,
|
|
84
|
+
onStreamActivity: options.onStreamActivity,
|
|
85
|
+
onTimeout: (error) => attemptController.abort(error),
|
|
86
|
+
};
|
|
87
|
+
const result = transportMode === 'generate'
|
|
88
|
+
? await generateChatV2(attemptChatOptions)
|
|
89
|
+
: await streamChatV2(attemptChatOptions);
|
|
63
90
|
await options.responseBodyCapture?.flush();
|
|
64
91
|
const statusCode = result.requestStatus ?? 200;
|
|
65
92
|
notifyChatV2CallFinished(options, {
|
|
@@ -84,10 +111,16 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
|
|
|
84
111
|
if (attempt >= retryPlan.repeatTimes) {
|
|
85
112
|
return { result, responseError };
|
|
86
113
|
}
|
|
114
|
+
await prepareProviderRetry();
|
|
87
115
|
await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
|
|
88
116
|
}
|
|
89
|
-
catch (
|
|
90
|
-
|
|
117
|
+
catch (caughtError) {
|
|
118
|
+
const error = !signal.aborted && isChatV2ProviderTimeoutError(attemptController.signal.reason)
|
|
119
|
+
? attemptController.signal.reason
|
|
120
|
+
: caughtError;
|
|
121
|
+
await options.responseBodyCapture?.flush({
|
|
122
|
+
waitForPending: !signal.aborted && !isChatV2ProviderTimeoutError(error),
|
|
123
|
+
});
|
|
91
124
|
if (!callWasObserved) {
|
|
92
125
|
notifyChatV2CallFinished(options, {
|
|
93
126
|
callId,
|
|
@@ -111,14 +144,18 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
|
|
|
111
144
|
// provider failure to profile fallback and run activity.
|
|
112
145
|
throw createLLMChatV2RetryAbortError();
|
|
113
146
|
}
|
|
114
|
-
if (!retryPlan.enabled || statusCode == null || statusCode === 200) {
|
|
147
|
+
if (isChatV2ProviderTimeoutError(error) || !retryPlan.enabled || statusCode == null || statusCode === 200) {
|
|
115
148
|
throw error;
|
|
116
149
|
}
|
|
117
150
|
if (attempt >= retryPlan.repeatTimes) {
|
|
118
151
|
throw error;
|
|
119
152
|
}
|
|
153
|
+
await prepareProviderRetry();
|
|
120
154
|
await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
|
|
121
155
|
}
|
|
156
|
+
finally {
|
|
157
|
+
signal.removeEventListener('abort', abortAttemptFromCaller);
|
|
158
|
+
}
|
|
122
159
|
}
|
|
123
160
|
}
|
|
124
161
|
/**
|
|
@@ -1,11 +1,39 @@
|
|
|
1
1
|
import { coerceTypeOptional } from '../../utils/coerceType.js';
|
|
2
2
|
import { createChatV2Model, resolveChatV2ProviderConfig, } from './providerOptions.js';
|
|
3
3
|
import { getChatV2ProviderCapabilities } from './chatV2ProviderRegistry.js';
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
import { isChatV2BuiltInProvider, normalizeChatV2CredentialNames, } from './chatV2CredentialNames.js';
|
|
5
|
+
function getNonEmptyString(value) {
|
|
6
6
|
return typeof value === 'string' && value.trim() ? value : undefined;
|
|
7
7
|
}
|
|
8
|
+
function getStringSetting(settings, key) {
|
|
9
|
+
return getNonEmptyString(settings[key]);
|
|
10
|
+
}
|
|
8
11
|
function resolveConfiguredCredential(provider, context, options) {
|
|
12
|
+
if (isChatV2BuiltInProvider(provider) && options.providerApiKeyNames?.[provider] != null) {
|
|
13
|
+
const names = normalizeChatV2CredentialNames(provider, options.providerApiKeyNames[provider]);
|
|
14
|
+
const programmaticValue = getStringSetting(context.settings, names.programmaticName);
|
|
15
|
+
if (programmaticValue) {
|
|
16
|
+
return {
|
|
17
|
+
value: programmaticValue,
|
|
18
|
+
reference: { source: 'programmatic', name: names.programmaticName },
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
const pluginEnvValue = getNonEmptyString(context.settings.pluginEnv?.[names.environmentVariableName]);
|
|
22
|
+
if (pluginEnvValue) {
|
|
23
|
+
return {
|
|
24
|
+
value: pluginEnvValue,
|
|
25
|
+
reference: { source: 'environment', name: names.environmentVariableName },
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
const processValue = getNonEmptyString(globalThis.process?.env?.[names.environmentVariableName]);
|
|
29
|
+
if (processValue) {
|
|
30
|
+
return {
|
|
31
|
+
value: processValue,
|
|
32
|
+
reference: { source: 'environment', name: names.environmentVariableName },
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
throw new Error(`${provider} API key is not set. Pass ${names.programmaticName} programmatically or configure ${names.environmentVariableName}.`);
|
|
36
|
+
}
|
|
9
37
|
switch (provider) {
|
|
10
38
|
case 'openai': {
|
|
11
39
|
const value = context.settings.openAiApiKey || context.settings.openAiKey || undefined;
|
|
@@ -82,6 +110,7 @@ export async function createResolvedChatV2Provider(options) {
|
|
|
82
110
|
onRequestBody: options.onRequestBody,
|
|
83
111
|
onResponseBody: options.onResponseBody,
|
|
84
112
|
transformRequestBody: options.transformRequestBody,
|
|
113
|
+
requestBodyOverlay: options.requestBodyOverlay,
|
|
85
114
|
customProviderApi: options.customProviderApi,
|
|
86
115
|
});
|
|
87
116
|
return {
|
|
@@ -15,6 +15,9 @@ function parseResponseBody(text) {
|
|
|
15
15
|
export function createChatV2ResponseBodyCapture() {
|
|
16
16
|
const entries = [];
|
|
17
17
|
const bodies = [];
|
|
18
|
+
const publishSettledBodies = () => {
|
|
19
|
+
bodies.splice(0, bodies.length, ...entries.filter((entry) => entry.captured).map((entry) => entry.value));
|
|
20
|
+
};
|
|
18
21
|
return {
|
|
19
22
|
bodies,
|
|
20
23
|
capture(response) {
|
|
@@ -31,6 +34,7 @@ export function createChatV2ResponseBodyCapture() {
|
|
|
31
34
|
.then((text) => {
|
|
32
35
|
entry.value = parseResponseBody(text);
|
|
33
36
|
entry.captured = true;
|
|
37
|
+
publishSettledBodies();
|
|
34
38
|
})
|
|
35
39
|
.catch(() => {
|
|
36
40
|
// The original response remains owned by the provider SDK.
|
|
@@ -40,7 +44,11 @@ export function createChatV2ResponseBodyCapture() {
|
|
|
40
44
|
// A malformed or already-consumed Response has no safe diagnostic body.
|
|
41
45
|
}
|
|
42
46
|
},
|
|
43
|
-
async flush() {
|
|
47
|
+
async flush(options = {}) {
|
|
48
|
+
if (options.waitForPending === false) {
|
|
49
|
+
publishSettledBodies();
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
44
52
|
// New fetches are normally sequential, but continue until no capture was
|
|
45
53
|
// added while an earlier clone was settling.
|
|
46
54
|
let observedEntryCount = 0;
|
|
@@ -49,7 +57,7 @@ export function createChatV2ResponseBodyCapture() {
|
|
|
49
57
|
observedEntryCount = entries.length;
|
|
50
58
|
await Promise.allSettled(pending.map((entry) => entry.settled));
|
|
51
59
|
}
|
|
52
|
-
|
|
60
|
+
publishSettledBodies();
|
|
53
61
|
},
|
|
54
62
|
};
|
|
55
63
|
}
|
|
@@ -2,9 +2,9 @@ import { createGoogleGenerativeAI } from '@ai-sdk/google';
|
|
|
2
2
|
import { createOpenAI } from '@ai-sdk/openai';
|
|
3
3
|
import { coerceTypeOptional } from '../../utils/coerceType.js';
|
|
4
4
|
import { cleanHeaders, getInputOrData } from '../../utils/inputs.js';
|
|
5
|
+
import { cloneRivetStoredValue } from '../StoredValueStore.js';
|
|
5
6
|
import { resolveChatV2Credential } from './chatV2ProviderProfile.js';
|
|
6
7
|
import { applyLLMChatV2ParallelToolCallProviderOptions } from './parallelToolCalls.js';
|
|
7
|
-
import { getCustomProviderApiContract } from './customProviderApi.js';
|
|
8
8
|
export function resolveLLMChatV2Headers(data, inputs) {
|
|
9
9
|
const resolvedHeaders = data.useHeadersInput && inputs['headers'] != null
|
|
10
10
|
? coerceTypeOptional(inputs['headers'], 'object')
|
|
@@ -18,6 +18,7 @@ export function resolveLLMChatV2ApiKey(data, inputs, context) {
|
|
|
18
18
|
context,
|
|
19
19
|
apiKeySource: data.apiKeySource === 'input' ? 'input' : 'configured',
|
|
20
20
|
inputs,
|
|
21
|
+
providerApiKeyNames: data.providerApiKeyNames,
|
|
21
22
|
customProgrammaticName: data.customProviderApiKeyProgrammaticName,
|
|
22
23
|
customEnvironmentName: data.customProviderApiKeyEnvVarName,
|
|
23
24
|
}).value;
|
|
@@ -38,16 +39,17 @@ function parseExtraProviderOptionsText(rawText) {
|
|
|
38
39
|
return normalizeExtraProviderOptions(parsed);
|
|
39
40
|
}
|
|
40
41
|
function normalizeExtraProviderOptions(value) {
|
|
41
|
-
if (value
|
|
42
|
+
if (value === undefined) {
|
|
42
43
|
return undefined;
|
|
43
44
|
}
|
|
44
45
|
if (typeof value === 'string') {
|
|
45
46
|
return parseExtraProviderOptionsText(value);
|
|
46
47
|
}
|
|
47
|
-
|
|
48
|
+
const cloned = cloneRivetStoredValue(value, 'Extra provider options');
|
|
49
|
+
if (cloned === null || typeof cloned !== 'object' || Array.isArray(cloned)) {
|
|
48
50
|
throw new Error('Extra provider options must be a JSON object.');
|
|
49
51
|
}
|
|
50
|
-
return
|
|
52
|
+
return cloned;
|
|
51
53
|
}
|
|
52
54
|
export function resolveLLMChatV2ExtraProviderOptions(data, inputs) {
|
|
53
55
|
if (!data.useExtraProviderOptionsInput) {
|
|
@@ -57,13 +59,6 @@ export function resolveLLMChatV2ExtraProviderOptions(data, inputs) {
|
|
|
57
59
|
}
|
|
58
60
|
function resolveProviderOptions(data, inputs) {
|
|
59
61
|
const providerOptions = {};
|
|
60
|
-
const extraProviderOptions = resolveLLMChatV2ExtraProviderOptions(data, inputs);
|
|
61
|
-
const providerOptionsKey = data.provider === 'custom'
|
|
62
|
-
? getCustomProviderApiContract(data.customProviderApi).providerOptionsKey
|
|
63
|
-
: data.provider;
|
|
64
|
-
if (extraProviderOptions) {
|
|
65
|
-
providerOptions[providerOptionsKey] = extraProviderOptions;
|
|
66
|
-
}
|
|
67
62
|
if (data.provider === 'openai') {
|
|
68
63
|
const previousResponseId = data.useOpenAIPreviousResponseIdInput && inputs['previousResponseId'] != null
|
|
69
64
|
? coerceTypeOptional(inputs['previousResponseId'], 'string')
|
|
@@ -1,3 +1,19 @@
|
|
|
1
|
+
export class ChatV2ProviderTimeoutError extends Error {
|
|
2
|
+
timeoutKind;
|
|
3
|
+
timeoutMs;
|
|
4
|
+
code = 'RIVET_LLM_PROVIDER_TIMEOUT';
|
|
5
|
+
constructor(timeoutKind, timeoutMs) {
|
|
6
|
+
super(timeoutKind === 'first-output'
|
|
7
|
+
? `LLM provider did not produce a useful response within ${timeoutMs} ms.`
|
|
8
|
+
: `LLM provider stream produced no activity for ${timeoutMs} ms.`);
|
|
9
|
+
this.timeoutKind = timeoutKind;
|
|
10
|
+
this.timeoutMs = timeoutMs;
|
|
11
|
+
this.name = 'ChatV2ProviderTimeoutError';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export function isChatV2ProviderTimeoutError(error) {
|
|
15
|
+
return error instanceof ChatV2ProviderTimeoutError;
|
|
16
|
+
}
|
|
1
17
|
export function shouldOutputChatV2RequestBody(options) {
|
|
2
18
|
return options.outputRequestBody === true;
|
|
3
19
|
}
|
|
@@ -6,7 +6,6 @@ const customProviderApiContracts = {
|
|
|
6
6
|
completions: {
|
|
7
7
|
api: 'completions',
|
|
8
8
|
adapter: 'openai-compatible',
|
|
9
|
-
providerOptionsKey: 'custom',
|
|
10
9
|
endpointPath: '/chat/completions',
|
|
11
10
|
label: 'Custom Completions',
|
|
12
11
|
structuredOutput: 'raw-response-format',
|
|
@@ -15,7 +14,6 @@ const customProviderApiContracts = {
|
|
|
15
14
|
responses: {
|
|
16
15
|
api: 'responses',
|
|
17
16
|
adapter: 'openai-responses',
|
|
18
|
-
providerOptionsKey: 'openai',
|
|
19
17
|
endpointPath: '/responses',
|
|
20
18
|
label: 'Custom Responses',
|
|
21
19
|
structuredOutput: 'sdk-output',
|
|
@@ -2,11 +2,13 @@ export * from './aiSdkBridge.js';
|
|
|
2
2
|
export * from './chatV2FeatureCompatibility.js';
|
|
3
3
|
export * from './chatV2Pipeline.js';
|
|
4
4
|
export * from './chatV2ProviderProfile.js';
|
|
5
|
+
export * from './chatV2CredentialNames.js';
|
|
5
6
|
export * from './chatV2RequestPlan.js';
|
|
6
7
|
export * from './chatV2ResponseFormat.js';
|
|
7
8
|
export * from './chatV2Shared.js';
|
|
8
9
|
export * from './chatV2Types.js';
|
|
9
10
|
export * from './llmProfileTypes.js';
|
|
11
|
+
export * from './llmProfileHealthStore.js';
|
|
10
12
|
export * from './llmProfileBody.js';
|
|
11
13
|
export * from './llmChatV2Body.js';
|
|
12
14
|
export * from './messageConverter.js';
|
|
@@ -16,6 +18,7 @@ export * from './toolConverter.js';
|
|
|
16
18
|
export * from './toolContinuationConnection.js';
|
|
17
19
|
export * from './chatV2ProviderRegistry.js';
|
|
18
20
|
export * from './llmChatV2NodeMigration.js';
|
|
21
|
+
export * from './llmChatV2NodeData.js';
|
|
19
22
|
export * from './llmInvocationCoordinator.js';
|
|
20
23
|
export * from './llmInvocationProjections.js';
|
|
21
24
|
export * from './llmInvocationDecision.js';
|