@librechat/agents 2.2.5 → 2.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.
@@ -1,4 +1,4 @@
1
- import { HumanMessage, AIMessage, SystemMessage, ToolMessage } from '@langchain/core/messages';
1
+ import { HumanMessage, AIMessage, SystemMessage, getBufferString, ToolMessage } from '@langchain/core/messages';
2
2
  import { Providers, ContentTypes } from '../common/enum.mjs';
3
3
 
4
4
  /**
@@ -116,19 +116,117 @@ const formatFromLangChain = (message) => {
116
116
  ...additional_kwargs,
117
117
  };
118
118
  };
119
+ /**
120
+ * Helper function to format an assistant message
121
+ * @param message The message to format
122
+ * @returns Array of formatted messages
123
+ */
124
+ function formatAssistantMessage(message) {
125
+ const formattedMessages = [];
126
+ let currentContent = [];
127
+ let lastAIMessage = null;
128
+ let hasReasoning = false;
129
+ if (Array.isArray(message.content)) {
130
+ for (const part of message.content) {
131
+ if (part.type === ContentTypes.TEXT && part.tool_call_ids) {
132
+ /*
133
+ If there's pending content, it needs to be aggregated as a single string to prepare for tool calls.
134
+ For Anthropic models, the "tool_calls" field on a message is only respected if content is a string.
135
+ */
136
+ if (currentContent.length > 0) {
137
+ let content = currentContent.reduce((acc, curr) => {
138
+ if (curr.type === ContentTypes.TEXT) {
139
+ return `${acc}${curr[ContentTypes.TEXT] || ''}\n`;
140
+ }
141
+ return acc;
142
+ }, '');
143
+ content = `${content}\n${part[ContentTypes.TEXT] ?? part.text ?? ''}`.trim();
144
+ lastAIMessage = new AIMessage({ content });
145
+ formattedMessages.push(lastAIMessage);
146
+ currentContent = [];
147
+ continue;
148
+ }
149
+ // Create a new AIMessage with this text and prepare for tool calls
150
+ lastAIMessage = new AIMessage({
151
+ content: part.text || '',
152
+ });
153
+ formattedMessages.push(lastAIMessage);
154
+ }
155
+ else if (part?.type === ContentTypes.TOOL_CALL) {
156
+ if (!lastAIMessage) {
157
+ throw new Error('Invalid tool call structure: No preceding AIMessage with tool_call_ids');
158
+ }
159
+ // Note: `tool_calls` list is defined when constructed by `AIMessage` class, and outputs should be excluded from it
160
+ const { output, args: _args, ..._tool_call } = part.tool_call;
161
+ const tool_call = _tool_call;
162
+ // TODO: investigate; args as dictionary may need to be providers-or-tool-specific
163
+ let args = _args;
164
+ try {
165
+ if (typeof _args === 'string') {
166
+ args = JSON.parse(_args);
167
+ }
168
+ }
169
+ catch (e) {
170
+ if (typeof _args === 'string') {
171
+ args = { input: _args };
172
+ }
173
+ }
174
+ tool_call.args = args;
175
+ if (!lastAIMessage.tool_calls) {
176
+ lastAIMessage.tool_calls = [];
177
+ }
178
+ lastAIMessage.tool_calls.push(tool_call);
179
+ formattedMessages.push(new ToolMessage({
180
+ tool_call_id: tool_call.id ?? '',
181
+ name: tool_call.name,
182
+ content: output || '',
183
+ }));
184
+ }
185
+ else if (part.type === ContentTypes.THINK) {
186
+ hasReasoning = true;
187
+ continue;
188
+ }
189
+ else if (part.type === ContentTypes.ERROR || part.type === ContentTypes.AGENT_UPDATE) {
190
+ continue;
191
+ }
192
+ else {
193
+ currentContent.push(part);
194
+ }
195
+ }
196
+ }
197
+ if (hasReasoning && currentContent.length > 0) {
198
+ const content = currentContent
199
+ .reduce((acc, curr) => {
200
+ if (curr.type === ContentTypes.TEXT) {
201
+ return `${acc}${curr[ContentTypes.TEXT] || ''}\n`;
202
+ }
203
+ return acc;
204
+ }, '')
205
+ .trim();
206
+ if (content) {
207
+ formattedMessages.push(new AIMessage({ content }));
208
+ }
209
+ }
210
+ else if (currentContent.length > 0) {
211
+ formattedMessages.push(new AIMessage({ content: currentContent }));
212
+ }
213
+ return formattedMessages;
214
+ }
119
215
  /**
120
216
  * Formats an array of messages for LangChain, handling tool calls and creating ToolMessage instances.
121
217
  *
122
- * @param {Array<Partial<TMessage>>} payload - The array of messages to format.
218
+ * @param {TPayload} payload - The array of messages to format.
123
219
  * @param {Record<number, number>} [indexTokenCountMap] - Optional map of message indices to token counts.
220
+ * @param {Set<string>} [tools] - Optional set of tool names that are allowed in the request.
124
221
  * @returns {Object} - Object containing formatted messages and updated indexTokenCountMap if provided.
125
222
  */
126
- const formatAgentMessages = (payload, indexTokenCountMap) => {
223
+ const formatAgentMessages = (payload, indexTokenCountMap, tools) => {
127
224
  const messages = [];
128
225
  // If indexTokenCountMap is provided, create a new map to track the updated indices
129
226
  const updatedIndexTokenCountMap = {};
130
227
  // Keep track of the mapping from original payload indices to result indices
131
228
  const indexMapping = {};
229
+ // Process messages with tool conversion if tools set is provided
132
230
  for (let i = 0; i < payload.length; i++) {
133
231
  const message = payload[i];
134
232
  // Q: Store the current length of messages to track where this payload message starts in the result?
@@ -147,93 +245,77 @@ const formatAgentMessages = (payload, indexTokenCountMap) => {
147
245
  }
148
246
  // For assistant messages, track the starting index before processing
149
247
  const startMessageIndex = messages.length;
150
- let currentContent = [];
151
- let lastAIMessage = null;
152
- let hasReasoning = false;
153
- if (Array.isArray(message.content)) {
154
- for (const part of message.content) {
155
- if (part.type === ContentTypes.TEXT && part.tool_call_ids) {
156
- /*
157
- If there's pending content, it needs to be aggregated as a single string to prepare for tool calls.
158
- For Anthropic models, the "tool_calls" field on a message is only respected if content is a string.
159
- */
160
- if (currentContent.length > 0) {
161
- let content = currentContent.reduce((acc, curr) => {
162
- if (curr.type === ContentTypes.TEXT) {
163
- return `${acc}${curr[ContentTypes.TEXT] || ''}\n`;
164
- }
165
- return acc;
166
- }, '');
167
- content = `${content}\n${part[ContentTypes.TEXT] ?? part.text ?? ''}`.trim();
168
- lastAIMessage = new AIMessage({ content });
169
- messages.push(lastAIMessage);
170
- currentContent = [];
171
- continue;
248
+ // If tools set is provided, we need to check if we need to convert tool messages to a string
249
+ if (tools) {
250
+ // First, check if this message contains tool calls
251
+ let hasToolCalls = false;
252
+ let hasInvalidTool = false;
253
+ const content = message.content;
254
+ if (content && Array.isArray(content)) {
255
+ for (const part of content) {
256
+ if (part?.type === ContentTypes.TOOL_CALL) {
257
+ hasToolCalls = true;
258
+ if (tools.size === 0) {
259
+ hasInvalidTool = true;
260
+ break;
261
+ }
262
+ const toolName = part.tool_call.name;
263
+ if (!tools.has(toolName)) {
264
+ hasInvalidTool = true;
265
+ }
172
266
  }
173
- // Create a new AIMessage with this text and prepare for tool calls
174
- lastAIMessage = new AIMessage({
175
- content: part.text || '',
176
- });
177
- messages.push(lastAIMessage);
178
267
  }
179
- else if (part.type === ContentTypes.TOOL_CALL) {
180
- if (!lastAIMessage) {
181
- throw new Error('Invalid tool call structure: No preceding AIMessage with tool_call_ids');
182
- }
183
- // Note: `tool_calls` list is defined when constructed by `AIMessage` class, and outputs should be excluded from it
184
- const { output, args: _args, ...tool_call } = part.tool_call;
185
- // TODO: investigate; args as dictionary may need to be providers-or-tool-specific
186
- let args = _args;
187
- try {
188
- if (typeof _args === 'string') {
189
- args = JSON.parse(_args);
268
+ }
269
+ // If this message has tool calls and at least one is invalid, we need to convert it
270
+ if (hasToolCalls && hasInvalidTool) {
271
+ // We need to collect all related messages (this message and any subsequent tool messages)
272
+ const toolSequence = [];
273
+ let sequenceEndIndex = i;
274
+ // Process the current assistant message to get the AIMessage with tool calls
275
+ const formattedMessages = formatAssistantMessage(message);
276
+ toolSequence.push(...formattedMessages);
277
+ // Look ahead for any subsequent assistant messages that might be part of this tool sequence
278
+ let j = i + 1;
279
+ while (j < payload.length && payload[j].role === 'assistant') {
280
+ // Check if this is a continuation of the tool sequence
281
+ let isToolResponse = false;
282
+ const content = payload[j].content;
283
+ if (content && Array.isArray(content)) {
284
+ for (const part of content) {
285
+ if (part?.type === ContentTypes.TOOL_CALL) {
286
+ isToolResponse = true;
287
+ break;
288
+ }
190
289
  }
191
290
  }
192
- catch (e) {
193
- if (typeof _args === 'string') {
194
- args = { input: _args };
195
- }
291
+ if (isToolResponse) {
292
+ // This is part of the tool sequence, add it
293
+ const nextMessages = formatAssistantMessage(payload[j]);
294
+ toolSequence.push(...nextMessages);
295
+ sequenceEndIndex = j;
296
+ j++;
196
297
  }
197
- tool_call.args = args;
198
- if (!lastAIMessage.tool_calls) {
199
- lastAIMessage.tool_calls = [];
298
+ else {
299
+ // This is not part of the tool sequence, stop looking
300
+ break;
200
301
  }
201
- lastAIMessage.tool_calls.push(tool_call);
202
- // Add the corresponding ToolMessage
203
- messages.push(new ToolMessage({
204
- tool_call_id: tool_call.id,
205
- name: tool_call.name,
206
- content: output || '',
207
- }));
208
- }
209
- else if (part.type === ContentTypes.THINK) {
210
- hasReasoning = true;
211
- continue;
212
- }
213
- else if (part.type === ContentTypes.ERROR || part.type === ContentTypes.AGENT_UPDATE) {
214
- continue;
215
302
  }
216
- else {
217
- currentContent.push(part);
303
+ // Convert the sequence to a string
304
+ const bufferString = getBufferString(toolSequence);
305
+ messages.push(new AIMessage({ content: bufferString }));
306
+ // Skip the messages we've already processed
307
+ i = sequenceEndIndex;
308
+ // Update the index mapping for this sequence
309
+ const resultIndices = [messages.length - 1];
310
+ for (let k = i; k >= i && k <= sequenceEndIndex; k++) {
311
+ indexMapping[k] = resultIndices;
218
312
  }
313
+ continue;
219
314
  }
220
315
  }
221
- if (hasReasoning && currentContent.length > 0) {
222
- const content = currentContent
223
- .reduce((acc, curr) => {
224
- if (curr.type === ContentTypes.TEXT) {
225
- return `${acc}${curr[ContentTypes.TEXT] || ''}\n`;
226
- }
227
- return acc;
228
- }, '')
229
- .trim();
230
- if (content) {
231
- messages.push(new AIMessage({ content }));
232
- }
233
- }
234
- else if (currentContent.length > 0) {
235
- messages.push(new AIMessage({ content: currentContent }));
236
- }
316
+ // Process the assistant message using the helper function
317
+ const formattedMessages = formatAssistantMessage(message);
318
+ messages.push(...formattedMessages);
237
319
  // Update the index mapping for this assistant message
238
320
  // Store all indices that were created from this original message
239
321
  const endMessageIndex = messages.length;
@@ -312,7 +394,6 @@ const formatContentStrings = (payload) => {
312
394
  function shiftIndexTokenCountMap(indexTokenCountMap, instructionsTokenCount) {
313
395
  // Create a new map to avoid modifying the original
314
396
  const shiftedMap = {};
315
- // Add the system message token count at index 0
316
397
  shiftedMap[0] = instructionsTokenCount;
317
398
  // Shift all existing indices by 1
318
399
  for (const [indexStr, tokenCount] of Object.entries(indexTokenCountMap)) {
@@ -1 +1 @@
1
- {"version":3,"file":"format.mjs","sources":["../../../src/messages/format.ts"],"sourcesContent":["import { ToolMessage, BaseMessage } from '@langchain/core/messages';\nimport { HumanMessage, AIMessage, SystemMessage } from '@langchain/core/messages';\nimport { MessageContentImageUrl } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { MessageContentComplex } from '@/types';\nimport { Providers, ContentTypes } from '@/common';\n\ninterface VisionMessageParams {\n message: {\n role: string;\n content: string;\n name?: string;\n [key: string]: any;\n };\n image_urls: MessageContentImageUrl[];\n endpoint?: Providers;\n}\n\n/**\n * Formats a message to OpenAI Vision API payload format.\n *\n * @param {VisionMessageParams} params - The parameters for formatting.\n * @returns {Object} - The formatted message.\n */\nexport const formatVisionMessage = ({ message, image_urls, endpoint }: VisionMessageParams): {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n} => {\n // Create a new object to avoid mutating the input\n const result: {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n } = {\n ...message,\n content: [] as MessageContentComplex[]\n };\n \n if (endpoint === Providers.ANTHROPIC) {\n result.content = [\n ...image_urls, \n { type: ContentTypes.TEXT, text: message.content }\n ] as MessageContentComplex[];\n return result;\n }\n\n result.content = [\n { type: ContentTypes.TEXT, text: message.content }, \n ...image_urls\n ] as MessageContentComplex[];\n\n return result;\n};\n\ninterface MessageInput {\n role?: string;\n _name?: string;\n sender?: string;\n text?: string;\n content?: string | MessageContentComplex[];\n image_urls?: MessageContentImageUrl[];\n lc_id?: string[];\n [key: string]: any;\n}\n\ninterface FormatMessageParams {\n message: MessageInput;\n userName?: string;\n assistantName?: string;\n endpoint?: Providers;\n langChain?: boolean;\n}\n\ninterface FormattedMessage {\n role: string;\n content: string | MessageContentComplex[];\n name?: string;\n [key: string]: any;\n}\n\n/**\n * Formats a message to OpenAI payload format based on the provided options.\n *\n * @param {FormatMessageParams} params - The parameters for formatting.\n * @returns {FormattedMessage | HumanMessage | AIMessage | SystemMessage} - The formatted message.\n */\nexport const formatMessage = ({ \n message, \n userName, \n assistantName, \n endpoint, \n langChain = false \n}: FormatMessageParams): FormattedMessage | HumanMessage | AIMessage | SystemMessage => {\n let { role: _role, _name, sender, text, content: _content, lc_id } = message;\n if (lc_id && lc_id[2] && !langChain) {\n const roleMapping: Record<string, string> = {\n SystemMessage: 'system',\n HumanMessage: 'user',\n AIMessage: 'assistant',\n };\n _role = roleMapping[lc_id[2]] || _role;\n }\n const role = _role ?? (sender && sender?.toLowerCase() === 'user' ? 'user' : 'assistant');\n const content = _content ?? text ?? '';\n const formattedMessage: FormattedMessage = {\n role,\n content,\n };\n\n const { image_urls } = message;\n if (Array.isArray(image_urls) && image_urls.length > 0 && role === 'user') {\n return formatVisionMessage({\n message: {\n ...formattedMessage,\n content: typeof formattedMessage.content === 'string' ? formattedMessage.content : ''\n },\n image_urls,\n endpoint,\n });\n }\n\n if (_name) {\n formattedMessage.name = _name;\n }\n\n if (userName && formattedMessage.role === 'user') {\n formattedMessage.name = userName;\n }\n\n if (assistantName && formattedMessage.role === 'assistant') {\n formattedMessage.name = assistantName;\n }\n\n if (formattedMessage.name) {\n // Conform to API regex: ^[a-zA-Z0-9_-]{1,64}$\n // https://community.openai.com/t/the-format-of-the-name-field-in-the-documentation-is-incorrect/175684/2\n formattedMessage.name = formattedMessage.name.replace(/[^a-zA-Z0-9_-]/g, '_');\n\n if (formattedMessage.name.length > 64) {\n formattedMessage.name = formattedMessage.name.substring(0, 64);\n }\n }\n\n if (!langChain) {\n return formattedMessage;\n }\n\n if (role === 'user') {\n return new HumanMessage(formattedMessage);\n } else if (role === 'assistant') {\n return new AIMessage(formattedMessage);\n } else {\n return new SystemMessage(formattedMessage);\n }\n};\n\n/**\n * Formats an array of messages for LangChain.\n *\n * @param {Array<MessageInput>} messages - The array of messages to format.\n * @param {Omit<FormatMessageParams, 'message' | 'langChain'>} formatOptions - The options for formatting each message.\n * @returns {Array<HumanMessage | AIMessage | SystemMessage>} - The array of formatted LangChain messages.\n */\nexport const formatLangChainMessages = (\n messages: Array<MessageInput>, \n formatOptions: Omit<FormatMessageParams, 'message' | 'langChain'>\n): Array<HumanMessage | AIMessage | SystemMessage> => {\n return messages.map((msg) => {\n const formatted = formatMessage({ ...formatOptions, message: msg, langChain: true });\n return formatted as HumanMessage | AIMessage | SystemMessage;\n });\n};\n\ninterface LangChainMessage {\n lc_kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n [key: string]: any;\n}\n\n/**\n * Formats a LangChain message object by merging properties from `lc_kwargs` or `kwargs` and `additional_kwargs`.\n *\n * @param {LangChainMessage} message - The message object to format.\n * @returns {Record<string, any>} The formatted LangChain message.\n */\nexport const formatFromLangChain = (message: LangChainMessage): Record<string, any> => {\n const kwargs = message.lc_kwargs ?? message.kwargs ?? {};\n const { additional_kwargs = {}, ...message_kwargs } = kwargs;\n return {\n ...message_kwargs,\n ...additional_kwargs,\n };\n};\n\ninterface TMessage {\n role?: string;\n content?: string | Array<{\n type: ContentTypes;\n [ContentTypes.TEXT]?: string;\n text?: string;\n tool_call_ids?: string[];\n [key: string]: any;\n }>;\n [key: string]: any;\n}\n\ninterface ToolCallPart {\n type: ContentTypes.TOOL_CALL;\n tool_call: {\n id: string;\n name: string;\n args: string | Record<string, unknown>;\n output?: string;\n [key: string]: any;\n };\n}\n\n/**\n * Formats an array of messages for LangChain, handling tool calls and creating ToolMessage instances.\n *\n * @param {Array<Partial<TMessage>>} payload - The array of messages to format.\n * @param {Record<number, number>} [indexTokenCountMap] - Optional map of message indices to token counts.\n * @returns {Object} - Object containing formatted messages and updated indexTokenCountMap if provided.\n */\nexport const formatAgentMessages = (\n payload: Array<Partial<TMessage>>, \n indexTokenCountMap?: Record<number, number>\n): {\n messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>;\n indexTokenCountMap?: Record<number, number>;\n} => {\n const messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage> = [];\n // If indexTokenCountMap is provided, create a new map to track the updated indices\n const updatedIndexTokenCountMap: Record<number, number> = {};\n // Keep track of the mapping from original payload indices to result indices\n const indexMapping: Record<number, number[]> = {};\n\n for (let i = 0; i < payload.length; i++) {\n const message = payload[i];\n // Q: Store the current length of messages to track where this payload message starts in the result?\n // const startIndex = messages.length;\n if (typeof message.content === 'string') {\n message.content = [{ type: ContentTypes.TEXT, [ContentTypes.TEXT]: message.content }];\n }\n if (message.role !== 'assistant') {\n messages.push(formatMessage({ \n message: message as MessageInput, \n langChain: true \n }) as HumanMessage | AIMessage | SystemMessage);\n \n // Update the index mapping for this message\n indexMapping[i] = [messages.length - 1];\n continue;\n }\n\n // For assistant messages, track the starting index before processing\n const startMessageIndex = messages.length;\n\n let currentContent: any[] = [];\n let lastAIMessage: AIMessage | null = null;\n\n let hasReasoning = false;\n if (Array.isArray(message.content)) {\n for (const part of message.content) {\n if (part.type === ContentTypes.TEXT && part.tool_call_ids) {\n /*\n If there's pending content, it needs to be aggregated as a single string to prepare for tool calls.\n For Anthropic models, the \"tool_calls\" field on a message is only respected if content is a string.\n */\n if (currentContent.length > 0) {\n let content = currentContent.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '');\n content = `${content}\\n${part[ContentTypes.TEXT] ?? part.text ?? ''}`.trim();\n lastAIMessage = new AIMessage({ content });\n messages.push(lastAIMessage);\n currentContent = [];\n continue;\n }\n\n // Create a new AIMessage with this text and prepare for tool calls\n lastAIMessage = new AIMessage({\n content: part.text || '',\n });\n\n messages.push(lastAIMessage);\n } else if (part.type === ContentTypes.TOOL_CALL) {\n if (!lastAIMessage) {\n throw new Error('Invalid tool call structure: No preceding AIMessage with tool_call_ids');\n }\n\n // Note: `tool_calls` list is defined when constructed by `AIMessage` class, and outputs should be excluded from it\n const { output, args: _args, ...tool_call } = (part.tool_call as any);\n // TODO: investigate; args as dictionary may need to be providers-or-tool-specific\n let args: any = _args;\n try {\n if (typeof _args === 'string') {\n args = JSON.parse(_args);\n }\n } catch (e) {\n if (typeof _args === 'string') {\n args = { input: _args };\n }\n }\n\n tool_call.args = args;\n if (!lastAIMessage.tool_calls) {\n lastAIMessage.tool_calls = [];\n }\n lastAIMessage.tool_calls.push(tool_call as ToolCall);\n\n // Add the corresponding ToolMessage\n messages.push(\n new ToolMessage({\n tool_call_id: tool_call.id,\n name: tool_call.name,\n content: output || '',\n }),\n );\n } else if (part.type === ContentTypes.THINK) {\n hasReasoning = true;\n continue;\n } else if (part.type === ContentTypes.ERROR || part.type === ContentTypes.AGENT_UPDATE) {\n continue;\n } else {\n currentContent.push(part);\n }\n }\n }\n\n if (hasReasoning && currentContent.length > 0) {\n const content = currentContent\n .reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '')\n .trim();\n \n if (content) {\n messages.push(new AIMessage({ content }));\n }\n } else if (currentContent.length > 0) {\n messages.push(new AIMessage({ content: currentContent }));\n }\n \n // Update the index mapping for this assistant message\n // Store all indices that were created from this original message\n const endMessageIndex = messages.length;\n const resultIndices = [];\n for (let j = startMessageIndex; j < endMessageIndex; j++) {\n resultIndices.push(j);\n }\n indexMapping[i] = resultIndices;\n }\n\n // Update the token count map if it was provided\n if (indexTokenCountMap) {\n for (let originalIndex = 0; originalIndex < payload.length; originalIndex++) {\n const resultIndices = indexMapping[originalIndex] || [];\n const tokenCount = indexTokenCountMap[originalIndex];\n \n if (tokenCount !== undefined) {\n if (resultIndices.length === 1) {\n // Simple 1:1 mapping\n updatedIndexTokenCountMap[resultIndices[0]] = tokenCount;\n } else if (resultIndices.length > 1) {\n // If one message was split into multiple, distribute the token count\n // This is a simplification - in reality, you might want a more sophisticated distribution\n const countPerMessage = Math.floor(tokenCount / resultIndices.length);\n resultIndices.forEach((resultIndex, idx) => {\n if (idx === resultIndices.length - 1) {\n // Give any remainder to the last message\n updatedIndexTokenCountMap[resultIndex] = tokenCount - (countPerMessage * (resultIndices.length - 1));\n } else {\n updatedIndexTokenCountMap[resultIndex] = countPerMessage;\n }\n });\n }\n }\n }\n }\n\n return {\n messages,\n indexTokenCountMap: indexTokenCountMap ? updatedIndexTokenCountMap : undefined\n };\n};\n\n/**\n * Formats an array of messages for LangChain, making sure all content fields are strings\n * @param {Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>} payload - The array of messages to format.\n * @returns {Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>} - The array of formatted LangChain messages, including ToolMessages for tool calls.\n */\nexport const formatContentStrings = (payload: Array<BaseMessage>): Array<BaseMessage> => {\n // Create a copy of the payload to avoid modifying the original\n const result = [...payload];\n\n for (const message of result) {\n if (typeof message.content === 'string') {\n continue;\n }\n\n if (!Array.isArray(message.content)) {\n continue;\n }\n\n // Reduce text types to a single string, ignore all other types\n const content = message.content.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '');\n\n message.content = content.trim();\n }\n\n return result;\n};\n\n/**\n * Adds a value at key 0 for system messages and shifts all key indices by one in an indexTokenCountMap.\n * This is useful when adding a system message at the beginning of a conversation.\n * \n * @param indexTokenCountMap - The original map of message indices to token counts\n * @param instructionsTokenCount - The token count for the system message to add at index 0\n * @returns A new map with the system message at index 0 and all other indices shifted by 1\n */\nexport function shiftIndexTokenCountMap(\n indexTokenCountMap: Record<number, number>,\n instructionsTokenCount: number\n): Record<number, number> {\n // Create a new map to avoid modifying the original\n const shiftedMap: Record<number, number> = {};\n \n // Add the system message token count at index 0\n shiftedMap[0] = instructionsTokenCount;\n \n // Shift all existing indices by 1\n for (const [indexStr, tokenCount] of Object.entries(indexTokenCountM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AK,MAAM,OAAO,IAAI,MAAM,EAAE;AAC5B,QAAA,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,EAAE;YACvC;;QAGF,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;YACnC;;;AAIF,QAAA,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,KAAI;YACnD,IAAI,IAAI,CAAC,IAAI,KAAK,YAAY,CAAC,IAAI,EAAE;AACnC,gBAAA,OAAO,CAAG,EAAA,GAAG,CAAG,EAAA,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,EAAE,CAAA,EAAA,CAAI;;AAEnD,YAAA,OAAO,GAAG;SACX,EAAE,EAAE,CAAC;AAEN,QAAA,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC,IAAI,EAAE;;AAGlC,IAAA,OAAO,MAAM;AACf;AAEA;;;;;;;AAOG;AACa,SAAA,uBAAuB,CACrC,kBAA0C,EAC1C,sBAA8B,EAAA;;IAG9B,MAAM,UAAU,GAA2B,EAAE;;AAG7C,IAAA,UAAU,CAAC,CAAC,CAAC,GAAG,sBAAsB;;AAGtC,IAAA,KAAK,MAAM,CAAC,QAAQ,EAAE,UAAU,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,kBAAkB,CAAC,EAAE;AACvE,QAAA,MAAM,KAAK,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC9B,QAAA,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,UAAU;;AAGpC,IAAA,OAAO,UAAU;AACnB;;;;"}
1
+ {"version":3,"file":"format.mjs","sources":["../../../src/messages/format.ts"],"sourcesContent":["import { ToolMessage, BaseMessage } from '@langchain/core/messages';\nimport { HumanMessage, AIMessage, SystemMessage, getBufferString } from '@langchain/core/messages';\nimport type { MessageContentImageUrl } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { MessageContentComplex, ToolCallPart, TPayload, TMessage } from '@/types';\nimport { Providers, ContentTypes } from '@/common';\n\ninterface VisionMessageParams {\n message: {\n role: string;\n content: string;\n name?: string;\n [key: string]: any;\n };\n image_urls: MessageContentImageUrl[];\n endpoint?: Providers;\n}\n\n/**\n * Formats a message to OpenAI Vision API payload format.\n *\n * @param {VisionMessageParams} params - The parameters for formatting.\n * @returns {Object} - The formatted message.\n */\nexport const formatVisionMessage = ({ message, image_urls, endpoint }: VisionMessageParams): {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n} => {\n // Create a new object to avoid mutating the input\n const result: {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n } = {\n ...message,\n content: [] as MessageContentComplex[]\n };\n \n if (endpoint === Providers.ANTHROPIC) {\n result.content = [\n ...image_urls, \n { type: ContentTypes.TEXT, text: message.content }\n ] as MessageContentComplex[];\n return result;\n }\n\n result.content = [\n { type: ContentTypes.TEXT, text: message.content }, \n ...image_urls\n ] as MessageContentComplex[];\n\n return result;\n};\n\ninterface MessageInput {\n role?: string;\n _name?: string;\n sender?: string;\n text?: string;\n content?: string | MessageContentComplex[];\n image_urls?: MessageContentImageUrl[];\n lc_id?: string[];\n [key: string]: any;\n}\n\ninterface FormatMessageParams {\n message: MessageInput;\n userName?: string;\n assistantName?: string;\n endpoint?: Providers;\n langChain?: boolean;\n}\n\ninterface FormattedMessage {\n role: string;\n content: string | MessageContentComplex[];\n name?: string;\n [key: string]: any;\n}\n\n/**\n * Formats a message to OpenAI payload format based on the provided options.\n *\n * @param {FormatMessageParams} params - The parameters for formatting.\n * @returns {FormattedMessage | HumanMessage | AIMessage | SystemMessage} - The formatted message.\n */\nexport const formatMessage = ({ \n message, \n userName, \n assistantName, \n endpoint, \n langChain = false \n}: FormatMessageParams): FormattedMessage | HumanMessage | AIMessage | SystemMessage => {\n let { role: _role, _name, sender, text, content: _content, lc_id } = message;\n if (lc_id && lc_id[2] && !langChain) {\n const roleMapping: Record<string, string> = {\n SystemMessage: 'system',\n HumanMessage: 'user',\n AIMessage: 'assistant',\n };\n _role = roleMapping[lc_id[2]] || _role;\n }\n const role = _role ?? (sender && sender?.toLowerCase() === 'user' ? 'user' : 'assistant');\n const content = _content ?? text ?? '';\n const formattedMessage: FormattedMessage = {\n role,\n content,\n };\n\n const { image_urls } = message;\n if (Array.isArray(image_urls) && image_urls.length > 0 && role === 'user') {\n return formatVisionMessage({\n message: {\n ...formattedMessage,\n content: typeof formattedMessage.content === 'string' ? formattedMessage.content : ''\n },\n image_urls,\n endpoint,\n });\n }\n\n if (_name) {\n formattedMessage.name = _name;\n }\n\n if (userName && formattedMessage.role === 'user') {\n formattedMessage.name = userName;\n }\n\n if (assistantName && formattedMessage.role === 'assistant') {\n formattedMessage.name = assistantName;\n }\n\n if (formattedMessage.name) {\n // Conform to API regex: ^[a-zA-Z0-9_-]{1,64}$\n // https://community.openai.com/t/the-format-of-the-name-field-in-the-documentation-is-incorrect/175684/2\n formattedMessage.name = formattedMessage.name.replace(/[^a-zA-Z0-9_-]/g, '_');\n\n if (formattedMessage.name.length > 64) {\n formattedMessage.name = formattedMessage.name.substring(0, 64);\n }\n }\n\n if (!langChain) {\n return formattedMessage;\n }\n\n if (role === 'user') {\n return new HumanMessage(formattedMessage);\n } else if (role === 'assistant') {\n return new AIMessage(formattedMessage);\n } else {\n return new SystemMessage(formattedMessage);\n }\n};\n\n/**\n * Formats an array of messages for LangChain.\n *\n * @param {Array<MessageInput>} messages - The array of messages to format.\n * @param {Omit<FormatMessageParams, 'message' | 'langChain'>} formatOptions - The options for formatting each message.\n * @returns {Array<HumanMessage | AIMessage | SystemMessage>} - The array of formatted LangChain messages.\n */\nexport const formatLangChainMessages = (\n messages: Array<MessageInput>, \n formatOptions: Omit<FormatMessageParams, 'message' | 'langChain'>\n): Array<HumanMessage | AIMessage | SystemMessage> => {\n return messages.map((msg) => {\n const formatted = formatMessage({ ...formatOptions, message: msg, langChain: true });\n return formatted as HumanMessage | AIMessage | SystemMessage;\n });\n};\n\ninterface LangChainMessage {\n lc_kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n [key: string]: any;\n}\n\n/**\n * Formats a LangChain message object by merging properties from `lc_kwargs` or `kwargs` and `additional_kwargs`.\n *\n * @param {LangChainMessage} message - The message object to format.\n * @returns {Record<string, any>} The formatted LangChain message.\n */\nexport const formatFromLangChain = (message: LangChainMessage): Record<string, any> => {\n const kwargs = message.lc_kwargs ?? message.kwargs ?? {};\n const { additional_kwargs = {}, ...message_kwargs } = kwargs;\n return {\n ...message_kwargs,\n ...additional_kwargs,\n };\n};\n\n/**\n * Helper function to format an assistant message\n * @param message The message to format\n * @returns Array of formatted messages\n */\nfunction formatAssistantMessage(message: Partial<TMessage>): Array<AIMessage | ToolMessage> {\n const formattedMessages: Array<AIMessage | ToolMessage> = [];\n let currentContent: MessageContentComplex[] = [];\n let lastAIMessage: AIMessage | null = null;\n let hasReasoning = false;\n\n if (Array.isArray(message.content)) {\n for (const part of message.content) {\n if (part.type === ContentTypes.TEXT && part.tool_call_ids) {\n /*\n If there's pending content, it needs to be aggregated as a single string to prepare for tool calls.\n For Anthropic models, the \"tool_calls\" field on a message is only respected if content is a string.\n */\n if (currentContent.length > 0) {\n let content = currentContent.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '');\n content = `${content}\\n${part[ContentTypes.TEXT] ?? part.text ?? ''}`.trim();\n lastAIMessage = new AIMessage({ content });\n formattedMessages.push(lastAIMessage);\n currentContent = [];\n continue;\n }\n // Create a new AIMessage with this text and prepare for tool calls\n lastAIMessage = new AIMessage({\n content: part.text || '',\n });\n formattedMessages.push(lastAIMessage);\n } else if (part?.type === ContentTypes.TOOL_CALL) {\n if (!lastAIMessage) {\n throw new Error('Invalid tool call structure: No preceding AIMessage with tool_call_ids');\n }\n\n // Note: `tool_calls` list is defined when constructed by `AIMessage` class, and outputs should be excluded from it\n const { output, args: _args, ..._tool_call } = (part.tool_call as ToolCallPart);\n const tool_call: ToolCallPart = _tool_call;\n // TODO: investigate; args as dictionary may need to be providers-or-tool-specific\n let args: any = _args;\n try {\n if (typeof _args === 'string') {\n args = JSON.parse(_args);\n }\n } catch (e) {\n if (typeof _args === 'string') {\n args = { input: _args };\n }\n }\n\n tool_call.args = args;\n if (!lastAIMessage.tool_calls) {\n lastAIMessage.tool_calls = [];\n }\n lastAIMessage.tool_calls.push(tool_call as ToolCall);\n\n formattedMessages.push(\n new ToolMessage({\n tool_call_id: tool_call.id ?? '',\n name: tool_call.name,\n content: output || '',\n }),\n );\n } else if (part.type === ContentTypes.THINK) {\n hasReasoning = true;\n continue;\n } else if (part.type === ContentTypes.ERROR || part.type === ContentTypes.AGENT_UPDATE) {\n continue;\n } else {\n currentContent.push(part);\n }\n }\n }\n\n if (hasReasoning && currentContent.length > 0) {\n const content = currentContent\n .reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '')\n .trim();\n \n if (content) {\n formattedMessages.push(new AIMessage({ content }));\n }\n } else if (currentContent.length > 0) {\n formattedMessages.push(new AIMessage({ content: currentContent }));\n }\n\n return formattedMessages;\n}\n\n/**\n * Formats an array of messages for LangChain, handling tool calls and creating ToolMessage instances.\n *\n * @param {TPayload} payload - The array of messages to format.\n * @param {Record<number, number>} [indexTokenCountMap] - Optional map of message indices to token counts.\n * @param {Set<string>} [tools] - Optional set of tool names that are allowed in the request.\n * @returns {Object} - Object containing formatted messages and updated indexTokenCountMap if provided.\n */\nexport const formatAgentMessages = (\n payload: TPayload, \n indexTokenCountMap?: Record<number, number>,\n tools?: Set<string>\n): {\n messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>;\n indexTokenCountMap?: Record<number, number>;\n} => {\n const messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage> = [];\n // If indexTokenCountMap is provided, create a new map to track the updated indices\n const updatedIndexTokenCountMap: Record<number, number> = {};\n // Keep track of the mapping from original payload indices to result indices\n const indexMapping: Record<number, number[]> = {};\n\n // Process messages with tool conversion if tools set is provided\n for (let i = 0; i < payload.length; i++) {\n const message = payload[i];\n // Q: Store the current length of messages to track where this payload message starts in the result?\n // const startIndex = messages.length;\n if (typeof message.content === 'string') {\n message.content = [{ type: ContentTypes.TEXT, [ContentTypes.TEXT]: message.content }];\n }\n if (message.role !== 'assistant') {\n messages.push(formatMessage({ \n message: message as MessageInput, \n langChain: true \n }) as HumanMessage | AIMessage | SystemMessage);\n \n // Update the index mapping for this message\n indexMapping[i] = [messages.length - 1];\n continue;\n }\n\n // For assistant messages, track the starting index before processing\n const startMessageIndex = messages.length;\n\n // If tools set is provided, we need to check if we need to convert tool messages to a string\n if (tools) {\n // First, check if this message contains tool calls\n let hasToolCalls = false;\n let hasInvalidTool = false;\n let toolNames: string[] = [];\n \n const content = message.content;\n if (content && Array.isArray(content)) {\n for (const part of content) {\n if (part?.type === ContentTypes.TOOL_CALL) {\n hasToolCalls = true;\n if (tools.size === 0) {\n hasInvalidTool = true;\n break;\n }\n const toolName = part.tool_call.name;\n toolNames.push(toolName);\n if (!tools.has(toolName)) {\n hasInvalidTool = true;\n }\n }\n }\n }\n \n // If this message has tool calls and at least one is invalid, we need to convert it\n if (hasToolCalls && hasInvalidTool) {\n // We need to collect all related messages (this message and any subsequent tool messages)\n const toolSequence: BaseMessage[] = [];\n let sequenceEndIndex = i;\n \n // Process the current assistant message to get the AIMessage with tool calls\n const formattedMessages = formatAssistantMessage(message);\n toolSequence.push(...formattedMessages);\n \n // Look ahead for any subsequent assistant messages that might be part of this tool sequence\n let j = i + 1;\n while (j < payload.length && payload[j].role === 'assistant') {\n // Check if this is a continuation of the tool sequence\n let isToolResponse = false;\n const content = payload[j].content;\n if (content && Array.isArray(content)) {\n for (const part of content) {\n if (part?.type === ContentTypes.TOOL_CALL) {\n isToolResponse = true;\n break;\n }\n }\n }\n \n if (isToolResponse) {\n // This is part of the tool sequence, add it\n const nextMessages = formatAssistantMessage(payload[j]);\n toolSequence.push(...nextMessages);\n sequenceEndIndex = j;\n j++;\n } else {\n // This is not part of the tool sequence, stop looking\n break;\n }\n }\n \n // Convert the sequence to a string\n const bufferString = getBufferString(toolSequence);\n messages.push(new AIMessage({ content: bufferString }));\n \n // Skip the messages we've already processed\n i = sequenceEndIndex;\n \n // Update the index mapping for this sequence\n const resultIndices = [messages.length - 1];\n for (let k = i; k >= i && k <= sequenceEndIndex; k++) {\n indexMapping[k] = resultIndices;\n }\n \n continue;\n }\n }\n\n // Process the assistant message using the helper function\n const formattedMessages = formatAssistantMessage(message);\n messages.push(...formattedMessages);\n \n // Update the index mapping for this assistant message\n // Store all indices that were created from this original message\n const endMessageIndex = messages.length;\n const resultIndices = [];\n for (let j = startMessageIndex; j < endMessageIndex; j++) {\n resultIndices.push(j);\n }\n indexMapping[i] = resultIndices;\n }\n\n // Update the token count map if it was provided\n if (indexTokenCountMap) {\n for (let originalIndex = 0; originalIndex < payload.length; originalIndex++) {\n const resultIndices = indexMapping[originalIndex] || [];\n const tokenCount = indexTokenCountMap[originalIndex];\n \n if (tokenCount !== undefined) {\n if (resultIndices.length === 1) {\n // Simple 1:1 mapping\n updatedIndexTokenCountMap[resultIndices[0]] = tokenCount;\n } else if (resultIndices.length > 1) {\n // If one message was split into multiple, distribute the token count\n // This is a simplification - in reality, you might want a more sophisticated distribution\n const countPerMessage = Math.floor(tokenCount / resultIndices.length);\n resultIndices.forEach((resultIndex, idx) => {\n if (idx === resultIndices.length - 1) {\n // Give any remainder to the last message\n updatedIndexTokenCountMap[resultIndex] = tokenCount - (countPerMessage * (resultIndices.length - 1));\n } else {\n updatedIndexTokenCountMap[resultIndex] = countPerMessage;\n }\n });\n }\n }\n }\n }\n\n return {\n messages,\n indexTokenCountMap: indexTokenCountMap ? updatedIndexTokenCountMap : undefined\n };\n};\n\n/**\n * Formats an array of messages for LangChain, making sure all content fields are strings\n * @param {Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>} payload - The array of messages to format.\n * @returns {Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>} - The array of formatted LangChain messages, including ToolMessages for tool calls.\n */\nexport const formatContentStrings = (payload: Array<BaseMessage>): Array<BaseMessage> => {\n // Create a copy of the payload to avoid modifying the original\n const result = [...payload];\n\n for (const message of result) {\n if (typeof message.content === 'string') {\n continue;\n }\n\n if (!Array.isArray(message.content)) {\n continue;\n }\n\n // Reduce text types to a single string, ignore all other types\n const content = message.content.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${curr[ContentTypes.TEXT] || ''}\\n`;\n }\n return acc;\n }, '');\n\n message.content = content.trim();\n }\n\n return result;\n};\n\n/**\n * Adds a value at key 0 for system messages and shifts all key indices by one in an indexTokenCountMap.\n * This is useful when adding a system message at the beginning of a conversation.\n * \n * @param indexTokenCountMap - The original map of message indices to token counts\n * @param instructionsTokenCount - The token count for the system message to add at index 0\n * @returns A new map with the system message at index 0 and all other indices shifted by 1\n */\nexport function shiftIndexTokenCountMap(\n indexTokenCountMap: Record<number, number>,\n instructionsTokenCount: number\n): Record<number, number> {\n // Create a new map to avoid modifying the original\n const shiftedMap: Record<number, number> = {};\n shiftedMap[0] = instructionsTokenCount;\n \n // Shift all existing indices by 1\n for (const [indexStr, tokenCount] of Object.entries(indexTokenCountMap)) {\n const index = Number(indexStr);\n shiftedMap[index + 1] = tokenCount;\n }\n \n return shiftedMap;\n}\n"],"names":[],"mappings":";;;AAkBA;;;;;AAKG;AACI,MAAM,mBAAmB,GAAG,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAuB,KAKtF;;AAEF,IAAA,MAAM,MAAM,GAKR;AACF,QAAA,GAAG,OAAO;AACV,QAAA,OAAO,EAAE;KACV;AAED,IAAA,IAAI,QAAQ,KA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AC;AAEN,QAAA,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC,IAAI,EAAE;;AAGlC,IAAA,OAAO,MAAM;AACf;AAEA;;;;;;;AAOG;AACa,SAAA,uBAAuB,CACrC,kBAA0C,EAC1C,sBAA8B,EAAA;;IAG9B,MAAM,UAAU,GAA2B,EAAE;AAC7C,IAAA,UAAU,CAAC,CAAC,CAAC,GAAG,sBAAsB;;AAGtC,IAAA,KAAK,MAAM,CAAC,QAAQ,EAAE,UAAU,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,kBAAkB,CAAC,EAAE;AACvE,QAAA,MAAM,KAAK,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC9B,QAAA,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,UAAU;;AAGpC,IAAA,OAAO,UAAU;AACnB;;;;"}
@@ -1,8 +1,8 @@
1
1
  import { ToolMessage, BaseMessage } from '@langchain/core/messages';
2
2
  import { HumanMessage, AIMessage, SystemMessage } from '@langchain/core/messages';
3
- import { MessageContentImageUrl } from '@langchain/core/messages';
4
- import type { MessageContentComplex } from '@/types';
5
- import { Providers, ContentTypes } from '@/common';
3
+ import type { MessageContentImageUrl } from '@langchain/core/messages';
4
+ import type { MessageContentComplex, TPayload } from '@/types';
5
+ import { Providers } from '@/common';
6
6
  interface VisionMessageParams {
7
7
  message: {
8
8
  role: string;
@@ -81,24 +81,15 @@ interface LangChainMessage {
81
81
  * @returns {Record<string, any>} The formatted LangChain message.
82
82
  */
83
83
  export declare const formatFromLangChain: (message: LangChainMessage) => Record<string, any>;
84
- interface TMessage {
85
- role?: string;
86
- content?: string | Array<{
87
- type: ContentTypes;
88
- text?: string;
89
- tool_call_ids?: string[];
90
- [key: string]: any;
91
- }>;
92
- [key: string]: any;
93
- }
94
84
  /**
95
85
  * Formats an array of messages for LangChain, handling tool calls and creating ToolMessage instances.
96
86
  *
97
- * @param {Array<Partial<TMessage>>} payload - The array of messages to format.
87
+ * @param {TPayload} payload - The array of messages to format.
98
88
  * @param {Record<number, number>} [indexTokenCountMap] - Optional map of message indices to token counts.
89
+ * @param {Set<string>} [tools] - Optional set of tool names that are allowed in the request.
99
90
  * @returns {Object} - Object containing formatted messages and updated indexTokenCountMap if provided.
100
91
  */
101
- export declare const formatAgentMessages: (payload: Array<Partial<TMessage>>, indexTokenCountMap?: Record<number, number>) => {
92
+ export declare const formatAgentMessages: (payload: TPayload, indexTokenCountMap?: Record<number, number>, tools?: Set<string>) => {
102
93
  messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>;
103
94
  indexTokenCountMap?: Record<number, number>;
104
95
  };
@@ -202,13 +202,42 @@ export type BedrockReasoningContentText = {
202
202
  signature?: string;
203
203
  };
204
204
  };
205
- export type MessageContentComplex = (ThinkingContentText | AgentUpdate | ReasoningContentText | MessageContentText | MessageContentImageUrl | (Record<string, any> & {
205
+ /**
206
+ * A call to a tool.
207
+ */
208
+ export type ToolCallPart = {
209
+ /** Type ("tool_call") according to Assistants Tool Call Structure */
210
+ type: ContentTypes.TOOL_CALL;
211
+ /** The name of the tool to be called */
212
+ name: string;
213
+ /** The arguments to the tool call */
214
+ args?: string | Record<string, any>;
215
+ /** If provided, an identifier associated with the tool call */
216
+ id?: string;
217
+ /** If provided, the output of the tool call */
218
+ output?: string;
219
+ /** Auth URL */
220
+ auth?: string;
221
+ /** Expiration time */
222
+ expires_at?: number;
223
+ };
224
+ export type ToolCallContent = {
225
+ type: ContentTypes.TOOL_CALL;
226
+ tool_call?: ToolCallPart;
227
+ };
228
+ export type MessageContentComplex = (ThinkingContentText | AgentUpdate | ToolCallContent | ReasoningContentText | MessageContentText | MessageContentImageUrl | (Record<string, any> & {
206
229
  type?: 'text' | 'image_url' | 'think' | 'thinking' | string;
207
230
  }) | (Record<string, any> & {
208
231
  type?: never;
209
232
  })) & {
210
233
  tool_call_ids?: string[];
211
234
  };
235
+ export interface TMessage {
236
+ role?: string;
237
+ content?: MessageContentComplex[] | string;
238
+ [key: string]: any;
239
+ }
240
+ export type TPayload = Array<Partial<TMessage>>;
212
241
  export type CustomChunk = Partial<OpenAITypes.ChatCompletionChunk> & {
213
242
  choices?: Partial<Array<Partial<OpenAITypes.Chat.Completions.ChatCompletionChunk.Choice> & {
214
243
  delta?: Partial<OpenAITypes.Chat.Completions.ChatCompletionChunk.Choice.Delta> & {
@@ -1,7 +1,7 @@
1
1
  import type { RunnableToolLike } from '@langchain/core/runnables';
2
2
  import type { StructuredToolInterface } from '@langchain/core/tools';
3
3
  import type { ToolCall } from '@langchain/core/messages/tool';
4
- import { ContentTypes, EnvVar } from '@/common';
4
+ import { EnvVar } from '@/common';
5
5
  /** Replacement type for `import type { ToolCall } from '@langchain/core/messages/tool'` in order to have stringified args typed */
6
6
  export type CustomToolCall = {
7
7
  name: string;
@@ -33,10 +33,6 @@ export type ToolEndEvent = {
33
33
  /** The content index of the tool call */
34
34
  index: number;
35
35
  };
36
- export type ToolCallContent = {
37
- type: ContentTypes.TOOL_CALL;
38
- tool_call: ToolCall;
39
- };
40
36
  export type CodeEnvFile = {
41
37
  id: string;
42
38
  name: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@librechat/agents",
3
- "version": "2.2.5",
3
+ "version": "2.2.6",
4
4
  "main": "./dist/cjs/main.cjs",
5
5
  "module": "./dist/esm/main.mjs",
6
6
  "types": "./dist/types/index.d.ts",