@librechat/agents 4.2.4 → 4.2.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 (103) hide show
  1. package/dist/cjs/harness/identity.cjs +26 -0
  2. package/dist/cjs/harness/identity.cjs.map +1 -0
  3. package/dist/cjs/harness/index.cjs +3 -15
  4. package/dist/cjs/harness/index.cjs.map +1 -1
  5. package/dist/cjs/harness/providerText.cjs +79 -0
  6. package/dist/cjs/harness/providerText.cjs.map +1 -0
  7. package/dist/cjs/llm/contextPressureMeter.cjs +1 -1
  8. package/dist/cjs/llm/contextPressureMeter.cjs.map +1 -1
  9. package/dist/cjs/llm/google/index.cjs +27 -6
  10. package/dist/cjs/llm/google/index.cjs.map +1 -1
  11. package/dist/cjs/llm/google/utils/common.cjs +27 -14
  12. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  13. package/dist/cjs/llm/google/utils/signatures.cjs +137 -0
  14. package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -0
  15. package/dist/cjs/llm/openai/index.cjs +21 -12
  16. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  17. package/dist/cjs/llm/openai/streamMetadata.cjs +4 -1
  18. package/dist/cjs/llm/openai/streamMetadata.cjs.map +1 -1
  19. package/dist/cjs/llm/providerTextBoundary.cjs +3 -0
  20. package/dist/cjs/llm/providerTextBoundary.cjs.map +1 -1
  21. package/dist/cjs/llm/vertexai/index.cjs +90 -7
  22. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  23. package/dist/cjs/main.cjs +11 -0
  24. package/dist/cjs/messages/content.cjs +4 -1
  25. package/dist/cjs/messages/content.cjs.map +1 -1
  26. package/dist/cjs/messages/format.cjs +11 -8
  27. package/dist/cjs/messages/format.cjs.map +1 -1
  28. package/dist/cjs/stream.cjs +4 -1
  29. package/dist/cjs/stream.cjs.map +1 -1
  30. package/dist/cjs/tools/BashExecutor.cjs +2 -1
  31. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  32. package/dist/cjs/tools/ToolNode.cjs +141 -94
  33. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  34. package/dist/cjs/tools/toolOutputReferences.cjs +39 -17
  35. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  36. package/dist/esm/harness/identity.mjs +24 -0
  37. package/dist/esm/harness/identity.mjs.map +1 -0
  38. package/dist/esm/harness/index.mjs +3 -15
  39. package/dist/esm/harness/index.mjs.map +1 -1
  40. package/dist/esm/harness/providerText.mjs +78 -0
  41. package/dist/esm/harness/providerText.mjs.map +1 -0
  42. package/dist/esm/llm/contextPressureMeter.mjs +1 -1
  43. package/dist/esm/llm/contextPressureMeter.mjs.map +1 -1
  44. package/dist/esm/llm/google/index.mjs +23 -7
  45. package/dist/esm/llm/google/index.mjs.map +1 -1
  46. package/dist/esm/llm/google/utils/common.mjs +27 -14
  47. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  48. package/dist/esm/llm/google/utils/signatures.mjs +132 -0
  49. package/dist/esm/llm/google/utils/signatures.mjs.map +1 -0
  50. package/dist/esm/llm/openai/index.mjs +21 -12
  51. package/dist/esm/llm/openai/index.mjs.map +1 -1
  52. package/dist/esm/llm/openai/streamMetadata.mjs +4 -1
  53. package/dist/esm/llm/openai/streamMetadata.mjs.map +1 -1
  54. package/dist/esm/llm/providerTextBoundary.mjs +3 -0
  55. package/dist/esm/llm/providerTextBoundary.mjs.map +1 -1
  56. package/dist/esm/llm/vertexai/index.mjs +91 -8
  57. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  58. package/dist/esm/main.mjs +4 -1
  59. package/dist/esm/messages/content.mjs +4 -1
  60. package/dist/esm/messages/content.mjs.map +1 -1
  61. package/dist/esm/messages/format.mjs +11 -8
  62. package/dist/esm/messages/format.mjs.map +1 -1
  63. package/dist/esm/stream.mjs +4 -1
  64. package/dist/esm/stream.mjs.map +1 -1
  65. package/dist/esm/tools/BashExecutor.mjs +2 -1
  66. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  67. package/dist/esm/tools/ToolNode.mjs +142 -95
  68. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  69. package/dist/esm/tools/toolOutputReferences.mjs +39 -18
  70. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  71. package/dist/types/harness/identity.d.ts +14 -0
  72. package/dist/types/harness/index.d.ts +5 -9
  73. package/dist/types/harness/providerText.d.ts +32 -0
  74. package/dist/types/index.d.ts +2 -0
  75. package/dist/types/llm/google/index.d.ts +4 -2
  76. package/dist/types/llm/google/utils/common.d.ts +5 -1
  77. package/dist/types/llm/google/utils/signatures.d.ts +23 -0
  78. package/dist/types/llm/openai/streamMetadata.d.ts +3 -3
  79. package/dist/types/llm/vertexai/index.d.ts +2 -17
  80. package/dist/types/messages/format.d.ts +3 -1
  81. package/dist/types/tools/ToolNode.d.ts +7 -7
  82. package/dist/types/tools/toolOutputReferences.d.ts +16 -4
  83. package/dist/types/types/llm.d.ts +2 -2
  84. package/package.json +1 -1
  85. package/src/harness/identity.ts +34 -0
  86. package/src/harness/index.ts +15 -23
  87. package/src/harness/providerText.ts +128 -0
  88. package/src/index.ts +9 -0
  89. package/src/llm/contextPressureMeter.ts +2 -4
  90. package/src/llm/google/index.ts +20 -6
  91. package/src/llm/google/utils/common.ts +23 -10
  92. package/src/llm/google/utils/signatures.ts +215 -0
  93. package/src/llm/openai/index.ts +60 -20
  94. package/src/llm/openai/streamMetadata.ts +14 -3
  95. package/src/llm/providerTextBoundary.ts +3 -0
  96. package/src/llm/vertexai/index.ts +127 -39
  97. package/src/messages/content.ts +14 -6
  98. package/src/messages/format.ts +42 -29
  99. package/src/stream.ts +10 -1
  100. package/src/tools/BashExecutor.ts +2 -1
  101. package/src/tools/ToolNode.ts +333 -256
  102. package/src/tools/toolOutputReferences.ts +101 -32
  103. package/src/types/llm.ts +10 -2
@@ -40,6 +40,12 @@ import {
40
40
  STREAMED_TOOL_CALL_ADAPTER_METADATA_KEY,
41
41
  GOOGLE_STREAMED_TOOL_CALL_ADAPTER,
42
42
  } from '@/tools/streamedToolCallSeals';
43
+ import {
44
+ GEMINI_PARTS,
45
+ GEMINI_REPLAY_UNSUPPORTED,
46
+ captureGeminiReplayParts,
47
+ restoreGeminiReplayParts,
48
+ } from './signatures';
43
49
  import {
44
50
  jsonSchemaToGeminiParameters,
45
51
  schemaToGenerativeAIParameters,
@@ -519,6 +525,9 @@ export function convertMessageContentToParts(
519
525
  ];
520
526
  }
521
527
 
528
+ const replayParts = restoreGeminiReplayParts(message);
529
+ if (replayParts != null) return replayParts as Part[];
530
+
522
531
  let functionCalls: FunctionCallPart[] = [];
523
532
  const messageParts: Part[] = [];
524
533
 
@@ -534,11 +543,9 @@ export function convertMessageContentToParts(
534
543
  );
535
544
  }
536
545
 
537
- const functionThoughtSignatures = (
538
- message.additional_kwargs as BaseMessage['additional_kwargs'] | undefined
539
- )?.[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY] as
540
- | Record<string, string>
541
- | undefined;
546
+ const storedSignatures = message.additional_kwargs[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY] as Record<string, string> | undefined;
547
+ let functionThoughtSignatures = storedSignatures != null && Object.keys(storedSignatures).length > 0 ? storedSignatures : undefined;
548
+ if (Object.hasOwn(message.additional_kwargs, GEMINI_PARTS) && message.additional_kwargs[GEMINI_REPLAY_UNSUPPORTED] !== true) functionThoughtSignatures = {};
542
549
 
543
550
  if (isAIMessage(message) && (message.tool_calls?.length ?? 0) > 0) {
544
551
  functionCalls = (message.tool_calls ?? []).map((tc) => {
@@ -549,7 +556,7 @@ export function convertMessageContentToParts(
549
556
  return signature;
550
557
  }
551
558
  }
552
- if (isGemini3PlusModel(model)) {
559
+ if (isGemini3PlusModel(model) && functionThoughtSignatures == null) {
553
560
  return DUMMY_SIGNATURE;
554
561
  }
555
562
  return '';
@@ -700,6 +707,7 @@ const GEMINI_FLASH_VERSION_PATTERN = /^gemini-(\d+)(?:\.(\d+))?-flash(?:$|-)/;
700
707
  const NO_PREFILL_GEMINI_MODELS = [
701
708
  'gemini-3.5-flash-lite',
702
709
  'gemini-4-argon',
710
+ 'gemini-4-hydrogen',
703
711
  ] as const;
704
712
 
705
713
  export function rejectsModelTurnPrefill(model?: string): boolean {
@@ -732,10 +740,10 @@ export function rejectsModelTurnPrefill(model?: string): boolean {
732
740
  * HTTP 400 for it, so we drop it and let the model generate fresh from the
733
741
  * preceding user turn. No-op for every other model, preserving working prefill.
734
742
  */
735
- export function dropUnsupportedModelTurnPrefill(
736
- contents: Content[] | undefined,
743
+ export function dropUnsupportedModelTurnPrefill<T extends { role: string }>(
744
+ contents: T[] | undefined,
737
745
  model?: string
738
- ): Content[] | undefined {
746
+ ): T[] | undefined {
739
747
  if (
740
748
  contents == null ||
741
749
  contents.length === 0 ||
@@ -755,6 +763,7 @@ export function convertResponseContentToChatGenerationChunk(
755
763
  extra: {
756
764
  usageMetadata?: UsageMetadata | undefined;
757
765
  index: number;
766
+ model?: string;
758
767
  }
759
768
  ): ChatGenerationChunk | null {
760
769
  if (!response.candidates || response.candidates.length === 0) {
@@ -906,7 +915,7 @@ export function convertResponseContentToChatGenerationChunk(
906
915
  }
907
916
  : undefined;
908
917
 
909
- return new ChatGenerationChunk({
918
+ const chunk = new ChatGenerationChunk({
910
919
  text,
911
920
  message: new AIMessageChunk({
912
921
  content: content,
@@ -920,6 +929,8 @@ export function convertResponseContentToChatGenerationChunk(
920
929
  }),
921
930
  generationInfo,
922
931
  });
932
+ captureGeminiReplayParts(chunk.message, candidateContent?.parts ?? [], extra.model);
933
+ return chunk;
923
934
  }
924
935
 
925
936
  /**
@@ -929,6 +940,7 @@ export function mapGenerateContentResultToChatResult(
929
940
  response: EnhancedGenerateContentResponse,
930
941
  extra?: {
931
942
  usageMetadata: UsageMetadata | undefined;
943
+ model?: string;
932
944
  }
933
945
  ): ChatResult {
934
946
  if (!response.candidates || response.candidates.length === 0) {
@@ -1060,6 +1072,7 @@ export function mapGenerateContentResultToChatResult(
1060
1072
  }),
1061
1073
  generationInfo,
1062
1074
  };
1075
+ captureGeminiReplayParts(generation.message, candidateContent?.parts ?? [], extra?.model);
1063
1076
  return {
1064
1077
  generations: [generation],
1065
1078
  llmOutput: {
@@ -0,0 +1,215 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { AIMessageChunk, isAIMessage } from '@langchain/core/messages';
3
+ import type { BaseMessage } from '@langchain/core/messages';
4
+ import type { GeminiPart } from '@langchain/google-common';
5
+ import type { Part } from '@google/generative-ai';
6
+
7
+ export const GEMINI_PARTS = '__gemini_parts__';
8
+ export const GEMINI_REPLAY_UNSUPPORTED = '__gemini_replay_unsupported__';
9
+ export const GEMINI_SIGNATURES = '__gemini_function_call_thought_signatures__';
10
+
11
+ export type GeminiReplayPart =
12
+ | {
13
+ type: 'text';
14
+ length: number;
15
+ hash: string;
16
+ thought?: boolean;
17
+ thoughtSignature?: string;
18
+ }
19
+ | {
20
+ type: 'function_call';
21
+ id: string;
22
+ hash: string;
23
+ thoughtSignature?: string;
24
+ };
25
+
26
+ function hashText(text: string): string {
27
+ return createHash('sha256').update(text).digest('hex');
28
+ }
29
+
30
+ export function isGeminiReplayParts(
31
+ value: unknown
32
+ ): value is GeminiReplayPart[] {
33
+ return (
34
+ Array.isArray(value) &&
35
+ Array.from(value).every((value: unknown) => {
36
+ if (value == null || typeof value !== 'object') return false;
37
+ const part = value as Partial<GeminiReplayPart>;
38
+ if (
39
+ part.thoughtSignature !== undefined &&
40
+ typeof part.thoughtSignature !== 'string'
41
+ )
42
+ return false;
43
+ if (part.type === 'function_call')
44
+ return (
45
+ typeof part.id === 'string' &&
46
+ part.id !== '' &&
47
+ typeof part.hash === 'string' &&
48
+ /^[a-f0-9]{64}$/.test(part.hash) &&
49
+ Object.keys(part).every((key) =>
50
+ ['type', 'id', 'hash', 'thoughtSignature'].includes(key)
51
+ )
52
+ );
53
+ return (
54
+ part.type === 'text' &&
55
+ typeof part.length === 'number' &&
56
+ Number.isSafeInteger(part.length) &&
57
+ part.length >= 0 &&
58
+ typeof part.hash === 'string' &&
59
+ /^[a-f0-9]{64}$/.test(part.hash) &&
60
+ (part.thought === undefined || typeof part.thought === 'boolean') &&
61
+ Object.keys(part).every((key) =>
62
+ ['type', 'length', 'hash', 'thought', 'thoughtSignature'].includes(
63
+ key
64
+ )
65
+ )
66
+ );
67
+ })
68
+ );
69
+ }
70
+
71
+ /** Captures native boundaries without duplicating prose. Known Gemini 1/2 models retain their existing signature formats for cross-model compatibility. */
72
+ export function captureGeminiReplayParts(
73
+ message: BaseMessage,
74
+ parts: readonly (Part | GeminiPart)[],
75
+ model?: string
76
+ ): void {
77
+ if (!isAIMessage(message)) return;
78
+ const sourceModel = model?.toLowerCase().split('/').pop() ?? '';
79
+ if (/^gemini-(?:[12](?:[.-]|$)|pro(?:-|$))/.test(sourceModel)) return;
80
+ message.additional_kwargs[GEMINI_REPLAY_UNSUPPORTED] = true;
81
+ const replay: GeminiReplayPart[] = [];
82
+ const signatures: Record<string, string> = {};
83
+ let callIndex = 0;
84
+ let reasoning = '';
85
+ for (const part of parts) {
86
+ const thoughtSignature =
87
+ 'thoughtSignature' in part && typeof part.thoughtSignature === 'string'
88
+ ? part.thoughtSignature
89
+ : undefined;
90
+ const signature = thoughtSignature != null ? { thoughtSignature } : {};
91
+ const thought =
92
+ 'thought' in part && typeof part.thought === 'boolean'
93
+ ? part.thought
94
+ : undefined;
95
+ if ('text' in part && typeof part.text === 'string') {
96
+ replay.push({
97
+ type: 'text',
98
+ length: part.text.length,
99
+ hash: hashText(part.text),
100
+ ...(thought != null ? { thought } : {}),
101
+ ...signature,
102
+ });
103
+ if (thought === true) reasoning += part.text;
104
+ continue;
105
+ }
106
+ if (!('functionCall' in part) || part.functionCall == null) continue;
107
+ const index = callIndex++;
108
+ const call = message.tool_calls?.[index];
109
+ if (call?.id == null || call.id === '') continue;
110
+ const nativeId =
111
+ 'id' in part.functionCall && typeof part.functionCall.id === 'string'
112
+ ? part.functionCall.id
113
+ : undefined;
114
+ if (nativeId != null && nativeId !== '') {
115
+ call.id = nativeId;
116
+ if (
117
+ message instanceof AIMessageChunk &&
118
+ Array.isArray(message.tool_call_chunks) &&
119
+ index < message.tool_call_chunks.length
120
+ ) {
121
+ message.tool_call_chunks[index].id = nativeId;
122
+ }
123
+ }
124
+ replay.push({
125
+ type: 'function_call',
126
+ id: call.id,
127
+ hash: hashText(JSON.stringify({ name: call.name, args: call.args })),
128
+ ...signature,
129
+ });
130
+ if (thoughtSignature != null) signatures[call.id] = thoughtSignature;
131
+ }
132
+ message.additional_kwargs[GEMINI_SIGNATURES] = signatures;
133
+ if (replay.length !== parts.length) return;
134
+ message.additional_kwargs[GEMINI_PARTS] = replay;
135
+ const hasThinkingContent =
136
+ Array.isArray(message.content) &&
137
+ message.content.some((block) => block.type === 'thinking');
138
+ if (reasoning !== '' && !hasThinkingContent)
139
+ message.additional_kwargs.reasoning = reasoning;
140
+ delete message.additional_kwargs[GEMINI_REPLAY_UNSUPPORTED];
141
+ }
142
+
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]
147
+ ): 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 = '';
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 += block.thinking;
163
+ else if (!('functionCall' in block)) return undefined;
164
+ }
165
+ let reasoning = contentReasoning;
166
+ if (typeof message.additional_kwargs.reasoning_content === 'string')
167
+ reasoning = message.additional_kwargs.reasoning_content;
168
+ if (typeof message.additional_kwargs.reasoning === 'string')
169
+ reasoning = message.additional_kwargs.reasoning;
170
+ const calls = new Map(
171
+ (message.tool_calls ?? []).map((call) => [call.id, call])
172
+ );
173
+ const parts: GeminiPart[] = [];
174
+ let textOffset = 0;
175
+ let reasoningOffset = 0;
176
+ for (const descriptor of replay) {
177
+ const signature =
178
+ descriptor.thoughtSignature != null
179
+ ? { thoughtSignature: descriptor.thoughtSignature }
180
+ : {};
181
+ if (descriptor.type === 'function_call') {
182
+ const call = calls.get(descriptor.id);
183
+ if (
184
+ call == null ||
185
+ hashText(JSON.stringify({ name: call.name, args: call.args })) !==
186
+ descriptor.hash
187
+ )
188
+ return undefined;
189
+ const functionCall = { id: call.id, name: call.name, args: call.args };
190
+ parts.push({ functionCall, ...signature });
191
+ calls.delete(descriptor.id);
192
+ continue;
193
+ }
194
+ const offset = descriptor.thought === true ? reasoningOffset : textOffset;
195
+ const source = descriptor.thought === true ? reasoning : text;
196
+ const value = source.slice(offset, offset + descriptor.length);
197
+ if (
198
+ value.length !== descriptor.length ||
199
+ hashText(value) !== descriptor.hash
200
+ )
201
+ return undefined;
202
+ if (descriptor.thought === true) reasoningOffset += descriptor.length;
203
+ else textOffset += descriptor.length;
204
+ parts.push({
205
+ text: value,
206
+ ...(descriptor.thought != null ? { thought: descriptor.thought } : {}),
207
+ ...signature,
208
+ });
209
+ }
210
+ return textOffset === text.length &&
211
+ reasoningOffset === reasoning.length &&
212
+ calls.size === 0
213
+ ? parts
214
+ : undefined;
215
+ }
@@ -1147,7 +1147,10 @@ type ResponsesAnnotationsBoundaryEvent = {
1147
1147
  export function ensureResponsesOutputAnnotations(
1148
1148
  event: ResponsesAnnotationsBoundaryEvent
1149
1149
  ): void {
1150
- if (event.type !== 'response.completed' && event.type !== 'response.incomplete') {
1150
+ if (
1151
+ event.type !== 'response.completed' &&
1152
+ event.type !== 'response.incomplete'
1153
+ ) {
1151
1154
  return;
1152
1155
  }
1153
1156
  const output = event.response?.output;
@@ -1418,7 +1421,8 @@ async function completionWithFilteredOpenAIStream(
1418
1421
 
1419
1422
  function attachLibreChatDeltaFields(
1420
1423
  chunk: BaseMessageChunk,
1421
- delta: Record<string, unknown>
1424
+ delta: Record<string, unknown>,
1425
+ rawResponse?: unknown
1422
1426
  ): BaseMessageChunk {
1423
1427
  if (!AIMessageChunk.isInstance(chunk)) {
1424
1428
  return chunk;
@@ -1439,12 +1443,32 @@ function attachLibreChatDeltaFields(
1439
1443
  chunk.additional_kwargs.provider_specific_fields =
1440
1444
  libreChatDelta.provider_specific_fields;
1441
1445
  }
1446
+ if ('usage' in chunk.response_metadata) {
1447
+ delete chunk.response_metadata.usage;
1448
+ }
1449
+ const rawRecord = rawResponse as
1450
+ | {
1451
+ provider?: unknown;
1452
+ choices?: Array<{ finish_reason?: unknown }>;
1453
+ }
1454
+ | undefined;
1455
+ const provider = rawRecord?.provider;
1456
+ if (
1457
+ typeof provider === 'string' &&
1458
+ provider.length > 0 &&
1459
+ (chunk.response_metadata.finish_reason != null ||
1460
+ rawRecord?.choices?.some((choice) => choice.finish_reason != null) ===
1461
+ true)
1462
+ ) {
1463
+ chunk.response_metadata.provider = provider;
1464
+ }
1442
1465
  return chunk;
1443
1466
  }
1444
1467
 
1445
1468
  function attachLibreChatMessageFields(
1446
1469
  message: BaseMessage,
1447
- rawMessage: Record<string, unknown>
1470
+ rawMessage: Record<string, unknown>,
1471
+ rawResponse?: unknown
1448
1472
  ): BaseMessage {
1449
1473
  if (!isAIMessage(message)) {
1450
1474
  return message;
@@ -1462,6 +1486,11 @@ function attachLibreChatMessageFields(
1462
1486
  message.additional_kwargs.provider_specific_fields =
1463
1487
  rawMessage.provider_specific_fields;
1464
1488
  }
1489
+ const provider = (rawResponse as { provider?: unknown } | undefined)
1490
+ ?.provider;
1491
+ if (typeof provider === 'string' && provider.length > 0) {
1492
+ message.response_metadata.provider = provider;
1493
+ }
1465
1494
  return message;
1466
1495
  }
1467
1496
 
@@ -2036,7 +2065,8 @@ class LibreChatOpenAICompletions extends OriginalChatOpenAICompletions {
2036
2065
  rawResponse,
2037
2066
  defaultRole
2038
2067
  ),
2039
- delta
2068
+ delta,
2069
+ rawResponse
2040
2070
  );
2041
2071
  if (isOfficialOpenAIBaseURL(this.clientConfig.baseURL)) {
2042
2072
  return stampSequentialStreamedToolCallAdapter(message);
@@ -2050,7 +2080,8 @@ class LibreChatOpenAICompletions extends OriginalChatOpenAICompletions {
2050
2080
  ): BaseMessage {
2051
2081
  return attachLibreChatMessageFields(
2052
2082
  super._convertCompletionsMessageToBaseMessage(message, rawResponse),
2053
- message as unknown as Record<string, unknown>
2083
+ message as unknown as Record<string, unknown>,
2084
+ rawResponse
2054
2085
  );
2055
2086
  }
2056
2087
 
@@ -2059,31 +2090,23 @@ class LibreChatOpenAICompletions extends OriginalChatOpenAICompletions {
2059
2090
  options: this['ParsedCallOptions'],
2060
2091
  runManager?: CallbackManagerForLLMRun
2061
2092
  ): Promise<ChatResult> {
2093
+ options.signal?.throwIfAborted();
2094
+ const params = this.invocationParams(options);
2062
2095
  if (
2096
+ params.stream !== true &&
2063
2097
  this.includeReasoningContent !== true &&
2064
2098
  this.includeReasoningDetails !== true
2065
2099
  ) {
2066
2100
  return super._generate(messages, options, runManager);
2067
2101
  }
2068
2102
 
2069
- options.signal?.throwIfAborted();
2070
2103
  const usageMetadata: Partial<UsageMetadata> = {};
2071
- const params = this.invocationParams(options);
2072
- const messagesMapped = _convertMessagesToOpenAIParams(
2073
- messages,
2074
- this.model,
2075
- {
2076
- includeReasoningContent: this.includeReasoningContent,
2077
- includeReasoningDetails: this.includeReasoningDetails,
2078
- convertReasoningDetailsToContent: this.convertReasoningDetailsToContent,
2079
- preserveToolCacheControl: this.preserveToolCacheControl,
2080
- }
2081
- );
2082
-
2083
2104
  if (params.stream === true) {
2084
2105
  const stream = this._streamResponseChunks(messages, options, runManager);
2085
2106
  const finalChunks = new Map<number, ChatGenerationChunk>();
2107
+ const seenScalarMetadata: SeenScalarMetadata = new Map();
2086
2108
  for await (const chunk of stream) {
2109
+ dropRepeatedScalarMetadata(chunk, seenScalarMetadata);
2087
2110
  chunk.message.response_metadata = {
2088
2111
  ...chunk.generationInfo,
2089
2112
  ...chunk.message.response_metadata,
@@ -2125,6 +2148,16 @@ class LibreChatOpenAICompletions extends OriginalChatOpenAICompletions {
2125
2148
  };
2126
2149
  }
2127
2150
 
2151
+ const messagesMapped = _convertMessagesToOpenAIParams(
2152
+ messages,
2153
+ this.model,
2154
+ {
2155
+ includeReasoningContent: this.includeReasoningContent,
2156
+ includeReasoningDetails: this.includeReasoningDetails,
2157
+ convertReasoningDetailsToContent: this.convertReasoningDetailsToContent,
2158
+ preserveToolCacheControl: this.preserveToolCacheControl,
2159
+ }
2160
+ );
2128
2161
  const data = await this.completionWithRetry(
2129
2162
  {
2130
2163
  ...params,
@@ -2440,7 +2473,9 @@ class LibreChatOpenAIResponses extends OriginalChatOpenAIResponses {
2440
2473
  cache_control: cacheControl,
2441
2474
  }),
2442
2475
  };
2443
- if (shouldIncludeEncryptedReasoning(this.model, params, this.astraRulesApply)) {
2476
+ if (
2477
+ shouldIncludeEncryptedReasoning(this.model, params, this.astraRulesApply)
2478
+ ) {
2444
2479
  params.include = [
2445
2480
  ...new Set([
2446
2481
  ...(params.include ?? []),
@@ -2730,7 +2765,9 @@ class LibreChatAzureOpenAIResponses extends OriginalAzureChatOpenAIResponses {
2730
2765
  promptCacheExplicit: this.promptCacheExplicit,
2731
2766
  safetyIdentifier: this.safetyIdentifier,
2732
2767
  });
2733
- if (shouldIncludeEncryptedReasoning(this.model, params, this.astraRulesApply)) {
2768
+ if (
2769
+ shouldIncludeEncryptedReasoning(this.model, params, this.astraRulesApply)
2770
+ ) {
2734
2771
  params.include = [
2735
2772
  ...new Set([
2736
2773
  ...(params.include ?? []),
@@ -3476,6 +3513,9 @@ export class ChatDeepSeek extends OriginalChatDeepSeek {
3476
3513
  data,
3477
3514
  defaultRole
3478
3515
  );
3516
+ if ('usage' in messageChunk.response_metadata) {
3517
+ delete messageChunk.response_metadata.usage;
3518
+ }
3479
3519
  defaultRole = delta.role ?? defaultRole;
3480
3520
 
3481
3521
  if (typeof messageChunk.content !== 'string') {
@@ -14,6 +14,8 @@ const REPEATED_SCALAR_METADATA_FIELDS = [
14
14
  'finish_reason',
15
15
  'service_tier',
16
16
  'system_fingerprint',
17
+ 'provider',
18
+ 'usage',
17
19
  ] as const;
18
20
 
19
21
  /** Per-completion-index set of scalar fields already emitted this stream. */
@@ -29,9 +31,9 @@ function completionIndex(
29
31
  /**
30
32
  * Strip scalar `response_metadata`/`generationInfo` fields that have already
31
33
  * appeared on an earlier chunk of the same completion (tracked in `seen`),
32
- * keeping the first occurrence so the aggregated message still carries the
33
- * value once. Scoped per completion index so multi-choice (`n > 1`) responses,
34
- * which `_generate` aggregates separately, keep each choice's own metadata.
34
+ * keeping the first occurrence (first nonempty snapshot for usage) so the
35
+ * aggregated message still carries the value once. Scoped per completion index
36
+ * so multi-choice (`n > 1`) responses keep each choice's own metadata.
35
37
  *
36
38
  * Deletes from a shallow clone rather than in place: providers such as
37
39
  * `ChatDeepSeek` split one raw chunk into several synthetic pieces that share
@@ -66,6 +68,15 @@ export function dropRepeatedScalarMetadata(
66
68
  if (!inGenerationInfo && !inResponseMetadata) {
67
69
  continue;
68
70
  }
71
+ if (
72
+ field === 'usage' &&
73
+ (!inGenerationInfo ||
74
+ Object.keys(generationInfo.usage ?? {}).length === 0) &&
75
+ (!inResponseMetadata ||
76
+ Object.keys(responseMetadata.usage ?? {}).length === 0)
77
+ ) {
78
+ continue;
79
+ }
69
80
  if (!seenFields.has(field)) {
70
81
  seenFields.add(field);
71
82
  continue;
@@ -13,6 +13,7 @@ import {
13
13
  STREAMED_TOOL_CALL_SEAL_METADATA_KEY,
14
14
  } from '@/tools/streamedToolCallSeals';
15
15
  import { GEMINI_SIGNATURES, RESPONSES_POSITIONS, stringMap, safetyRatings, replayPositions, ResponsesTextProjection, keys } from '@/llm/providerTextControls';
16
+ import { GEMINI_PARTS, GEMINI_REPLAY_UNSUPPORTED, isGeminiReplayParts } from '@/llm/google/utils/signatures';
16
17
  import {
17
18
  ProviderTextAttempt,
18
19
  ProviderTextProtectionError,
@@ -48,6 +49,8 @@ const additionalControls: Readonly<Partial<Record<string, (value: unknown) => bo
48
49
 
49
50
  const geminiControls: Readonly<Partial<Record<string, (value: unknown) => boolean>>> = {
50
51
  [GEMINI_SIGNATURES]: stringMap,
52
+ [GEMINI_PARTS]: isGeminiReplayParts,
53
+ [GEMINI_REPLAY_UNSUPPORTED]: (value) => value === true,
51
54
  finishReason: (value) => ['STOP', 'MAX_TOKENS', 'SAFETY', 'RECITATION', 'OTHER', 'MALFORMED_FUNCTION_CALL', 'FINISH_REASON_UNSPECIFIED'].includes(String(value)),
52
55
  safetyRatings,
53
56
  avgLogprobs: (value) => typeof value === 'number' && Number.isFinite(value),