@librechat/agents 4.0.4 → 4.0.5
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.
- package/dist/cjs/llm/bedrock/index.cjs +115 -76
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/utils/harmony.cjs +147 -0
- package/dist/cjs/llm/bedrock/utils/harmony.cjs.map +1 -0
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +13 -6
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/utils/message_outputs.cjs +68 -0
- package/dist/cjs/llm/bedrock/utils/message_outputs.cjs.map +1 -1
- package/dist/cjs/llm/invoke.cjs +13 -3
- package/dist/cjs/llm/invoke.cjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +118 -80
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/bedrock/utils/harmony.mjs +146 -0
- package/dist/esm/llm/bedrock/utils/harmony.mjs.map +1 -0
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs +13 -7
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/bedrock/utils/message_outputs.mjs +68 -2
- package/dist/esm/llm/bedrock/utils/message_outputs.mjs.map +1 -1
- package/dist/esm/llm/invoke.mjs +13 -3
- package/dist/esm/llm/invoke.mjs.map +1 -1
- package/dist/types/llm/bedrock/index.d.ts +14 -1
- package/dist/types/llm/bedrock/utils/harmony.d.ts +34 -0
- package/dist/types/llm/bedrock/utils/message_inputs.d.ts +10 -1
- package/dist/types/llm/invoke.d.ts +7 -0
- package/package.json +1 -1
- package/src/llm/bedrock/index.ts +83 -5
- package/src/llm/bedrock/utils/harmony.ts +235 -0
- package/src/llm/bedrock/utils/message_inputs.ts +34 -11
- package/src/llm/invoke.ts +32 -10
|
@@ -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
|
-
/**
|
|
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
|
-
*
|
|
1142
|
-
*
|
|
1143
|
-
*
|
|
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
|
|
1149
|
+
export function isBedrockOpenAIModel(model?: string): boolean {
|
|
1147
1150
|
if (model == null || model === '') {
|
|
1148
|
-
return
|
|
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
|
|
1160
|
+
return false;
|
|
1158
1161
|
}
|
|
1159
1162
|
id = modelId;
|
|
1160
1163
|
}
|
|
1161
|
-
return
|
|
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
|
|
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
|
-
|
|
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
|
}
|
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
|
|
1503
|
-
|
|
1504
|
-
|
|
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
|
|
1532
|
+
return { messages: [finalChunk] };
|
|
1511
1533
|
}
|
|
1512
1534
|
|
|
1513
1535
|
const finalMessage = snapshotValidatedModelChunk(
|