@librechat/agents 4.2.13 → 4.2.15

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 (147) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +75 -19
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/graphs/Graph.cjs +52 -6
  4. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  5. package/dist/cjs/harness/providerText.cjs +1 -0
  6. package/dist/cjs/harness/providerText.cjs.map +1 -1
  7. package/dist/cjs/llm/google/utils/signatures.cjs +22 -14
  8. package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -1
  9. package/dist/cjs/llm/invoke.cjs +122 -13
  10. package/dist/cjs/llm/invoke.cjs.map +1 -1
  11. package/dist/cjs/llm/openai/index.cjs +8 -2
  12. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  13. package/dist/cjs/llm/openai/typedContent.cjs +94 -0
  14. package/dist/cjs/llm/openai/typedContent.cjs.map +1 -0
  15. package/dist/cjs/llm/prepareProviderRequest.cjs +102 -7
  16. package/dist/cjs/llm/prepareProviderRequest.cjs.map +1 -1
  17. package/dist/cjs/llm/providerTextBatch.cjs +128 -0
  18. package/dist/cjs/llm/providerTextBatch.cjs.map +1 -0
  19. package/dist/cjs/llm/providerTextBoundary.cjs +81 -12
  20. package/dist/cjs/llm/providerTextBoundary.cjs.map +1 -1
  21. package/dist/cjs/main.cjs +3 -0
  22. package/dist/cjs/messages/content.cjs +3 -3
  23. package/dist/cjs/messages/content.cjs.map +1 -1
  24. package/dist/cjs/messages/vision.cjs +77 -0
  25. package/dist/cjs/messages/vision.cjs.map +1 -0
  26. package/dist/cjs/protection/providerText.cjs +56 -6
  27. package/dist/cjs/protection/providerText.cjs.map +1 -1
  28. package/dist/cjs/protection/providerTextAdmission.cjs +5 -0
  29. package/dist/cjs/protection/providerTextAdmission.cjs.map +1 -1
  30. package/dist/cjs/run.cjs +7 -2
  31. package/dist/cjs/run.cjs.map +1 -1
  32. package/dist/cjs/runtime/client.cjs +2 -0
  33. package/dist/cjs/runtime/client.cjs.map +1 -1
  34. package/dist/cjs/stream.cjs +9 -2
  35. package/dist/cjs/stream.cjs.map +1 -1
  36. package/dist/cjs/summarization/node.cjs +6 -2
  37. package/dist/cjs/summarization/node.cjs.map +1 -1
  38. package/dist/cjs/tools/handlers.cjs +47 -1
  39. package/dist/cjs/tools/handlers.cjs.map +1 -1
  40. package/dist/cjs/tools/search/citations.cjs +194 -0
  41. package/dist/cjs/tools/search/citations.cjs.map +1 -0
  42. package/dist/cjs/tools/search/firecrawl.cjs +4 -9
  43. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  44. package/dist/cjs/tools/search/google.cjs +68 -0
  45. package/dist/cjs/tools/search/google.cjs.map +1 -0
  46. package/dist/cjs/tools/search/openai.cjs +80 -0
  47. package/dist/cjs/tools/search/openai.cjs.map +1 -0
  48. package/dist/cjs/utils/tokens.cjs +6 -0
  49. package/dist/cjs/utils/tokens.cjs.map +1 -1
  50. package/dist/esm/agents/AgentContext.mjs +76 -20
  51. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  52. package/dist/esm/graphs/Graph.mjs +53 -7
  53. package/dist/esm/graphs/Graph.mjs.map +1 -1
  54. package/dist/esm/harness/providerText.mjs +1 -0
  55. package/dist/esm/harness/providerText.mjs.map +1 -1
  56. package/dist/esm/llm/google/utils/signatures.mjs +22 -14
  57. package/dist/esm/llm/google/utils/signatures.mjs.map +1 -1
  58. package/dist/esm/llm/invoke.mjs +124 -15
  59. package/dist/esm/llm/invoke.mjs.map +1 -1
  60. package/dist/esm/llm/openai/index.mjs +8 -2
  61. package/dist/esm/llm/openai/index.mjs.map +1 -1
  62. package/dist/esm/llm/openai/typedContent.mjs +93 -0
  63. package/dist/esm/llm/openai/typedContent.mjs.map +1 -0
  64. package/dist/esm/llm/prepareProviderRequest.mjs +102 -7
  65. package/dist/esm/llm/prepareProviderRequest.mjs.map +1 -1
  66. package/dist/esm/llm/providerTextBatch.mjs +128 -0
  67. package/dist/esm/llm/providerTextBatch.mjs.map +1 -0
  68. package/dist/esm/llm/providerTextBoundary.mjs +81 -12
  69. package/dist/esm/llm/providerTextBoundary.mjs.map +1 -1
  70. package/dist/esm/main.mjs +4 -4
  71. package/dist/esm/messages/content.mjs +3 -3
  72. package/dist/esm/messages/content.mjs.map +1 -1
  73. package/dist/esm/messages/vision.mjs +73 -0
  74. package/dist/esm/messages/vision.mjs.map +1 -0
  75. package/dist/esm/protection/providerText.mjs +55 -7
  76. package/dist/esm/protection/providerText.mjs.map +1 -1
  77. package/dist/esm/protection/providerTextAdmission.mjs +5 -0
  78. package/dist/esm/protection/providerTextAdmission.mjs.map +1 -1
  79. package/dist/esm/run.mjs +7 -2
  80. package/dist/esm/run.mjs.map +1 -1
  81. package/dist/esm/runtime/client.mjs +2 -0
  82. package/dist/esm/runtime/client.mjs.map +1 -1
  83. package/dist/esm/stream.mjs +9 -2
  84. package/dist/esm/stream.mjs.map +1 -1
  85. package/dist/esm/summarization/node.mjs +6 -2
  86. package/dist/esm/summarization/node.mjs.map +1 -1
  87. package/dist/esm/tools/handlers.mjs +47 -2
  88. package/dist/esm/tools/handlers.mjs.map +1 -1
  89. package/dist/esm/tools/search/citations.mjs +190 -0
  90. package/dist/esm/tools/search/citations.mjs.map +1 -0
  91. package/dist/esm/tools/search/firecrawl.mjs +4 -9
  92. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  93. package/dist/esm/tools/search/google.mjs +67 -0
  94. package/dist/esm/tools/search/google.mjs.map +1 -0
  95. package/dist/esm/tools/search/openai.mjs +80 -0
  96. package/dist/esm/tools/search/openai.mjs.map +1 -0
  97. package/dist/esm/utils/tokens.mjs +6 -1
  98. package/dist/esm/utils/tokens.mjs.map +1 -1
  99. package/dist/types/agents/AgentContext.d.ts +20 -1
  100. package/dist/types/graphs/Graph.d.ts +14 -0
  101. package/dist/types/index.d.ts +2 -2
  102. package/dist/types/llm/openai/typedContent.d.ts +14 -0
  103. package/dist/types/llm/prepareProviderRequest.d.ts +7 -1
  104. package/dist/types/llm/providerTextBatch.d.ts +26 -0
  105. package/dist/types/llm/providerTextBoundary.d.ts +7 -1
  106. package/dist/types/messages/content.d.ts +2 -1
  107. package/dist/types/messages/vision.d.ts +20 -0
  108. package/dist/types/protection/providerText.d.ts +29 -1
  109. package/dist/types/protection/providerTextAdmission.d.ts +1 -0
  110. package/dist/types/tools/handlers.d.ts +13 -0
  111. package/dist/types/tools/search/citations.d.ts +88 -0
  112. package/dist/types/tools/search/firecrawl.d.ts +3 -1
  113. package/dist/types/tools/search/google.d.ts +11 -0
  114. package/dist/types/tools/search/openai.d.ts +3 -0
  115. package/dist/types/tools/search/types.d.ts +24 -0
  116. package/dist/types/types/graph.d.ts +8 -0
  117. package/dist/types/types/stream.d.ts +12 -0
  118. package/dist/types/utils/tokens.d.ts +3 -0
  119. package/package.json +1 -1
  120. package/src/agents/AgentContext.ts +188 -78
  121. package/src/graphs/Graph.ts +117 -8
  122. package/src/harness/providerText.ts +1 -0
  123. package/src/index.ts +2 -0
  124. package/src/llm/google/utils/signatures.ts +52 -36
  125. package/src/llm/invoke.ts +160 -16
  126. package/src/llm/openai/index.ts +18 -5
  127. package/src/llm/openai/typedContent.ts +110 -0
  128. package/src/llm/prepareProviderRequest.ts +206 -7
  129. package/src/llm/providerTextBatch.ts +158 -0
  130. package/src/llm/providerTextBoundary.ts +119 -13
  131. package/src/messages/content.ts +10 -4
  132. package/src/messages/vision.ts +109 -0
  133. package/src/protection/providerText.ts +95 -6
  134. package/src/protection/providerTextAdmission.ts +6 -0
  135. package/src/run.ts +22 -1
  136. package/src/runtime/client.ts +3 -0
  137. package/src/stream.ts +18 -2
  138. package/src/summarization/node.ts +4 -0
  139. package/src/tools/handlers.ts +110 -5
  140. package/src/tools/search/citations.ts +375 -0
  141. package/src/tools/search/firecrawl.ts +13 -16
  142. package/src/tools/search/google.ts +122 -0
  143. package/src/tools/search/openai.ts +118 -0
  144. package/src/tools/search/types.ts +21 -0
  145. package/src/types/graph.ts +8 -0
  146. package/src/types/stream.ts +9 -0
  147. package/src/utils/tokens.ts +13 -1
@@ -1,8 +1,10 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { AIMessageChunk, isAIMessage } from '@langchain/core/messages';
3
+ import type { ToolCall } from '@langchain/core/messages/tool';
3
4
  import type { BaseMessage } from '@langchain/core/messages';
4
5
  import type { GeminiPart } from '@langchain/google-common';
5
6
  import type { Part } from '@google/generative-ai';
7
+ import { stripSearchAnchors } from '@/tools/search/citations';
6
8
 
7
9
  export const GEMINI_PARTS = '__gemini_parts__';
8
10
  export const GEMINI_REPLAY_UNSUPPORTED = '__gemini_replay_unsupported__';
@@ -140,43 +142,13 @@ export function captureGeminiReplayParts(
140
142
  delete message.additional_kwargs[GEMINI_REPLAY_UNSUPPORTED];
141
143
  }
142
144
 
143
- /** Returns original parts only when the current message still matches every text hash and call id. */
144
- export function restoreGeminiReplayParts(
145
- message: BaseMessage,
146
- replay: unknown = message.additional_kwargs[GEMINI_PARTS]
145
+ function matchReplayParts(
146
+ replay: readonly GeminiReplayPart[],
147
+ text: string,
148
+ reasoning: string,
149
+ toolCalls: readonly ToolCall[]
147
150
  ): GeminiPart[] | undefined {
148
- if (
149
- message.additional_kwargs[GEMINI_REPLAY_UNSUPPORTED] === true ||
150
- !isAIMessage(message) ||
151
- !isGeminiReplayParts(replay)
152
- )
153
- return undefined;
154
- let text = '';
155
- let contentReasoning: string | undefined;
156
- if (typeof message.content === 'string') text = message.content;
157
- else
158
- for (const block of message.content) {
159
- if (block.type === 'text' && typeof block.text === 'string')
160
- text += block.text;
161
- else if (block.type === 'thinking' && typeof block.thinking === 'string')
162
- contentReasoning = (contentReasoning ?? '') + block.thinking;
163
- else if (
164
- block.type === 'reasoning' &&
165
- typeof block.reasoning === 'string'
166
- )
167
- contentReasoning = (contentReasoning ?? '') + block.reasoning;
168
- else if (!('functionCall' in block)) return undefined;
169
- }
170
- let reasoning = contentReasoning ?? '';
171
- if (typeof message.additional_kwargs.reasoning_content === 'string')
172
- reasoning = message.additional_kwargs.reasoning_content;
173
- if (typeof message.additional_kwargs.reasoning === 'string')
174
- reasoning = message.additional_kwargs.reasoning;
175
- if (contentReasoning != null && contentReasoning !== reasoning)
176
- return undefined;
177
- const calls = new Map(
178
- (message.tool_calls ?? []).map((call) => [call.id, call])
179
- );
151
+ const calls = new Map(toolCalls.map((call) => [call.id, call]));
180
152
  const parts: GeminiPart[] = [];
181
153
  let textOffset = 0;
182
154
  let reasoningOffset = 0;
@@ -220,3 +192,47 @@ export function restoreGeminiReplayParts(
220
192
  ? parts
221
193
  : undefined;
222
194
  }
195
+
196
+ /** Returns original parts only when the current message still matches every text hash and call id. */
197
+ export function restoreGeminiReplayParts(
198
+ message: BaseMessage,
199
+ replay: unknown = message.additional_kwargs[GEMINI_PARTS]
200
+ ): GeminiPart[] | undefined {
201
+ if (
202
+ message.additional_kwargs[GEMINI_REPLAY_UNSUPPORTED] === true ||
203
+ !isAIMessage(message) ||
204
+ !isGeminiReplayParts(replay)
205
+ )
206
+ return undefined;
207
+ let text = '';
208
+ let contentReasoning: string | undefined;
209
+ if (typeof message.content === 'string') text = message.content;
210
+ else
211
+ for (const block of message.content) {
212
+ if (block.type === 'text' && typeof block.text === 'string')
213
+ text += block.text;
214
+ else if (block.type === 'thinking' && typeof block.thinking === 'string')
215
+ contentReasoning = (contentReasoning ?? '') + block.thinking;
216
+ else if (
217
+ block.type === 'reasoning' &&
218
+ typeof block.reasoning === 'string'
219
+ )
220
+ contentReasoning = (contentReasoning ?? '') + block.reasoning;
221
+ else if (!('functionCall' in block)) return undefined;
222
+ }
223
+ let reasoning = contentReasoning ?? '';
224
+ if (typeof message.additional_kwargs.reasoning_content === 'string')
225
+ reasoning = message.additional_kwargs.reasoning_content;
226
+ if (typeof message.additional_kwargs.reasoning === 'string')
227
+ reasoning = message.additional_kwargs.reasoning;
228
+ if (contentReasoning != null && contentReasoning !== reasoning)
229
+ return undefined;
230
+ const toolCalls = message.tool_calls ?? [];
231
+ const parts = matchReplayParts(replay, text, reasoning, toolCalls);
232
+ if (parts != null) return parts;
233
+ /** Citation anchors added to the saved answer are not part of what Gemini signed. */
234
+ const stripped = stripSearchAnchors(text);
235
+ return stripped === text
236
+ ? undefined
237
+ : matchReplayParts(replay, stripped, reasoning, toolCalls);
238
+ }
package/src/llm/invoke.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { concat } from '@langchain/core/utils/stream';
2
2
  import { AIMessageChunk } from '@langchain/core/messages';
3
3
  import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
4
- import { getCallbackManagerForConfig } from '@langchain/core/runnables';
4
+ import { ensureConfig, getCallbackManagerForConfig } from '@langchain/core/runnables';
5
5
  import type { Serialized } from '@langchain/core/load/serializable';
6
6
  import type { RunnableConfig } from '@langchain/core/runnables';
7
7
  import type { ChatGeneration } from '@langchain/core/outputs';
@@ -25,8 +25,10 @@ import {
25
25
  STREAM_LIMIT_ATTEMPT_KEY,
26
26
  } from '@/llm/streamLimits';
27
27
  import {
28
+ BATCHED_PROVIDER_EVENT_OWNER,
28
29
  validateProviderTextProtection,
29
30
  ProviderTextProtectionError,
31
+ ProviderTextAttempt,
30
32
  createProviderTextRestartCancellation,
31
33
  isProviderTextRestartCancellation,
32
34
  } from '@/protection/providerText';
@@ -208,6 +210,74 @@ function withModelStartHandler({
208
210
  };
209
211
  }
210
212
 
213
+ /** Publication errors must not start a second attempt after text was committed. */
214
+ async function dispatchBatchEvent(
215
+ attempt: ProviderTextAttempt,
216
+ dispatch: () => void | Promise<void>
217
+ ): Promise<void> {
218
+ attempt.check();
219
+ try {
220
+ const pending = dispatch();
221
+ if (pending != null) await attempt.wait(pending, false);
222
+ attempt.check();
223
+ } catch (error) {
224
+ attempt.check();
225
+ if (error instanceof StreamLimitExceededError || error instanceof PreparedSubagentError) {
226
+ throw error;
227
+ }
228
+ const failure = new ProviderTextProtectionError('unavailable');
229
+ attempt.stop(failure);
230
+ throw failure;
231
+ }
232
+ }
233
+
234
+ function withBatchCloseDeadline(
235
+ stream: AsyncIterable<AIMessageChunk>,
236
+ attempt: ProviderTextAttempt
237
+ ): AsyncIterable<AIMessageChunk> {
238
+ return {
239
+ [Symbol.asyncIterator](): AsyncIterator<AIMessageChunk> {
240
+ const iterator = stream[Symbol.asyncIterator]();
241
+ return {
242
+ next: iterator.next.bind(iterator),
243
+ async return(): Promise<IteratorResult<AIMessageChunk>> {
244
+ // LangChain's iterator close can wait on an in-flight native callback.
245
+ const closing = iterator.return?.();
246
+ if (closing != null) await attempt.wait(closing, false).catch(() => {});
247
+ return { done: true, value: undefined };
248
+ },
249
+ };
250
+ },
251
+ };
252
+ }
253
+
254
+ function captureBatchStart(context: InvokeContext | undefined): {
255
+ callback: BaseCallbackHandler;
256
+ dispatch: (attempt: ProviderTextAttempt) => Promise<void>;
257
+ } | undefined {
258
+ const handler = context?.handlerRegistry?.getHandler(GraphEvents.CHAT_MODEL_START);
259
+ if (handler == null) return;
260
+ let start: { messages: BaseMessage[][]; metadata?: Record<string, unknown> } | undefined;
261
+ const callback = BaseCallbackHandler.fromMethods({
262
+ handleChatModelStart(_llm, messages, _runId, _parentId, _extra, _tags, metadata): void {
263
+ start = { messages, metadata };
264
+ },
265
+ });
266
+ callback.name = 'batched-provider-start';
267
+ callback.awaitHandlers = true;
268
+ return {
269
+ callback,
270
+ dispatch: (attempt): Promise<void> => {
271
+ const event = start;
272
+ start = undefined;
273
+ if (event == null) throw new ProviderTextProtectionError('incompatible');
274
+ return dispatchBatchEvent(attempt, () => handler.handle(
275
+ GraphEvents.CHAT_MODEL_START, { input: { messages: event.messages } }, event.metadata, context
276
+ ));
277
+ },
278
+ };
279
+ }
280
+
211
281
  function getManualToolStreamNormalizationProvider(
212
282
  provider: t.ProviderName
213
283
  ): t.ProviderName {
@@ -665,6 +735,9 @@ export async function attemptInvoke(
665
735
  const policy =
666
736
  params.providerTextProtection ?? params.context?.providerTextProtection;
667
737
  if (policy != null) validateProviderTextProtection(policy);
738
+ if (policy?.batching != null && params.context?.preemption != null) {
739
+ throw new ProviderTextProtectionError('unsupported');
740
+ }
668
741
  const provider = resolveAttemptProvider(params);
669
742
  const providerStampedConfig: RunnableConfig = {
670
743
  ...config,
@@ -676,12 +749,36 @@ export async function attemptInvoke(
676
749
  },
677
750
  };
678
751
  const preparedRequest = resolveAttemptRequest(params, providerStampedConfig);
752
+ const batchConfig = policy?.batching == null ? undefined : ensureConfig(providerStampedConfig);
753
+ const batchStart = batchConfig == null ? undefined : captureBatchStart(params.context);
754
+ let batchAttempt: ProviderTextAttempt | undefined;
755
+ let unbindBatchSignal: (() => void) | undefined;
756
+ let batchEntered = false;
757
+ let finishBatch: (() => void) | undefined;
758
+ const batchInvocation = batchConfig == null ? undefined : {
759
+ getAttempt(signal?: AbortSignal): ProviderTextAttempt {
760
+ const attempt = batchAttempt;
761
+ if (attempt == null || batchEntered) throw new ProviderTextProtectionError('incompatible');
762
+ attempt.signal.throwIfAborted();
763
+ attempt.check();
764
+ unbindBatchSignal = attempt.followSignal(signal);
765
+ batchEntered = true;
766
+ finishBatch = attempt.holdFinish();
767
+ return attempt;
768
+ },
769
+ dispatchStart: batchStart?.dispatch,
770
+ };
679
771
  const request =
680
772
  policy == null
681
773
  ? preparedRequest
682
774
  : {
683
775
  ...preparedRequest,
684
- model: withProviderTextBoundary(preparedRequest.model, policy, provider),
776
+ model: withProviderTextBoundary(
777
+ preparedRequest.model,
778
+ policy,
779
+ provider,
780
+ batchInvocation
781
+ ),
685
782
  };
686
783
  const configuredModel =
687
784
  providerStampedConfig.metadata?.[Constants.INVOKED_MODEL];
@@ -689,9 +786,10 @@ export async function attemptInvoke(
689
786
  request.modelId ??
690
787
  (typeof configuredModel === 'string' ? configuredModel : undefined);
691
788
  const stampedConfig: RunnableConfig = {
692
- ...providerStampedConfig,
789
+ ...(batchConfig ?? providerStampedConfig),
790
+ ...(batchStart != null && { callbacks: appendCallbacks(batchConfig?.callbacks, [batchStart.callback]) }),
693
791
  metadata: {
694
- ...providerStampedConfig.metadata,
792
+ ...(batchConfig ?? providerStampedConfig).metadata,
695
793
  ...(modelId == null
696
794
  ? {}
697
795
  : {
@@ -708,6 +806,7 @@ export async function attemptInvoke(
708
806
  * rebuild that already attributes the serving provider.
709
807
  */
710
808
  [STREAM_LIMIT_ATTEMPT_KEY]: ++streamLimitAttemptSeq,
809
+ ...(batchInvocation != null && { [BATCHED_PROVIDER_EVENT_OWNER]: true }),
711
810
  },
712
811
  };
713
812
  const rawLeaseTarget = params.context ?? params.streamLimitState;
@@ -732,6 +831,12 @@ export async function attemptInvoke(
732
831
  const preparedAttempt = resolveGenerationKey(stampedConfig.metadata);
733
832
  prepared?.begin(preparedAttempt, stampedConfig);
734
833
  try {
834
+ if (batchConfig != null && policy != null) {
835
+ batchAttempt = new ProviderTextAttempt(policy, batchConfig.signal);
836
+ const attempt = batchAttempt;
837
+ finishBatch = (): void => attempt.finish();
838
+ stampedConfig.signal = attempt.signal;
839
+ }
735
840
  const result = await attemptInvokeBody(
736
841
  {
737
842
  request,
@@ -740,9 +845,11 @@ export async function attemptInvoke(
740
845
  onModelComplete: params.onModelComplete,
741
846
  preemptAgentId: params.preemptAgentId,
742
847
  providerTextProtection: policy,
848
+ ...(batchInvocation != null && { batchAttempt: (): ProviderTextAttempt | undefined => batchAttempt }),
743
849
  },
744
850
  stampedConfig
745
851
  );
852
+ batchAttempt?.check();
746
853
  const calls = collectAttemptToolCalls(result.messages);
747
854
  prepared?.finish(preparedAttempt, calls);
748
855
  return result;
@@ -757,9 +864,30 @@ export async function attemptInvoke(
757
864
  prepared?.finish(preparedAttempt, undefined, cancelled);
758
865
  throw cancelled;
759
866
  }
760
- prepared?.finish(preparedAttempt, undefined, error);
761
- throw error;
867
+ let failure = error;
868
+ if (
869
+ !(error instanceof StreamLimitExceededError) &&
870
+ !(error instanceof PreparedSubagentError)
871
+ ) {
872
+ // An awaited native error callback can replace the provider's error.
873
+ if (batchAttempt != null) {
874
+ try {
875
+ batchAttempt.check();
876
+ if (batchAttempt.hasPublishedText && !(error instanceof ProviderTextProtectionError)) {
877
+ const unavailable = new ProviderTextProtectionError('unavailable');
878
+ batchAttempt.stop(unavailable);
879
+ failure = unavailable;
880
+ }
881
+ } catch (abort) {
882
+ failure = abort;
883
+ }
884
+ }
885
+ }
886
+ prepared?.finish(preparedAttempt, undefined, failure);
887
+ throw failure;
762
888
  } finally {
889
+ unbindBatchSignal?.();
890
+ finishBatch?.();
763
891
  const chunks = params.context?.eagerEventToolCallChunks;
764
892
  if (prepared != null && chunks != null) {
765
893
  const prefix = `prepared:${preparedAttempt}\u0000`;
@@ -783,6 +911,7 @@ async function attemptInvokeBody(
783
911
  onModelComplete,
784
912
  preemptAgentId,
785
913
  providerTextProtection,
914
+ batchAttempt,
786
915
  }: Pick<
787
916
  AttemptInvokeCommonParams,
788
917
  | 'context'
@@ -792,6 +921,7 @@ async function attemptInvokeBody(
792
921
  | 'providerTextProtection'
793
922
  > & {
794
923
  request: PreparedProviderRequest;
924
+ batchAttempt?: () => ProviderTextAttempt | undefined;
795
925
  },
796
926
  config: RunnableConfig
797
927
  ): Promise<Partial<t.BaseGraphState>> {
@@ -1095,7 +1225,11 @@ async function attemptInvokeBody(
1095
1225
  * close below is conditional.
1096
1226
  */
1097
1227
  if (!evaluatePreemptRestart()) {
1098
- const stream = await model.stream(messagesForProvider, streamConfig);
1228
+ const nativeStream = await model.stream(messagesForProvider, streamConfig);
1229
+ const attempt = batchAttempt?.();
1230
+ const stream = attempt == null
1231
+ ? nativeStream
1232
+ : withBatchCloseDeadline(nativeStream, attempt);
1099
1233
  if (onChunk) {
1100
1234
  const attemptMetadata = config.metadata as
1101
1235
  | Record<string, unknown>
@@ -1115,18 +1249,23 @@ async function attemptInvokeBody(
1115
1249
  chunk,
1116
1250
  });
1117
1251
  }
1118
- await onChunk(chunk, attemptMetadata);
1252
+ const attempt = batchAttempt?.();
1253
+ if (attempt == null) await onChunk(chunk, attemptMetadata);
1254
+ else await dispatchBatchEvent(attempt, () => onChunk(chunk, attemptMetadata));
1119
1255
  finalChunk = appendStreamChunk({
1120
1256
  current: finalChunk,
1121
1257
  next: chunk,
1122
1258
  provider,
1123
1259
  });
1124
1260
  }
1125
- } else if (registeredStreamHandler == null) {
1261
+ } else if (registeredStreamHandler == null || batchAttempt != null) {
1126
1262
  const metadata = config.metadata as
1127
1263
  | Record<string, unknown>
1128
1264
  | undefined;
1129
- const streamHandler = new ChatModelStreamHandler();
1265
+ const streamHandler = registeredStreamHandler ?? new ChatModelStreamHandler();
1266
+ const observer = batchAttempt != null && registeredStreamHandler == null
1267
+ ? context?.handlerRegistry?.getHandler(GraphEvents.CHAT_MODEL_STREAM)
1268
+ : undefined;
1130
1269
  for await (const rawChunk of stream) {
1131
1270
  throwIfBreakerTripped();
1132
1271
  const chunk = snapshotValidatedModelChunk(rawChunk);
@@ -1150,12 +1289,16 @@ async function attemptInvokeBody(
1150
1289
  if (handlingChunk != null) {
1151
1290
  dispatchingChunk = true;
1152
1291
  try {
1153
- await streamHandler.handle(
1154
- GraphEvents.CHAT_MODEL_STREAM,
1155
- { chunk: handlingChunk },
1156
- metadata,
1157
- context
1158
- );
1292
+ const attempt = batchAttempt?.();
1293
+ if (attempt == null) {
1294
+ await streamHandler.handle(GraphEvents.CHAT_MODEL_STREAM, { chunk: handlingChunk }, metadata, context);
1295
+ } else {
1296
+ const data = { chunk: handlingChunk };
1297
+ await dispatchBatchEvent(attempt, () => streamHandler.handle(GraphEvents.CHAT_MODEL_STREAM, data, metadata, context));
1298
+ if (observer != null) {
1299
+ await dispatchBatchEvent(attempt, () => observer.handle(GraphEvents.CHAT_MODEL_STREAM, data, metadata, context));
1300
+ }
1301
+ }
1159
1302
  } finally {
1160
1303
  dispatchingChunk = false;
1161
1304
  }
@@ -1456,6 +1599,7 @@ async function attemptInvokeBody(
1456
1599
  );
1457
1600
  }
1458
1601
 
1602
+ batchAttempt?.()?.check();
1459
1603
  if (finalChunk == null) {
1460
1604
  throw new Error(EMPTY_PROVIDER_RESPONSE_MESSAGE);
1461
1605
  }
@@ -62,6 +62,10 @@ import {
62
62
  hasToolCallChunks,
63
63
  getReasoningKwargsText,
64
64
  } from '@/llm/stream/chunkAdapters';
65
+ import {
66
+ splitTypedDeltaContent,
67
+ flattenTypedMessageContent,
68
+ } from './typedContent';
65
69
  import { registerProviderTextChunkConstructor } from '@/llm/providerTextChunk';
66
70
  import { createResponsesToolArgumentConverter } from './responseToolArguments';
67
71
  import { isReasoningModel, _convertMessagesToOpenAIParams } from './utils';
@@ -1398,7 +1402,14 @@ async function* filterOpenAIChatCompletionStream(
1398
1402
  if (chunk == null) {
1399
1403
  continue;
1400
1404
  }
1401
- yield chunk;
1405
+ const pieces = splitTypedDeltaContent(chunk);
1406
+ if (pieces == null) {
1407
+ yield chunk;
1408
+ continue;
1409
+ }
1410
+ for (const piece of pieces) {
1411
+ yield piece;
1412
+ }
1402
1413
  }
1403
1414
  }
1404
1415
 
@@ -1408,10 +1419,12 @@ async function completionWithFilteredOpenAIStream(
1408
1419
  completionWithRetry: OpenAIChatCompletionRetry
1409
1420
  ): Promise<OpenAIChatCompletionResult> {
1410
1421
  if (request.stream !== true) {
1411
- return (await completionWithRetry(
1412
- request,
1413
- requestOptions
1414
- )) as OpenAIChatCompletion;
1422
+ return flattenTypedMessageContent(
1423
+ (await completionWithRetry(
1424
+ request,
1425
+ requestOptions
1426
+ )) as OpenAIChatCompletion
1427
+ );
1415
1428
  }
1416
1429
 
1417
1430
  const stream = await completionWithRetry(request, requestOptions);
@@ -0,0 +1,110 @@
1
+ import type { OpenAIClient } from '@langchain/openai';
2
+
3
+ type Chunk = OpenAIClient.Chat.Completions.ChatCompletionChunk;
4
+ type Completion = OpenAIClient.Chat.Completions.ChatCompletion;
5
+ type Choice = Chunk['choices'][number];
6
+ type Delta = Choice['delta'] & { reasoning_content?: string };
7
+ /** Usage-only chunks carry no choice, Azure content-filter chunks no delta. */
8
+ type StreamChoice = Omit<Choice, 'delta'> & { delta?: Delta };
9
+ type Message = Completion['choices'][number]['message'] & {
10
+ reasoning_content?: string;
11
+ };
12
+ type TextPart = { type: 'text'; text?: string };
13
+ /**
14
+ * Mistral reasoning models send Chat Completions `content` as a list of typed
15
+ * parts instead of a string: `thinking` parts, each holding a list of `text`
16
+ * parts, carry the reasoning, and `text` parts carry the answer. Other part
17
+ * types are read as neither.
18
+ */
19
+ type ContentPart = TextPart | { type: 'thinking'; thinking?: TextPart[] };
20
+ type TypedText = { text: string; reasoning: string };
21
+
22
+ function readTypedContent(content: ContentPart[]): TypedText {
23
+ let text = '';
24
+ let reasoning = '';
25
+ for (const part of content) {
26
+ if (part.type === 'text' && typeof part.text === 'string') {
27
+ text += part.text;
28
+ continue;
29
+ }
30
+ if (part.type !== 'thinking' || !Array.isArray(part.thinking)) {
31
+ continue;
32
+ }
33
+ for (const thought of part.thinking) {
34
+ if (typeof thought.text === 'string') {
35
+ reasoning += thought.text;
36
+ }
37
+ }
38
+ }
39
+ return { text, reasoning };
40
+ }
41
+
42
+ /**
43
+ * Rewrites a streamed chunk whose `delta.content` is a typed list as string
44
+ * content with the reasoning in `reasoning_content`, or returns `undefined`
45
+ * when the content is not a list. The chunk that closes the reasoning also
46
+ * opens the answer or a tool call, so it splits in two: the reasoning first,
47
+ * then the rest of the delta.
48
+ */
49
+ export function splitTypedDeltaContent(chunk: Chunk): Chunk[] | undefined {
50
+ const choice = chunk.choices[0] as StreamChoice | undefined;
51
+ const delta = choice?.delta;
52
+ const content: unknown = delta?.content;
53
+ if (choice == null || delta == null || !Array.isArray(content)) {
54
+ return undefined;
55
+ }
56
+ const { text, reasoning } = readTypedContent(content);
57
+ const rest: Delta = { ...delta, content: text };
58
+ const others = chunk.choices.slice(1);
59
+ const continues = text !== '' || (rest.tool_calls?.length ?? 0) > 0;
60
+ if (reasoning === '' || !continues) {
61
+ if (reasoning !== '') {
62
+ rest.reasoning_content = reasoning;
63
+ }
64
+ return [{ ...chunk, choices: [{ ...choice, delta: rest }, ...others] }];
65
+ }
66
+ const thought: Delta = { content: '', reasoning_content: reasoning };
67
+ if (rest.role != null) {
68
+ thought.role = rest.role;
69
+ }
70
+ return [
71
+ {
72
+ ...chunk,
73
+ choices: [
74
+ { ...choice, delta: thought, finish_reason: null, logprobs: null },
75
+ ],
76
+ },
77
+ { ...chunk, choices: [{ ...choice, delta: rest }, ...others] },
78
+ ];
79
+ }
80
+
81
+ function flattenMessage(message: Message | undefined): Message | undefined {
82
+ const content: unknown = message?.content;
83
+ if (message == null || !Array.isArray(content)) {
84
+ return undefined;
85
+ }
86
+ const { text, reasoning } = readTypedContent(content);
87
+ const flat: Message = { ...message, content: text };
88
+ if (reasoning !== '') {
89
+ flat.reasoning_content = reasoning;
90
+ }
91
+ return flat;
92
+ }
93
+
94
+ /** Rewrites the typed `message.content` lists of a non-streamed completion. */
95
+ export function flattenTypedMessageContent(completion: Completion): Completion {
96
+ if (!Array.isArray(completion.choices)) {
97
+ return completion;
98
+ }
99
+ let choices: Completion['choices'] | undefined;
100
+ for (let i = 0; i < completion.choices.length; i++) {
101
+ const choice = completion.choices[i];
102
+ const message = flattenMessage(choice.message);
103
+ if (message == null) {
104
+ continue;
105
+ }
106
+ choices ??= [...completion.choices];
107
+ choices[i] = { ...choice, message };
108
+ }
109
+ return choices == null ? completion : { ...completion, choices };
110
+ }