@valerypopoff/rivet2-core 2.0.1 → 2.0.3

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.
@@ -13,7 +13,7 @@ import { replayExecutionRecording } from './RecordingPlayer.js';
13
13
  import { didLoopControllerBreak, LOOP_NOT_BROKEN_SENTINEL } from './loopControllerBreak.js';
14
14
  import { buildNodeProcessContext } from './ProcessContextBuilder.js';
15
15
  import { processSplitRunNode } from './SplitRunProcessor.js';
16
- import { areRequiredInputsConnected, getInputNodesTo, getOutputNodesFrom, getStartNodes, getWaitingForInputNode, hasErroredInputNode, } from './NodeExecutionPlanner.js';
16
+ import { getInputNodesTo, getMissingRequiredInputs, getOutputNodesFrom, getStartNodes, getWaitingForInputNode, hasErroredInputNode, } from './NodeExecutionPlanner.js';
17
17
  import { wireSubprocessorEvents, wireSubprocessorLifecycle } from './SubprocessorBridge.js';
18
18
  import { emitDetached } from '../utils/emitDetached.js';
19
19
  // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
@@ -551,9 +551,9 @@ export class GraphProcessor {
551
551
  #hasErroredInputNode(node, inputNodes, trace = false) {
552
552
  return hasErroredInputNode(this.#executionState, node, inputNodes, trace ? (message) => this.#emitTraceEvent(message) : undefined);
553
553
  }
554
- /** Returns true if all required inputs have connections. */
555
- #areRequiredInputsConnected(node) {
556
- return areRequiredInputsConnected(this.#executionState, node);
554
+ /** Returns required inputs without connections. */
555
+ #getMissingRequiredInputs(node) {
556
+ return getMissingRequiredInputs(this.#executionState, node);
557
557
  }
558
558
  /** Accumulates cost from a node's output. */
559
559
  #accumulateCost(output) {
@@ -576,10 +576,7 @@ export class GraphProcessor {
576
576
  if (this.#hasErroredInputNode(node, inputNodes)) {
577
577
  return;
578
578
  }
579
- if (!this.#areRequiredInputsConnected(node)) {
580
- return;
581
- }
582
- this.#emitTraceEvent(`Node ${node.title} has required inputs nodes: ${inputNodes.map((n) => n.title).join(', ')}`);
579
+ this.#emitTraceEvent(`Node ${node.title} has input nodes: ${inputNodes.map((n) => n.title).join(', ')}`);
583
580
  const attachedData = this.#getAttachedDataTo(node);
584
581
  if (node.type === 'raceInputs' || attachedData.races) {
585
582
  for (const inputNode of inputNodes) {
@@ -611,6 +608,10 @@ export class GraphProcessor {
611
608
  if (this.#shouldSkipNodeProcessing(node, inputNodes)) {
612
609
  return;
613
610
  }
611
+ const attachedData = this.#getAttachedDataTo(node);
612
+ if (this.#shouldSkipCompletedRaceNode(node, attachedData)) {
613
+ return;
614
+ }
614
615
  const inputValues = this.#getInputValuesForNode(node);
615
616
  if (this.#excludedDueToControlFlow(node, inputValues, nanoid(), LOOP_NOT_BROKEN_SENTINEL)) {
616
617
  this.#emitTraceEvent(`Node ${node.title} is excluded due to control flow`);
@@ -621,7 +622,15 @@ export class GraphProcessor {
621
622
  this.#emitTraceEvent(`Node ${node.title} is waiting for input node ${waitingForInputNode}`);
622
623
  return;
623
624
  }
624
- const attachedData = this.#getAttachedDataTo(node);
625
+ if (this.#excludedDueToControlFlow(node, inputValues, nanoid())) {
626
+ this.#emitTraceEvent(`Node ${node.title} is excluded due to control flow`);
627
+ return;
628
+ }
629
+ const missingRequiredInputs = this.#getMissingRequiredInputs(node);
630
+ if (missingRequiredInputs.length > 0) {
631
+ this.#excludeNodeWithMissingRequiredInputs(node, inputValues, missingRequiredInputs);
632
+ return;
633
+ }
625
634
  if (this.#beginNodeProcessing(node, attachedData) === false) {
626
635
  return;
627
636
  }
@@ -669,25 +678,36 @@ export class GraphProcessor {
669
678
  if (this.#hasErroredInputNode(node, inputNodes, true)) {
670
679
  return true;
671
680
  }
672
- if (!this.#areRequiredInputsConnected(node)) {
673
- this.#emitTraceEvent(`Node ${node.title} has required inputs nodes: ${inputNodes.map((n) => n.title).join(', ')}`);
674
- return true;
675
- }
676
681
  return false;
677
682
  }
683
+ #excludeNodeWithMissingRequiredInputs(node, inputValues, missingRequiredInputs) {
684
+ const missingInputNames = missingRequiredInputs.map((input) => input.title || input.id).join(', ');
685
+ const processId = nanoid();
686
+ this.#emitTraceEvent(`Excluding node ${node.title} because required inputs are not connected: ${missingInputNames}`);
687
+ this.#excludeNode(node, processId, inputValues, 'missing required input');
688
+ }
678
689
  #beginNodeProcessing(node, attachedData) {
679
- if (attachedData.races?.completed) {
680
- this.#emitTraceEvent(`Node ${node.title} is part of a race that was completed`);
690
+ if (this.#shouldSkipCompletedRaceNode(node, attachedData)) {
681
691
  return false;
682
692
  }
683
693
  this.#currentlyProcessing.add(node.id);
684
694
  if (node.type === 'loopController') {
685
695
  this.#loopControllersSeen.add(node.id);
686
696
  }
697
+ this.#registerNodeInActiveLoop(node, attachedData);
698
+ return true;
699
+ }
700
+ #shouldSkipCompletedRaceNode(node, attachedData) {
701
+ if (attachedData.races?.completed) {
702
+ this.#emitTraceEvent(`Node ${node.title} is part of a race that was completed`);
703
+ return true;
704
+ }
705
+ return false;
706
+ }
707
+ #registerNodeInActiveLoop(node, attachedData) {
687
708
  if (attachedData.loopInfo && attachedData.loopInfo.loopControllerId !== node.id) {
688
709
  attachedData.loopInfo.nodes.add(node.id);
689
710
  }
690
- return true;
691
711
  }
692
712
  #handleLoopControllerPostProcess(node, attachedData) {
693
713
  if (node.type !== 'loopController') {
@@ -1050,16 +1070,14 @@ export class GraphProcessor {
1050
1070
  #excludedDueToControlFlow(node, inputValues, processId, typeOfExclusion = undefined) {
1051
1071
  if (node.disabled) {
1052
1072
  this.#emitTraceEvent(`Excluding node ${node.title} because it's disabled`);
1053
- this.#visitedNodes.add(node.id);
1054
- this.#markAsExcluded(node, processId, inputValues, 'disabled');
1073
+ this.#excludeNode(node, processId, inputValues, 'disabled');
1055
1074
  return true;
1056
1075
  }
1057
1076
  if (node.isConditional && typeOfExclusion === undefined) {
1058
1077
  const ifValue = coerceTypeOptional(inputValues[IF_PORT.id], 'boolean');
1059
1078
  if (ifValue === false) {
1060
1079
  this.#emitTraceEvent(`Excluding node ${node.title} because if port is false`);
1061
- this.#visitedNodes.add(node.id);
1062
- this.#markAsExcluded(node, processId, inputValues, 'if port is false');
1080
+ this.#excludeNode(node, processId, inputValues, 'if port is false');
1063
1081
  return true;
1064
1082
  }
1065
1083
  }
@@ -1081,13 +1099,23 @@ export class GraphProcessor {
1081
1099
  if (inputIsExcludedValue) {
1082
1100
  this.#emitTraceEvent(`Excluding node ${node.title} because of control flow. Input is has excluded value: ${controlFlowExcludedValues[0]?.[0]}`);
1083
1101
  }
1084
- this.#visitedNodes.add(node.id);
1085
- this.#markAsExcluded(node, processId, inputValues, 'input is excluded value');
1102
+ this.#excludeNode(node, processId, inputValues, 'input is excluded value');
1086
1103
  }
1087
1104
  return true;
1088
1105
  }
1089
1106
  return false;
1090
1107
  }
1108
+ #excludeNode(node, processId, inputValues, reason) {
1109
+ const attachedData = this.#getAttachedDataTo(node);
1110
+ this.#registerNodeInActiveLoop(node, attachedData);
1111
+ this.#visitedNodes.add(node.id);
1112
+ this.#markAsExcluded(node, processId, inputValues, reason);
1113
+ this.#currentlyProcessing.delete(node.id);
1114
+ this.#remainingNodes.delete(node.id);
1115
+ const outputNodes = getOutputNodesFrom(this.#executionState, node);
1116
+ this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
1117
+ this.#queueOutputNodes(node, outputNodes.nodes);
1118
+ }
1091
1119
  #markAsExcluded(node, processId, inputValues, reason) {
1092
1120
  const outputs = {};
1093
1121
  for (const output of this.#definitions[node.id].outputs) {
@@ -48,11 +48,11 @@ export function hasErroredInputNode(state, node, inputNodes, onTrace) {
48
48
  }
49
49
  return false;
50
50
  }
51
- export function areRequiredInputsConnected(state, node) {
51
+ export function getMissingRequiredInputs(state, node) {
52
52
  const connections = state.connections[node.id] ?? [];
53
- return state.definitions[node.id].inputs.every((input) => {
53
+ return state.definitions[node.id].inputs.filter((input) => {
54
54
  const connectionToInput = connections.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);
55
- return connectionToInput || !input.required;
55
+ return input.required && !connectionToInput;
56
56
  });
57
57
  }
58
58
  export function getWaitingForInputNode(state, node, inputNodes, inputValues) {
@@ -56,6 +56,8 @@ import { contextNode } from './nodes/ContextNode.js';
56
56
  export * from './nodes/ContextNode.js';
57
57
  import { coalesceNode } from './nodes/CoalesceNode.js';
58
58
  export * from './nodes/CoalesceNode.js';
59
+ import { didRunNode } from './nodes/DidRunNode.js';
60
+ export * from './nodes/DidRunNode.js';
59
61
  import { passthroughNode } from './nodes/PassthroughNode.js';
60
62
  export * from './nodes/PassthroughNode.js';
61
63
  import { popNode } from './nodes/PopNode.js';
@@ -205,6 +207,7 @@ export const registerBuiltInNodes = (registry) => {
205
207
  .register(raiseEventNode)
206
208
  .register(contextNode)
207
209
  .register(coalesceNode)
210
+ .register(didRunNode)
208
211
  .register(passthroughNode)
209
212
  .register(popNode)
210
213
  .register(setGlobalNode)
@@ -1,3 +1,23 @@
1
+ function subscribeOwnGraphRunLifecycle(processor, onLifecycleEvent) {
2
+ let ownGraphRunId;
3
+ const unsubscribeGraphStart = processor.on('graphStart', (event) => {
4
+ ownGraphRunId ??= event.execution.graphRunId;
5
+ });
6
+ const onPossibleLifecycleEvent = (event) => {
7
+ if (ownGraphRunId != null && event.execution.graphRunId === ownGraphRunId) {
8
+ onLifecycleEvent();
9
+ }
10
+ };
11
+ const unsubscribeGraphFinish = processor.on('graphFinish', onPossibleLifecycleEvent);
12
+ const unsubscribeGraphAbort = processor.on('graphAbort', onPossibleLifecycleEvent);
13
+ const unsubscribeGraphError = processor.on('graphError', onPossibleLifecycleEvent);
14
+ return () => {
15
+ unsubscribeGraphStart();
16
+ unsubscribeGraphFinish();
17
+ unsubscribeGraphAbort();
18
+ unsubscribeGraphError();
19
+ };
20
+ }
1
21
  export function wireSubprocessorEvents(processor, parentEmitter, parentState) {
2
22
  const unsubscribers = [
3
23
  processor.on('nodeError', (event) => parentEmitter.emit('nodeError', event)),
@@ -36,14 +56,8 @@ export function wireSubprocessorEvents(processor, parentEmitter, parentState) {
36
56
  }
37
57
  cleanedUp = true;
38
58
  unsubscribers.forEach((unsubscribe) => unsubscribe());
39
- unsubscribeAny();
40
- unsubscribeGraphFinish();
41
- unsubscribeGraphAbort();
42
- unsubscribeGraphError();
43
59
  };
44
- const unsubscribeGraphFinish = processor.on('graphFinish', cleanup);
45
- const unsubscribeGraphAbort = processor.on('graphAbort', cleanup);
46
- const unsubscribeGraphError = processor.on('graphError', cleanup);
60
+ unsubscribers.push(unsubscribeAny, subscribeOwnGraphRunLifecycle(processor, cleanup));
47
61
  }
48
62
  export function wireSubprocessorLifecycle(processor, options) {
49
63
  const abortFromSignal = () => {
@@ -60,23 +74,19 @@ export function wireSubprocessorLifecycle(processor, options) {
60
74
  };
61
75
  options.signal?.addEventListener('abort', abortFromSignal, { once: true });
62
76
  options.parentAbortSignal.addEventListener('abort', abortFromParent, { once: true });
63
- const unsubscribeParentPause = options.onParentPause(pauseProcessor);
64
- const unsubscribeParentResume = options.onParentResume(resumeProcessor);
77
+ const unsubscribers = [
78
+ () => options.signal?.removeEventListener('abort', abortFromSignal),
79
+ () => options.parentAbortSignal.removeEventListener('abort', abortFromParent),
80
+ options.onParentPause(pauseProcessor),
81
+ options.onParentResume(resumeProcessor),
82
+ ];
65
83
  let cleanedUp = false;
66
84
  const cleanup = () => {
67
85
  if (cleanedUp) {
68
86
  return;
69
87
  }
70
88
  cleanedUp = true;
71
- options.signal?.removeEventListener('abort', abortFromSignal);
72
- options.parentAbortSignal.removeEventListener('abort', abortFromParent);
73
- unsubscribeParentPause();
74
- unsubscribeParentResume();
75
- unsubscribeGraphFinish();
76
- unsubscribeGraphAbort();
77
- unsubscribeGraphError();
89
+ unsubscribers.forEach((unsubscribe) => unsubscribe());
78
90
  };
79
- const unsubscribeGraphFinish = processor.on('graphFinish', cleanup);
80
- const unsubscribeGraphAbort = processor.on('graphAbort', cleanup);
81
- const unsubscribeGraphError = processor.on('graphError', cleanup);
91
+ unsubscribers.push(subscribeOwnGraphRunLifecycle(processor, cleanup));
82
92
  }
@@ -1,12 +1,33 @@
1
- export async function consumeAiSdkStream(fullStream, onPartialOutputs) {
1
+ function buildResponseText(textBlocks, dedupeDuplicateTextBlocks) {
2
+ const blockTexts = Array.from(textBlocks.values()).filter((text) => text.length > 0);
3
+ if (blockTexts.length === 0) {
4
+ return '';
5
+ }
6
+ if (dedupeDuplicateTextBlocks && blockTexts.length > 1) {
7
+ const longestText = blockTexts.reduce((longest, text) => (text.length > longest.length ? text : longest));
8
+ if (blockTexts.every((text) => longestText.startsWith(text))) {
9
+ return longestText;
10
+ }
11
+ }
12
+ return blockTexts.join('');
13
+ }
14
+ export async function consumeAiSdkStream(fullStream, onPartialOutputs, options = {}) {
2
15
  let responseText = '';
3
16
  let reasoning = '';
4
17
  const functionCalls = [];
5
18
  let usage;
19
+ const textBlocks = new Map();
6
20
  for await (const part of fullStream) {
7
21
  switch (part.type) {
22
+ case 'text-start': {
23
+ if (!textBlocks.has(part.id)) {
24
+ textBlocks.set(part.id, '');
25
+ }
26
+ break;
27
+ }
8
28
  case 'text-delta': {
9
- responseText += part.text;
29
+ textBlocks.set(part.id, `${textBlocks.get(part.id) ?? ''}${part.text}`);
30
+ responseText = buildResponseText(textBlocks, !!options.dedupeDuplicateTextBlocks);
10
31
  onPartialOutputs(responseText, functionCalls);
11
32
  break;
12
33
  }
@@ -1,5 +1,6 @@
1
1
  import { streamText } from 'ai';
2
2
  import { consumeAiSdkStream } from '../chat/aiSdkStreaming.js';
3
+ import { isChatV2StructuredResponseFormat } from './chatV2ResponseFormat.js';
3
4
  function keepPromiseHandled(value) {
4
5
  const promise = Promise.resolve(value);
5
6
  void promise.catch(() => undefined);
@@ -22,6 +23,9 @@ function defaultStreamExecutor(args) {
22
23
  finishReason: 'finishReason' in result
23
24
  ? keepPromiseHandled(Promise.resolve(result.finishReason).then((value) => (value == null ? undefined : String(value))))
24
25
  : undefined,
26
+ output: args.output != null && 'output' in result
27
+ ? keepPromiseHandled(Promise.resolve(result.output))
28
+ : undefined,
25
29
  providerMetadata: 'providerMetadata' in result
26
30
  ? keepPromiseHandled(Promise.resolve(result.providerMetadata))
27
31
  : undefined,
@@ -34,6 +38,38 @@ function defaultStreamExecutor(args) {
34
38
  async function resolveOptionalValue(value) {
35
39
  return value == null ? undefined : await value;
36
40
  }
41
+ async function resolveOptionalStructuredOutput(value) {
42
+ if (value == null) {
43
+ return undefined;
44
+ }
45
+ try {
46
+ return await value;
47
+ }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ }
52
+ function collapseRepeatedStructuredJsonText(responseText) {
53
+ if (responseText.length === 0 || responseText.length % 2 !== 0) {
54
+ return responseText;
55
+ }
56
+ const midpoint = responseText.length / 2;
57
+ const firstHalf = responseText.slice(0, midpoint);
58
+ const firstNonWhitespaceCharacter = firstHalf.trimStart()[0];
59
+ if (firstHalf !== responseText.slice(midpoint)) {
60
+ return responseText;
61
+ }
62
+ if (firstNonWhitespaceCharacter !== '{' && firstNonWhitespaceCharacter !== '[') {
63
+ return responseText;
64
+ }
65
+ try {
66
+ JSON.parse(firstHalf);
67
+ return firstHalf;
68
+ }
69
+ catch {
70
+ return responseText;
71
+ }
72
+ }
37
73
  async function executeStream(options, executor) {
38
74
  const args = {
39
75
  model: options.model,
@@ -67,14 +103,25 @@ async function executeStream(options, executor) {
67
103
  args.abortSignal = options.abortSignal;
68
104
  const handle = await executor(args);
69
105
  markOptionalPromiseHandled(handle.finishReason);
106
+ markOptionalPromiseHandled(handle.output);
70
107
  markOptionalPromiseHandled(handle.providerMetadata);
71
108
  markOptionalPromiseHandled(handle.requestStatus);
72
109
  markOptionalPromiseHandled(handle.usage);
110
+ const isStructuredOutput = isChatV2StructuredResponseFormat(options.responseFormat);
73
111
  const streamed = await consumeAiSdkStream(handle.fullStream, (text, functionCalls) => {
74
- options.onPartialOutput?.({ text, functionCalls });
112
+ options.onPartialOutput?.({
113
+ text: isStructuredOutput ? collapseRepeatedStructuredJsonText(text) : text,
114
+ functionCalls,
115
+ });
116
+ }, {
117
+ dedupeDuplicateTextBlocks: isStructuredOutput,
75
118
  });
119
+ const responseText = isStructuredOutput
120
+ ? collapseRepeatedStructuredJsonText(streamed.responseText)
121
+ : streamed.responseText;
76
122
  return {
77
- responseText: streamed.responseText,
123
+ responseText,
124
+ structuredOutput: options.responseOutput != null ? await resolveOptionalStructuredOutput(handle.output) : undefined,
78
125
  functionCalls: streamed.functionCalls,
79
126
  usage: streamed.usage ?? (await resolveOptionalValue(handle.usage)),
80
127
  reasoning: streamed.reasoning,
@@ -1,3 +1,4 @@
1
+ import { isChatV2StructuredResponseFormat, } from './chatV2ResponseFormat.js';
1
2
  export const LLM_CHAT_V2_TOOL_RESPONSE_FORMAT_CONFLICT_COPY = {
2
3
  title: '"Tool use" conflicts with "Structured outputs"',
3
4
  paragraphs: [
@@ -6,7 +7,7 @@ export const LLM_CHAT_V2_TOOL_RESPONSE_FORMAT_CONFLICT_COPY = {
6
7
  ],
7
8
  };
8
9
  export function isLLMChatV2StructuredResponseFormat(responseFormat) {
9
- return responseFormat === 'json' || responseFormat === 'json_schema';
10
+ return isChatV2StructuredResponseFormat(responseFormat);
10
11
  }
11
12
  export function hasLLMChatV2ToolResponseFormatConflict(data) {
12
13
  return !!data.useToolCalling && isLLMChatV2StructuredResponseFormat(data.responseFormat);
@@ -1,8 +1,10 @@
1
+ import { inferType } from '../../utils/coerceType.js';
1
2
  import { coercePromptToChatMessages, prependSystemPrompt } from '../chat/chatMessages.js';
2
3
  import { createAssistantMessagesOutput } from '../chat/streamChatResponse.js';
3
4
  import { streamChatV2 } from './aiSdkBridge.js';
4
5
  import { chatMessagesToModelMessages } from './messageConverter.js';
5
6
  import { calculateChatV2Cost } from './modelRegistry.js';
7
+ import { isChatV2StructuredResponseFormat } from './chatV2ResponseFormat.js';
6
8
  import { chatV2ToolsToAiSdk } from './toolConverter.js';
7
9
  import { getChatV2ProviderErrorStatusCode, isChatV2ProviderApiCallError, isChatV2ProviderFetchError, normalizeChatV2ProviderError, } from './chatV2Errors.js';
8
10
  import { normalizeLLMChatV2RetryCooldownMs, normalizeLLMChatV2RetryCount, waitForLLMChatV2RetryCooldown, } from './chatV2Retry.js';
@@ -57,9 +59,24 @@ function normalizeUsage(usage, options) {
57
59
  totalCost: calculateChatV2Cost(options.provider, options.modelId, promptTokens, completionTokens),
58
60
  };
59
61
  }
60
- function buildCommonOutputs(requestMessages, response, functionCalls, usage, reasoning, requestStatus, responseError, requestStatuses, requestErrors, options) {
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) {
61
78
  const outputs = {
62
- ['response']: { type: 'string', value: response },
79
+ ['response']: buildResponseOutput(response, structuredOutput, options.responseFormat),
63
80
  ['in-messages']: { type: 'chat-message[]', value: requestMessages },
64
81
  ['all-messages']: createAssistantMessagesOutput(requestMessages, response, functionCalls, {
65
82
  functionCallMode: options.functionCallMode,
@@ -92,15 +109,7 @@ function buildCommonOutputs(requestMessages, response, functionCalls, usage, rea
92
109
  };
93
110
  }
94
111
  if (options.outputReasoning) {
95
- outputs['reasoning'] = Array.isArray(reasoning)
96
- ? {
97
- type: 'string[]',
98
- value: reasoning,
99
- }
100
- : {
101
- type: 'string',
102
- value: reasoning,
103
- };
112
+ outputs['reasoning'] = buildReasoningOutput(reasoning);
104
113
  }
105
114
  if (options.outputRequestStatus) {
106
115
  if (options.retryOnNon200) {
@@ -126,6 +135,30 @@ function buildCommonOutputs(requestMessages, response, functionCalls, usage, rea
126
135
  }
127
136
  return outputs;
128
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
+ }
129
162
  function getProviderFailureMessage(error) {
130
163
  if (error instanceof Error) {
131
164
  return error.message;
@@ -319,6 +352,7 @@ export async function runChatV2Pipeline(options) {
319
352
  stopSequences: options.stopSequences,
320
353
  seed: options.seed,
321
354
  responseOutput: options.responseOutput,
355
+ responseFormat: options.responseFormat,
322
356
  providerOptions: options.providerOptions,
323
357
  toolChoice: options.toolChoice,
324
358
  abortSignal: options.context.signal,
@@ -326,13 +360,14 @@ export async function runChatV2Pipeline(options) {
326
360
  onPartialOutput: options.emitPartialOutputs === false
327
361
  ? undefined
328
362
  : ({ text, functionCalls }) => {
329
- options.context.onPartialOutputs?.(buildCommonOutputs(requestMessages, text, functionCalls, undefined, '', undefined, undefined, [], [], {
363
+ options.context.onPartialOutputs?.(buildCommonOutputs(requestMessages, text, undefined, functionCalls, undefined, '', undefined, undefined, [], [], {
330
364
  outputUsage: false,
331
365
  outputReasoning: false,
332
366
  outputRequestStatus: false,
333
367
  includeFunctionCalls: options.includeFunctionCalls,
334
368
  functionCallMode: options.functionCallMode,
335
369
  retryOnNon200: false,
370
+ responseFormat: undefined,
336
371
  }));
337
372
  },
338
373
  }, options).catch((caughtError) => {
@@ -359,13 +394,14 @@ export async function runChatV2Pipeline(options) {
359
394
  const responseError = streamed.responseError
360
395
  ? normalizeProviderFailureMessage(streamed.responseError, options)
361
396
  : undefined;
362
- const commonOutputs = buildCommonOutputs(requestMessages, streamed.result.responseText, streamed.result.functionCalls, usage, streamed.result.reasoning, streamed.result.requestStatus, responseError, requestStatuses, requestErrors, {
397
+ const commonOutputs = buildCommonOutputs(requestMessages, streamed.result.responseText, streamed.result.structuredOutput, streamed.result.functionCalls, usage, streamed.result.reasoning, streamed.result.requestStatus, responseError, requestStatuses, requestErrors, {
363
398
  outputUsage: options.outputUsage,
364
399
  outputReasoning: options.outputReasoning,
365
400
  outputRequestStatus: options.outputRequestStatus,
366
401
  includeFunctionCalls: options.includeFunctionCalls,
367
402
  functionCallMode: options.functionCallMode,
368
403
  retryOnNon200: options.retryOnNon200,
404
+ responseFormat: options.responseFormat,
369
405
  });
370
406
  const allMessagesOutput = commonOutputs['all-messages'];
371
407
  if (allMessagesOutput?.type !== 'chat-message[]') {
@@ -1,6 +1,9 @@
1
1
  import { Output, jsonSchema } from 'ai';
2
2
  import { coerceTypeOptional } from '../../utils/coerceType.js';
3
3
  import { getInputOrData } from '../../utils/inputs.js';
4
+ export function isChatV2StructuredResponseFormat(responseFormat) {
5
+ return responseFormat === 'json' || responseFormat === 'json_schema';
6
+ }
4
7
  function getResponseSchema(inputs) {
5
8
  const responseSchemaInput = inputs['responseSchema'];
6
9
  if (responseSchemaInput?.type === 'gpt-function') {
@@ -12,6 +15,40 @@ function normalizeOptionalString(value) {
12
15
  const trimmed = value?.trim();
13
16
  return trimmed ? trimmed : undefined;
14
17
  }
18
+ function toJsonValue(value, path = 'Response Schema', seen = new WeakSet()) {
19
+ if (value === undefined) {
20
+ throw new Error(`${path} must be JSON-compatible; undefined values are not supported.`);
21
+ }
22
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') {
23
+ return value;
24
+ }
25
+ if (typeof value === 'number') {
26
+ if (!Number.isFinite(value)) {
27
+ throw new Error(`${path} must be JSON-compatible; non-finite numbers are not supported.`);
28
+ }
29
+ return value;
30
+ }
31
+ if (Array.isArray(value)) {
32
+ return value.map((item, index) => toJsonValue(item, `${path}[${index}]`, seen));
33
+ }
34
+ if (typeof value === 'object') {
35
+ const prototype = Object.getPrototypeOf(value);
36
+ if (prototype !== Object.prototype && prototype !== null) {
37
+ throw new Error(`${path} must be JSON-compatible; only plain objects are supported.`);
38
+ }
39
+ if (seen.has(value)) {
40
+ throw new Error(`${path} must be JSON-compatible; circular references are not supported.`);
41
+ }
42
+ seen.add(value);
43
+ const jsonObject = {};
44
+ for (const [key, item] of Object.entries(value)) {
45
+ jsonObject[key] = toJsonValue(item, `${path}.${key}`, seen);
46
+ }
47
+ seen.delete(value);
48
+ return jsonObject;
49
+ }
50
+ throw new Error(`${path} must be JSON-compatible; ${typeof value} values are not supported.`);
51
+ }
15
52
  export function resolveChatV2ResponseFormatParameters(data, inputs) {
16
53
  const responseFormat = data.responseFormat ?? '';
17
54
  if (!responseFormat) {
@@ -50,8 +87,44 @@ export function createChatV2ResponseOutput(parameters) {
50
87
  });
51
88
  }
52
89
  return Output.object({
53
- schema: jsonSchema(parameters.schema),
90
+ schema: jsonSchema(toJsonValue(parameters.schema)),
54
91
  name: parameters.schemaName,
55
92
  description: parameters.schemaDescription,
56
93
  });
57
94
  }
95
+ export function mergeCustomProviderResponseFormatOptions(provider, providerOptions, parameters) {
96
+ if (provider !== 'custom' || parameters == null) {
97
+ return providerOptions;
98
+ }
99
+ const customOptions = providerOptions?.custom ?? {};
100
+ if (parameters.responseFormat === 'json') {
101
+ return {
102
+ ...providerOptions,
103
+ custom: {
104
+ ...customOptions,
105
+ response_format: { type: 'json_object' },
106
+ },
107
+ };
108
+ }
109
+ if (parameters.responseFormat !== 'json_schema') {
110
+ return providerOptions;
111
+ }
112
+ const jsonSchemaOptions = {
113
+ name: parameters.schemaName,
114
+ strict: true,
115
+ schema: toJsonValue(parameters.schema),
116
+ };
117
+ if (parameters.schemaDescription != null) {
118
+ jsonSchemaOptions.description = parameters.schemaDescription;
119
+ }
120
+ return {
121
+ ...providerOptions,
122
+ custom: {
123
+ ...customOptions,
124
+ response_format: {
125
+ type: 'json_schema',
126
+ json_schema: jsonSchemaOptions,
127
+ },
128
+ },
129
+ };
130
+ }
@@ -1,6 +1,6 @@
1
1
  import { coerceTypeOptional } from '../../utils/coerceType.js';
2
2
  import { getInputOrData } from '../../utils/inputs.js';
3
- import { createChatV2ResponseOutput, resolveChatV2ResponseFormatParameters } from './chatV2ResponseFormat.js';
3
+ import { createChatV2ResponseOutput, mergeCustomProviderResponseFormatOptions, resolveChatV2ResponseFormatParameters, } from './chatV2ResponseFormat.js';
4
4
  import { hasLLMChatV2ToolResponseFormatConflict, LLM_CHAT_V2_TOOL_RESPONSE_FORMAT_CONFLICT_COPY, } from './chatV2FeatureCompatibility.js';
5
5
  import { createChatV2Model, parseChatV2Provider, resolveChatV2ProviderConfig } from './providerOptions.js';
6
6
  import { buildLLMChatV2EditorCacheKey, cloneLLMChatV2EditorCacheOutputs, resolveLLMChatV2EditorCache, } from './chatV2EditorCache.js';
@@ -34,9 +34,9 @@ export async function resolveLLMChatV2RuntimeConfig(params) {
34
34
  const functions = data.useToolCalling && inputs['functions'] != null
35
35
  ? coerceTypeOptional(inputs['functions'], 'gpt-function[]')
36
36
  : undefined;
37
- const providerOptions = resolveLLMChatV2RuntimeProviderOptions(data, inputs);
38
37
  const toolChoice = resolveLLMChatV2ToolChoice(data);
39
38
  const responseFormatParameters = resolveChatV2ResponseFormatParameters(data, inputs);
39
+ const providerOptions = mergeCustomProviderResponseFormatOptions(provider, resolveLLMChatV2RuntimeProviderOptions(data, inputs), responseFormatParameters);
40
40
  const generationParameters = resolveLLMChatV2GenerationParameters(data, inputs);
41
41
  const runOptions = {
42
42
  provider,
@@ -48,6 +48,7 @@ export async function resolveLLMChatV2RuntimeConfig(params) {
48
48
  additionalTools: resolveLLMChatV2BuiltInTools(data, context, providerConfig, apiKey),
49
49
  ...generationParameters,
50
50
  responseOutput: createChatV2ResponseOutput(responseFormatParameters),
51
+ responseFormat: responseFormatParameters?.responseFormat,
51
52
  outputUsage: data.outputUsage,
52
53
  outputReasoning: data.outputReasoning,
53
54
  outputRequestStatus: data.outputRequestStatus,
@@ -41,7 +41,10 @@ function applyAccumulatedUsage(result, usage, outputUsage) {
41
41
  }
42
42
  function appendReasoningRound(accumulated, reasoning) {
43
43
  const roundReasoning = Array.isArray(reasoning) ? reasoning : [reasoning];
44
- const nonEmptyReasoning = roundReasoning.map((part) => part.trim()).filter((part) => part.length > 0);
44
+ const nonEmptyReasoning = roundReasoning
45
+ .filter((part) => typeof part === 'string')
46
+ .map((part) => part.trim())
47
+ .filter((part) => part.length > 0);
45
48
  if (nonEmptyReasoning.length === 0) {
46
49
  return;
47
50
  }