@valerypopoff/rivet2-core 2.1.8 → 2.1.10
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 +4457 -1809
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/webAppRuntime.cjs +298 -21
- package/dist/cjs/webAppRuntime.cjs.map +4 -4
- package/dist/esm/exports.js +1 -0
- package/dist/esm/model/AgentResponseTrace.js +448 -0
- package/dist/esm/model/ConnectedToolContinuationHost.js +33 -0
- package/dist/esm/model/GraphProcessor.js +152 -74
- package/dist/esm/model/NodeImpl.js +6 -0
- package/dist/esm/model/ProcessContextBuilder.js +3 -1
- package/dist/esm/model/RecordingPlayer.js +164 -22
- package/dist/esm/model/SplitRunProcessor.js +68 -18
- package/dist/esm/model/SubprocessorBridge.js +2 -0
- package/dist/esm/model/ToolCallContinuationCoordinator.js +13 -4
- package/dist/esm/model/UiGraph.js +21 -0
- package/dist/esm/model/UiGraphActionProtocol.js +2 -0
- package/dist/esm/model/UiGraphBrowserRuntime.js +133 -4
- package/dist/esm/model/UiGraphRendererStyles.js +221 -0
- package/dist/esm/model/UiGraphRuntimeModel.js +9 -3
- package/dist/esm/model/UiGraphSchema.js +7 -1
- package/dist/esm/model/chat/aiSdkMessages.js +8 -0
- package/dist/esm/model/chat/aiSdkTools.js +3 -2
- package/dist/esm/model/chat-v2/chatV2CallObserver.js +11 -5
- package/dist/esm/model/chat-v2/chatV2EditorCache.js +58 -10
- package/dist/esm/model/chat-v2/chatV2Errors.js +7 -19
- package/dist/esm/model/chat-v2/chatV2FeatureCompatibility.js +1 -1
- package/dist/esm/model/chat-v2/chatV2Outputs.js +56 -106
- package/dist/esm/model/chat-v2/chatV2Pipeline.js +142 -149
- package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +9 -2
- package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +9 -0
- package/dist/esm/model/chat-v2/chatV2RequestPlan.js +5 -5
- package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +55 -0
- package/dist/esm/model/chat-v2/chatV2ResponseFormat.js +8 -4
- package/dist/esm/model/chat-v2/chatV2Retry.js +4 -3
- package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -1
- package/dist/esm/model/chat-v2/chatV2Shared.js +1 -6
- package/dist/esm/model/chat-v2/chatV2Types.js +7 -1
- package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +78 -0
- package/dist/esm/model/chat-v2/customProviderApi.js +42 -0
- package/dist/esm/model/chat-v2/developerMessageRoles.js +45 -0
- package/dist/esm/model/chat-v2/index.js +12 -0
- package/dist/esm/model/chat-v2/llmChatV2Body.js +281 -0
- package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +32 -0
- package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +20 -0
- package/dist/esm/model/chat-v2/llmChatV2NodeData.js +8 -54
- package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +41 -20
- package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +24 -0
- package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +178 -94
- package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +60 -0
- package/dist/esm/model/chat-v2/llmInvocationDecision.js +11 -0
- package/dist/esm/model/chat-v2/llmInvocationJournal.js +43 -0
- package/dist/esm/model/chat-v2/llmInvocationPlan.js +68 -0
- package/dist/esm/model/chat-v2/llmInvocationProjections.js +5 -0
- package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +48 -0
- package/dist/esm/model/chat-v2/llmModelCandidate.js +75 -0
- package/dist/esm/model/chat-v2/llmProfile.js +31 -65
- package/dist/esm/model/chat-v2/llmProfileBody.js +183 -0
- package/dist/esm/model/chat-v2/llmProfileFallback.js +244 -0
- package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +67 -0
- package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +3 -0
- package/dist/esm/model/chat-v2/llmProfileTypes.js +1 -18
- package/dist/esm/model/chat-v2/llmResponseMaterializer.js +42 -0
- package/dist/esm/model/chat-v2/messageConverter.js +14 -0
- package/dist/esm/model/chat-v2/modelRegistry.js +54 -4
- package/dist/esm/model/chat-v2/parallelToolCalls.js +9 -2
- package/dist/esm/model/chat-v2/providerOptions.js +120 -21
- package/dist/esm/model/chat-v2/rivetToolRegistry.js +9 -0
- package/dist/esm/model/chat-v2/toolCallCodec.js +52 -0
- package/dist/esm/model/chat-v2/toolContinuation.js +72 -39
- package/dist/esm/model/chat-v2/toolHandlerResolver.js +23 -0
- package/dist/esm/model/chat-v2/toolRoundExecutor.js +12 -0
- package/dist/esm/model/nodes/AssembleMessageNode.js +6 -0
- package/dist/esm/model/nodes/ChatNode.js +6 -0
- package/dist/esm/model/nodes/ChatNodeBase.js +1 -0
- package/dist/esm/model/nodes/DelegateFunctionCallNode.js +26 -1
- package/dist/esm/model/nodes/LLMChatV2Node.js +131 -144
- package/dist/esm/model/nodes/LLMProfileNode.js +27 -8
- package/dist/esm/model/nodes/PromptNode.js +16 -2
- package/dist/esm/model/nodes/ToolNode.js +7 -0
- package/dist/esm/model/nodes/toolCallDelegation.js +193 -110
- package/dist/esm/plugins/anthropic/anthropic.js +4 -4
- package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +29 -28
- package/dist/esm/plugins/google/google.js +25 -18
- package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +21 -7
- package/dist/esm/recording/ExecutionRecorder.js +13 -5
- package/dist/esm/utils/chatMessageToOpenAIChatCompletionMessage.js +4 -0
- package/dist/esm/utils/emitDetached.js +6 -3
- package/dist/esm/utils/openai.js +60 -16
- package/dist/esm/utils/serialization/serialization.js +2 -0
- package/dist/esm/webAppRuntime.js +3 -2
- package/dist/types/exports.d.ts +1 -0
- package/dist/types/model/AgentResponseTrace.d.ts +110 -0
- package/dist/types/model/ConnectedToolContinuationHost.d.ts +34 -0
- package/dist/types/model/DataValue.d.ts +7 -1
- package/dist/types/model/ExecutorProtocol.d.ts +25 -7
- package/dist/types/model/GraphProcessor.d.ts +27 -5
- package/dist/types/model/NodeBase.d.ts +6 -0
- package/dist/types/model/NodeImpl.d.ts +18 -1
- package/dist/types/model/Nodes.d.ts +2 -2
- package/dist/types/model/ProcessContext.d.ts +51 -0
- package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
- package/dist/types/model/RecordingPlayer.d.ts +6 -0
- package/dist/types/model/SplitRunProcessor.d.ts +11 -3
- package/dist/types/model/UiGraph.d.ts +8 -0
- package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
- package/dist/types/model/UiGraphBrowserRuntime.d.ts +11 -2
- package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
- package/dist/types/model/UiGraphRuntimeModel.d.ts +2 -0
- package/dist/types/model/UiGraphSchema.d.ts +1 -0
- package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +2 -0
- package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +3 -1
- package/dist/types/model/chat-v2/chatV2Outputs.d.ts +7 -17
- package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +29 -0
- package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +5 -0
- package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +8 -0
- package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
- package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +19 -0
- package/dist/types/model/chat-v2/chatV2ResponseFormat.d.ts +3 -2
- package/dist/types/model/chat-v2/chatV2Retry.d.ts +2 -0
- package/dist/types/model/chat-v2/chatV2Shared.d.ts +0 -1
- package/dist/types/model/chat-v2/chatV2Types.d.ts +35 -1
- package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +14 -0
- package/dist/types/model/chat-v2/customProviderApi.d.ts +23 -0
- package/dist/types/model/chat-v2/developerMessageRoles.d.ts +10 -0
- package/dist/types/model/chat-v2/index.d.ts +12 -0
- package/dist/types/model/chat-v2/llmChatV2Body.d.ts +24 -0
- package/dist/types/model/chat-v2/llmChatV2CacheBoundary.d.ts +10 -0
- package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +13 -0
- package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +13 -3
- package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +8 -0
- package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +18 -4
- package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +16 -0
- package/dist/types/model/chat-v2/llmInvocationDecision.d.ts +21 -0
- package/dist/types/model/chat-v2/llmInvocationJournal.d.ts +38 -0
- package/dist/types/model/chat-v2/llmInvocationPlan.d.ts +41 -0
- package/dist/types/model/chat-v2/llmInvocationProjections.d.ts +3 -0
- package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +26 -0
- package/dist/types/model/chat-v2/llmModelCandidate.d.ts +18 -0
- package/dist/types/model/chat-v2/llmProfile.d.ts +7 -0
- package/dist/types/model/chat-v2/llmProfileBody.d.ts +20 -0
- package/dist/types/model/chat-v2/llmProfileFallback.d.ts +47 -0
- package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +189 -0
- package/dist/types/model/chat-v2/llmProfileTypes.d.ts +1 -1
- package/dist/types/model/chat-v2/llmResponseMaterializer.d.ts +20 -0
- package/dist/types/model/chat-v2/modelRegistry.d.ts +17 -187
- package/dist/types/model/chat-v2/parallelToolCalls.d.ts +3 -1
- package/dist/types/model/chat-v2/providerOptions.d.ts +11 -0
- package/dist/types/model/chat-v2/rivetToolRegistry.d.ts +11 -0
- package/dist/types/model/chat-v2/toolCallCodec.d.ts +7 -0
- package/dist/types/model/chat-v2/toolContinuation.d.ts +3 -3
- package/dist/types/model/chat-v2/toolHandlerResolver.d.ts +25 -0
- package/dist/types/model/chat-v2/toolRoundExecutor.d.ts +18 -0
- package/dist/types/model/nodes/AssembleMessageNode.d.ts +2 -1
- package/dist/types/model/nodes/ChatNode.d.ts +2 -1
- package/dist/types/model/nodes/DelegateFunctionCallNode.d.ts +2 -1
- package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
- package/dist/types/model/nodes/LLMProfileNode.d.ts +2 -1
- package/dist/types/model/nodes/PromptNode.d.ts +6 -3
- package/dist/types/model/nodes/ToolNode.d.ts +2 -1
- package/dist/types/model/nodes/toolCallDelegation.d.ts +10 -3
- package/dist/types/plugins/anthropic/anthropic.d.ts +1 -0
- package/dist/types/plugins/google/google.d.ts +14 -9
- package/dist/types/plugins/google/nodes/ChatGoogleNode.d.ts +2 -1
- package/dist/types/recording/RecordedEvents.d.ts +6 -0
- package/dist/types/utils/emitDetached.d.ts +3 -2
- package/dist/types/utils/openai.d.ts +49 -0
- package/dist/types/webAppRuntime.d.ts +4 -2
- package/package.json +2 -2
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { isChatV2ResponseValidationError, runChatV2PipelineExecution } from './chatV2Pipeline.js';
|
|
2
|
+
import {} from './chatV2Types.js';
|
|
3
|
+
import { getCustomProviderApiContract } from './customProviderApi.js';
|
|
4
|
+
function formatCandidateIdentity(candidate) {
|
|
5
|
+
const providerLabel = candidate.provider === 'custom'
|
|
6
|
+
? getCustomProviderApiContract(candidate.customProviderApi).label
|
|
7
|
+
: candidate.provider;
|
|
8
|
+
return `${providerLabel}/${candidate.model}`;
|
|
9
|
+
}
|
|
10
|
+
export class LLMProfileFallbackExhaustedError extends Error {
|
|
11
|
+
attempts;
|
|
12
|
+
constructor(attempts) {
|
|
13
|
+
super(buildExhaustedMessage(attempts));
|
|
14
|
+
this.attempts = attempts;
|
|
15
|
+
this.name = 'LLMProfileFallbackExhaustedError';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function getLLMAttemptErrorMessage(error) {
|
|
19
|
+
try {
|
|
20
|
+
return error instanceof Error ? error.message : String(error);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return 'Provider request failed with unreadable error metadata.';
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function buildExhaustedMessage(attempts) {
|
|
27
|
+
const details = attempts
|
|
28
|
+
.map((attempt) => {
|
|
29
|
+
const stage = attempt.stage === 'request'
|
|
30
|
+
? `request${attempt.attemptIndex == null ? '' : ` attempt ${attempt.attemptIndex}`}`
|
|
31
|
+
: attempt.stage === 'response-validation'
|
|
32
|
+
? 'response validation'
|
|
33
|
+
: 'configuration';
|
|
34
|
+
const status = attempt.status == null ? '' : ` (${attempt.status})`;
|
|
35
|
+
const error = attempt.error ? `: ${attempt.error.replace(/\r\n|\r|\n/g, '\n ')}` : '';
|
|
36
|
+
return `Profile ${attempt.profileIndex} (${formatCandidateIdentity(attempt)}), round ${attempt.roundIndex}, ${stage} ${attempt.outcome}${status}${error}`;
|
|
37
|
+
})
|
|
38
|
+
.join('\n');
|
|
39
|
+
return details
|
|
40
|
+
? `LLM Profile fallback chain exhausted.\n${details}`
|
|
41
|
+
: 'LLM Profile fallback chain exhausted before a provider request could be made.';
|
|
42
|
+
}
|
|
43
|
+
function pluralize(count, singular, plural = `${singular}s`) {
|
|
44
|
+
return `${count} ${count === 1 ? singular : plural}`;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Produces the concise, developer-facing companion to the full attempt trace.
|
|
48
|
+
* It deliberately includes candidates that were never reached, so a successful
|
|
49
|
+
* primary profile does not make the configured fallback order invisible.
|
|
50
|
+
*/
|
|
51
|
+
export function buildLLMProfileFallbackSummary(candidates, attempts) {
|
|
52
|
+
return candidates
|
|
53
|
+
.map((candidate, profileIndex) => {
|
|
54
|
+
const profileAttempts = attempts.filter((attempt) => attempt.profileIndex === profileIndex);
|
|
55
|
+
const identity = `Profile ${profileIndex} (${formatCandidateIdentity(candidate)})`;
|
|
56
|
+
if (profileAttempts.length === 0) {
|
|
57
|
+
return `${identity}: not attempted.`;
|
|
58
|
+
}
|
|
59
|
+
const successfulRounds = [
|
|
60
|
+
...new Set(profileAttempts
|
|
61
|
+
.filter((attempt) => attempt.stage === 'request' &&
|
|
62
|
+
attempt.outcome === 'success' &&
|
|
63
|
+
!profileAttempts.some((candidate) => candidate.stage === 'response-validation' && candidate.roundIndex === attempt.roundIndex))
|
|
64
|
+
.map((attempt) => attempt.roundIndex)),
|
|
65
|
+
];
|
|
66
|
+
const failedConfiguration = profileAttempts.some((attempt) => attempt.stage === 'configuration' && attempt.outcome === 'failure');
|
|
67
|
+
const failedRequestAttempts = profileAttempts.filter((attempt) => attempt.stage === 'request' && attempt.outcome === 'failure');
|
|
68
|
+
const hasSuccessfulRequest = profileAttempts.some((attempt) => attempt.stage === 'request' && attempt.outcome === 'success');
|
|
69
|
+
const failedResponseValidations = profileAttempts.filter((attempt) => attempt.stage === 'response-validation' && attempt.outcome === 'failure');
|
|
70
|
+
const clauses = [];
|
|
71
|
+
if (successfulRounds.length > 0) {
|
|
72
|
+
clauses.push(`succeeded in model ${pluralize(successfulRounds.length, 'round')} (${successfulRounds.join(', ')})`);
|
|
73
|
+
}
|
|
74
|
+
if (failedConfiguration) {
|
|
75
|
+
clauses.push('failed during configuration');
|
|
76
|
+
}
|
|
77
|
+
if (failedRequestAttempts.length > 0) {
|
|
78
|
+
const lastFailedRequest = failedRequestAttempts.at(-1);
|
|
79
|
+
const status = lastFailedRequest.status == null ? '' : `; last status ${lastFailedRequest.status}`;
|
|
80
|
+
clauses.push(hasSuccessfulRequest
|
|
81
|
+
? `had ${pluralize(failedRequestAttempts.length, 'failed provider attempt')}${status}`
|
|
82
|
+
: `failed after ${pluralize(failedRequestAttempts.length, 'provider attempt')}${status}`);
|
|
83
|
+
}
|
|
84
|
+
if (failedResponseValidations.length > 0) {
|
|
85
|
+
clauses.push(`failed response validation in ${pluralize(failedResponseValidations.length, 'model round')}`);
|
|
86
|
+
}
|
|
87
|
+
return `${identity}: ${clauses.join('; ')}.`;
|
|
88
|
+
})
|
|
89
|
+
.join('\n');
|
|
90
|
+
}
|
|
91
|
+
function clearPartialResponse(options) {
|
|
92
|
+
if (!options.emitPartialOutputs) {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
options.context.onPartialOutputs?.({
|
|
97
|
+
['response']: {
|
|
98
|
+
type: 'string',
|
|
99
|
+
value: '',
|
|
100
|
+
},
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
// A presentation callback must not prevent recovery through a fallback profile.
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function throwIfAborted(signal) {
|
|
108
|
+
if (!signal.aborted) {
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
// Do not turn an abort that happens between candidates into a backup-model
|
|
112
|
+
// request. Prefer the host's Error reason when it supplied one, while still
|
|
113
|
+
// giving graph execution a normal Error for the browser's default reason.
|
|
114
|
+
throw signal.reason instanceof Error ? signal.reason : new Error('LLM Chat request was aborted.');
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Creates one forward-only fallback chain for a whole LLM Chat invocation.
|
|
118
|
+
* A model which succeeds in an earlier tool round stays active for subsequent
|
|
119
|
+
* rounds; only a later failure advances farther through the configured chain.
|
|
120
|
+
*/
|
|
121
|
+
export function createLLMProfileFallbackRunner(params) {
|
|
122
|
+
const attempts = [];
|
|
123
|
+
const recordAttempt = (attempt) => {
|
|
124
|
+
attempts.push(attempt);
|
|
125
|
+
try {
|
|
126
|
+
params.onAttempt?.(attempt);
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
// Diagnostics must not alter profile recovery.
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
let activeProfileIndex = 0;
|
|
133
|
+
let nextRoundIndex = 0;
|
|
134
|
+
let exhausted = false;
|
|
135
|
+
return {
|
|
136
|
+
attempts,
|
|
137
|
+
summary: () => buildLLMProfileFallbackSummary(params.candidates, attempts),
|
|
138
|
+
wasExhausted: () => exhausted,
|
|
139
|
+
run: async (roundOptions) => {
|
|
140
|
+
const roundIndex = nextRoundIndex;
|
|
141
|
+
let lastError;
|
|
142
|
+
for (let profileIndex = activeProfileIndex; profileIndex < params.candidates.length; profileIndex++) {
|
|
143
|
+
throwIfAborted(roundOptions.context.signal);
|
|
144
|
+
const candidate = params.candidates[profileIndex];
|
|
145
|
+
let candidateOptions;
|
|
146
|
+
try {
|
|
147
|
+
candidateOptions = await params.resolveCandidate(profileIndex, roundOptions);
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
if (roundOptions.context.signal.aborted) {
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
lastError = error;
|
|
154
|
+
recordAttempt({
|
|
155
|
+
roundIndex,
|
|
156
|
+
profileIndex,
|
|
157
|
+
provider: candidate.provider,
|
|
158
|
+
model: candidate.model,
|
|
159
|
+
...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
|
|
160
|
+
stage: 'configuration',
|
|
161
|
+
outcome: 'failure',
|
|
162
|
+
error: getLLMAttemptErrorMessage(error),
|
|
163
|
+
});
|
|
164
|
+
clearPartialResponse(roundOptions);
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
// Candidate resolution can be asynchronous (for example, plugin or
|
|
168
|
+
// provider configuration). Do not start a physical request if the
|
|
169
|
+
// graph was cancelled while that resolution was in flight.
|
|
170
|
+
throwIfAborted(roundOptions.context.signal);
|
|
171
|
+
const previousOnProviderAttempt = candidateOptions.onProviderAttempt;
|
|
172
|
+
candidateOptions = {
|
|
173
|
+
...candidateOptions,
|
|
174
|
+
profileIndex,
|
|
175
|
+
roundIndex,
|
|
176
|
+
onProviderAttempt: (attempt) => {
|
|
177
|
+
try {
|
|
178
|
+
previousOnProviderAttempt?.(attempt);
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
// A caller-owned observer must not prevent this runner from
|
|
182
|
+
// retaining the profile-chain diagnostics it owns.
|
|
183
|
+
}
|
|
184
|
+
recordAttempt({
|
|
185
|
+
roundIndex,
|
|
186
|
+
profileIndex,
|
|
187
|
+
provider: candidate.provider,
|
|
188
|
+
model: candidate.model,
|
|
189
|
+
...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
|
|
190
|
+
stage: 'request',
|
|
191
|
+
outcome: attempt.outcome === 'success' ? 'success' : attempt.outcome === 'aborted' ? 'aborted' : 'failure',
|
|
192
|
+
attemptIndex: attempt.attemptIndex,
|
|
193
|
+
...(attempt.status == null ? {} : { status: attempt.status }),
|
|
194
|
+
...(attempt.error == null ? {} : { error: getLLMAttemptErrorMessage(attempt.error) }),
|
|
195
|
+
});
|
|
196
|
+
},
|
|
197
|
+
};
|
|
198
|
+
let execution;
|
|
199
|
+
try {
|
|
200
|
+
execution = await runChatV2PipelineExecution(candidateOptions);
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
if (roundOptions.context.signal.aborted) {
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
// The candidate's provider/model is part of request construction.
|
|
207
|
+
// Treat a failure there as an unsuccessful candidate too: it is
|
|
208
|
+
// exactly what a fallback chain is intended to recover from. This
|
|
209
|
+
// also lets a later profile whose provider supports the same shared
|
|
210
|
+
// prompt/schema continue. If every candidate has the same graph
|
|
211
|
+
// configuration problem, the aggregate error retains every failed
|
|
212
|
+
// candidate diagnostic.
|
|
213
|
+
lastError = error;
|
|
214
|
+
const responseValidationFailure = isChatV2ResponseValidationError(error);
|
|
215
|
+
recordAttempt({
|
|
216
|
+
roundIndex,
|
|
217
|
+
profileIndex,
|
|
218
|
+
provider: candidate.provider,
|
|
219
|
+
model: candidate.model,
|
|
220
|
+
...(candidate.customProviderApi == null ? {} : { customProviderApi: candidate.customProviderApi }),
|
|
221
|
+
stage: responseValidationFailure ? 'response-validation' : 'configuration',
|
|
222
|
+
outcome: 'failure',
|
|
223
|
+
error: getLLMAttemptErrorMessage(error),
|
|
224
|
+
});
|
|
225
|
+
clearPartialResponse(roundOptions);
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
if (execution.outcome === 'success') {
|
|
229
|
+
activeProfileIndex = profileIndex;
|
|
230
|
+
nextRoundIndex += 1;
|
|
231
|
+
return execution.result;
|
|
232
|
+
}
|
|
233
|
+
lastError = execution.failure.normalizedError;
|
|
234
|
+
clearPartialResponse(roundOptions);
|
|
235
|
+
}
|
|
236
|
+
exhausted = true;
|
|
237
|
+
// A scalar profile keeps its underlying provider/configuration error.
|
|
238
|
+
if (params.candidates.length === 1 && lastError !== undefined) {
|
|
239
|
+
throw lastError;
|
|
240
|
+
}
|
|
241
|
+
throw new LLMProfileFallbackExhaustedError(attempts);
|
|
242
|
+
},
|
|
243
|
+
};
|
|
244
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
export const llmProfileFieldSpecs = [
|
|
2
|
+
{ key: 'model', inputId: 'model', valueKind: 'string' },
|
|
3
|
+
{ key: 'useModelInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
4
|
+
{ key: 'temperature', inputId: 'temperature', valueKind: 'required-number' },
|
|
5
|
+
{ key: 'useTemperatureInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
6
|
+
{ key: 'topP', inputId: 'topP', valueKind: 'optional-number' },
|
|
7
|
+
{ key: 'useTopPInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
8
|
+
{ key: 'topK', inputId: 'topK', valueKind: 'optional-number' },
|
|
9
|
+
{ key: 'useTopKInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
10
|
+
{ key: 'presencePenalty', inputId: 'presencePenalty', valueKind: 'optional-number' },
|
|
11
|
+
{ key: 'usePresencePenaltyInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
12
|
+
{ key: 'frequencyPenalty', inputId: 'frequencyPenalty', valueKind: 'optional-number' },
|
|
13
|
+
{ key: 'useFrequencyPenaltyInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
14
|
+
{ key: 'stopSequences', inputId: 'stopSequences' },
|
|
15
|
+
{ key: 'useStopSequencesInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
16
|
+
{ key: 'seed', inputId: 'seed', valueKind: 'optional-number' },
|
|
17
|
+
{ key: 'useSeedInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
18
|
+
{ key: 'maxTokens', inputId: 'maxTokens', valueKind: 'required-number' },
|
|
19
|
+
{ key: 'useMaxTokensInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
20
|
+
{ key: 'provider' },
|
|
21
|
+
{ key: 'apiKeySource', inputId: 'apiKey' },
|
|
22
|
+
{ key: 'customProviderApiKeyProgrammaticName', valueKind: 'string' },
|
|
23
|
+
{ key: 'customProviderApiKeyEnvVarName', valueKind: 'string' },
|
|
24
|
+
{ key: 'customProviderBaseURL', inputId: 'customProviderBaseURL', valueKind: 'string' },
|
|
25
|
+
{ key: 'useCustomProviderBaseURLInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
26
|
+
{ key: 'customProviderApi' },
|
|
27
|
+
{ key: 'headers', inputId: 'headers' },
|
|
28
|
+
{ key: 'useHeadersInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
29
|
+
{ key: 'extraProviderOptions', inputId: 'extraProviderOptions', valueKind: 'string' },
|
|
30
|
+
{ key: 'useExtraProviderOptionsInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
31
|
+
{ key: 'openAIReasoningEffort', valueKind: 'string' },
|
|
32
|
+
{ key: 'openAIReasoningSummary', valueKind: 'string' },
|
|
33
|
+
{ key: 'openAIPreviousResponseId', inputId: 'previousResponseId', valueKind: 'string' },
|
|
34
|
+
{ key: 'useOpenAIPreviousResponseIdInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
35
|
+
{ key: 'enableOpenAIWebSearch', valueKind: 'boolean' },
|
|
36
|
+
{ key: 'openAIWebSearchContextSize' },
|
|
37
|
+
{ key: 'enableOpenAICodeInterpreter', valueKind: 'boolean' },
|
|
38
|
+
{ key: 'anthropicThinkingMode' },
|
|
39
|
+
{ key: 'anthropicThinkingBudget', inputId: 'anthropicThinkingBudget', valueKind: 'optional-number' },
|
|
40
|
+
{ key: 'useAnthropicThinkingBudgetInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
41
|
+
{ key: 'anthropicEffort' },
|
|
42
|
+
{ key: 'anthropicCacheControlTtl' },
|
|
43
|
+
{ key: 'googleThinkingBudget', inputId: 'googleThinkingBudget', valueKind: 'optional-number' },
|
|
44
|
+
{ key: 'useGoogleThinkingBudgetInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
45
|
+
{ key: 'googleThinkingLevel' },
|
|
46
|
+
{ key: 'googleIncludeThoughts', valueKind: 'boolean' },
|
|
47
|
+
{ key: 'enableGoogleSearchGrounding', valueKind: 'boolean' },
|
|
48
|
+
{ key: 'enableGoogleUrlContext', valueKind: 'boolean' },
|
|
49
|
+
];
|
|
50
|
+
export const llmProfileDataKeys = llmProfileFieldSpecs.map((field) => field.key);
|
|
51
|
+
export const llmProfileInputIds = llmProfileFieldSpecs
|
|
52
|
+
.flatMap((field) => ('inputId' in field ? [field.inputId] : []))
|
|
53
|
+
.filter((inputId, index, inputIds) => inputIds.indexOf(inputId) === index);
|
|
54
|
+
function keysForValueKind(valueKind) {
|
|
55
|
+
return llmProfileFieldSpecs
|
|
56
|
+
.filter((field) => 'valueKind' in field && field.valueKind === valueKind)
|
|
57
|
+
.map((field) => field.key);
|
|
58
|
+
}
|
|
59
|
+
/** Runtime validation categories for resolved LLM Profile values. */
|
|
60
|
+
export const llmProfileStringDataKeys = keysForValueKind('string');
|
|
61
|
+
export const llmProfileBooleanDataKeys = keysForValueKind('boolean');
|
|
62
|
+
export const llmProfileRequiredNumberDataKeys = keysForValueKind('required-number');
|
|
63
|
+
export const llmProfileOptionalNumberDataKeys = keysForValueKind('optional-number');
|
|
64
|
+
/** A serialized profile must be self-contained, not driven by hidden ports. */
|
|
65
|
+
export const llmProfileResolvedInputToggleDataKeys = llmProfileFieldSpecs
|
|
66
|
+
.filter((field) => 'resolvedInputToggle' in field && field.resolvedInputToggle)
|
|
67
|
+
.map((field) => field.key);
|
|
@@ -3,6 +3,7 @@ import { getInputOrData } from '../../utils/inputs.js';
|
|
|
3
3
|
import { resolveChatV2Credential } from './chatV2ProviderProfile.js';
|
|
4
4
|
import { resolveLLMChatV2ExtraProviderOptions, resolveLLMChatV2GenerationParameters, resolveLLMChatV2Headers, } from './chatV2RuntimeOptions.js';
|
|
5
5
|
import { LLM_PROFILE_VALUE_VERSION } from './llmProfileTypes.js';
|
|
6
|
+
import { parseCustomProviderApi } from './customProviderApi.js';
|
|
6
7
|
export function resolveLLMProfileNodeValue(params) {
|
|
7
8
|
const { data, inputs, context } = params;
|
|
8
9
|
const runtimeData = data;
|
|
@@ -25,6 +26,7 @@ export function resolveLLMProfileNodeValue(params) {
|
|
|
25
26
|
const googleThinkingBudget = data.provider === 'google' && data.useGoogleThinkingBudgetInput
|
|
26
27
|
? coerceTypeOptional(inputs['googleThinkingBudget'], 'number') ?? data.googleThinkingBudget
|
|
27
28
|
: data.googleThinkingBudget;
|
|
29
|
+
const customProviderApi = parseCustomProviderApi(data.customProviderApi);
|
|
28
30
|
const credential = resolveChatV2Credential({
|
|
29
31
|
provider: data.provider,
|
|
30
32
|
context,
|
|
@@ -58,6 +60,7 @@ export function resolveLLMProfileNodeValue(params) {
|
|
|
58
60
|
useSeedInput: false,
|
|
59
61
|
customProviderBaseURL,
|
|
60
62
|
useCustomProviderBaseURLInput: false,
|
|
63
|
+
customProviderApi,
|
|
61
64
|
openAIPreviousResponseId,
|
|
62
65
|
useOpenAIPreviousResponseIdInput: false,
|
|
63
66
|
headers: Object.entries(headers ?? {}).map(([key, value]) => ({ key, value })),
|
|
@@ -5,24 +5,7 @@ export const LLM_PROFILE_VALUE_VERSION = 1;
|
|
|
5
5
|
* until their matching provider or input toggle is enabled. This lets editor
|
|
6
6
|
* operations preserve recoverable connections across configuration changes.
|
|
7
7
|
*/
|
|
8
|
-
export
|
|
9
|
-
'model',
|
|
10
|
-
'apiKey',
|
|
11
|
-
'customProviderBaseURL',
|
|
12
|
-
'previousResponseId',
|
|
13
|
-
'temperature',
|
|
14
|
-
'maxTokens',
|
|
15
|
-
'topP',
|
|
16
|
-
'topK',
|
|
17
|
-
'presencePenalty',
|
|
18
|
-
'frequencyPenalty',
|
|
19
|
-
'stopSequences',
|
|
20
|
-
'seed',
|
|
21
|
-
'headers',
|
|
22
|
-
'extraProviderOptions',
|
|
23
|
-
'anthropicThinkingBudget',
|
|
24
|
-
'googleThinkingBudget',
|
|
25
|
-
];
|
|
8
|
+
export { llmProfileInputIds } from './llmProfileFieldRegistry.js';
|
|
26
9
|
export function createLLMProfileNodeData() {
|
|
27
10
|
return pickLLMChatV2ProfileData(createLLMChatV2NodeData());
|
|
28
11
|
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { inferType } from '../../utils/coerceType.js';
|
|
2
|
+
import { isChatV2StructuredResponseFormat } from './chatV2ResponseFormat.js';
|
|
3
|
+
function tryParseJson(value) {
|
|
4
|
+
try {
|
|
5
|
+
return JSON.parse(value);
|
|
6
|
+
}
|
|
7
|
+
catch {
|
|
8
|
+
return undefined;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export function materializeLLMResponse(params) {
|
|
12
|
+
const { rawText, structuredOutput, responseFormat } = params;
|
|
13
|
+
let value;
|
|
14
|
+
let source;
|
|
15
|
+
if (!isChatV2StructuredResponseFormat(responseFormat)) {
|
|
16
|
+
value = { type: 'string', value: rawText };
|
|
17
|
+
source = 'plain-text';
|
|
18
|
+
}
|
|
19
|
+
else if (structuredOutput !== undefined) {
|
|
20
|
+
value = inferType(structuredOutput);
|
|
21
|
+
source = 'sdk-structured';
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
const parsed = tryParseJson(rawText);
|
|
25
|
+
if (parsed === undefined) {
|
|
26
|
+
value = { type: 'string', value: rawText };
|
|
27
|
+
source = 'plain-text';
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
value = inferType(parsed);
|
|
31
|
+
source = 'text-json';
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const validationRequested = responseFormat === 'json_schema';
|
|
35
|
+
const valid = !validationRequested || value.type === 'object';
|
|
36
|
+
return {
|
|
37
|
+
rawText,
|
|
38
|
+
value,
|
|
39
|
+
source,
|
|
40
|
+
validation: !validationRequested ? 'not-requested' : valid ? 'valid' : 'invalid',
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -104,6 +104,20 @@ export async function chatMessagesToModelMessages(messages, options) {
|
|
|
104
104
|
});
|
|
105
105
|
break;
|
|
106
106
|
}
|
|
107
|
+
case 'developer': {
|
|
108
|
+
// AI SDK ModelMessage is provider-neutral and currently exposes only
|
|
109
|
+
// `system` for instruction messages. OpenAI and OpenAI-compatible
|
|
110
|
+
// transports restore the explicit role at the request-body boundary.
|
|
111
|
+
// Providers without a developer role receive it as a system instruction.
|
|
112
|
+
result.push({
|
|
113
|
+
role: 'system',
|
|
114
|
+
content: stringifyParts(msg.message),
|
|
115
|
+
providerOptions: options.provider === 'anthropic'
|
|
116
|
+
? getAnthropicCacheMetadata(!!msg.isCacheBreakpoint, options.anthropicCacheControlTtl)
|
|
117
|
+
: undefined,
|
|
118
|
+
});
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
107
121
|
case 'user': {
|
|
108
122
|
const parts = Array.isArray(msg.message) ? msg.message : [msg.message];
|
|
109
123
|
if (parts.length === 1 && typeof parts[0] === 'string' && !msg.isCacheBreakpoint) {
|
|
@@ -1,10 +1,48 @@
|
|
|
1
1
|
import { anthropicModels } from '../../plugins/anthropic/anthropic.js';
|
|
2
2
|
import { generativeAiGoogleModels } from '../../plugins/google/google.js';
|
|
3
3
|
import { openaiModels } from '../../utils/openai.js';
|
|
4
|
+
const TOKENS_PER_THOUSAND = 1_000;
|
|
5
|
+
function isFiniteNonNegative(value) {
|
|
6
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0;
|
|
7
|
+
}
|
|
8
|
+
function normalizePerThousandTokenModelRegistry(provider, models) {
|
|
9
|
+
return Object.fromEntries(Object.entries(models).map(([modelId, model]) => {
|
|
10
|
+
if (model.pricing === 'unpriced') {
|
|
11
|
+
if (model.cost != null) {
|
|
12
|
+
throw new Error(`Unpriced ${provider} LLM Chat model ${modelId} must not define a rate.`);
|
|
13
|
+
}
|
|
14
|
+
return [
|
|
15
|
+
modelId,
|
|
16
|
+
{
|
|
17
|
+
maxTokens: model.maxTokens,
|
|
18
|
+
displayName: model.displayName,
|
|
19
|
+
},
|
|
20
|
+
];
|
|
21
|
+
}
|
|
22
|
+
if (model.cost == null ||
|
|
23
|
+
!isFiniteNonNegative(model.cost.prompt) ||
|
|
24
|
+
!isFiniteNonNegative(model.cost.completion)) {
|
|
25
|
+
throw new Error(`Invalid ${provider} LLM Chat pricing for model ${modelId}.`);
|
|
26
|
+
}
|
|
27
|
+
return [
|
|
28
|
+
modelId,
|
|
29
|
+
{
|
|
30
|
+
maxTokens: model.maxTokens,
|
|
31
|
+
displayName: model.displayName,
|
|
32
|
+
cost: {
|
|
33
|
+
prompt: model.cost.prompt / TOKENS_PER_THOUSAND,
|
|
34
|
+
completion: model.cost.completion / TOKENS_PER_THOUSAND,
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
];
|
|
38
|
+
}));
|
|
39
|
+
}
|
|
4
40
|
const chatV2ModelRegistry = {
|
|
5
|
-
|
|
41
|
+
// OpenAI and Google catalogs predate LLM Chat V2 and store USD per 1,000
|
|
42
|
+
// tokens for their legacy nodes. Normalize them once at this boundary.
|
|
43
|
+
openai: normalizePerThousandTokenModelRegistry('OpenAI', openaiModels),
|
|
6
44
|
anthropic: anthropicModels,
|
|
7
|
-
google: generativeAiGoogleModels,
|
|
45
|
+
google: normalizePerThousandTokenModelRegistry('Google', generativeAiGoogleModels),
|
|
8
46
|
custom: {},
|
|
9
47
|
};
|
|
10
48
|
export function getChatV2ModelRegistry() {
|
|
@@ -16,8 +54,20 @@ export function getChatV2ModelInfo(provider, modelId) {
|
|
|
16
54
|
}
|
|
17
55
|
export function calculateChatV2Cost(provider, modelId, promptTokens, completionTokens) {
|
|
18
56
|
const model = getChatV2ModelInfo(provider, modelId);
|
|
19
|
-
if (model == null) {
|
|
57
|
+
if (model?.cost == null || !isFiniteNonNegative(promptTokens) || !isFiniteNonNegative(completionTokens)) {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
const cost = model.cost.prompt * promptTokens + model.cost.completion * completionTokens;
|
|
61
|
+
return isFiniteNonNegative(cost) ? cost : undefined;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Estimates a call only when the provider reported both billable text-token
|
|
65
|
+
* counts. Cache discounts, long-context premiums, and provider tool fees stay
|
|
66
|
+
* outside this baseline estimate until their billing inputs are modeled.
|
|
67
|
+
*/
|
|
68
|
+
export function calculateChatV2UsageCost(provider, modelId, usage) {
|
|
69
|
+
if (!isFiniteNonNegative(usage?.inputTokens) || !isFiniteNonNegative(usage.outputTokens)) {
|
|
20
70
|
return undefined;
|
|
21
71
|
}
|
|
22
|
-
return
|
|
72
|
+
return calculateChatV2Cost(provider, modelId, usage.inputTokens, usage.outputTokens);
|
|
23
73
|
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
import { getCustomProviderApiContract } from './customProviderApi.js';
|
|
2
|
+
import { getChatV2ProviderCapabilities } from './chatV2ProviderRegistry.js';
|
|
3
|
+
export const LLM_CHAT_V2_PARALLEL_TOOL_CALLS_HELPER_MESSAGE = 'Allows the model to request multiple tool calls in one round.';
|
|
2
4
|
export function supportsLLMChatV2ParallelToolCalls(provider) {
|
|
3
|
-
return provider
|
|
5
|
+
return getChatV2ProviderCapabilities(provider).parallelToolCalls;
|
|
4
6
|
}
|
|
5
7
|
function mergeProviderOptions(providerOptions, provider, options) {
|
|
6
8
|
return {
|
|
@@ -26,6 +28,11 @@ export function applyLLMChatV2ParallelToolCallProviderOptions(params) {
|
|
|
26
28
|
disableParallelToolUse: !parallelToolCalls,
|
|
27
29
|
});
|
|
28
30
|
case 'custom':
|
|
31
|
+
if (getCustomProviderApiContract(params.customProviderApi).parallelToolCalls === 'openai-option') {
|
|
32
|
+
return mergeProviderOptions(providerOptions, 'openai', {
|
|
33
|
+
parallelToolCalls: !!parallelToolCalls,
|
|
34
|
+
});
|
|
35
|
+
}
|
|
29
36
|
// OpenAI-compatible endpoints vary widely. Do not send an unsupported
|
|
30
37
|
// field to existing/default Custom-provider graphs unless the user
|
|
31
38
|
// explicitly opts in to requesting parallel calls.
|