@valerypopoff/rivet2-core 2.1.9 → 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 +5618 -2533
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/webAppRuntime.cjs +333 -22
- package/dist/cjs/webAppRuntime.cjs.map +4 -4
- package/dist/esm/api/createProcessor.js +2 -0
- package/dist/esm/exports.js +1 -0
- package/dist/esm/integrations/CodeRunner.js +2 -7
- package/dist/esm/integrations/CodeRunnerOptions.js +7 -0
- package/dist/esm/model/AgentResponseTrace.js +558 -0
- package/dist/esm/model/ConnectedToolContinuationHost.js +33 -0
- package/dist/esm/model/GraphProcessor.js +165 -74
- package/dist/esm/model/NodeImpl.js +6 -0
- package/dist/esm/model/ProcessContextBuilder.js +3 -1
- package/dist/esm/model/RecordingPlayer.js +212 -25
- package/dist/esm/model/SplitRunProcessor.js +49 -8
- package/dist/esm/model/SubprocessorBridge.js +3 -0
- package/dist/esm/model/ToolCallContinuationCoordinator.js +7 -3
- package/dist/esm/model/UiGraph.js +21 -0
- package/dist/esm/model/UiGraphActionProtocol.js +3 -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/aiSdkTools.js +3 -2
- package/dist/esm/model/chat-v2/aiSdkBridge.js +146 -14
- package/dist/esm/model/chat-v2/chatV2CallObserver.js +11 -5
- package/dist/esm/model/chat-v2/chatV2CredentialNames.js +93 -0
- package/dist/esm/model/chat-v2/chatV2EditorCache.js +47 -20
- 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 +48 -108
- package/dist/esm/model/chat-v2/chatV2Pipeline.js +101 -149
- package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +39 -4
- package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +9 -0
- package/dist/esm/model/chat-v2/chatV2RequestPlan.js +2 -3
- package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +63 -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 +7 -7
- package/dist/esm/model/chat-v2/chatV2Shared.js +1 -1
- package/dist/esm/model/chat-v2/chatV2Types.js +20 -8
- package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +78 -0
- package/dist/esm/model/chat-v2/customProviderApi.js +40 -0
- package/dist/esm/model/chat-v2/index.js +15 -0
- package/dist/esm/model/chat-v2/llmChatV2Body.js +289 -0
- package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +32 -0
- package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +25 -0
- package/dist/esm/model/chat-v2/llmChatV2NodeData.js +13 -50
- package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +117 -24
- package/dist/esm/model/chat-v2/llmChatV2NodeMigration.js +24 -0
- package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +150 -199
- 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 +79 -0
- package/dist/esm/model/chat-v2/llmProfile.js +52 -65
- package/dist/esm/model/chat-v2/llmProfileBody.js +193 -0
- package/dist/esm/model/chat-v2/llmProfileFallback.js +442 -100
- package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +74 -0
- package/dist/esm/model/chat-v2/llmProfileHealthStore.js +326 -0
- package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +55 -33
- 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/modelRegistry.js +54 -4
- package/dist/esm/model/chat-v2/parallelToolCalls.js +9 -2
- package/dist/esm/model/chat-v2/providerOptions.js +116 -24
- 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 -35
- 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/ChatNode.js +6 -0
- package/dist/esm/model/nodes/ChatNodeBase.js +1 -0
- package/dist/esm/model/nodes/CodeNewNode.js +5 -47
- package/dist/esm/model/nodes/CodeNode.js +4 -46
- package/dist/esm/model/nodes/DelegateFunctionCallNode.js +19 -6
- package/dist/esm/model/nodes/ExpressionNode.js +5 -8
- package/dist/esm/model/nodes/LLMChatV2Node.js +121 -229
- package/dist/esm/model/nodes/LLMProfileNode.js +27 -8
- package/dist/esm/model/nodes/MatchNode.js +86 -41
- package/dist/esm/model/nodes/PromptNode.js +7 -0
- package/dist/esm/model/nodes/ToolNode.js +7 -0
- package/dist/esm/model/nodes/toolCallDelegation.js +177 -110
- package/dist/esm/plugins/anthropic/anthropic.js +4 -4
- package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +7 -0
- 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/google/google.js +5 -9
- package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +4 -1
- package/dist/esm/plugins.js +1 -2
- package/dist/esm/recording/ExecutionRecorder.js +62 -13
- package/dist/esm/utils/emitDetached.js +6 -3
- package/dist/esm/utils/openai.js +60 -16
- package/dist/esm/utils/serialization/serialization.js +2 -19
- package/dist/esm/webAppRuntime.js +3 -2
- package/dist/types/api/createProcessor.d.ts +3 -0
- package/dist/types/exports.d.ts +1 -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 +123 -0
- package/dist/types/model/ConnectedToolContinuationHost.d.ts +34 -0
- package/dist/types/model/EditorDefinition.d.ts +16 -0
- package/dist/types/model/ExecutorProtocol.d.ts +32 -11
- package/dist/types/model/GraphProcessor.d.ts +41 -9
- package/dist/types/model/NodeBase.d.ts +0 -10
- 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 +99 -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 +10 -3
- package/dist/types/model/UiGraph.d.ts +8 -0
- package/dist/types/model/UiGraphActionProtocol.d.ts +3 -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/chatV2CredentialNames.d.ts +30 -0
- package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +2 -3
- package/dist/types/model/chat-v2/chatV2Outputs.d.ts +6 -16
- package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +13 -17
- package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +7 -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 +25 -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/chatV2RuntimeOptions.d.ts +3 -8
- package/dist/types/model/chat-v2/chatV2Types.d.ts +44 -10
- package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +14 -0
- package/dist/types/model/chat-v2/customProviderApi.d.ts +22 -0
- package/dist/types/model/chat-v2/index.d.ts +15 -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 +19 -3
- package/dist/types/model/chat-v2/llmChatV2NodeMigration.d.ts +8 -0
- package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +14 -16
- 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 +20 -0
- package/dist/types/model/chat-v2/llmProfile.d.ts +14 -0
- package/dist/types/model/chat-v2/llmProfileBody.d.ts +20 -0
- package/dist/types/model/chat-v2/llmProfileFallback.d.ts +36 -49
- package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +209 -0
- 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 +4 -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 +12 -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/ChatNode.d.ts +2 -1
- 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/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/MatchNode.d.ts +6 -0
- package/dist/types/model/nodes/PromptNode.d.ts +4 -1
- 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/gentrace/gentraceSdk.d.ts +0 -1
- package/dist/types/plugins/gentrace/plugin.d.ts +55 -9
- package/dist/types/plugins/google/google.d.ts +2 -8
- package/dist/types/plugins.d.ts +1 -1
- package/dist/types/recording/ExecutionRecorder.d.ts +7 -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,74 @@
|
|
|
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: 'providerApiKeyNames' },
|
|
23
|
+
{ key: 'customProviderApiKeyProgrammaticName', valueKind: 'string' },
|
|
24
|
+
{ key: 'customProviderApiKeyEnvVarName', valueKind: 'string' },
|
|
25
|
+
{ key: 'customProviderBaseURL', inputId: 'customProviderBaseURL', valueKind: 'string' },
|
|
26
|
+
{ key: 'useCustomProviderBaseURLInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
27
|
+
{ key: 'customProviderApi' },
|
|
28
|
+
{ key: 'headers', inputId: 'headers' },
|
|
29
|
+
{ key: 'useHeadersInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
30
|
+
{ key: 'extraProviderOptions', inputId: 'extraProviderOptions', valueKind: 'string' },
|
|
31
|
+
{ key: 'useExtraProviderOptionsInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
32
|
+
{ key: 'openAIReasoningEffort', valueKind: 'string' },
|
|
33
|
+
{ key: 'openAIReasoningSummary', valueKind: 'string' },
|
|
34
|
+
{ key: 'openAIPreviousResponseId', inputId: 'previousResponseId', valueKind: 'string' },
|
|
35
|
+
{ key: 'useOpenAIPreviousResponseIdInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
36
|
+
{ key: 'enableOpenAIWebSearch', valueKind: 'boolean' },
|
|
37
|
+
{ key: 'openAIWebSearchContextSize' },
|
|
38
|
+
{ key: 'enableOpenAICodeInterpreter', valueKind: 'boolean' },
|
|
39
|
+
{ key: 'anthropicThinkingMode' },
|
|
40
|
+
{ key: 'anthropicThinkingBudget', inputId: 'anthropicThinkingBudget', valueKind: 'optional-number' },
|
|
41
|
+
{ key: 'useAnthropicThinkingBudgetInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
42
|
+
{ key: 'anthropicEffort' },
|
|
43
|
+
{ key: 'anthropicCacheControlTtl' },
|
|
44
|
+
{ key: 'googleThinkingBudget', inputId: 'googleThinkingBudget', valueKind: 'optional-number' },
|
|
45
|
+
{ key: 'useGoogleThinkingBudgetInput', valueKind: 'boolean', resolvedInputToggle: true },
|
|
46
|
+
{ key: 'googleThinkingLevel' },
|
|
47
|
+
{ key: 'googleIncludeThoughts', valueKind: 'boolean' },
|
|
48
|
+
{ key: 'enableGoogleSearchGrounding', valueKind: 'boolean' },
|
|
49
|
+
{ key: 'enableGoogleUrlContext', valueKind: 'boolean' },
|
|
50
|
+
{ key: 'enableCircuitBreaker', valueKind: 'boolean' },
|
|
51
|
+
{ key: 'firstOutputTimeoutMs', valueKind: 'required-number' },
|
|
52
|
+
{ key: 'streamInactivityTimeoutMs', valueKind: 'required-number' },
|
|
53
|
+
{ key: 'circuitBreakerFailureThreshold', valueKind: 'required-number' },
|
|
54
|
+
{ key: 'circuitBreakerFailureWindowMs', valueKind: 'required-number' },
|
|
55
|
+
{ key: 'circuitBreakerOpenDurationMs', valueKind: 'required-number' },
|
|
56
|
+
];
|
|
57
|
+
export const llmProfileDataKeys = llmProfileFieldSpecs.map((field) => field.key);
|
|
58
|
+
export const llmProfileInputIds = llmProfileFieldSpecs
|
|
59
|
+
.flatMap((field) => ('inputId' in field ? [field.inputId] : []))
|
|
60
|
+
.filter((inputId, index, inputIds) => inputIds.indexOf(inputId) === index);
|
|
61
|
+
function keysForValueKind(valueKind) {
|
|
62
|
+
return llmProfileFieldSpecs
|
|
63
|
+
.filter((field) => 'valueKind' in field && field.valueKind === valueKind)
|
|
64
|
+
.map((field) => field.key);
|
|
65
|
+
}
|
|
66
|
+
/** Runtime validation categories for resolved LLM Profile values. */
|
|
67
|
+
export const llmProfileStringDataKeys = keysForValueKind('string');
|
|
68
|
+
export const llmProfileBooleanDataKeys = keysForValueKind('boolean');
|
|
69
|
+
export const llmProfileRequiredNumberDataKeys = keysForValueKind('required-number');
|
|
70
|
+
export const llmProfileOptionalNumberDataKeys = keysForValueKind('optional-number');
|
|
71
|
+
/** A serialized profile must be self-contained, not driven by hidden ports. */
|
|
72
|
+
export const llmProfileResolvedInputToggleDataKeys = llmProfileFieldSpecs
|
|
73
|
+
.filter((field) => 'resolvedInputToggle' in field && field.resolvedInputToggle)
|
|
74
|
+
.map((field) => field.key);
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
import { nanoid } from 'nanoid/non-secure';
|
|
2
|
+
import CryptoJS from 'crypto-js';
|
|
3
|
+
import stableStringify from 'safe-stable-stringify';
|
|
4
|
+
export const DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS = 30_000;
|
|
5
|
+
export const DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS = 30_000;
|
|
6
|
+
export const DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD = 3;
|
|
7
|
+
export const DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS = 300_000;
|
|
8
|
+
export const DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS = 300_000;
|
|
9
|
+
const LLM_PROFILE_HALF_OPEN_LEASE_SAFETY_MARGIN_MS = 5_000;
|
|
10
|
+
const LLM_PROFILE_CLOSED_PERMIT_MIN_RETENTION_MS = 24 * 60 * 60 * 1_000;
|
|
11
|
+
export class RivetLLMProfileHealthPolicyError extends Error {
|
|
12
|
+
constructor(message) {
|
|
13
|
+
super(`LLM profile suspension policy is invalid: ${message}`);
|
|
14
|
+
this.name = 'RivetLLMProfileHealthPolicyError';
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function requirePositiveInteger(value, label) {
|
|
18
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {
|
|
19
|
+
throw new RivetLLMProfileHealthPolicyError(`${label} must be a positive integer.`);
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
export function resolveRivetLLMProfileCircuitBreakerPolicy(configuration) {
|
|
24
|
+
if (configuration.enableCircuitBreaker !== true) {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
const firstOutputTimeoutMs = requirePositiveInteger(configuration.firstOutputTimeoutMs ?? DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS, 'Useful output wait time');
|
|
28
|
+
const streamInactivityTimeoutMs = requirePositiveInteger(configuration.streamInactivityTimeoutMs ?? DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS, 'Stream inactivity timeout');
|
|
29
|
+
const failureThreshold = requirePositiveInteger(configuration.circuitBreakerFailureThreshold ?? DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD, 'Failures before suspension');
|
|
30
|
+
const failureWindowMs = requirePositiveInteger(configuration.circuitBreakerFailureWindowMs ?? DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS, 'Failure window');
|
|
31
|
+
const openDurationMs = requirePositiveInteger(configuration.circuitBreakerOpenDurationMs ?? DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS, 'Suspension duration');
|
|
32
|
+
return {
|
|
33
|
+
failureThreshold,
|
|
34
|
+
failureWindowMs,
|
|
35
|
+
openDurationMs,
|
|
36
|
+
// A live streaming probe renews this lease on useful output. The bounded
|
|
37
|
+
// safety margin lets a dead owner recover promptly without coupling the
|
|
38
|
+
// probe lease to the (usually much longer) circuit cooldown.
|
|
39
|
+
halfOpenLeaseMs: Math.max(firstOutputTimeoutMs, streamInactivityTimeoutMs) + LLM_PROFILE_HALF_OPEN_LEASE_SAFETY_MARGIN_MS,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function sha256(value) {
|
|
43
|
+
return `sha256:${CryptoJS.SHA256(value).toString(CryptoJS.enc.Hex)}`;
|
|
44
|
+
}
|
|
45
|
+
export function createRivetLLMProfileHealthIdentity(params) {
|
|
46
|
+
// Circuit health belongs to the physical provider route and credentials,
|
|
47
|
+
// not to generation policy. A temperature/cooldown edit must not silently
|
|
48
|
+
// create a fresh circuit, while changing the model, endpoint, auth, or
|
|
49
|
+
// routing headers must never inherit another route's outage history.
|
|
50
|
+
const routingConfiguration = {
|
|
51
|
+
provider: params.configuration.provider,
|
|
52
|
+
model: params.configuration.model,
|
|
53
|
+
...(params.configuration.provider !== 'custom'
|
|
54
|
+
? {}
|
|
55
|
+
: {
|
|
56
|
+
customProviderApi: params.configuration.customProviderApi ?? 'completions',
|
|
57
|
+
customProviderBaseURL: params.configuration.customProviderBaseURL,
|
|
58
|
+
}),
|
|
59
|
+
headers: canonicalizeEffectiveRoutingHeaders(params.chatNodeHeaders, params.configuration.headers),
|
|
60
|
+
};
|
|
61
|
+
const serialized = stableStringify({
|
|
62
|
+
routingConfiguration,
|
|
63
|
+
credential: params.credential,
|
|
64
|
+
}) ?? '';
|
|
65
|
+
const configurationFingerprint = sha256(serialized);
|
|
66
|
+
const projectId = params.projectId == null ? undefined : String(params.projectId);
|
|
67
|
+
const profileNodeId = params.profileNodeId == null ? undefined : String(params.profileNodeId);
|
|
68
|
+
const key = sha256(stableStringify({
|
|
69
|
+
kind: 'rivet-llm-profile-health',
|
|
70
|
+
projectId,
|
|
71
|
+
profileNodeId,
|
|
72
|
+
configurationFingerprint,
|
|
73
|
+
}) ?? '');
|
|
74
|
+
return {
|
|
75
|
+
key: `llm-profile:${key}`,
|
|
76
|
+
...(params.projectId == null ? {} : { projectId: params.projectId }),
|
|
77
|
+
...(params.profileNodeId == null ? {} : { profileNodeId: params.profileNodeId }),
|
|
78
|
+
provider: params.configuration.provider,
|
|
79
|
+
model: params.configuration.model,
|
|
80
|
+
...(params.configuration.provider !== 'custom'
|
|
81
|
+
? {}
|
|
82
|
+
: { customProviderApi: params.configuration.customProviderApi ?? 'completions' }),
|
|
83
|
+
configurationFingerprint,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
function canonicalizeEffectiveRoutingHeaders(chatNodeHeaders, profileHeaders) {
|
|
87
|
+
// Provider resolution spreads project-wide headers first and profile
|
|
88
|
+
// headers second. Normalize names here because HTTP field names are
|
|
89
|
+
// case-insensitive, while preserving that same profile-wins precedence.
|
|
90
|
+
// Values remain confined to the SHA-256 input and never enter the public
|
|
91
|
+
// identity or store key in plaintext.
|
|
92
|
+
const headers = new Map();
|
|
93
|
+
for (const [key, value] of Object.entries(chatNodeHeaders ?? {})) {
|
|
94
|
+
const normalizedKey = key.trim().toLowerCase();
|
|
95
|
+
if (normalizedKey)
|
|
96
|
+
headers.set(normalizedKey, value);
|
|
97
|
+
}
|
|
98
|
+
for (const { key, value } of profileHeaders) {
|
|
99
|
+
const normalizedKey = key.trim().toLowerCase();
|
|
100
|
+
if (normalizedKey)
|
|
101
|
+
headers.set(normalizedKey, value);
|
|
102
|
+
}
|
|
103
|
+
return [...headers.entries()].sort(([left], [right]) => left.localeCompare(right));
|
|
104
|
+
}
|
|
105
|
+
function requireMatchingProjectScope(existing, identity) {
|
|
106
|
+
const storedProjectId = existing.identity.projectId == null ? undefined : String(existing.identity.projectId);
|
|
107
|
+
const requestProjectId = identity.projectId == null ? undefined : String(identity.projectId);
|
|
108
|
+
if (storedProjectId !== requestProjectId) {
|
|
109
|
+
throw new Error(`LLM profile reliability key ${identity.key} belongs to a different project scope.`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function closedPermitRetentionMs(policy) {
|
|
113
|
+
return Math.max(LLM_PROFILE_CLOSED_PERMIT_MIN_RETENTION_MS, policy.failureWindowMs, policy.openDurationMs, policy.halfOpenLeaseMs);
|
|
114
|
+
}
|
|
115
|
+
function pruneClosedPermits(entry, now) {
|
|
116
|
+
for (const [permitId, expiresAt] of entry.closedPermits) {
|
|
117
|
+
if (expiresAt <= now)
|
|
118
|
+
entry.closedPermits.delete(permitId);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function pruneFailures(entry, policy, now) {
|
|
122
|
+
const windowStart = now - policy.failureWindowMs;
|
|
123
|
+
entry.failureTimestamps = entry.failureTimestamps.filter((timestamp) => timestamp >= windowStart);
|
|
124
|
+
}
|
|
125
|
+
function getState(entry, now) {
|
|
126
|
+
if (entry.openUntil == null)
|
|
127
|
+
return 'closed';
|
|
128
|
+
if (entry.openUntil > now)
|
|
129
|
+
return 'open';
|
|
130
|
+
return 'half-open';
|
|
131
|
+
}
|
|
132
|
+
function toSnapshot(entry, policy, now) {
|
|
133
|
+
pruneFailures(entry, policy, now);
|
|
134
|
+
const state = getState(entry, now);
|
|
135
|
+
return {
|
|
136
|
+
identity: entry.identity,
|
|
137
|
+
state,
|
|
138
|
+
failureCount: entry.failureTimestamps.length,
|
|
139
|
+
...(entry.openUntil == null ? {} : { openUntil: entry.openUntil }),
|
|
140
|
+
...(state !== 'half-open' || entry.halfOpenLeaseUntil == null
|
|
141
|
+
? {}
|
|
142
|
+
: { halfOpenLeaseUntil: entry.halfOpenLeaseUntil }),
|
|
143
|
+
updatedAt: entry.updatedAt,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/** Process-local reference implementation used when a host does not supply durable shared storage. */
|
|
147
|
+
export class InMemoryRivetLLMProfileHealthStore {
|
|
148
|
+
#entries = new Map();
|
|
149
|
+
#now;
|
|
150
|
+
constructor(options = {}) {
|
|
151
|
+
this.#now = options.now ?? Date.now;
|
|
152
|
+
}
|
|
153
|
+
#pruneStaleEntries(now) {
|
|
154
|
+
for (const [key, entry] of this.#entries) {
|
|
155
|
+
pruneFailures(entry, entry.policy, now);
|
|
156
|
+
pruneClosedPermits(entry, now);
|
|
157
|
+
const isEmptyClosedEntry = entry.failureTimestamps.length === 0 &&
|
|
158
|
+
entry.openUntil == null &&
|
|
159
|
+
entry.halfOpenPermitId == null &&
|
|
160
|
+
entry.closedPermits.size === 0;
|
|
161
|
+
if (isEmptyClosedEntry && entry.updatedAt + closedPermitRetentionMs(entry.policy) <= now) {
|
|
162
|
+
this.#entries.delete(key);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
begin(request) {
|
|
167
|
+
const { identity, policy } = request;
|
|
168
|
+
const now = this.#now();
|
|
169
|
+
this.#pruneStaleEntries(now);
|
|
170
|
+
let entry = this.#entries.get(identity.key);
|
|
171
|
+
if (entry == null) {
|
|
172
|
+
entry = { identity, failureTimestamps: [], updatedAt: now, policy, closedPermits: new Map() };
|
|
173
|
+
this.#entries.set(identity.key, entry);
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
requireMatchingProjectScope(entry, identity);
|
|
177
|
+
entry.identity = identity;
|
|
178
|
+
entry.policy = policy;
|
|
179
|
+
}
|
|
180
|
+
pruneFailures(entry, policy, now);
|
|
181
|
+
pruneClosedPermits(entry, now);
|
|
182
|
+
if (entry.openUntil != null && entry.openUntil > now) {
|
|
183
|
+
return {
|
|
184
|
+
disposition: 'deny',
|
|
185
|
+
state: 'open',
|
|
186
|
+
retryAt: entry.openUntil,
|
|
187
|
+
snapshot: toSnapshot(entry, policy, now),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
if (entry.openUntil != null) {
|
|
191
|
+
if (entry.halfOpenPermitId != null && (entry.halfOpenLeaseUntil ?? 0) > now) {
|
|
192
|
+
return {
|
|
193
|
+
disposition: 'deny',
|
|
194
|
+
state: 'half-open',
|
|
195
|
+
retryAt: entry.halfOpenLeaseUntil,
|
|
196
|
+
snapshot: toSnapshot(entry, policy, now),
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
const permitId = nanoid();
|
|
200
|
+
entry.halfOpenPermitId = permitId;
|
|
201
|
+
entry.halfOpenLeaseUntil = now + policy.halfOpenLeaseMs;
|
|
202
|
+
entry.updatedAt = now;
|
|
203
|
+
return {
|
|
204
|
+
disposition: 'allow',
|
|
205
|
+
state: 'half-open',
|
|
206
|
+
permitId,
|
|
207
|
+
snapshot: toSnapshot(entry, policy, now),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
const permitId = nanoid();
|
|
211
|
+
entry.closedPermits.set(permitId, now + closedPermitRetentionMs(policy));
|
|
212
|
+
entry.updatedAt = now;
|
|
213
|
+
return {
|
|
214
|
+
disposition: 'allow',
|
|
215
|
+
state: 'closed',
|
|
216
|
+
permitId,
|
|
217
|
+
snapshot: toSnapshot(entry, policy, now),
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
finish(request) {
|
|
221
|
+
const { identity, policy, permitId, outcome } = request;
|
|
222
|
+
const now = this.#now();
|
|
223
|
+
this.#pruneStaleEntries(now);
|
|
224
|
+
const entry = this.#entries.get(identity.key);
|
|
225
|
+
if (entry == null) {
|
|
226
|
+
return {
|
|
227
|
+
identity,
|
|
228
|
+
state: 'closed',
|
|
229
|
+
failureCount: 0,
|
|
230
|
+
updatedAt: now,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
requireMatchingProjectScope(entry, identity);
|
|
234
|
+
entry.identity = identity;
|
|
235
|
+
entry.policy = policy;
|
|
236
|
+
pruneFailures(entry, policy, now);
|
|
237
|
+
pruneClosedPermits(entry, now);
|
|
238
|
+
const ownsHalfOpenLease = entry.halfOpenPermitId === permitId;
|
|
239
|
+
const ownsClosedPermit = entry.closedPermits.delete(permitId);
|
|
240
|
+
if (!ownsHalfOpenLease && !ownsClosedPermit) {
|
|
241
|
+
return toSnapshot(entry, policy, now);
|
|
242
|
+
}
|
|
243
|
+
if (outcome === 'healthy' && ownsHalfOpenLease) {
|
|
244
|
+
entry.failureTimestamps = [];
|
|
245
|
+
entry.openUntil = undefined;
|
|
246
|
+
entry.halfOpenPermitId = undefined;
|
|
247
|
+
entry.halfOpenLeaseUntil = undefined;
|
|
248
|
+
// Requests admitted before the circuit opened belong to the previous
|
|
249
|
+
// health generation. Once the single recovery probe succeeds, their
|
|
250
|
+
// eventual results must not immediately poison the recovered circuit.
|
|
251
|
+
entry.closedPermits.clear();
|
|
252
|
+
}
|
|
253
|
+
else if (outcome === 'unhealthy') {
|
|
254
|
+
const wasOpen = entry.openUntil != null;
|
|
255
|
+
entry.failureTimestamps.push(now);
|
|
256
|
+
if (ownsHalfOpenLease || (!wasOpen && entry.failureTimestamps.length >= policy.failureThreshold)) {
|
|
257
|
+
entry.openUntil = now + policy.openDurationMs;
|
|
258
|
+
}
|
|
259
|
+
if (ownsHalfOpenLease) {
|
|
260
|
+
entry.halfOpenPermitId = undefined;
|
|
261
|
+
entry.halfOpenLeaseUntil = undefined;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
else if (outcome === 'ignored' && ownsHalfOpenLease) {
|
|
265
|
+
entry.halfOpenPermitId = undefined;
|
|
266
|
+
entry.halfOpenLeaseUntil = undefined;
|
|
267
|
+
}
|
|
268
|
+
entry.updatedAt = now;
|
|
269
|
+
return toSnapshot(entry, policy, now);
|
|
270
|
+
}
|
|
271
|
+
renew(request) {
|
|
272
|
+
const now = this.#now();
|
|
273
|
+
this.#pruneStaleEntries(now);
|
|
274
|
+
const entry = this.#entries.get(request.identity.key);
|
|
275
|
+
if (entry == null) {
|
|
276
|
+
return {
|
|
277
|
+
identity: request.identity,
|
|
278
|
+
state: 'closed',
|
|
279
|
+
failureCount: 0,
|
|
280
|
+
updatedAt: now,
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
requireMatchingProjectScope(entry, request.identity);
|
|
284
|
+
if (entry.halfOpenPermitId === request.permitId) {
|
|
285
|
+
entry.halfOpenLeaseUntil = Math.max(entry.halfOpenLeaseUntil ?? 0, now + request.leaseDurationMs);
|
|
286
|
+
entry.updatedAt = now;
|
|
287
|
+
}
|
|
288
|
+
else if (entry.closedPermits.has(request.permitId)) {
|
|
289
|
+
entry.closedPermits.set(request.permitId, Math.max(entry.closedPermits.get(request.permitId) ?? 0, now + closedPermitRetentionMs(entry.policy)));
|
|
290
|
+
entry.updatedAt = now;
|
|
291
|
+
}
|
|
292
|
+
return toSnapshot(entry, entry.policy, now);
|
|
293
|
+
}
|
|
294
|
+
reset(request) {
|
|
295
|
+
if (request.key != null) {
|
|
296
|
+
this.#entries.delete(request.key);
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
for (const [key, entry] of this.#entries) {
|
|
300
|
+
if (entry.identity.projectId === request.projectId) {
|
|
301
|
+
this.#entries.delete(key);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
list(request = {}) {
|
|
306
|
+
const now = this.#now();
|
|
307
|
+
this.#pruneStaleEntries(now);
|
|
308
|
+
return [...this.#entries.entries()]
|
|
309
|
+
.filter(([, entry]) => request.projectId == null || entry.identity.projectId === request.projectId)
|
|
310
|
+
.map(([, entry]) => {
|
|
311
|
+
pruneFailures(entry, entry.policy, now);
|
|
312
|
+
pruneClosedPermits(entry, now);
|
|
313
|
+
const state = getState(entry, now);
|
|
314
|
+
return {
|
|
315
|
+
identity: entry.identity,
|
|
316
|
+
state,
|
|
317
|
+
failureCount: entry.failureTimestamps.length,
|
|
318
|
+
...(entry.openUntil == null ? {} : { openUntil: entry.openUntil }),
|
|
319
|
+
...(state !== 'half-open' || entry.halfOpenLeaseUntil == null
|
|
320
|
+
? {}
|
|
321
|
+
: { halfOpenLeaseUntil: entry.halfOpenLeaseUntil }),
|
|
322
|
+
updatedAt: entry.updatedAt,
|
|
323
|
+
};
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
}
|
|
@@ -3,6 +3,8 @@ 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';
|
|
7
|
+
import { createRivetLLMProfileHealthIdentity } from './llmProfileHealthStore.js';
|
|
6
8
|
export function resolveLLMProfileNodeValue(params) {
|
|
7
9
|
const { data, inputs, context } = params;
|
|
8
10
|
const runtimeData = data;
|
|
@@ -25,49 +27,69 @@ export function resolveLLMProfileNodeValue(params) {
|
|
|
25
27
|
const googleThinkingBudget = data.provider === 'google' && data.useGoogleThinkingBudgetInput
|
|
26
28
|
? coerceTypeOptional(inputs['googleThinkingBudget'], 'number') ?? data.googleThinkingBudget
|
|
27
29
|
: data.googleThinkingBudget;
|
|
30
|
+
const customProviderApi = parseCustomProviderApi(data.customProviderApi);
|
|
28
31
|
const credential = resolveChatV2Credential({
|
|
29
32
|
provider: data.provider,
|
|
30
33
|
context,
|
|
31
34
|
apiKeySource: data.apiKeySource === 'input' ? 'input' : 'configured',
|
|
32
35
|
inputs,
|
|
36
|
+
providerApiKeyNames: data.providerApiKeyNames,
|
|
33
37
|
customProgrammaticName: data.customProviderApiKeyProgrammaticName,
|
|
34
38
|
customEnvironmentName: data.customProviderApiKeyEnvVarName,
|
|
35
39
|
});
|
|
40
|
+
const configuration = {
|
|
41
|
+
...data,
|
|
42
|
+
model,
|
|
43
|
+
useModelInput: false,
|
|
44
|
+
temperature: generation.temperature ?? data.temperature,
|
|
45
|
+
useTemperatureInput: false,
|
|
46
|
+
maxTokens: generation.maxTokens ?? data.maxTokens,
|
|
47
|
+
useMaxTokensInput: false,
|
|
48
|
+
topP: generation.topP,
|
|
49
|
+
useTopPInput: false,
|
|
50
|
+
topK: generation.topK,
|
|
51
|
+
useTopKInput: false,
|
|
52
|
+
presencePenalty: generation.presencePenalty,
|
|
53
|
+
usePresencePenaltyInput: false,
|
|
54
|
+
frequencyPenalty: generation.frequencyPenalty,
|
|
55
|
+
useFrequencyPenaltyInput: false,
|
|
56
|
+
stopSequences: generation.stopSequences ?? [],
|
|
57
|
+
useStopSequencesInput: false,
|
|
58
|
+
seed: generation.seed,
|
|
59
|
+
useSeedInput: false,
|
|
60
|
+
customProviderBaseURL,
|
|
61
|
+
useCustomProviderBaseURLInput: false,
|
|
62
|
+
customProviderApi,
|
|
63
|
+
openAIPreviousResponseId,
|
|
64
|
+
useOpenAIPreviousResponseIdInput: false,
|
|
65
|
+
headers: Object.entries(headers ?? {}).map(([key, value]) => ({ key, value })),
|
|
66
|
+
useHeadersInput: false,
|
|
67
|
+
extraProviderOptions: extraProviderOptions == null ? '' : JSON.stringify(extraProviderOptions),
|
|
68
|
+
useExtraProviderOptionsInput: false,
|
|
69
|
+
anthropicThinkingBudget,
|
|
70
|
+
useAnthropicThinkingBudgetInput: false,
|
|
71
|
+
googleThinkingBudget,
|
|
72
|
+
useGoogleThinkingBudgetInput: false,
|
|
73
|
+
};
|
|
74
|
+
// A profile can be resolved outside a loaded project, for example by a
|
|
75
|
+
// programmatic caller or a focused node test. Its health identity is
|
|
76
|
+
// project-scoped, so defer attaching it until LLM Chat binds the profile to
|
|
77
|
+
// the executing project in that case.
|
|
78
|
+
const projectId = context.project?.metadata?.id;
|
|
36
79
|
return {
|
|
37
80
|
version: LLM_PROFILE_VALUE_VERSION,
|
|
38
81
|
credential,
|
|
39
|
-
configuration
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
presencePenalty: generation.presencePenalty,
|
|
52
|
-
usePresencePenaltyInput: false,
|
|
53
|
-
frequencyPenalty: generation.frequencyPenalty,
|
|
54
|
-
useFrequencyPenaltyInput: false,
|
|
55
|
-
stopSequences: generation.stopSequences ?? [],
|
|
56
|
-
useStopSequencesInput: false,
|
|
57
|
-
seed: generation.seed,
|
|
58
|
-
useSeedInput: false,
|
|
59
|
-
customProviderBaseURL,
|
|
60
|
-
useCustomProviderBaseURLInput: false,
|
|
61
|
-
openAIPreviousResponseId,
|
|
62
|
-
useOpenAIPreviousResponseIdInput: false,
|
|
63
|
-
headers: Object.entries(headers ?? {}).map(([key, value]) => ({ key, value })),
|
|
64
|
-
useHeadersInput: false,
|
|
65
|
-
extraProviderOptions: extraProviderOptions == null ? '' : JSON.stringify(extraProviderOptions),
|
|
66
|
-
useExtraProviderOptionsInput: false,
|
|
67
|
-
anthropicThinkingBudget,
|
|
68
|
-
useAnthropicThinkingBudgetInput: false,
|
|
69
|
-
googleThinkingBudget,
|
|
70
|
-
useGoogleThinkingBudgetInput: false,
|
|
71
|
-
},
|
|
82
|
+
configuration,
|
|
83
|
+
...(projectId == null
|
|
84
|
+
? {}
|
|
85
|
+
: {
|
|
86
|
+
healthIdentity: createRivetLLMProfileHealthIdentity({
|
|
87
|
+
configuration,
|
|
88
|
+
credential,
|
|
89
|
+
chatNodeHeaders: context.settings.chatNodeHeaders,
|
|
90
|
+
projectId,
|
|
91
|
+
profileNodeId: context.node.id,
|
|
92
|
+
}),
|
|
93
|
+
}),
|
|
72
94
|
};
|
|
73
95
|
}
|
|
@@ -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
|
+
}
|
|
@@ -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
|
}
|