@valerypopoff/rivet2-core 2.0.6 → 2.0.8

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.
Files changed (34) hide show
  1. package/dist/cjs/bundle.cjs +1440 -769
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +8 -2
  4. package/dist/esm/model/GraphPreprocessor.js +129 -7
  5. package/dist/esm/model/GraphProcessor.js +204 -82
  6. package/dist/esm/model/NodeExclusionPolicy.js +67 -0
  7. package/dist/esm/model/NodeExecutionPlanner.js +66 -22
  8. package/dist/esm/model/Nodes.js +3 -0
  9. package/dist/esm/model/chat-v2/chatV2Outputs.js +183 -0
  10. package/dist/esm/model/chat-v2/chatV2Pipeline.js +30 -212
  11. package/dist/esm/model/nodes/CodeNewNode.js +207 -0
  12. package/dist/esm/model/nodes/CodeNode.js +11 -10
  13. package/dist/esm/model/nodes/CommentNode.js +1 -1
  14. package/dist/esm/model/nodes/ExpressionNode.js +23 -39
  15. package/dist/esm/model/nodes/HttpCallNode.js +20 -18
  16. package/dist/esm/model/nodes/ObjectNode.js +1 -0
  17. package/dist/esm/model/nodes/ToolNode.js +1 -0
  18. package/dist/esm/model/nodes/codeNodeErrorDiagnostics.js +16 -11
  19. package/dist/esm/model/nodes/jsListCallbackHelpers.js +26 -30
  20. package/dist/esm/model/nodes/jsValueInterpolation.js +56 -2
  21. package/dist/esm/utils/serialization/serialization.js +22 -1
  22. package/dist/types/api/createProcessor.d.ts +8 -2
  23. package/dist/types/model/EditorDefinition.d.ts +2 -0
  24. package/dist/types/model/GraphPreprocessor.d.ts +36 -2
  25. package/dist/types/model/GraphProcessor.d.ts +12 -1
  26. package/dist/types/model/NodeExclusionPolicy.d.ts +21 -0
  27. package/dist/types/model/NodeExecutionPlanner.d.ts +3 -8
  28. package/dist/types/model/Nodes.d.ts +3 -2
  29. package/dist/types/model/ProcessContext.d.ts +2 -2
  30. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +29 -0
  31. package/dist/types/model/nodes/CodeNewNode.d.ts +27 -0
  32. package/dist/types/model/nodes/codeNodeErrorDiagnostics.d.ts +4 -2
  33. package/dist/types/model/nodes/jsValueInterpolation.d.ts +20 -0
  34. package/package.json +1 -1
@@ -0,0 +1,67 @@
1
+ import { getScalarTypeOf } from './DataValue.js';
2
+ import { IF_PORT, } from './NodeBase.js';
3
+ import { coerceTypeOptional } from '../utils/coerceType.js';
4
+ import { entries } from '../utils/typeSafety.js';
5
+ import { LOOP_NOT_BROKEN_SENTINEL } from './loopControllerBreak.js';
6
+ const nodesAllowedToConsumeExcludedValue = new Set([
7
+ 'if',
8
+ 'ifElse',
9
+ 'coalesce',
10
+ 'graphOutput',
11
+ 'raceInputs',
12
+ 'loopController',
13
+ ]);
14
+ function isControlFlowExcluded(value) {
15
+ return value != null && getScalarTypeOf(value.type) === 'control-flow-excluded';
16
+ }
17
+ export function getControlFlowExclusionDecision({ inputValues, node, typeOfExclusion, }) {
18
+ if (node.disabled) {
19
+ return {
20
+ action: 'exclude',
21
+ reason: 'disabled',
22
+ traceMessage: `Excluding node ${node.title} because it's disabled`,
23
+ };
24
+ }
25
+ if (node.isConditional && typeOfExclusion === undefined) {
26
+ const ifValue = coerceTypeOptional(inputValues[IF_PORT.id], 'boolean');
27
+ if (ifValue === false) {
28
+ return {
29
+ action: 'exclude',
30
+ reason: 'if port is false',
31
+ traceMessage: `Excluding node ${node.title} because if port is false`,
32
+ };
33
+ }
34
+ }
35
+ const controlFlowExcludedValues = entries(inputValues).filter(([, value]) => isControlFlowExcluded(value) && (typeOfExclusion === undefined || value.value === typeOfExclusion));
36
+ const isWaitingForLoop = controlFlowExcludedValues.some(([, value]) => value?.value === LOOP_NOT_BROKEN_SENTINEL);
37
+ const allowedToConsumeExcludedValue = nodesAllowedToConsumeExcludedValue.has(node.type) && !isWaitingForLoop;
38
+ if (controlFlowExcludedValues.length === 0 || allowedToConsumeExcludedValue) {
39
+ return { action: 'continue' };
40
+ }
41
+ if (isWaitingForLoop) {
42
+ return { action: 'defer' };
43
+ }
44
+ return {
45
+ action: 'exclude',
46
+ reason: 'input is excluded value',
47
+ traceMessage: `Excluding node ${node.title} because of control flow. Input is has excluded value: ${controlFlowExcludedValues[0]?.[0]}`,
48
+ };
49
+ }
50
+ export function getMissingRequiredInputExclusion(node, missingRequiredInputs) {
51
+ const missingInputNames = missingRequiredInputs.map((input) => input.title || input.id).join(', ');
52
+ return {
53
+ action: 'exclude',
54
+ reason: 'missing required input',
55
+ traceMessage: `Excluding node ${node.title} because required inputs are not connected: ${missingInputNames}`,
56
+ };
57
+ }
58
+ export function createExcludedNodeOutputs(node, outputDefinitions) {
59
+ const outputs = {};
60
+ for (const output of outputDefinitions) {
61
+ outputs[output.id] = { type: 'control-flow-excluded', value: undefined };
62
+ }
63
+ if (node.type === 'loopController') {
64
+ outputs['break'] = { type: 'control-flow-excluded', value: LOOP_NOT_BROKEN_SENTINEL };
65
+ }
66
+ return outputs;
67
+ }
@@ -1,40 +1,71 @@
1
- import { uniqBy } from 'lodash-es';
2
1
  import { getScalarTypeOf } from './DataValue.js';
3
- import { isNotNull } from '../utils/genericUtilFunctions.js';
4
2
  export function getStartNodes(state, graphNodes, runToNodeIds) {
5
- return runToNodeIds
6
- ? graphNodes.filter((node) => runToNodeIds.includes(node.id))
7
- : graphNodes.filter((node) => getOutputNodesFrom(state, node).nodes.length === 0);
3
+ if (runToNodeIds) {
4
+ return graphNodes.filter((node) => runToNodeIds.includes(node.id));
5
+ }
6
+ return state.executionPlan?.startNodes ?? graphNodes.filter((node) => getOutputNodesFrom(state, node).nodes.length === 0);
8
7
  }
9
8
  export function getInputNodesTo(state, node) {
9
+ const plannedInputNodes = state.executionPlan?.inputNodesByNode[node.id];
10
+ if (plannedInputNodes) {
11
+ return plannedInputNodes;
12
+ }
10
13
  const connections = state.connections[node.id];
11
14
  if (!connections) {
12
15
  return [];
13
16
  }
14
- const connectionsToNode = connections.filter((conn) => conn.inputNodeId === node.id).filter(isNotNull);
15
17
  const inputDefinitions = state.definitions[node.id]?.inputs ?? [];
16
- return connectionsToNode
17
- .filter((connection) => {
18
- const connectionDefinition = inputDefinitions.find((def) => def.id === connection.inputId);
19
- return connectionDefinition != null;
20
- })
21
- .map((conn) => state.nodesById[conn.outputNodeId])
22
- .filter(isNotNull);
18
+ const validInputIds = new Set(inputDefinitions.map((definition) => definition.id));
19
+ const inputNodes = [];
20
+ for (const connection of connections) {
21
+ if (connection.inputNodeId !== node.id || !validInputIds.has(connection.inputId)) {
22
+ continue;
23
+ }
24
+ const inputNode = state.nodesById[connection.outputNodeId];
25
+ if (inputNode) {
26
+ inputNodes.push(inputNode);
27
+ }
28
+ }
29
+ return inputNodes;
23
30
  }
24
31
  export function getOutputNodesFrom(state, node) {
32
+ const plannedOutputNodes = state.executionPlan?.outputNodeResultsByNode[node.id];
33
+ if (plannedOutputNodes) {
34
+ return plannedOutputNodes;
35
+ }
25
36
  const connections = state.connections[node.id];
26
37
  if (!connections) {
27
38
  return { nodes: [], connections: [], connectionsToNodes: [] };
28
39
  }
29
- const connectionsFromNode = connections.filter((conn) => conn.outputNodeId === node.id);
30
40
  const outputDefinitions = state.definitions[node.id]?.outputs ?? [];
31
- const outputConnections = connectionsFromNode.filter((connection) => {
32
- const connectionDefinition = outputDefinitions.find((def) => def.id === connection.outputId);
33
- return connectionDefinition != null;
34
- });
35
- const outputNodes = uniqBy(outputConnections.map((conn) => state.nodesById[conn.inputNodeId]).filter(isNotNull), (candidate) => candidate.id);
41
+ const validOutputIds = new Set(outputDefinitions.map((definition) => definition.id));
42
+ const outputConnections = [];
43
+ const outputConnectionsByNode = new Map();
44
+ const outputNodes = [];
45
+ const seenOutputNodeIds = new Set();
46
+ for (const connection of connections) {
47
+ if (connection.outputNodeId !== node.id || !validOutputIds.has(connection.outputId)) {
48
+ continue;
49
+ }
50
+ outputConnections.push(connection);
51
+ const outputNode = state.nodesById[connection.inputNodeId];
52
+ if (!outputNode) {
53
+ continue;
54
+ }
55
+ if (!seenOutputNodeIds.has(outputNode.id)) {
56
+ outputNodes.push(outputNode);
57
+ seenOutputNodeIds.add(outputNode.id);
58
+ }
59
+ const nodeConnections = outputConnectionsByNode.get(outputNode.id);
60
+ if (nodeConnections) {
61
+ nodeConnections.push(connection);
62
+ }
63
+ else {
64
+ outputConnectionsByNode.set(outputNode.id, [connection]);
65
+ }
66
+ }
36
67
  const connectionsToNodes = outputNodes.map((outputNode) => ({
37
- connections: outputConnections.filter((conn) => conn.inputNodeId === outputNode.id),
68
+ connections: outputConnectionsByNode.get(outputNode.id) ?? [],
38
69
  node: outputNode,
39
70
  }));
40
71
  return { nodes: outputNodes, connections: outputConnections, connectionsToNodes };
@@ -49,10 +80,19 @@ export function hasErroredInputNode(state, node, inputNodes, onTrace) {
49
80
  return false;
50
81
  }
51
82
  export function getMissingRequiredInputs(state, node) {
83
+ const plannedMissingInputs = state.executionPlan?.missingRequiredInputsByNode[node.id];
84
+ if (plannedMissingInputs) {
85
+ return plannedMissingInputs;
86
+ }
52
87
  const connections = state.connections[node.id] ?? [];
88
+ const connectedInputIds = new Set();
89
+ for (const connection of connections) {
90
+ if (connection.inputNodeId === node.id) {
91
+ connectedInputIds.add(connection.inputId);
92
+ }
93
+ }
53
94
  return state.definitions[node.id].inputs.filter((input) => {
54
- const connectionToInput = connections.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);
55
- return input.required && !connectionToInput;
95
+ return input.required && !connectedInputIds.has(input.id);
56
96
  });
57
97
  }
58
98
  export function getWaitingForInputNode(state, node, inputNodes, inputValues) {
@@ -75,6 +115,10 @@ export function getWaitingForInputNode(state, node, inputNodes, inputValues) {
75
115
  return waitingForInputNode;
76
116
  }
77
117
  function nodesAreInSameCycle(state, a, b) {
118
+ const plannedCycleIndexByNode = state.executionPlan?.cycleIndexByNode;
119
+ if (plannedCycleIndexByNode) {
120
+ return plannedCycleIndexByNode[a] != null && plannedCycleIndexByNode[a] === plannedCycleIndexByNode[b];
121
+ }
78
122
  return state.stronglyConnectedComponents.find((cycle) => cycle.find((node) => node.id === a) && cycle.find((node) => node.id === b));
79
123
  }
80
124
  function isControlFlowExcluded(value) {
@@ -14,6 +14,8 @@ import { extractRegexNode } from './nodes/ExtractRegexNode.js';
14
14
  export * from './nodes/ExtractRegexNode.js';
15
15
  import { codeNode } from './nodes/CodeNode.js';
16
16
  export * from './nodes/CodeNode.js';
17
+ import { codeNewNode } from './nodes/CodeNewNode.js';
18
+ export * from './nodes/CodeNewNode.js';
17
19
  import { expressionNode } from './nodes/ExpressionNode.js';
18
20
  export * from './nodes/ExpressionNode.js';
19
21
  import { matchNode } from './nodes/MatchNode.js';
@@ -186,6 +188,7 @@ export const registerBuiltInNodes = (registry) => {
186
188
  .register(promptNode)
187
189
  .register(extractRegexNode)
188
190
  .register(codeNode)
191
+ .register(codeNewNode)
189
192
  .register(expressionNode)
190
193
  .register(matchNode)
191
194
  .register(ifNode)
@@ -0,0 +1,183 @@
1
+ import { inferType } from '../../utils/coerceType.js';
2
+ import { createAssistantMessagesOutput } from '../chat/streamChatResponse.js';
3
+ import { isChatV2StructuredResponseFormat } from './chatV2ResponseFormat.js';
4
+ import { calculateChatV2Cost } from './modelRegistry.js';
5
+ const CHAT_V2_REQUEST_STATUS_PORT_ID = 'requestStatus';
6
+ const CHAT_V2_REQUEST_ERROR_PORT_ID = 'requestError';
7
+ function toFunctionCallOutputValue(functionCall) {
8
+ let argumentsValue = functionCall.lastParsedArguments;
9
+ if (argumentsValue == null) {
10
+ try {
11
+ argumentsValue = JSON.parse(functionCall.arguments);
12
+ }
13
+ catch {
14
+ argumentsValue = functionCall.arguments;
15
+ }
16
+ }
17
+ return {
18
+ name: functionCall.name,
19
+ arguments: argumentsValue,
20
+ id: functionCall.id,
21
+ };
22
+ }
23
+ function createControlFlowExcludedOutput() {
24
+ return {
25
+ type: 'control-flow-excluded',
26
+ value: undefined,
27
+ };
28
+ }
29
+ export function normalizeChatV2Usage(usage, options) {
30
+ if (usage == null) {
31
+ return undefined;
32
+ }
33
+ const promptTokens = usage.inputTokens ?? 0;
34
+ const completionTokens = usage.outputTokens ?? 0;
35
+ const totalTokens = usage.totalTokens ?? promptTokens + completionTokens;
36
+ const cachedTokens = (usage.inputTokenDetails?.cacheReadTokens ?? 0) + (usage.inputTokenDetails?.cacheWriteTokens ?? 0);
37
+ const reasoningTokens = usage.outputTokenDetails?.reasoningTokens ?? 0;
38
+ return {
39
+ promptTokens,
40
+ completionTokens,
41
+ totalTokens,
42
+ cachedTokens,
43
+ reasoningTokens,
44
+ totalCost: calculateChatV2Cost(options.provider, options.modelId, promptTokens, completionTokens),
45
+ };
46
+ }
47
+ function tryParseStructuredResponseText(response) {
48
+ try {
49
+ return JSON.parse(response);
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ }
55
+ function createChatV2ResponseOutput(response, structuredOutput, responseFormat) {
56
+ if (!isChatV2StructuredResponseFormat(responseFormat)) {
57
+ return { type: 'string', value: response };
58
+ }
59
+ const parsedOutput = structuredOutput !== undefined ? structuredOutput : tryParseStructuredResponseText(response);
60
+ return parsedOutput !== undefined ? inferType(parsedOutput) : { type: 'string', value: response };
61
+ }
62
+ function createChatV2ReasoningOutput(reasoning) {
63
+ if (Array.isArray(reasoning)) {
64
+ const nonEmptyReasoning = reasoning.filter((part) => typeof part === 'string' && part.trim().length > 0);
65
+ return nonEmptyReasoning.length > 0
66
+ ? {
67
+ type: 'string[]',
68
+ value: nonEmptyReasoning,
69
+ }
70
+ : createControlFlowExcludedOutput();
71
+ }
72
+ const reasoningText = typeof reasoning === 'string' ? reasoning : '';
73
+ return reasoningText.trim().length > 0
74
+ ? {
75
+ type: 'string',
76
+ value: reasoningText,
77
+ }
78
+ : createControlFlowExcludedOutput();
79
+ }
80
+ function createChatV2RetryAttemptOutput(type, values) {
81
+ return values.length > 0
82
+ ? {
83
+ type,
84
+ value: values,
85
+ }
86
+ : createControlFlowExcludedOutput();
87
+ }
88
+ export function createChatV2CommonOutputs({ requestMessages, response, structuredOutput, functionCalls, usage, reasoning, requestStatus, responseError, requestStatuses, requestErrors, outputUsage, outputReasoning, outputRequestStatus, includeFunctionCalls, functionCallMode, retryOnNon200, responseFormat, }) {
89
+ const outputs = {
90
+ ['response']: createChatV2ResponseOutput(response, structuredOutput, responseFormat),
91
+ ['in-messages']: { type: 'chat-message[]', value: requestMessages },
92
+ ['all-messages']: createAssistantMessagesOutput(requestMessages, response, functionCalls, {
93
+ functionCallMode,
94
+ }),
95
+ ['responseTokens']: { type: 'number', value: usage?.completionTokens ?? 0 },
96
+ };
97
+ if (functionCalls.length > 0) {
98
+ outputs['function-calls'] = {
99
+ type: 'object[]',
100
+ value: functionCalls.map(toFunctionCallOutputValue),
101
+ };
102
+ }
103
+ else if (includeFunctionCalls) {
104
+ outputs['function-calls'] = createControlFlowExcludedOutput();
105
+ }
106
+ if (outputUsage) {
107
+ outputs['usage'] = {
108
+ type: 'object',
109
+ value: usage ?? {
110
+ promptTokens: 0,
111
+ completionTokens: 0,
112
+ totalTokens: 0,
113
+ cachedTokens: 0,
114
+ reasoningTokens: 0,
115
+ totalCost: undefined,
116
+ },
117
+ };
118
+ }
119
+ if (outputReasoning) {
120
+ outputs['reasoning'] = createChatV2ReasoningOutput(reasoning);
121
+ }
122
+ if (outputRequestStatus) {
123
+ if (retryOnNon200) {
124
+ outputs[CHAT_V2_REQUEST_STATUS_PORT_ID] = createChatV2RetryAttemptOutput('number[]', requestStatuses.length > 0 ? requestStatuses : [requestStatus ?? 200]);
125
+ outputs[CHAT_V2_REQUEST_ERROR_PORT_ID] = createChatV2RetryAttemptOutput('string[]', requestErrors);
126
+ }
127
+ else {
128
+ outputs[CHAT_V2_REQUEST_STATUS_PORT_ID] = {
129
+ type: 'number',
130
+ value: requestStatus ?? 200,
131
+ };
132
+ outputs[CHAT_V2_REQUEST_ERROR_PORT_ID] =
133
+ responseError != null
134
+ ? {
135
+ type: 'string',
136
+ value: responseError,
137
+ }
138
+ : createControlFlowExcludedOutput();
139
+ }
140
+ }
141
+ return outputs;
142
+ }
143
+ export function createChatV2ProviderFailureOutputs({ requestMessages, responseStatus, responseError, requestStatuses, requestErrors, outputUsage, outputReasoning, includeFunctionCalls, retryOnNon200, }) {
144
+ const outputs = {
145
+ [CHAT_V2_REQUEST_ERROR_PORT_ID]: retryOnNon200
146
+ ? createChatV2RetryAttemptOutput('string[]', requestErrors)
147
+ : {
148
+ type: 'string',
149
+ value: responseError,
150
+ },
151
+ [CHAT_V2_REQUEST_STATUS_PORT_ID]: retryOnNon200
152
+ ? createChatV2RetryAttemptOutput('number[]', requestStatuses)
153
+ : responseStatus == null
154
+ ? {
155
+ type: 'control-flow-excluded',
156
+ value: undefined,
157
+ }
158
+ : {
159
+ type: 'number',
160
+ value: responseStatus,
161
+ },
162
+ ['response']: createControlFlowExcludedOutput(),
163
+ ['in-messages']: {
164
+ type: 'chat-message[]',
165
+ value: requestMessages,
166
+ },
167
+ ['all-messages']: {
168
+ type: 'chat-message[]',
169
+ value: requestMessages,
170
+ },
171
+ ['responseTokens']: createControlFlowExcludedOutput(),
172
+ };
173
+ if (includeFunctionCalls) {
174
+ outputs['function-calls'] = createControlFlowExcludedOutput();
175
+ }
176
+ if (outputUsage) {
177
+ outputs['usage'] = createControlFlowExcludedOutput();
178
+ }
179
+ if (outputReasoning) {
180
+ outputs['reasoning'] = createControlFlowExcludedOutput();
181
+ }
182
+ return outputs;
183
+ }
@@ -1,15 +1,10 @@
1
- import { inferType } from '../../utils/coerceType.js';
2
1
  import { coercePromptToChatMessages, prependSystemPrompt } from '../chat/chatMessages.js';
3
- import { createAssistantMessagesOutput } from '../chat/streamChatResponse.js';
4
2
  import { streamChatV2 } from './aiSdkBridge.js';
5
3
  import { chatMessagesToModelMessages } from './messageConverter.js';
6
- import { calculateChatV2Cost } from './modelRegistry.js';
7
- import { isChatV2StructuredResponseFormat } from './chatV2ResponseFormat.js';
8
4
  import { chatV2ToolsToAiSdk } from './toolConverter.js';
9
5
  import { getChatV2ProviderErrorStatusCode, isChatV2ProviderApiCallError, isChatV2ProviderFetchError, normalizeChatV2ProviderError, } from './chatV2Errors.js';
10
6
  import { normalizeLLMChatV2RetryCooldownMs, normalizeLLMChatV2RetryCount, waitForLLMChatV2RetryCooldown, } from './chatV2Retry.js';
11
- const REQUEST_STATUS_PORT_ID = 'requestStatus';
12
- const REQUEST_ERROR_PORT_ID = 'requestError';
7
+ import { createChatV2CommonOutputs, createChatV2ProviderFailureOutputs, normalizeChatV2Usage, } from './chatV2Outputs.js';
13
8
  class StreamChatV2RetryFailure extends Error {
14
9
  error;
15
10
  requestStatuses;
@@ -25,214 +20,12 @@ class StreamChatV2RetryFailure extends Error {
25
20
  function isStreamChatV2RetryFailure(error) {
26
21
  return error instanceof StreamChatV2RetryFailure;
27
22
  }
28
- function toFunctionCallOutputValue(functionCall) {
29
- let argumentsValue = functionCall.lastParsedArguments;
30
- if (argumentsValue == null) {
31
- try {
32
- argumentsValue = JSON.parse(functionCall.arguments);
33
- }
34
- catch {
35
- argumentsValue = functionCall.arguments;
36
- }
37
- }
38
- return {
39
- name: functionCall.name,
40
- arguments: argumentsValue,
41
- id: functionCall.id,
42
- };
43
- }
44
- function normalizeUsage(usage, options) {
45
- if (usage == null) {
46
- return undefined;
47
- }
48
- const promptTokens = usage.inputTokens ?? 0;
49
- const completionTokens = usage.outputTokens ?? 0;
50
- const totalTokens = usage.totalTokens ?? promptTokens + completionTokens;
51
- const cachedTokens = (usage.inputTokenDetails?.cacheReadTokens ?? 0) + (usage.inputTokenDetails?.cacheWriteTokens ?? 0);
52
- const reasoningTokens = usage.outputTokenDetails?.reasoningTokens ?? 0;
53
- return {
54
- promptTokens,
55
- completionTokens,
56
- totalTokens,
57
- cachedTokens,
58
- reasoningTokens,
59
- totalCost: calculateChatV2Cost(options.provider, options.modelId, promptTokens, completionTokens),
60
- };
61
- }
62
- function tryParseStructuredResponseText(response) {
63
- try {
64
- return JSON.parse(response);
65
- }
66
- catch {
67
- return undefined;
68
- }
69
- }
70
- function buildResponseOutput(response, structuredOutput, responseFormat) {
71
- if (!isChatV2StructuredResponseFormat(responseFormat)) {
72
- return { type: 'string', value: response };
73
- }
74
- const parsedOutput = structuredOutput !== undefined ? structuredOutput : tryParseStructuredResponseText(response);
75
- return parsedOutput !== undefined ? inferType(parsedOutput) : { type: 'string', value: response };
76
- }
77
- function buildCommonOutputs(requestMessages, response, structuredOutput, functionCalls, usage, reasoning, requestStatus, responseError, requestStatuses, requestErrors, options) {
78
- const outputs = {
79
- ['response']: buildResponseOutput(response, structuredOutput, options.responseFormat),
80
- ['in-messages']: { type: 'chat-message[]', value: requestMessages },
81
- ['all-messages']: createAssistantMessagesOutput(requestMessages, response, functionCalls, {
82
- functionCallMode: options.functionCallMode,
83
- }),
84
- ['responseTokens']: { type: 'number', value: usage?.completionTokens ?? 0 },
85
- };
86
- if (functionCalls.length > 0) {
87
- outputs['function-calls'] = {
88
- type: 'object[]',
89
- value: functionCalls.map(toFunctionCallOutputValue),
90
- };
91
- }
92
- else if (options.includeFunctionCalls) {
93
- outputs['function-calls'] = {
94
- type: 'control-flow-excluded',
95
- value: undefined,
96
- };
97
- }
98
- if (options.outputUsage) {
99
- outputs['usage'] = {
100
- type: 'object',
101
- value: usage ?? {
102
- promptTokens: 0,
103
- completionTokens: 0,
104
- totalTokens: 0,
105
- cachedTokens: 0,
106
- reasoningTokens: 0,
107
- totalCost: undefined,
108
- },
109
- };
110
- }
111
- if (options.outputReasoning) {
112
- outputs['reasoning'] = buildReasoningOutput(reasoning);
113
- }
114
- if (options.outputRequestStatus) {
115
- if (options.retryOnNon200) {
116
- outputs[REQUEST_STATUS_PORT_ID] = buildRetryAttemptOutput('number[]', requestStatuses.length > 0 ? requestStatuses : [requestStatus ?? 200]);
117
- outputs[REQUEST_ERROR_PORT_ID] = buildRetryAttemptOutput('string[]', requestErrors);
118
- }
119
- else {
120
- outputs[REQUEST_STATUS_PORT_ID] = {
121
- type: 'number',
122
- value: requestStatus ?? 200,
123
- };
124
- outputs[REQUEST_ERROR_PORT_ID] =
125
- responseError != null
126
- ? {
127
- type: 'string',
128
- value: responseError,
129
- }
130
- : {
131
- type: 'control-flow-excluded',
132
- value: undefined,
133
- };
134
- }
135
- }
136
- return outputs;
137
- }
138
- function buildReasoningOutput(reasoning) {
139
- if (Array.isArray(reasoning)) {
140
- const nonEmptyReasoning = reasoning.filter((part) => typeof part === 'string' && part.trim().length > 0);
141
- return nonEmptyReasoning.length > 0
142
- ? {
143
- type: 'string[]',
144
- value: nonEmptyReasoning,
145
- }
146
- : {
147
- type: 'control-flow-excluded',
148
- value: undefined,
149
- };
150
- }
151
- const reasoningText = typeof reasoning === 'string' ? reasoning : '';
152
- return reasoningText.trim().length > 0
153
- ? {
154
- type: 'string',
155
- value: reasoningText,
156
- }
157
- : {
158
- type: 'control-flow-excluded',
159
- value: undefined,
160
- };
161
- }
162
23
  function getProviderFailureMessage(error) {
163
24
  if (error instanceof Error) {
164
25
  return error.message;
165
26
  }
166
27
  return String(error);
167
28
  }
168
- function buildProviderFailureOutputs(requestMessages, responseStatus, responseError, requestStatuses, requestErrors, options) {
169
- const outputs = {};
170
- Object.assign(outputs, {
171
- [REQUEST_ERROR_PORT_ID]: options.retryOnNon200
172
- ? buildRetryAttemptOutput('string[]', requestErrors)
173
- : {
174
- type: 'string',
175
- value: responseError,
176
- },
177
- [REQUEST_STATUS_PORT_ID]: options.retryOnNon200
178
- ? buildRetryAttemptOutput('number[]', requestStatuses)
179
- : responseStatus == null
180
- ? {
181
- type: 'control-flow-excluded',
182
- value: undefined,
183
- }
184
- : {
185
- type: 'number',
186
- value: responseStatus,
187
- },
188
- ['response']: {
189
- type: 'control-flow-excluded',
190
- value: undefined,
191
- },
192
- ['in-messages']: {
193
- type: 'chat-message[]',
194
- value: requestMessages,
195
- },
196
- ['all-messages']: {
197
- type: 'chat-message[]',
198
- value: requestMessages,
199
- },
200
- ['responseTokens']: {
201
- type: 'control-flow-excluded',
202
- value: undefined,
203
- },
204
- });
205
- if (options.includeFunctionCalls) {
206
- outputs['function-calls'] = {
207
- type: 'control-flow-excluded',
208
- value: undefined,
209
- };
210
- }
211
- if (options.outputUsage) {
212
- outputs['usage'] = {
213
- type: 'control-flow-excluded',
214
- value: undefined,
215
- };
216
- }
217
- if (options.outputReasoning) {
218
- outputs['reasoning'] = {
219
- type: 'control-flow-excluded',
220
- value: undefined,
221
- };
222
- }
223
- return outputs;
224
- }
225
- function buildRetryAttemptOutput(type, values) {
226
- return values.length > 0
227
- ? {
228
- type,
229
- value: values,
230
- }
231
- : {
232
- type: 'control-flow-excluded',
233
- value: undefined,
234
- };
235
- }
236
29
  function buildNon200StatusError(statusCode) {
237
30
  const error = new Error(`Provider request returned non-200 status: ${statusCode}`);
238
31
  error.name = 'AI_APICallError';
@@ -303,7 +96,12 @@ function buildProviderFailureResult(requestMessages, options, normalizedError, r
303
96
  : [statusCode]
304
97
  : [];
305
98
  const retryRequestErrors = options.retryOnNon200 ? (requestErrors.length > 0 ? requestErrors : [responseError]) : [];
306
- const commonOutputs = buildProviderFailureOutputs(requestMessages, statusCode, responseError, retryRequestStatuses, retryRequestErrors, {
99
+ const commonOutputs = createChatV2ProviderFailureOutputs({
100
+ requestMessages,
101
+ responseStatus: statusCode,
102
+ responseError,
103
+ requestStatuses: retryRequestStatuses,
104
+ requestErrors: retryRequestErrors,
307
105
  outputUsage: options.outputUsage,
308
106
  outputReasoning: options.outputReasoning,
309
107
  includeFunctionCalls: options.includeFunctionCalls,
@@ -360,7 +158,17 @@ export async function runChatV2Pipeline(options) {
360
158
  onPartialOutput: options.emitPartialOutputs === false
361
159
  ? undefined
362
160
  : ({ text, functionCalls }) => {
363
- options.context.onPartialOutputs?.(buildCommonOutputs(requestMessages, text, undefined, functionCalls, undefined, '', undefined, undefined, [], [], {
161
+ options.context.onPartialOutputs?.(createChatV2CommonOutputs({
162
+ requestMessages,
163
+ response: text,
164
+ structuredOutput: undefined,
165
+ functionCalls,
166
+ usage: undefined,
167
+ reasoning: '',
168
+ requestStatus: undefined,
169
+ responseError: undefined,
170
+ requestStatuses: [],
171
+ requestErrors: [],
364
172
  outputUsage: false,
365
173
  outputReasoning: false,
366
174
  outputRequestStatus: false,
@@ -388,13 +196,23 @@ export async function runChatV2Pipeline(options) {
388
196
  if ('commonOutputs' in streamed) {
389
197
  return streamed;
390
198
  }
391
- const usage = normalizeUsage(streamed.result.usage, options);
199
+ const usage = normalizeChatV2Usage(streamed.result.usage, options);
392
200
  const requestStatuses = streamed.requestStatuses;
393
201
  const requestErrors = normalizeProviderFailureMessages(streamed.requestErrors, options);
394
202
  const responseError = streamed.responseError
395
203
  ? normalizeProviderFailureMessage(streamed.responseError, options)
396
204
  : undefined;
397
- const commonOutputs = buildCommonOutputs(requestMessages, streamed.result.responseText, streamed.result.structuredOutput, streamed.result.functionCalls, usage, streamed.result.reasoning, streamed.result.requestStatus, responseError, requestStatuses, requestErrors, {
205
+ const commonOutputs = createChatV2CommonOutputs({
206
+ requestMessages,
207
+ response: streamed.result.responseText,
208
+ structuredOutput: streamed.result.structuredOutput,
209
+ functionCalls: streamed.result.functionCalls,
210
+ usage,
211
+ reasoning: streamed.result.reasoning,
212
+ requestStatus: streamed.result.requestStatus,
213
+ responseError,
214
+ requestStatuses,
215
+ requestErrors,
398
216
  outputUsage: options.outputUsage,
399
217
  outputReasoning: options.outputReasoning,
400
218
  outputRequestStatus: options.outputRequestStatus,