@librechat/agents 4.0.4 → 4.0.6

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 (47) hide show
  1. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +6 -6
  2. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  3. package/dist/cjs/llm/bedrock/index.cjs +115 -76
  4. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  5. package/dist/cjs/llm/bedrock/utils/harmony.cjs +147 -0
  6. package/dist/cjs/llm/bedrock/utils/harmony.cjs.map +1 -0
  7. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +13 -6
  8. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
  9. package/dist/cjs/llm/bedrock/utils/message_outputs.cjs +68 -0
  10. package/dist/cjs/llm/bedrock/utils/message_outputs.cjs.map +1 -1
  11. package/dist/cjs/llm/google/index.cjs +1 -1
  12. package/dist/cjs/llm/google/index.cjs.map +1 -1
  13. package/dist/cjs/llm/google/utils/common.cjs +8 -2
  14. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  15. package/dist/cjs/llm/invoke.cjs +13 -3
  16. package/dist/cjs/llm/invoke.cjs.map +1 -1
  17. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +6 -6
  18. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  19. package/dist/esm/llm/bedrock/index.mjs +118 -80
  20. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  21. package/dist/esm/llm/bedrock/utils/harmony.mjs +146 -0
  22. package/dist/esm/llm/bedrock/utils/harmony.mjs.map +1 -0
  23. package/dist/esm/llm/bedrock/utils/message_inputs.mjs +13 -7
  24. package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
  25. package/dist/esm/llm/bedrock/utils/message_outputs.mjs +68 -2
  26. package/dist/esm/llm/bedrock/utils/message_outputs.mjs.map +1 -1
  27. package/dist/esm/llm/google/index.mjs +2 -2
  28. package/dist/esm/llm/google/index.mjs.map +1 -1
  29. package/dist/esm/llm/google/utils/common.mjs +8 -3
  30. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  31. package/dist/esm/llm/invoke.mjs +13 -3
  32. package/dist/esm/llm/invoke.mjs.map +1 -1
  33. package/dist/types/llm/anthropic/utils/message_inputs.d.ts +1 -0
  34. package/dist/types/llm/bedrock/index.d.ts +14 -1
  35. package/dist/types/llm/bedrock/utils/harmony.d.ts +34 -0
  36. package/dist/types/llm/bedrock/utils/message_inputs.d.ts +10 -1
  37. package/dist/types/llm/google/index.d.ts +1 -0
  38. package/dist/types/llm/google/utils/common.d.ts +2 -0
  39. package/dist/types/llm/invoke.d.ts +7 -0
  40. package/package.json +1 -1
  41. package/src/llm/anthropic/utils/message_inputs.ts +16 -16
  42. package/src/llm/bedrock/index.ts +83 -5
  43. package/src/llm/bedrock/utils/harmony.ts +235 -0
  44. package/src/llm/bedrock/utils/message_inputs.ts +34 -11
  45. package/src/llm/google/index.ts +5 -3
  46. package/src/llm/google/utils/common.ts +19 -5
  47. package/src/llm/invoke.ts +32 -10
@@ -25,6 +25,7 @@ import { ChatBedrockConverse } from '@langchain/aws';
25
25
  import { AIMessageChunk } from '@langchain/core/messages';
26
26
  import { ChatGenerationChunk, ChatResult } from '@langchain/core/outputs';
27
27
  import {
28
+ ConverseCommand,
28
29
  ConverseStreamCommand,
29
30
  type ConverseStreamOutput,
30
31
  type GuardrailConfiguration,
@@ -38,6 +39,7 @@ import type { ContentBlockDeltaEvent } from './types';
38
39
  import {
39
40
  convertToConverseMessages,
40
41
  createConverseToolUseStopChunk,
42
+ convertConverseMessageToLangChainMessage,
41
43
  handleConverseStreamContentBlockStart,
42
44
  handleConverseStreamContentBlockDelta,
43
45
  handleConverseStreamMetadata,
@@ -51,6 +53,17 @@ import { smoothStream, resolveStreamDelay, isSignalAborted } from '@/llm/stream/
51
53
  import { linkStreamLimitCanonical } from '@/llm/streamLimits';
52
54
  import { applyCachePointsToConversePayload } from './cachePoints';
53
55
  import { insertBedrockToolCachePoint } from './toolCache';
56
+ import { isBedrockOpenAIModel } from './utils/message_inputs';
57
+ import { neutralizeHarmonyToolConfig } from './utils/harmony';
58
+
59
+ /**
60
+ * A `200 OK` ConverseStream whose event stream closes before a single event: no
61
+ * `messageStart`, no `messageStop`, no exception event. OpenAI models do this for a
62
+ * request their chat template cannot render (see `./utils/harmony`). Surfaced as an error
63
+ * so the turn fails with this explanation instead of resolving to no message at all.
64
+ */
65
+ export const BEDROCK_EMPTY_STREAM_MESSAGE =
66
+ 'Amazon Bedrock ended the response stream without sending any events. The model could not process this request; it may contain text the model rejects.';
54
67
 
55
68
  /**
56
69
  * Service tier type for Bedrock invocations.
@@ -200,10 +213,13 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
200
213
 
201
214
  /**
202
215
  * Get the model ID to use for API calls.
203
- * Returns applicationInferenceProfile if set, otherwise returns this.model.
216
+ * Returns applicationInferenceProfile if set and non-empty, otherwise returns this.model.
204
217
  */
205
218
  protected getModelId(): string {
206
- return this.applicationInferenceProfile ?? this.model;
219
+ return this.applicationInferenceProfile != null &&
220
+ this.applicationInferenceProfile !== ''
221
+ ? this.applicationInferenceProfile
222
+ : this.model;
207
223
  }
208
224
 
209
225
  /**
@@ -215,14 +231,17 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
215
231
  serviceTier?: { type: ServiceTierType };
216
232
  } {
217
233
  const baseParams = super.invocationParams(options);
234
+ const baseToolConfig = isBedrockOpenAIModel(this.model)
235
+ ? neutralizeHarmonyToolConfig(baseParams.toolConfig)
236
+ : baseParams.toolConfig;
218
237
  const toolConfig =
219
238
  this.promptCache === true && supportsBedrockToolCache(this.cacheModelId)
220
239
  ? insertBedrockToolCachePoint(
221
- baseParams.toolConfig,
240
+ baseToolConfig,
222
241
  true,
223
242
  resolveBedrockPromptCacheTtl(this.promptCacheTtl, this.cacheModelId)
224
243
  )
225
- : baseParams.toolConfig;
244
+ : baseToolConfig;
226
245
 
227
246
  /** Service tier from options or fall back to class-level setting */
228
247
  const serviceTierType = options?.serviceTier ?? this.serviceTier;
@@ -243,6 +262,9 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
243
262
  options: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions,
244
263
  runManager?: CallbackManagerForLLMRun
245
264
  ): Promise<ChatResult> {
265
+ if (isBedrockOpenAIModel(this.model)) {
266
+ return this.generateWithLocalConverter(messages, options);
267
+ }
246
268
  const originalModel = this.model;
247
269
  if (
248
270
  this.applicationInferenceProfile != null &&
@@ -258,6 +280,55 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
258
280
  }
259
281
  }
260
282
 
283
+ /**
284
+ * Non-streaming Converse through this package's converter, as the stream already uses.
285
+ * The parent's converter replays reasoning and sends harmony control tokens as written,
286
+ * both of which OpenAI models on Bedrock fail on.
287
+ */
288
+ private async generateWithLocalConverter(
289
+ messages: BaseMessage[],
290
+ options: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions
291
+ ): Promise<ChatResult> {
292
+ const { converseMessages, converseSystem } = convertToConverseMessages(
293
+ messages,
294
+ { model: this.model }
295
+ );
296
+ const params = this.invocationParams(options);
297
+ const modelId = this.getModelId();
298
+ applyCachePointsToConversePayload({
299
+ cacheControl: options.cache_control,
300
+ system: converseSystem,
301
+ messages: converseMessages,
302
+ params,
303
+ modelId,
304
+ });
305
+ const { output, ...responseMetadata } = await this.client.send(
306
+ new ConverseCommand({
307
+ modelId,
308
+ messages: converseMessages,
309
+ ...(converseSystem.length > 0 ? { system: converseSystem } : {}),
310
+ requestMetadata: options.requestMetadata,
311
+ ...(params as Record<string, unknown>),
312
+ }),
313
+ { abortSignal: options.signal }
314
+ );
315
+ if (output?.message == null) {
316
+ throw new Error('No message found in Bedrock response.');
317
+ }
318
+ const message = convertConverseMessageToLangChainMessage(
319
+ output.message,
320
+ responseMetadata
321
+ );
322
+ return {
323
+ generations: [
324
+ {
325
+ text: typeof message.content === 'string' ? message.content : '',
326
+ message,
327
+ },
328
+ ],
329
+ };
330
+ }
331
+
261
332
  /**
262
333
  * Own the stream end-to-end so we have direct access to every
263
334
  * `contentBlockDelta.contentBlockIndex` from the AWS SDK.
@@ -313,8 +384,10 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
313
384
  const stream: AsyncIterable<ConverseStreamOutput> | undefined =
314
385
  response.stream;
315
386
  if (!stream) {
316
- return;
387
+ throw new Error(BEDROCK_EMPTY_STREAM_MESSAGE);
317
388
  }
389
+ const isStreamAborted = (): boolean =>
390
+ streamAbortController.signal.aborted;
318
391
 
319
392
  const seenBlockIndices = new Set<number>();
320
393
  const toolUseBlockIndices = new Set<number>();
@@ -387,7 +460,9 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
387
460
  const source = (async function* (): AsyncGenerator<
388
461
  SmoothItem<BedrockEmittedChunk>
389
462
  > {
463
+ let sawEvent = false;
390
464
  for await (const event of stream) {
465
+ sawEvent = true;
391
466
  if (event.contentBlockStart != null) {
392
467
  const startChunk = handleConverseStreamContentBlockStart(
393
468
  event.contentBlockStart
@@ -500,6 +575,9 @@ export class CustomChatBedrockConverse extends ChatBedrockConverse {
500
575
  };
501
576
  }
502
577
  }
578
+ if (!sawEvent && !isStreamAborted()) {
579
+ throw new Error(BEDROCK_EMPTY_STREAM_MESSAGE);
580
+ }
503
581
  })();
504
582
 
505
583
  const smoothed = smoothStream({
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Plain-text OpenAI harmony control tokens in Bedrock requests to OpenAI models.
3
+ *
4
+ * OpenAI models on Bedrock render the conversation into the harmony chat format, and a
5
+ * literal header such as `<|channel|>analysis` inside message text is not treated as text:
6
+ * Bedrock answers `200 OK` with an event stream that closes without a single event (no
7
+ * `messageStart`, no `messageStop`, no exception). It is deterministic for the request, so
8
+ * every later turn that still carries the text fails the same way. Pasted transcripts,
9
+ * attached text files, and fetched pages that document the format all carry such headers.
10
+ *
11
+ * The ASCII bars of each harmony special token (and only those, so other `<|name|>` text is
12
+ * sent as written) are swapped for fullwidth bars (`<|channel|>`): the model
13
+ * still reads the token, but nothing renders it as a control token. Zero-width characters
14
+ * and spaces between `<`, `|` and the name do not help (verified live), so they are
15
+ * tolerated inside the match and kept.
16
+ */
17
+ import type { ConverseStreamCommandInput } from '@aws-sdk/client-bedrock-runtime';
18
+ import type {
19
+ BedrockMessage,
20
+ BedrockContentBlock,
21
+ BedrockSystemContentBlock,
22
+ } from '../types';
23
+
24
+ /** The JSON document type Converse uses for `toolUse.input` and `toolResult` JSON. */
25
+ type DocumentType = Exclude<
26
+ NonNullable<BedrockContentBlock['toolUse']>['input'],
27
+ undefined
28
+ >;
29
+
30
+ const GAP = '[\\s\\u200B-\\u200D\\u2060\\uFEFF]*';
31
+ /** The special tokens of OpenAI's harmony (`o200k_harmony`) encoding. */
32
+ const HARMONY_TOKEN_NAMES =
33
+ 'startoftext|endoftext|endofprompt|start|end|message|channel|constrain|return|call|reserved_\\d+';
34
+ const HARMONY_CONTROL_TOKEN = new RegExp(
35
+ `<${GAP}\\|${GAP}(?:${HARMONY_TOKEN_NAMES})${GAP}\\|${GAP}>`,
36
+ 'g'
37
+ );
38
+ const ASCII_BAR = /\|/g;
39
+ const FULLWIDTH_BAR = '|';
40
+
41
+ type ToolResultContentBlock = NonNullable<
42
+ NonNullable<BedrockContentBlock['toolResult']>['content']
43
+ >[number];
44
+
45
+ /** The text with every harmony control token rendered inert; the same string when none. */
46
+ export function neutralizeHarmonyControlTokens(text: string): string {
47
+ if (!text.includes('|')) {
48
+ return text;
49
+ }
50
+ return text.replace(HARMONY_CONTROL_TOKEN, (token) =>
51
+ token.replace(ASCII_BAR, FULLWIDTH_BAR)
52
+ );
53
+ }
54
+
55
+ /**
56
+ * A JSON document with `rewrite` applied to its string values, given the key each one sits
57
+ * under (an array item inherits its array's key); the same reference when nothing changed.
58
+ * Keys are never rewritten: they are structure (argument and property names), and rewriting
59
+ * them could merge two keys or rename an argument the tool expects.
60
+ */
61
+ function rewriteDocument(
62
+ value: DocumentType,
63
+ rewrite: (text: string, key: string | undefined) => string,
64
+ key?: string
65
+ ): DocumentType {
66
+ if (typeof value === 'string') {
67
+ return rewrite(value, key);
68
+ }
69
+ if (Array.isArray(value)) {
70
+ let next: DocumentType[] | undefined;
71
+ for (let i = 0; i < value.length; i++) {
72
+ const item = rewriteDocument(value[i], rewrite, key);
73
+ if (item !== value[i]) {
74
+ next ??= value.slice();
75
+ next[i] = item;
76
+ }
77
+ }
78
+ return next ?? value;
79
+ }
80
+ if (value == null || typeof value !== 'object') {
81
+ return value;
82
+ }
83
+ let next: Record<string, DocumentType> | undefined;
84
+ for (const entryKey of Object.keys(value)) {
85
+ const entry = value[entryKey];
86
+ const item = rewriteDocument(entry, rewrite, entryKey);
87
+ if (item !== entry) {
88
+ next ??= { ...value };
89
+ next[entryKey] = item;
90
+ }
91
+ }
92
+ return next ?? value;
93
+ }
94
+
95
+ /** Tool inputs and results replayed as history: every string value is free text. */
96
+ function neutralizeDocument(value: DocumentType): DocumentType {
97
+ return rewriteDocument(value, neutralizeHarmonyControlTokens);
98
+ }
99
+
100
+ /** Schema annotations that carry prose and take no part in validation. */
101
+ const SCHEMA_TEXT_KEYS = new Set(['description', 'title', '$comment']);
102
+
103
+ /**
104
+ * A tool's input schema is a contract the model's arguments must satisfy, so only its prose
105
+ * is neutralized. Names, `enum`/`const` values, defaults and patterns are sent as written:
106
+ * rewriting them would have the model produce values the bound tool does not accept.
107
+ */
108
+ function neutralizeSchema(value: DocumentType): DocumentType {
109
+ return rewriteDocument(value, (text, key) =>
110
+ key != null && SCHEMA_TEXT_KEYS.has(key)
111
+ ? neutralizeHarmonyControlTokens(text)
112
+ : text
113
+ );
114
+ }
115
+
116
+ function neutralizeToolResultBlock(
117
+ block: ToolResultContentBlock
118
+ ): ToolResultContentBlock {
119
+ if (typeof block.text === 'string') {
120
+ const text = neutralizeHarmonyControlTokens(block.text);
121
+ return text === block.text ? block : { ...block, text };
122
+ }
123
+ if (block.json !== undefined) {
124
+ const json = neutralizeDocument(block.json);
125
+ return json === block.json ? block : { ...block, json };
126
+ }
127
+ return block;
128
+ }
129
+
130
+ /** Maps each item, returning the same array when no item changed. */
131
+ function mapChanged<T>(items: T[], map: (item: T) => T): T[] {
132
+ let next: T[] | undefined;
133
+ for (let i = 0; i < items.length; i++) {
134
+ const item = map(items[i]);
135
+ if (item !== items[i]) {
136
+ next ??= items.slice();
137
+ next[i] = item;
138
+ }
139
+ }
140
+ return next ?? items;
141
+ }
142
+
143
+ function neutralizeContentBlock(
144
+ block: BedrockContentBlock
145
+ ): BedrockContentBlock {
146
+ if (typeof block.text === 'string') {
147
+ const text = neutralizeHarmonyControlTokens(block.text);
148
+ return text === block.text ? block : { ...block, text };
149
+ }
150
+ if (block.toolUse != null) {
151
+ const { input } = block.toolUse;
152
+ const next = input === undefined ? input : neutralizeDocument(input);
153
+ return next === input
154
+ ? block
155
+ : { ...block, toolUse: { ...block.toolUse, input: next } };
156
+ }
157
+ const content = block.toolResult?.content;
158
+ if (block.toolResult != null && content != null) {
159
+ const next = mapChanged(content, neutralizeToolResultBlock);
160
+ return next === content
161
+ ? block
162
+ : { ...block, toolResult: { ...block.toolResult, content: next } };
163
+ }
164
+ return block;
165
+ }
166
+
167
+ function neutralizeSystemBlock(
168
+ block: BedrockSystemContentBlock
169
+ ): BedrockSystemContentBlock {
170
+ if (typeof block.text !== 'string') {
171
+ return block;
172
+ }
173
+ const text = neutralizeHarmonyControlTokens(block.text);
174
+ return text === block.text ? block : { ...block, text };
175
+ }
176
+
177
+ type ToolConfiguration = NonNullable<ConverseStreamCommandInput['toolConfig']>;
178
+ type ToolEntry = NonNullable<ToolConfiguration['tools']>[number];
179
+
180
+ function neutralizeTool(tool: ToolEntry): ToolEntry {
181
+ const spec = tool.toolSpec;
182
+ if (spec == null) {
183
+ return tool;
184
+ }
185
+ const description =
186
+ spec.description == null
187
+ ? spec.description
188
+ : neutralizeHarmonyControlTokens(spec.description);
189
+ const schema = spec.inputSchema?.json;
190
+ const json = schema === undefined ? schema : neutralizeSchema(schema);
191
+ if (description === spec.description && json === schema) {
192
+ return tool;
193
+ }
194
+ return {
195
+ ...tool,
196
+ toolSpec: {
197
+ ...spec,
198
+ description,
199
+ ...(spec.inputSchema != null ? { inputSchema: { json } } : {}),
200
+ },
201
+ } as ToolEntry;
202
+ }
203
+
204
+ /**
205
+ * Tool descriptions and schema prose are rendered into the same prompt as messages, so a tool
206
+ * that documents the format carries the same failure. Returns the same configuration when no tool
207
+ * changed; a changed tool is copied, leaving the bound tools untouched.
208
+ */
209
+ export function neutralizeHarmonyToolConfig(
210
+ toolConfig: ToolConfiguration | undefined
211
+ ): ToolConfiguration | undefined {
212
+ const tools = toolConfig?.tools;
213
+ if (toolConfig == null || tools == null) {
214
+ return toolConfig;
215
+ }
216
+ const next = mapChanged(tools, neutralizeTool);
217
+ return next === tools ? toolConfig : { ...toolConfig, tools: next };
218
+ }
219
+
220
+ /**
221
+ * Neutralizes harmony control tokens across a converted request. Messages are updated in
222
+ * place (the converter owns them); a block that changes is replaced by a copy, so content
223
+ * shared with the LangChain input is never mutated.
224
+ */
225
+ export function neutralizeHarmonyRequest(
226
+ messages: BedrockMessage[],
227
+ system: BedrockSystemContentBlock[]
228
+ ): BedrockSystemContentBlock[] {
229
+ for (const message of messages) {
230
+ if (message.content != null) {
231
+ message.content = mapChanged(message.content, neutralizeContentBlock);
232
+ }
233
+ }
234
+ return mapChanged(system, neutralizeSystemBlock);
235
+ }
@@ -29,6 +29,7 @@ import type {
29
29
  MessageContentReasoningBlock,
30
30
  } from '../types';
31
31
  import { serializeStructuredValueBounded } from '@/utils/toolContent';
32
+ import { neutralizeHarmonyRequest } from './harmony';
32
33
  import { isReasoningContentBlock } from '@/messages/reasoningTypes';
33
34
  import { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';
34
35
 
@@ -1133,19 +1134,21 @@ function convertToolMessageToConverseMessage(msg: BaseMessage): BedrockMessage {
1133
1134
 
1134
1135
  /** Options for {@link convertToConverseMessages}. */
1135
1136
  export interface ConvertToConverseMessagesOptions {
1136
- /** The model the request is for, which decides whether prior reasoning is replayed. */
1137
+ /**
1138
+ * The model the request is for, which decides whether prior reasoning is replayed and
1139
+ * whether harmony control tokens in text are neutralized.
1140
+ */
1137
1141
  model?: string;
1138
1142
  }
1139
1143
 
1140
1144
  /**
1141
- * OpenAI Bedrock models reject prior `reasoningContent`, including on Claude-to-GPT handoffs.
1142
- * Only suppress replay for identified OpenAI targets; other model families retain the existing
1143
- * behavior because their Bedrock reasoning-replay requirements have not been verified here.
1144
- * Missing model IDs and opaque resource ARNs also retain the existing behavior.
1145
+ * Whether the model is an identified OpenAI model on Bedrock (`openai.*`, a geo/global
1146
+ * inference profile such as `global.openai.*`, or an ARN naming one). Missing model IDs and
1147
+ * opaque resource ARNs are not identified.
1145
1148
  */
1146
- export function replaysBedrockReasoning(model?: string): boolean {
1149
+ export function isBedrockOpenAIModel(model?: string): boolean {
1147
1150
  if (model == null || model === '') {
1148
- return true;
1151
+ return false;
1149
1152
  }
1150
1153
  let id = model.toLowerCase();
1151
1154
  if (id.startsWith('arn:')) {
@@ -1154,11 +1157,21 @@ export function replaysBedrockReasoning(model?: string): boolean {
1154
1157
  id
1155
1158
  )?.[1];
1156
1159
  if (modelId == null) {
1157
- return true;
1160
+ return false;
1158
1161
  }
1159
1162
  id = modelId;
1160
1163
  }
1161
- return !/(?:^|\.)openai\./.test(id);
1164
+ return /(?:^|\.)openai\./.test(id);
1165
+ }
1166
+
1167
+ /**
1168
+ * OpenAI Bedrock models reject prior `reasoningContent`, including on Claude-to-GPT handoffs.
1169
+ * Only suppress replay for identified OpenAI targets; other model families retain the existing
1170
+ * behavior because their Bedrock reasoning-replay requirements have not been verified here.
1171
+ * Missing model IDs and opaque resource ARNs also retain the existing behavior.
1172
+ */
1173
+ export function replaysBedrockReasoning(model?: string): boolean {
1174
+ return !isBedrockOpenAIModel(model);
1162
1175
  }
1163
1176
 
1164
1177
  /**
@@ -1171,7 +1184,8 @@ export function convertToConverseMessages(
1171
1184
  converseMessages: BedrockMessage[];
1172
1185
  converseSystem: BedrockSystemContentBlock[];
1173
1186
  } {
1174
- const replayReasoning = replaysBedrockReasoning(options.model);
1187
+ const openAITarget = isBedrockOpenAIModel(options.model);
1188
+ const replayReasoning = !openAITarget;
1175
1189
  const converseSystem = messages
1176
1190
  .filter((msg) => msg._getType() === 'system')
1177
1191
  .flatMap((msg) => convertSystemMessageToConverseMessage(msg));
@@ -1237,5 +1251,14 @@ export function convertToConverseMessages(
1237
1251
  );
1238
1252
  }
1239
1253
 
1240
- return { converseMessages: combinedConverseMessages, converseSystem };
1254
+ if (!openAITarget) {
1255
+ return { converseMessages: combinedConverseMessages, converseSystem };
1256
+ }
1257
+ return {
1258
+ converseMessages: combinedConverseMessages,
1259
+ converseSystem: neutralizeHarmonyRequest(
1260
+ combinedConverseMessages,
1261
+ converseSystem
1262
+ ),
1263
+ };
1241
1264
  }
@@ -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 === '') {
package/src/llm/invoke.ts CHANGED
@@ -695,6 +695,29 @@ function resolveAttemptRequest(
695
695
  });
696
696
  }
697
697
 
698
+ const EMPTY_PROVIDER_RESPONSE_MESSAGE =
699
+ 'The model provider returned an empty response.';
700
+
701
+ /**
702
+ * Tool calls across an attempt's messages. A missing message means the provider produced
703
+ * nothing, which is reported as such rather than surfacing as a `TypeError` from reading
704
+ * `tool_calls` off `undefined`.
705
+ */
706
+ export function collectAttemptToolCalls(
707
+ messages: ReadonlyArray<BaseMessage | null | undefined> | undefined
708
+ ): ToolCall[] {
709
+ const calls: ToolCall[] = [];
710
+ for (const message of messages ?? []) {
711
+ if (message == null) {
712
+ throw new Error(EMPTY_PROVIDER_RESPONSE_MESSAGE);
713
+ }
714
+ if ('tool_calls' in message) {
715
+ calls.push(...((message.tool_calls as ToolCall[] | undefined) ?? []));
716
+ }
717
+ }
718
+ return calls;
719
+ }
720
+
698
721
  /**
699
722
  * One model attempt. Stamps the attempt identity into callback metadata
700
723
  * (see the generation-key notes in `streamLimits.ts`), leases the attempt's
@@ -786,12 +809,7 @@ export async function attemptInvoke(
786
809
  },
787
810
  stampedConfig
788
811
  );
789
- const calls =
790
- result.messages?.flatMap((message) =>
791
- 'tool_calls' in message
792
- ? ((message.tool_calls as ToolCall[] | undefined) ?? [])
793
- : []
794
- ) ?? [];
812
+ const calls = collectAttemptToolCalls(result.messages);
795
813
  prepared?.finish(preparedAttempt, calls);
796
814
  return result;
797
815
  } catch (error) {
@@ -1499,15 +1517,19 @@ async function attemptInvokeBody(
1499
1517
  );
1500
1518
  }
1501
1519
 
1502
- if (finalChunk != null) detachValidatedModelToolCalls(finalChunk);
1503
- if ((finalChunk?.tool_calls?.length ?? 0) > 0) {
1504
- finalChunk!.tool_calls = finalChunk!.tool_calls?.filter(
1520
+ if (finalChunk == null) {
1521
+ throw new Error(EMPTY_PROVIDER_RESPONSE_MESSAGE);
1522
+ }
1523
+
1524
+ detachValidatedModelToolCalls(finalChunk);
1525
+ if ((finalChunk.tool_calls?.length ?? 0) > 0) {
1526
+ finalChunk.tool_calls = finalChunk.tool_calls?.filter(
1505
1527
  (tool_call: ToolCall) => !!tool_call.name
1506
1528
  );
1507
1529
  }
1508
1530
 
1509
1531
  assertNotTruncatedToolCall(finalChunk, provider);
1510
- return { messages: [finalChunk as AIMessageChunk] };
1532
+ return { messages: [finalChunk] };
1511
1533
  }
1512
1534
 
1513
1535
  const finalMessage = snapshotValidatedModelChunk(