@librechat/agents 4.2.13 → 4.2.14

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 (121) hide show
  1. package/dist/cjs/graphs/Graph.cjs +45 -3
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/harness/providerText.cjs +1 -0
  4. package/dist/cjs/harness/providerText.cjs.map +1 -1
  5. package/dist/cjs/llm/google/utils/signatures.cjs +22 -14
  6. package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -1
  7. package/dist/cjs/llm/invoke.cjs +122 -13
  8. package/dist/cjs/llm/invoke.cjs.map +1 -1
  9. package/dist/cjs/llm/openai/index.cjs +8 -2
  10. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  11. package/dist/cjs/llm/openai/typedContent.cjs +94 -0
  12. package/dist/cjs/llm/openai/typedContent.cjs.map +1 -0
  13. package/dist/cjs/llm/prepareProviderRequest.cjs +80 -3
  14. package/dist/cjs/llm/prepareProviderRequest.cjs.map +1 -1
  15. package/dist/cjs/llm/providerTextBatch.cjs +128 -0
  16. package/dist/cjs/llm/providerTextBatch.cjs.map +1 -0
  17. package/dist/cjs/llm/providerTextBoundary.cjs +81 -12
  18. package/dist/cjs/llm/providerTextBoundary.cjs.map +1 -1
  19. package/dist/cjs/main.cjs +2 -0
  20. package/dist/cjs/protection/providerText.cjs +56 -6
  21. package/dist/cjs/protection/providerText.cjs.map +1 -1
  22. package/dist/cjs/protection/providerTextAdmission.cjs +5 -0
  23. package/dist/cjs/protection/providerTextAdmission.cjs.map +1 -1
  24. package/dist/cjs/run.cjs +7 -2
  25. package/dist/cjs/run.cjs.map +1 -1
  26. package/dist/cjs/runtime/client.cjs +2 -0
  27. package/dist/cjs/runtime/client.cjs.map +1 -1
  28. package/dist/cjs/stream.cjs +9 -2
  29. package/dist/cjs/stream.cjs.map +1 -1
  30. package/dist/cjs/tools/handlers.cjs +47 -1
  31. package/dist/cjs/tools/handlers.cjs.map +1 -1
  32. package/dist/cjs/tools/search/citations.cjs +194 -0
  33. package/dist/cjs/tools/search/citations.cjs.map +1 -0
  34. package/dist/cjs/tools/search/firecrawl.cjs +4 -9
  35. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  36. package/dist/cjs/tools/search/google.cjs +68 -0
  37. package/dist/cjs/tools/search/google.cjs.map +1 -0
  38. package/dist/cjs/tools/search/openai.cjs +80 -0
  39. package/dist/cjs/tools/search/openai.cjs.map +1 -0
  40. package/dist/cjs/utils/tokens.cjs +5 -0
  41. package/dist/cjs/utils/tokens.cjs.map +1 -1
  42. package/dist/esm/graphs/Graph.mjs +46 -4
  43. package/dist/esm/graphs/Graph.mjs.map +1 -1
  44. package/dist/esm/harness/providerText.mjs +1 -0
  45. package/dist/esm/harness/providerText.mjs.map +1 -1
  46. package/dist/esm/llm/google/utils/signatures.mjs +22 -14
  47. package/dist/esm/llm/google/utils/signatures.mjs.map +1 -1
  48. package/dist/esm/llm/invoke.mjs +124 -15
  49. package/dist/esm/llm/invoke.mjs.map +1 -1
  50. package/dist/esm/llm/openai/index.mjs +8 -2
  51. package/dist/esm/llm/openai/index.mjs.map +1 -1
  52. package/dist/esm/llm/openai/typedContent.mjs +93 -0
  53. package/dist/esm/llm/openai/typedContent.mjs.map +1 -0
  54. package/dist/esm/llm/prepareProviderRequest.mjs +80 -3
  55. package/dist/esm/llm/prepareProviderRequest.mjs.map +1 -1
  56. package/dist/esm/llm/providerTextBatch.mjs +128 -0
  57. package/dist/esm/llm/providerTextBatch.mjs.map +1 -0
  58. package/dist/esm/llm/providerTextBoundary.mjs +81 -12
  59. package/dist/esm/llm/providerTextBoundary.mjs.map +1 -1
  60. package/dist/esm/main.mjs +3 -3
  61. package/dist/esm/protection/providerText.mjs +55 -7
  62. package/dist/esm/protection/providerText.mjs.map +1 -1
  63. package/dist/esm/protection/providerTextAdmission.mjs +5 -0
  64. package/dist/esm/protection/providerTextAdmission.mjs.map +1 -1
  65. package/dist/esm/run.mjs +7 -2
  66. package/dist/esm/run.mjs.map +1 -1
  67. package/dist/esm/runtime/client.mjs +2 -0
  68. package/dist/esm/runtime/client.mjs.map +1 -1
  69. package/dist/esm/stream.mjs +9 -2
  70. package/dist/esm/stream.mjs.map +1 -1
  71. package/dist/esm/tools/handlers.mjs +47 -2
  72. package/dist/esm/tools/handlers.mjs.map +1 -1
  73. package/dist/esm/tools/search/citations.mjs +190 -0
  74. package/dist/esm/tools/search/citations.mjs.map +1 -0
  75. package/dist/esm/tools/search/firecrawl.mjs +4 -9
  76. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  77. package/dist/esm/tools/search/google.mjs +67 -0
  78. package/dist/esm/tools/search/google.mjs.map +1 -0
  79. package/dist/esm/tools/search/openai.mjs +80 -0
  80. package/dist/esm/tools/search/openai.mjs.map +1 -0
  81. package/dist/esm/utils/tokens.mjs +5 -0
  82. package/dist/esm/utils/tokens.mjs.map +1 -1
  83. package/dist/types/graphs/Graph.d.ts +14 -0
  84. package/dist/types/index.d.ts +2 -2
  85. package/dist/types/llm/openai/typedContent.d.ts +14 -0
  86. package/dist/types/llm/providerTextBatch.d.ts +26 -0
  87. package/dist/types/llm/providerTextBoundary.d.ts +7 -1
  88. package/dist/types/protection/providerText.d.ts +29 -1
  89. package/dist/types/protection/providerTextAdmission.d.ts +1 -0
  90. package/dist/types/tools/handlers.d.ts +13 -0
  91. package/dist/types/tools/search/citations.d.ts +88 -0
  92. package/dist/types/tools/search/firecrawl.d.ts +3 -1
  93. package/dist/types/tools/search/google.d.ts +11 -0
  94. package/dist/types/tools/search/openai.d.ts +3 -0
  95. package/dist/types/tools/search/types.d.ts +24 -0
  96. package/dist/types/types/stream.d.ts +12 -0
  97. package/dist/types/utils/tokens.d.ts +1 -0
  98. package/package.json +1 -1
  99. package/src/graphs/Graph.ts +103 -3
  100. package/src/harness/providerText.ts +1 -0
  101. package/src/index.ts +2 -0
  102. package/src/llm/google/utils/signatures.ts +52 -36
  103. package/src/llm/invoke.ts +160 -16
  104. package/src/llm/openai/index.ts +18 -5
  105. package/src/llm/openai/typedContent.ts +110 -0
  106. package/src/llm/prepareProviderRequest.ts +154 -4
  107. package/src/llm/providerTextBatch.ts +158 -0
  108. package/src/llm/providerTextBoundary.ts +119 -13
  109. package/src/protection/providerText.ts +95 -6
  110. package/src/protection/providerTextAdmission.ts +6 -0
  111. package/src/run.ts +22 -1
  112. package/src/runtime/client.ts +3 -0
  113. package/src/stream.ts +18 -2
  114. package/src/tools/handlers.ts +110 -5
  115. package/src/tools/search/citations.ts +375 -0
  116. package/src/tools/search/firecrawl.ts +13 -16
  117. package/src/tools/search/google.ts +122 -0
  118. package/src/tools/search/openai.ts +118 -0
  119. package/src/tools/search/types.ts +21 -0
  120. package/src/types/stream.ts +9 -0
  121. package/src/utils/tokens.ts +9 -0
@@ -37,6 +37,7 @@ import type {
37
37
  GraphFactoryRequest,
38
38
  } from '@/graphs/graphFactory';
39
39
  import type { OverflowRecoveryPlan } from '@/llm/contextOverflowRecovery';
40
+ import type { GoogleGroundingMetadata } from '@/tools/search/types';
40
41
  import type { FallbackErrorContext } from '@/llm/invoke';
41
42
  import type { HandoffRouting } from './handoff';
42
43
  import type { HookRegistry } from '@/hooks';
@@ -184,6 +185,7 @@ import {
184
185
  isThinkingEnabled,
185
186
  getConfiguredCompletionTokens,
186
187
  } from '@/llm/request';
188
+ import { handleNativeSearchCitations, handleToolCalls } from '@/tools/handlers';
187
189
  import { createToolHistoryPreparation } from '@/messages/toolHistoryProjection';
188
190
  import { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';
189
191
  import { shouldTraceToolNodeForLangfuse } from '@/langfuseToolOutputTracing';
@@ -203,11 +205,11 @@ import { isRunStepResumeState } from '@/tools/runStepResume';
203
205
  import { resolveLocalToolsForBinding } from '@/tools/local';
204
206
  import { createSummarizeNode } from '@/summarization/node';
205
207
  import { getTruncationStopReason } from '@/llm/truncation';
208
+ import { SearchCitations } from '@/tools/search/citations';
206
209
  import { createSchemaOnlyTools } from '@/tools/schema';
207
210
  import { AgentContext } from '@/agents/AgentContext';
208
211
  import { createFakeStreamingLLM } from '@/llm/fake';
209
212
  import { handoffStateAnnotation } from './handoff';
210
- import { handleToolCalls } from '@/tools/handlers';
211
213
  import { resolveMaxSeals } from '@/llm/preempt';
212
214
  import { initializeModel } from '@/llm/init';
213
215
  import { HandlerRegistry } from '@/events';
@@ -847,6 +849,8 @@ export abstract class Graph<
847
849
  callerSignal?: AbortSignal;
848
850
  /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */
849
851
  invokedToolIds?: Set<string>;
852
+ /** Provider-native web search sources and the anchors still owed to their citations. */
853
+ searchCitations = new SearchCitations();
850
854
  /** Explicit host policy. Never inferred from missing ToolNode claims. */
851
855
  clientDelegatedToolNames?: ReadonlySet<string>;
852
856
  handlerRegistry: HandlerRegistry | undefined;
@@ -955,6 +959,7 @@ export abstract class Graph<
955
959
  this.messageStepHasToolCalls = new Map();
956
960
  this.prelimMessageIdsByStepKey = new Map();
957
961
  this.invokedToolIds = undefined;
962
+ this.searchCitations = new SearchCitations();
958
963
  this.handlerRegistry = undefined;
959
964
  this.parentToolHandlerRegistry = undefined;
960
965
  this.hookRegistry = undefined;
@@ -1661,6 +1666,25 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1661
1666
  this.streamLimits = resolveStreamLimits(streamLimits);
1662
1667
  if (providerTextProtection != null)
1663
1668
  validateProviderTextProtection(providerTextProtection);
1669
+ if (providerTextProtection?.batching != null) {
1670
+ const agent = agents[0];
1671
+ if (
1672
+ this.isMultiAgentGraph() ||
1673
+ agents.length !== 1 ||
1674
+ preemption != null ||
1675
+ (clientDelegatedToolNames?.length ?? 0) > 0 ||
1676
+ (agent.tools?.length ?? 0) > 0 ||
1677
+ (agent.graphTools?.length ?? 0) > 0 ||
1678
+ (agent.toolDefinitions?.length ?? 0) > 0 ||
1679
+ (agent.toolRegistry?.size ?? 0) > 0 ||
1680
+ (agent.subagentConfigs?.length ?? 0) > 0 ||
1681
+ agent.summarizationEnabled === true ||
1682
+ agent.summarizeOnly === true ||
1683
+ agent.initialSummary != null
1684
+ ) {
1685
+ throw new ProviderTextProtectionError('unsupported');
1686
+ }
1687
+ }
1664
1688
  this.providerTextProtection = providerTextProtection;
1665
1689
  const toolResultGate =
1666
1690
  toolResultProtection == null
@@ -1854,6 +1878,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1854
1878
  new Map()
1855
1879
  );
1856
1880
  this.invokedToolIds = resetIfNotEmpty(this.invokedToolIds, undefined);
1881
+ this.searchCitations = new SearchCitations();
1857
1882
  this.resetPreemptTurnState();
1858
1883
  this.resetPreemptTotals();
1859
1884
  const hasScopedCheckpoint =
@@ -2356,6 +2381,15 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
2356
2381
  return false;
2357
2382
  }
2358
2383
 
2384
+ const anchors = this.searchCitations.release(stepId);
2385
+ if (anchors != null && this.config != null) {
2386
+ await this.dispatchMessageDelta(
2387
+ stepId,
2388
+ { content: [{ type: ContentTypes.TEXT, text: anchors.text }] },
2389
+ anchors.metadata ?? options?.metadata
2390
+ );
2391
+ }
2392
+
2359
2393
  const closedAt = options?.at ?? Date.now();
2360
2394
  runStep.status = status;
2361
2395
  if (status === 'completed') {
@@ -2484,6 +2518,54 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
2484
2518
  await this.closeRunStep(stepId, 'completed', { metadata, at: closeAt });
2485
2519
  }
2486
2520
 
2521
+ /** Gemini grounding and OpenAI url_citation arrive after the text they cite. */
2522
+ private tracksSearchText(metadata?: Record<string, unknown>): boolean {
2523
+ if (metadata == null) {
2524
+ return false;
2525
+ }
2526
+ try {
2527
+ const { provider } = this.getAgentContext(metadata);
2528
+ return (
2529
+ isGoogleLike(provider) ||
2530
+ provider === Providers.OPENAI ||
2531
+ provider === Providers.AZURE
2532
+ );
2533
+ } catch (_e) {
2534
+ return false;
2535
+ }
2536
+ }
2537
+
2538
+ /** Keeps a Gemini chunk's grounding for the lane's model call. */
2539
+ groundSearchCitations(
2540
+ metadata: Record<string, unknown> | undefined,
2541
+ grounding: GoogleGroundingMetadata
2542
+ ): void {
2543
+ this.searchCitations.ground(
2544
+ this.getStepAgentKey(metadata),
2545
+ grounding,
2546
+ metadata
2547
+ );
2548
+ }
2549
+
2550
+ /**
2551
+ * Turns the web search citations a finished agent model call carried into
2552
+ * a `web_search` result and anchors in its text. Model calls outside an
2553
+ * agent node (summaries, tool internals) never own the lane's text.
2554
+ */
2555
+ async settleSearchCitations(
2556
+ metadata?: Record<string, unknown>
2557
+ ): Promise<void> {
2558
+ const node = metadata?.langgraph_node;
2559
+ if (typeof node !== 'string' || !node.startsWith(AGENT)) {
2560
+ return;
2561
+ }
2562
+ const call = this.searchCitations.take(this.getStepAgentKey(metadata));
2563
+ if (call == null) {
2564
+ return;
2565
+ }
2566
+ await handleNativeSearchCitations({ graph: this, call, metadata });
2567
+ }
2568
+
2487
2569
  /**
2488
2570
  * Closes the tracked open MESSAGE_CREATION step for the event's agent lane.
2489
2571
  * Fires on every model end, so the empty-map check short-circuits ahead of
@@ -5951,6 +6033,12 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
5951
6033
 
5952
6034
  createWorkflow(): t.CompiledStateWorkflow {
5953
6035
  this.hasCompiledCheckpointer = this.compileOptions?.checkpointer != null;
6036
+ if (
6037
+ this.hasCompiledCheckpointer &&
6038
+ this.providerTextProtection?.batching != null
6039
+ ) {
6040
+ throw new ProviderTextProtectionError('unsupported');
6041
+ }
5954
6042
  const agentNode = this.createAgentNode(this.defaultAgentId);
5955
6043
  const StateAnnotation = Annotation.Root({
5956
6044
  messages: Annotation<BaseMessage[]>({
@@ -6318,11 +6406,23 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
6318
6406
  if (!this.config) {
6319
6407
  throw new Error('No config provided');
6320
6408
  }
6409
+ const content = Array.isArray(delta.content)
6410
+ ? (this.searchCitations.anchor(id, delta.content, metadata) ??
6411
+ delta.content)
6412
+ : delta.content;
6321
6413
  const messageDelta: t.MessageDeltaEvent = {
6322
6414
  id,
6323
- delta,
6415
+ delta: content === delta.content ? delta : { ...delta, content },
6324
6416
  };
6325
- if (hasTextDeltaContent(delta.content)) {
6417
+ if (content != null && this.tracksSearchText(metadata)) {
6418
+ this.searchCitations.track(
6419
+ this.getStepAgentKey(metadata),
6420
+ id,
6421
+ content,
6422
+ metadata
6423
+ );
6424
+ }
6425
+ if (hasTextDeltaContent(content)) {
6326
6426
  this.messageStepHasTextDeltas.add(id);
6327
6427
  }
6328
6428
  const handler = this.handlerRegistry?.getHandler(
@@ -66,6 +66,7 @@ export function createHostProviderTextService(options: {
66
66
  const identity = boundIdentity(options.identity);
67
67
  const policy = options.policy;
68
68
  validateProviderTextProtection(policy);
69
+ if (policy.batching != null) throw new ProviderTextProtectionError('unsupported');
69
70
  const { admission, inspectionTimeoutMs } = options;
70
71
  if (inspectionTimeoutMs !== undefined)
71
72
  validateProviderTextTimeout(inspectionTimeoutMs);
package/src/index.ts CHANGED
@@ -125,11 +125,13 @@ export * from './rerank';
125
125
 
126
126
  export {
127
127
  PROVIDER_TEXT_PROTECTION_VERSION,
128
+ PROVIDER_TEXT_BATCHING_VERSION,
128
129
  ProviderTextProtectionError,
129
130
  serializeProviderTextProtectionError,
130
131
  deserializeProviderTextProtectionError,
131
132
  } from './protection/providerText';
132
133
  export type {
134
+ ProviderTextBatching,
133
135
  ProviderTextProtection,
134
136
  ProviderTextProtectionResult,
135
137
  ProviderTextProtectionErrorCode,
@@ -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);