@librechat/agents 4.0.5 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +6 -4
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/decisions/breaker.cjs +59 -0
  4. package/dist/cjs/decisions/breaker.cjs.map +1 -0
  5. package/dist/cjs/decisions/core.cjs +44 -0
  6. package/dist/cjs/decisions/dialect.cjs +65 -12
  7. package/dist/cjs/decisions/dialect.cjs.map +1 -1
  8. package/dist/cjs/decisions/hook.cjs +19 -0
  9. package/dist/cjs/decisions/hook.cjs.map +1 -0
  10. package/dist/cjs/decisions/http.cjs +2 -1
  11. package/dist/cjs/decisions/http.cjs.map +1 -1
  12. package/dist/cjs/decisions/index.cjs +6 -0
  13. package/dist/cjs/decisions/node.cjs +315 -0
  14. package/dist/cjs/decisions/node.cjs.map +1 -0
  15. package/dist/cjs/decisions/probe.cjs +56 -0
  16. package/dist/cjs/decisions/probe.cjs.map +1 -0
  17. package/dist/cjs/decisions/redact.cjs +109 -0
  18. package/dist/cjs/decisions/redact.cjs.map +1 -0
  19. package/dist/cjs/decisions/structuredChat.cjs +2 -3
  20. package/dist/cjs/decisions/structuredChat.cjs.map +1 -1
  21. package/dist/cjs/decisions/transport.cjs +56 -23
  22. package/dist/cjs/decisions/transport.cjs.map +1 -1
  23. package/dist/cjs/decisions/types.cjs +2 -0
  24. package/dist/cjs/decisions/types.cjs.map +1 -1
  25. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +7 -6
  26. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  27. package/dist/cjs/llm/bedrock/cachePoints.cjs +20 -0
  28. package/dist/cjs/llm/bedrock/cachePoints.cjs.map +1 -1
  29. package/dist/cjs/llm/bedrock/index.cjs +8 -5
  30. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  31. package/dist/cjs/llm/google/index.cjs +1 -1
  32. package/dist/cjs/llm/google/index.cjs.map +1 -1
  33. package/dist/cjs/llm/google/utils/common.cjs +8 -2
  34. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  35. package/dist/cjs/main.cjs +45 -0
  36. package/dist/cjs/rerank/bm25.cjs +110 -0
  37. package/dist/cjs/rerank/bm25.cjs.map +1 -0
  38. package/dist/cjs/rerank/cache.cjs +50 -0
  39. package/dist/cjs/rerank/cache.cjs.map +1 -0
  40. package/dist/cjs/rerank/core.cjs +29 -0
  41. package/dist/cjs/rerank/crossEncoder.cjs +172 -0
  42. package/dist/cjs/rerank/crossEncoder.cjs.map +1 -0
  43. package/dist/cjs/rerank/fallback.cjs +280 -0
  44. package/dist/cjs/rerank/fallback.cjs.map +1 -0
  45. package/dist/cjs/rerank/index.cjs +8 -0
  46. package/dist/cjs/rerank/outcome.cjs +382 -0
  47. package/dist/cjs/rerank/outcome.cjs.map +1 -0
  48. package/dist/cjs/rerank/pin.cjs +74 -0
  49. package/dist/cjs/rerank/pin.cjs.map +1 -0
  50. package/dist/cjs/rerank/semaphore.cjs +38 -0
  51. package/dist/cjs/rerank/semaphore.cjs.map +1 -0
  52. package/dist/cjs/rerank/systemone.cjs +476 -50
  53. package/dist/cjs/rerank/systemone.cjs.map +1 -1
  54. package/dist/cjs/session/AgentSession.cjs +1 -1
  55. package/dist/cjs/session/AgentSession.cjs.map +1 -1
  56. package/dist/cjs/tools/local/LocalCodingTools.cjs +67 -19
  57. package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
  58. package/dist/cjs/tools/local/LocalExecutionTools.cjs +12 -1
  59. package/dist/cjs/tools/local/LocalExecutionTools.cjs.map +1 -1
  60. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs +63 -16
  61. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs.map +1 -1
  62. package/dist/cjs/tools/local/toolResultCaps.cjs +32 -0
  63. package/dist/cjs/tools/local/toolResultCaps.cjs.map +1 -0
  64. package/dist/esm/agents/AgentContext.mjs +7 -5
  65. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  66. package/dist/esm/decisions/breaker.mjs +56 -0
  67. package/dist/esm/decisions/breaker.mjs.map +1 -0
  68. package/dist/esm/decisions/core.mjs +11 -0
  69. package/dist/esm/decisions/dialect.mjs +65 -12
  70. package/dist/esm/decisions/dialect.mjs.map +1 -1
  71. package/dist/esm/decisions/hook.mjs +19 -0
  72. package/dist/esm/decisions/hook.mjs.map +1 -0
  73. package/dist/esm/decisions/http.mjs +2 -1
  74. package/dist/esm/decisions/http.mjs.map +1 -1
  75. package/dist/esm/decisions/index.mjs +6 -0
  76. package/dist/esm/decisions/node.mjs +313 -0
  77. package/dist/esm/decisions/node.mjs.map +1 -0
  78. package/dist/esm/decisions/probe.mjs +54 -0
  79. package/dist/esm/decisions/probe.mjs.map +1 -0
  80. package/dist/esm/decisions/redact.mjs +108 -0
  81. package/dist/esm/decisions/redact.mjs.map +1 -0
  82. package/dist/esm/decisions/structuredChat.mjs +2 -3
  83. package/dist/esm/decisions/structuredChat.mjs.map +1 -1
  84. package/dist/esm/decisions/transport.mjs +56 -23
  85. package/dist/esm/decisions/transport.mjs.map +1 -1
  86. package/dist/esm/decisions/types.mjs +2 -0
  87. package/dist/esm/decisions/types.mjs.map +1 -1
  88. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +7 -7
  89. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  90. package/dist/esm/llm/bedrock/cachePoints.mjs +20 -1
  91. package/dist/esm/llm/bedrock/cachePoints.mjs.map +1 -1
  92. package/dist/esm/llm/bedrock/index.mjs +7 -4
  93. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  94. package/dist/esm/llm/google/index.mjs +2 -2
  95. package/dist/esm/llm/google/index.mjs.map +1 -1
  96. package/dist/esm/llm/google/utils/common.mjs +8 -3
  97. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  98. package/dist/esm/main.mjs +15 -3
  99. package/dist/esm/rerank/bm25.mjs +108 -0
  100. package/dist/esm/rerank/bm25.mjs.map +1 -0
  101. package/dist/esm/rerank/cache.mjs +50 -0
  102. package/dist/esm/rerank/cache.mjs.map +1 -0
  103. package/dist/esm/rerank/core.mjs +9 -0
  104. package/dist/esm/rerank/crossEncoder.mjs +172 -0
  105. package/dist/esm/rerank/crossEncoder.mjs.map +1 -0
  106. package/dist/esm/rerank/fallback.mjs +278 -0
  107. package/dist/esm/rerank/fallback.mjs.map +1 -0
  108. package/dist/esm/rerank/index.mjs +8 -0
  109. package/dist/esm/rerank/outcome.mjs +360 -0
  110. package/dist/esm/rerank/outcome.mjs.map +1 -0
  111. package/dist/esm/rerank/pin.mjs +73 -0
  112. package/dist/esm/rerank/pin.mjs.map +1 -0
  113. package/dist/esm/rerank/semaphore.mjs +38 -0
  114. package/dist/esm/rerank/semaphore.mjs.map +1 -0
  115. package/dist/esm/rerank/systemone.mjs +476 -50
  116. package/dist/esm/rerank/systemone.mjs.map +1 -1
  117. package/dist/esm/session/AgentSession.mjs +1 -1
  118. package/dist/esm/session/AgentSession.mjs.map +1 -1
  119. package/dist/esm/tools/local/LocalCodingTools.mjs +67 -19
  120. package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
  121. package/dist/esm/tools/local/LocalExecutionTools.mjs +12 -1
  122. package/dist/esm/tools/local/LocalExecutionTools.mjs.map +1 -1
  123. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs +63 -17
  124. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs.map +1 -1
  125. package/dist/esm/tools/local/toolResultCaps.mjs +31 -0
  126. package/dist/esm/tools/local/toolResultCaps.mjs.map +1 -0
  127. package/dist/types/decisions/breaker.d.ts +37 -0
  128. package/dist/types/decisions/core.d.ts +19 -0
  129. package/dist/types/decisions/hook.d.ts +9 -0
  130. package/dist/types/decisions/index.d.ts +3 -8
  131. package/dist/types/decisions/node.d.ts +90 -0
  132. package/dist/types/decisions/probe.d.ts +37 -0
  133. package/dist/types/decisions/redact.d.ts +22 -0
  134. package/dist/types/decisions/structuredChat.d.ts +1 -0
  135. package/dist/types/decisions/transport.d.ts +16 -3
  136. package/dist/types/decisions/types.d.ts +43 -4
  137. package/dist/types/llm/anthropic/utils/message_inputs.d.ts +1 -0
  138. package/dist/types/llm/bedrock/cachePoints.d.ts +7 -0
  139. package/dist/types/llm/bedrock/index.d.ts +2 -1
  140. package/dist/types/llm/google/index.d.ts +1 -0
  141. package/dist/types/llm/google/utils/common.d.ts +2 -0
  142. package/dist/types/rerank/bm25.d.ts +46 -0
  143. package/dist/types/rerank/cache.d.ts +40 -0
  144. package/dist/types/rerank/core.d.ts +24 -0
  145. package/dist/types/rerank/crossEncoder.d.ts +48 -0
  146. package/dist/types/rerank/fallback.d.ts +67 -0
  147. package/dist/types/rerank/index.d.ts +1 -3
  148. package/dist/types/rerank/outcome.d.ts +144 -0
  149. package/dist/types/rerank/pin.d.ts +48 -0
  150. package/dist/types/rerank/semaphore.d.ts +9 -0
  151. package/dist/types/rerank/systemone.d.ts +51 -5
  152. package/dist/types/rerank/types.d.ts +116 -1
  153. package/dist/types/tools/local/resolveLocalExecutionTools.d.ts +6 -0
  154. package/dist/types/tools/local/toolResultCaps.d.ts +16 -0
  155. package/dist/types/types/tools.d.ts +16 -0
  156. package/package.json +26 -1
  157. package/src/agents/AgentContext.ts +33 -4
  158. package/src/decisions/breaker.ts +110 -0
  159. package/src/decisions/core.ts +23 -0
  160. package/src/decisions/dialect.ts +134 -20
  161. package/src/decisions/hook.ts +32 -0
  162. package/src/decisions/http.ts +4 -1
  163. package/src/decisions/index.ts +3 -12
  164. package/src/decisions/node.ts +671 -0
  165. package/src/decisions/probe.ts +114 -0
  166. package/src/decisions/redact.ts +222 -0
  167. package/src/decisions/structuredChat.ts +6 -8
  168. package/src/decisions/transport.ts +104 -22
  169. package/src/decisions/types.ts +46 -5
  170. package/src/llm/anthropic/utils/message_inputs.ts +16 -16
  171. package/src/llm/bedrock/cachePoints.ts +47 -0
  172. package/src/llm/bedrock/index.ts +35 -13
  173. package/src/llm/google/index.ts +5 -3
  174. package/src/llm/google/utils/common.ts +19 -5
  175. package/src/rerank/bm25.ts +190 -0
  176. package/src/rerank/cache.ts +103 -0
  177. package/src/rerank/core.ts +47 -0
  178. package/src/rerank/crossEncoder.ts +289 -0
  179. package/src/rerank/fallback.ts +625 -0
  180. package/src/rerank/index.ts +1 -3
  181. package/src/rerank/outcome.ts +767 -0
  182. package/src/rerank/pin.ts +157 -0
  183. package/src/rerank/semaphore.ts +47 -0
  184. package/src/rerank/systemone.ts +914 -88
  185. package/src/rerank/types.ts +143 -1
  186. package/src/session/AgentSession.ts +3 -1
  187. package/src/tools/local/LocalCodingTools.ts +139 -19
  188. package/src/tools/local/LocalExecutionTools.ts +21 -1
  189. package/src/tools/local/resolveLocalExecutionTools.ts +116 -11
  190. package/src/tools/local/toolResultCaps.ts +60 -0
  191. package/src/types/tools.ts +16 -0
@@ -38,8 +38,8 @@ import {
38
38
  cloneToolMessageWithContent,
39
39
  serializeStructuredValueBounded,
40
40
  } from '@/utils/toolContent';
41
- import { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';
42
41
  import { isReasoningContentBlock } from '@/messages/reasoningTypes';
42
+ import { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';
43
43
  import { Constants } from '@/common';
44
44
 
45
45
  type StandardTextBlock = Data.StandardTextBlock;
@@ -56,10 +56,14 @@ type GoogleFunctionCallBlock = MessageContentComplex & {
56
56
  };
57
57
 
58
58
  const ANTHROPIC_EMPTY_TEXT_PLACEHOLDER = '_';
59
- const CLAUDE_4_RELEASE_DATE_MODEL_PATTERN =
60
- /claude-(?:opus|sonnet|haiku)-4-\d{8}(?:[-.@]|$)/i;
61
- const CLAUDE_4_MINOR_MODEL_PATTERN =
62
- /claude-(?:opus|sonnet|haiku)-4[-.](\d+)(?:[-.@]|$)/i;
59
+ /**
60
+ * Name-first Claude ids (`claude-sonnet-4-6`, `claude-haiku-5.5`, Bedrock and
61
+ * Vertex forms included). The minor is one or two digits so an 8-digit release
62
+ * date (`claude-opus-4-20250514`) reads as major only. Number-first ids
63
+ * (`claude-3-5-sonnet`) predate 4.6 and never match.
64
+ */
65
+ const CLAUDE_FAMILY_VERSION_PATTERN =
66
+ /claude-(?:opus|sonnet|haiku|fable|mythos)-(\d+)(?:[-.](\d{1,2}))?(?!\d)/i;
63
67
 
64
68
  function _formatImage(imageUrl: string) {
65
69
  const parsed = parseBase64DataUrl({ dataUrl: imageUrl });
@@ -1047,10 +1051,7 @@ function _formatContent(message: BaseMessage) {
1047
1051
  name: correspondingToolCall.name,
1048
1052
  input: functionCallPart.functionCall.args,
1049
1053
  };
1050
- } else if (
1051
- isAIMessage(message) &&
1052
- isReasoningContentBlock(contentPart)
1053
- ) {
1054
+ } else if (isAIMessage(message) && isReasoningContentBlock(contentPart)) {
1054
1055
  // Foreign reasoning on an ASSISTANT turn (Bedrock `reasoning_content`,
1055
1056
  // Google `reasoning`, LibreChat `think`) carries provider-specific
1056
1057
  // signatures Anthropic cannot validate; drop it so a cross-provider
@@ -1217,17 +1218,16 @@ export function _convertMessagesToAnthropicPayload(
1217
1218
  } as AnthropicMessageCreateParams;
1218
1219
  }
1219
1220
 
1221
+ /** Claude 4.6 and every later release (5.x, Fable, Mythos) reject a trailing assistant prefill. */
1220
1222
  export function modelDisallowsAssistantPrefill(model?: string): boolean {
1221
- const modelId = model ?? '';
1222
- if (CLAUDE_4_RELEASE_DATE_MODEL_PATTERN.test(modelId)) {
1223
- return false;
1224
- }
1225
-
1226
- const match = CLAUDE_4_MINOR_MODEL_PATTERN.exec(modelId);
1223
+ const match = CLAUDE_FAMILY_VERSION_PATTERN.exec(model ?? '');
1227
1224
  if (!match) {
1228
1225
  return false;
1229
1226
  }
1230
- return Number(match[1]) >= 6;
1227
+ const [, majorText, minorText = '0'] = match;
1228
+ const major = Number(majorText);
1229
+ const minor = Number(minorText);
1230
+ return major > 4 || (major === 4 && minor >= 6);
1231
1231
  }
1232
1232
 
1233
1233
  function messagesHaveCacheControl(
@@ -5,6 +5,7 @@ import type {
5
5
  ConverseCommandParams,
6
6
  } from '@langchain/aws';
7
7
  import type * as Bedrock from '@aws-sdk/client-bedrock-runtime';
8
+ import { modelDisallowsAssistantPrefill } from '@/llm/anthropic/utils/message_inputs';
8
9
 
9
10
  function isConverseCachePoint(block: unknown): boolean {
10
11
  return Boolean(
@@ -84,3 +85,49 @@ export function applyCachePointsToConversePayload(fields: {
84
85
  tools.push(cacheBlock as unknown as Bedrock.Tool);
85
86
  }
86
87
  }
88
+
89
+ /**
90
+ * Drop trailing assistant turns for Claude models that reject a prefill (4.6 and
91
+ * later), mirroring `stripUnsupportedAssistantPrefill` for the Converse payload.
92
+ * A cache point that rode a stripped turn is re-anchored on the new tail when no
93
+ * surviving message carries one, so the request keeps its message caching.
94
+ */
95
+ export function stripUnsupportedConversePrefill(
96
+ messages: Bedrock.Message[],
97
+ model?: string
98
+ ): Bedrock.Message[] {
99
+ if (
100
+ !modelDisallowsAssistantPrefill(model) ||
101
+ messages.length <= 1 ||
102
+ messages[messages.length - 1]?.role !== 'assistant'
103
+ ) {
104
+ return messages;
105
+ }
106
+
107
+ const nextMessages = [...messages];
108
+ let strippedCachePoint: Bedrock.ContentBlock | undefined;
109
+ while (
110
+ nextMessages.length > 1 &&
111
+ nextMessages[nextMessages.length - 1]?.role === 'assistant'
112
+ ) {
113
+ const stripped = nextMessages.pop();
114
+ strippedCachePoint ??= stripped?.content?.find((block) =>
115
+ isConverseCachePoint(block)
116
+ );
117
+ }
118
+
119
+ const survivorsHaveCachePoint = nextMessages.some((message) =>
120
+ (message.content ?? []).some((block) => isConverseCachePoint(block))
121
+ );
122
+ if (strippedCachePoint == null || survivorsHaveCachePoint) {
123
+ return nextMessages;
124
+ }
125
+
126
+ const lastIndex = nextMessages.length - 1;
127
+ const tail = nextMessages[lastIndex];
128
+ nextMessages[lastIndex] = {
129
+ ...tail,
130
+ content: [...(tail.content ?? []), strippedCachePoint],
131
+ };
132
+ return nextMessages;
133
+ }
@@ -49,12 +49,20 @@ import {
49
49
  supportsBedrockToolCache,
50
50
  type PromptCacheTtl,
51
51
  } from '@/messages/cache';
52
- import { smoothStream, resolveStreamDelay, isSignalAborted } from '@/llm/stream/smoother';
52
+ import {
53
+ applyCachePointsToConversePayload,
54
+ stripUnsupportedConversePrefill,
55
+ } from './cachePoints';
56
+ import {
57
+ smoothStream,
58
+ resolveStreamDelay,
59
+ isSignalAborted,
60
+ } from '@/llm/stream/smoother';
61
+ import { modelDisallowsAssistantPrefill } from '@/llm/anthropic/utils/message_inputs';
53
62
  import { linkStreamLimitCanonical } from '@/llm/streamLimits';
54
- import { applyCachePointsToConversePayload } from './cachePoints';
55
- import { insertBedrockToolCachePoint } from './toolCache';
56
63
  import { isBedrockOpenAIModel } from './utils/message_inputs';
57
64
  import { neutralizeHarmonyToolConfig } from './utils/harmony';
65
+ import { insertBedrockToolCachePoint } from './toolCache';
58
66
 
59
67
  /**
60
68
  * A `200 OK` ConverseStream whose event stream closes before a single event: no
@@ -262,7 +270,10 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
262
270
  options: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions,
263
271
  runManager?: CallbackManagerForLLMRun
264
272
  ): Promise<ChatResult> {
265
- if (isBedrockOpenAIModel(this.model)) {
273
+ if (
274
+ isBedrockOpenAIModel(this.model) ||
275
+ modelDisallowsAssistantPrefill(this.model)
276
+ ) {
266
277
  return this.generateWithLocalConverter(messages, options);
267
278
  }
268
279
  const originalModel = this.model;
@@ -283,15 +294,18 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
283
294
  /**
284
295
  * Non-streaming Converse through this package's converter, as the stream already uses.
285
296
  * The parent's converter replays reasoning and sends harmony control tokens as written,
286
- * both of which OpenAI models on Bedrock fail on.
297
+ * both of which OpenAI models on Bedrock fail on, and it cannot strip a trailing
298
+ * assistant prefill that Claude 4.6 and later reject.
287
299
  */
288
300
  private async generateWithLocalConverter(
289
301
  messages: BaseMessage[],
290
302
  options: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions
291
303
  ): Promise<ChatResult> {
292
- const { converseMessages, converseSystem } = convertToConverseMessages(
293
- messages,
294
- { model: this.model }
304
+ const { converseMessages: convertedMessages, converseSystem } =
305
+ convertToConverseMessages(messages, { model: this.model });
306
+ const converseMessages = stripUnsupportedConversePrefill(
307
+ convertedMessages,
308
+ this.model
295
309
  );
296
310
  const params = this.invocationParams(options);
297
311
  const modelId = this.getModelId();
@@ -341,9 +355,11 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
341
355
  options: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions,
342
356
  runManager?: CallbackManagerForLLMRun
343
357
  ): AsyncGenerator<ChatGenerationChunk> {
344
- const { converseMessages, converseSystem } = convertToConverseMessages(
345
- messages,
346
- { model: this.model }
358
+ const { converseMessages: convertedMessages, converseSystem } =
359
+ convertToConverseMessages(messages, { model: this.model });
360
+ const converseMessages = stripUnsupportedConversePrefill(
361
+ convertedMessages,
362
+ this.model
347
363
  );
348
364
  const params = this.invocationParams(options);
349
365
 
@@ -541,7 +557,10 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
541
557
  yield {
542
558
  text: '',
543
559
  smooth: false,
544
- emit: (): BedrockEmittedChunk => ({ chunk: metadataChunk, callbackToken: '' }),
560
+ emit: (): BedrockEmittedChunk => ({
561
+ chunk: metadataChunk,
562
+ callbackToken: '',
563
+ }),
545
564
  };
546
565
  } else if (event.contentBlockStop != null) {
547
566
  const stopIdx = event.contentBlockStop.contentBlockIndex;
@@ -571,7 +590,10 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
571
590
  yield {
572
591
  text: '',
573
592
  smooth: false,
574
- emit: (): BedrockEmittedChunk => ({ chunk: eventChunk, callbackToken: '' }),
593
+ emit: (): BedrockEmittedChunk => ({
594
+ chunk: eventChunk,
595
+ callbackToken: '',
596
+ }),
575
597
  };
576
598
  }
577
599
  }
@@ -16,14 +16,15 @@ import type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager
16
16
  import type { BaseMessage, UsageMetadata } from '@langchain/core/messages';
17
17
  import type { GeminiApiUsageMetadata, InputTokenDetails } from './types';
18
18
  import type { GoogleClientOptions, GoogleThinkingConfig } from '@/types';
19
- import { smoothGenerationChunks } from '@/llm/stream/chunkAdapters';
20
- import { resolveStreamDelay } from '@/llm/stream/smoother';
21
19
  import {
22
20
  convertResponseContentToChatGenerationChunk,
23
21
  convertBaseMessagesToContent,
22
+ isGemini3PlusModel,
24
23
  dropUnsupportedModelTurnPrefill,
25
24
  mapGenerateContentResultToChatResult,
26
25
  } from './utils/common';
26
+ import { smoothGenerationChunks } from '@/llm/stream/chunkAdapters';
27
+ import { resolveStreamDelay } from '@/llm/stream/smoother';
27
28
 
28
29
  type GoogleToolConfigWithServerSideInvocations = ToolConfig & {
29
30
  includeServerSideToolInvocations?: boolean;
@@ -45,13 +46,14 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
45
46
  /**
46
47
  * Override to add gemini-3 model support for multimodal and function calling thought signatures
47
48
  */
49
+ /** Gemini 3 and later accept image, audio, video and PDF input. */
48
50
  get _isMultimodalModel(): boolean {
49
51
  return (
50
52
  this.model.startsWith('gemini-1.5') ||
51
53
  this.model.startsWith('gemini-2') ||
52
54
  (this.model.startsWith('gemma-3-') &&
53
55
  !this.model.startsWith('gemma-3-1b')) ||
54
- this.model.startsWith('gemini-3')
56
+ isGemini3PlusModel(this.model)
55
57
  );
56
58
  }
57
59
 
@@ -104,6 +104,15 @@ function createGoogleFunctionResponsePart({
104
104
  */
105
105
  export const iife = <T>(fn: () => T): T => fn();
106
106
 
107
+ /** `gemini-3`, `gemini-3.8-flash`, `gemini-4-argon`, and any later major version. */
108
+ const GEMINI_3_PLUS_PATTERN = /^gemini-(?:[3-9]|[1-9]\d+)(?:[.-]|$)/;
109
+
110
+ /** Whether `model` (optionally `models/` or provider prefixed) is Gemini 3 or later. */
111
+ export function isGemini3PlusModel(model?: string): boolean {
112
+ const modelId = model?.toLowerCase().split('/').pop() ?? '';
113
+ return GEMINI_3_PLUS_PATTERN.test(modelId);
114
+ }
115
+
107
116
  export function getMessageAuthor(message: BaseMessage): string {
108
117
  const type = message._getType();
109
118
  if (ChatMessage.isInstance(message)) {
@@ -540,7 +549,7 @@ export function convertMessageContentToParts(
540
549
  return signature;
541
550
  }
542
551
  }
543
- if (model?.includes('gemini-3') === true) {
552
+ if (isGemini3PlusModel(model)) {
544
553
  return DUMMY_SIGNATURE;
545
554
  }
546
555
  return '';
@@ -681,12 +690,17 @@ const NO_PREFILL_FLASH_MIN_VERSION = { major: 3, minor: 6 } as const;
681
690
  const GEMINI_FLASH_VERSION_PATTERN = /^gemini-(\d+)(?:\.(\d+))?-flash(?:$|-)/;
682
691
 
683
692
  /**
684
- * Models that reject prefill despite predating
685
- * {@link NO_PREFILL_FLASH_MIN_VERSION}. Gemini 3.5 Flash-Lite enforces the
693
+ * Models that reject prefill outside the Flash version cutoff
694
+ * ({@link NO_PREFILL_FLASH_MIN_VERSION}). Gemini 3.5 Flash-Lite enforces the
686
695
  * restriction while its sibling Gemini 3.5 Flash still accepts a trailing model
687
- * turn, so the 3.5 generation cannot be expressed as a version cutoff.
696
+ * turn, so the 3.5 generation cannot be expressed as a version cutoff. Gemini 4
697
+ * Argon is not a Flash model; its histories cannot end in a `model` turn.
698
+ * @see https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/guides/gemini-4-argon
688
699
  */
689
- const NO_PREFILL_GEMINI_MODELS = ['gemini-3.5-flash-lite'] as const;
700
+ const NO_PREFILL_GEMINI_MODELS = [
701
+ 'gemini-3.5-flash-lite',
702
+ 'gemini-4-argon',
703
+ ] as const;
690
704
 
691
705
  export function rejectsModelTurnPrefill(model?: string): boolean {
692
706
  if (model == null || model === '') {
@@ -0,0 +1,190 @@
1
+ import type { RankRequest, RerankOutcome, OutcomeReranker } from './types';
2
+ import {
3
+ isAborted,
4
+ stepOutcome,
5
+ documentCount,
6
+ emptyRerankUsage,
7
+ rankRequestProblem,
8
+ } from './outcome';
9
+ import { DecisionError } from '../decisions/types';
10
+
11
+ const STOP_WORDS: ReadonlySet<string> = new Set(
12
+ 'which what where who how does that this the and for with from into over under of to in on at by an a is are be been do did as it its their they them or not no via when after before while than then also each all any some one two'.split(
13
+ ' '
14
+ )
15
+ );
16
+
17
+ /**
18
+ * Codegraph's measured BM25 tokenizer for code and its prose: camelCase,
19
+ * snake_case, kebab-case, dotted names, and paths split into words, which
20
+ * are lower-cased; words of two letters or fewer and English stop words are
21
+ * dropped. It keeps only ASCII letters and digits, so CJK text yields no
22
+ * words and accented words split into fragments; pass a `tokenize` of your
23
+ * own for other scripts.
24
+ */
25
+ export function tokenizeCode(text: string): string[] {
26
+ return text
27
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
28
+ .replace(/[_\-./`]/g, ' ')
29
+ .toLowerCase()
30
+ .split(/[^a-z0-9]+/)
31
+ .filter((word) => word.length > 2 && !STOP_WORDS.has(word));
32
+ }
33
+
34
+ export type Tokenize = (text: string) => string[];
35
+
36
+ export interface CorpusStats {
37
+ /** Okapi idf, +1 smoothed so it is never negative. */
38
+ idf: Map<string, number>;
39
+ /** Mean document length in tokens. */
40
+ avgdl: number;
41
+ /** Documents counted. */
42
+ n: number;
43
+ }
44
+
45
+ /** Statistics over the whole corpus a shortlist is drawn from, not over the shortlist. */
46
+ export function corpusStats(
47
+ documents: Iterable<string>,
48
+ options: { tokenize?: Tokenize } = {}
49
+ ): CorpusStats {
50
+ const tokenize = options.tokenize ?? tokenizeCode;
51
+ const frequency = new Map<string, number>();
52
+ let total = 0;
53
+ let n = 0;
54
+ for (const document of documents) {
55
+ const tokens = tokenize(document);
56
+ total += tokens.length;
57
+ n += 1;
58
+ for (const term of new Set(tokens)) {
59
+ frequency.set(term, (frequency.get(term) ?? 0) + 1);
60
+ }
61
+ }
62
+ const idf = new Map<string, number>();
63
+ for (const [term, seen] of frequency) {
64
+ idf.set(term, Math.log(1 + (n - seen + 0.5) / (seen + 0.5)));
65
+ }
66
+ return { idf, avgdl: n > 0 ? total / n : 0, n };
67
+ }
68
+
69
+ export interface Bm25RerankerOptions {
70
+ /** Corpus idf from `corpusStats`, or a function of the term. */
71
+ idf: ReadonlyMap<string, number> | ((term: string) => number);
72
+ /** The corpus's mean document length in tokens. */
73
+ avgdl: number;
74
+ /** Defaults to 1.2. */
75
+ k1?: number;
76
+ /** Defaults to 0.75. */
77
+ b?: number;
78
+ /** Must match the tokenizer the statistics were built with. Defaults to `tokenizeCode`. */
79
+ tokenize?: Tokenize;
80
+ }
81
+
82
+ /** Any `ReadonlyMap`, including a wrapper or a `Map` from another realm, where `instanceof Map` is false. */
83
+ function isIdfMap(value: unknown): value is ReadonlyMap<string, number> {
84
+ return (
85
+ typeof value === 'object' &&
86
+ value !== null &&
87
+ 'get' in value &&
88
+ 'values' in value &&
89
+ typeof value.get === 'function' &&
90
+ typeof value.values === 'function'
91
+ );
92
+ }
93
+
94
+ /**
95
+ * In-process Okapi BM25. Corpus statistics are required: idf over a 50-document
96
+ * shortlist alone is close to degenerate. A term the corpus never saw counts
97
+ * as rare as its rarest term. Never throws once built, and costs nothing.
98
+ * Scoring is synchronous: an already-aborted `signal` is `aborted` before any
99
+ * work, and neither an abort nor `deadlineMs` stops a pass once it starts. A
100
+ * query the tokenizer leaves no terms in (only stop words, or a script it
101
+ * does not read) is `unsupported`, not an all-zero ranking, so a chain moves
102
+ * on.
103
+ */
104
+ export function createBm25Reranker(
105
+ options: Bm25RerankerOptions
106
+ ): OutcomeReranker {
107
+ const k1 = options.k1 ?? 1.2;
108
+ const b = options.b ?? 0.75;
109
+ const tokenize = options.tokenize ?? tokenizeCode;
110
+ const { idf, avgdl } = options;
111
+ let idfOf: ((term: string) => number) | undefined;
112
+ if (isIdfMap(idf)) {
113
+ let rarest = 0;
114
+ for (const value of idf.values()) {
115
+ rarest = Math.max(rarest, value);
116
+ }
117
+ idfOf = (term: string): number => idf.get(term) ?? rarest;
118
+ } else if (typeof idf === 'function') {
119
+ idfOf = idf;
120
+ }
121
+ if (
122
+ idfOf === undefined ||
123
+ typeof avgdl !== 'number' ||
124
+ !Number.isFinite(avgdl) ||
125
+ avgdl <= 0 ||
126
+ !Number.isFinite(k1) ||
127
+ k1 < 0 ||
128
+ !Number.isFinite(b) ||
129
+ b < 0 ||
130
+ b > 1 ||
131
+ typeof tokenize !== 'function'
132
+ ) {
133
+ throw new DecisionError(
134
+ 'bad_request',
135
+ 'bm25 reranker requires corpus statistics (corpusStats)',
136
+ { provider: 'bm25' }
137
+ );
138
+ }
139
+ const termIdf = idfOf;
140
+ const kind = 'bm25' as const;
141
+ const model = 'okapi';
142
+
143
+ return {
144
+ id: 'bm25:okapi',
145
+ kind,
146
+ model,
147
+ async rank(request: RankRequest): Promise<RerankOutcome> {
148
+ const startedAt = performance.now();
149
+ const documents = documentCount(request);
150
+ const base = { kind, documents, startedAt, model };
151
+ const problem = rankRequestProblem(request);
152
+ if (problem !== undefined) {
153
+ return stepOutcome({ ...base, reason: problem, called: false });
154
+ }
155
+ // Scoring runs to the end once started, so a cancelled caller is honored only before it.
156
+ if (isAborted(request.signal)) {
157
+ return stepOutcome({ ...base, reason: 'aborted', called: false });
158
+ }
159
+ try {
160
+ const terms = tokenize(request.query);
161
+ if (terms.length === 0) {
162
+ // Every score would be zero: identity order dressed as a ranking.
163
+ return stepOutcome({ ...base, reason: 'unsupported', called: false });
164
+ }
165
+ const scores = request.documents.map((document) => {
166
+ const tokens = tokenize(document);
167
+ const frequency = new Map<string, number>();
168
+ for (const token of tokens) {
169
+ frequency.set(token, (frequency.get(token) ?? 0) + 1);
170
+ }
171
+ const norm = k1 * (1 - b + (b * tokens.length) / avgdl);
172
+ let score = 0;
173
+ for (const term of terms) {
174
+ const seen = frequency.get(term);
175
+ if (seen !== undefined) {
176
+ score += (termIdf(term) * (seen * (k1 + 1))) / (seen + norm);
177
+ }
178
+ }
179
+ return Number.isFinite(score) ? score : null;
180
+ });
181
+ if (scores.includes(null)) {
182
+ return stepOutcome({ ...base, reason: 'error' });
183
+ }
184
+ return stepOutcome({ ...base, scores, usage: emptyRerankUsage() });
185
+ } catch {
186
+ return stepOutcome({ ...base, reason: 'error' });
187
+ }
188
+ },
189
+ };
190
+ }
@@ -0,0 +1,103 @@
1
+ import { DecisionError } from '../decisions/types';
2
+
3
+ /** What a cached score is keyed on: the document text, not an identity that survives edits. */
4
+ export interface RerankCacheKey {
5
+ query: string;
6
+ document: string;
7
+ /** The model that produced the score; only an echo of the configured model is cached. */
8
+ model: string;
9
+ /** Identifies the rubric and instructions the score answers. */
10
+ rubric: string;
11
+ /**
12
+ * The serialized decision state the score was measured in when a custom
13
+ * `state` built it; empty for the default `{ query, document }`.
14
+ */
15
+ state: string;
16
+ }
17
+
18
+ /**
19
+ * Per-document scores; a host can supply its own (for example, hashed keys or
20
+ * a shared store). Both are synchronous: a throw from either is a miss, `set`
21
+ * is not awaited, and a promise either returns is ignored (its rejection
22
+ * included), so an asynchronous store must be fronted by a synchronous one.
23
+ */
24
+ export interface RerankScoreCache {
25
+ get(key: RerankCacheKey): number | undefined;
26
+ set(key: RerankCacheKey, score: number): void;
27
+ }
28
+
29
+ export interface MemoryScoreCache extends RerankScoreCache {
30
+ readonly size: number;
31
+ clear(): void;
32
+ }
33
+
34
+ export interface ScoreCacheOptions {
35
+ /** Entries kept, a positive integer, least recently used evicted first. Defaults to 20,000. */
36
+ max?: number;
37
+ /** A positive finite lifetime. Defaults to one day. */
38
+ ttlMs?: number;
39
+ now?: () => number;
40
+ }
41
+
42
+ /**
43
+ * A bounded in-memory LRU whose entries expire after `ttlMs`; keys hold the
44
+ * full document text. Throws on a `max` or `ttlMs` that would unbound it.
45
+ */
46
+ export function createScoreCache(
47
+ options: ScoreCacheOptions = {}
48
+ ): MemoryScoreCache {
49
+ const max = options.max ?? 20_000;
50
+ const ttlMs = options.ttlMs ?? 86_400_000;
51
+ if (
52
+ !Number.isSafeInteger(max) ||
53
+ max < 1 ||
54
+ typeof ttlMs !== 'number' ||
55
+ !Number.isFinite(ttlMs) ||
56
+ ttlMs <= 0
57
+ ) {
58
+ throw new DecisionError(
59
+ 'bad_request',
60
+ 'invalid score cache configuration',
61
+ {
62
+ provider: 'score-cache',
63
+ }
64
+ );
65
+ }
66
+ const now = options.now ?? Date.now;
67
+ const entries = new Map<string, { score: number; at: number }>();
68
+ const keyOf = (key: RerankCacheKey): string =>
69
+ JSON.stringify([key.query, key.document, key.model, key.rubric, key.state]);
70
+ return {
71
+ get(key: RerankCacheKey): number | undefined {
72
+ const id = keyOf(key);
73
+ const entry = entries.get(id);
74
+ if (!entry) {
75
+ return undefined;
76
+ }
77
+ entries.delete(id);
78
+ if (now() - entry.at > ttlMs) {
79
+ return undefined;
80
+ }
81
+ entries.set(id, entry);
82
+ return entry.score;
83
+ },
84
+ set(key: RerankCacheKey, score: number): void {
85
+ const id = keyOf(key);
86
+ entries.delete(id);
87
+ entries.set(id, { score, at: now() });
88
+ while (entries.size > max) {
89
+ const oldest = entries.keys().next();
90
+ if (oldest.done === true) {
91
+ break;
92
+ }
93
+ entries.delete(oldest.value);
94
+ }
95
+ },
96
+ get size(): number {
97
+ return entries.size;
98
+ },
99
+ clear(): void {
100
+ entries.clear();
101
+ },
102
+ };
103
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Light `@librechat/agents/rerank` entry: the index-based reranking contract,
3
+ * the never-throwing outcome layer, and the System One, cross-encoder, BM25,
4
+ * and fallback rerankers, with no LangChain or other third-party runtime
5
+ * import. The web-search adapter stays on the root entry because it extends
6
+ * the search tool's reranker.
7
+ */
8
+ export type * from './types';
9
+ export { createSystemOneReranker } from './systemone';
10
+ export type {
11
+ SystemOnePin,
12
+ SystemOneMode,
13
+ SystemOneReranker,
14
+ SystemOneRerankerOptions,
15
+ } from './systemone';
16
+ export { createCrossEncoderReranker } from './crossEncoder';
17
+ export type { CrossEncoderRerankerOptions } from './crossEncoder';
18
+ export { createBm25Reranker, corpusStats, tokenizeCode } from './bm25';
19
+ export type { Bm25RerankerOptions, CorpusStats, Tokenize } from './bm25';
20
+ export { noneReranker, withFallback, STEP_GRACE_MS } from './fallback';
21
+ export type {
22
+ FallbackStep,
23
+ FallbackOptions,
24
+ FallbackReranker,
25
+ } from './fallback';
26
+ export { probePin, PIN_SENTINEL_MODEL } from './pin';
27
+ export type { PinProbe, PinProbeOptions } from './pin';
28
+ export { createSemaphore } from './semaphore';
29
+ export type { RerankSemaphore } from './semaphore';
30
+ export { createScoreCache } from './cache';
31
+ export type {
32
+ RerankCacheKey,
33
+ RerankScoreCache,
34
+ MemoryScoreCache,
35
+ ScoreCacheOptions,
36
+ } from './cache';
37
+ export {
38
+ rerankCost,
39
+ rankedEntries,
40
+ estimatedUsage,
41
+ identityOutcome,
42
+ emptyRerankUsage,
43
+ toOutcomeReranker,
44
+ isRerankPermutation,
45
+ ESTIMATED_TOKENS_PER_DOCUMENT,
46
+ } from './outcome';
47
+ export type { RerankCost, RerankPrice, RerankPrices } from './outcome';