@langchain/core 1.1.2 → 1.1.4
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/CHANGELOG.md +18 -0
- package/dist/chat_history.cjs +1 -1
- package/dist/chat_history.js +1 -1
- package/dist/language_models/chat_models.cjs +1 -1
- package/dist/language_models/chat_models.js +1 -1
- package/dist/messages/ai.cjs +6 -48
- package/dist/messages/ai.cjs.map +1 -1
- package/dist/messages/ai.js +6 -48
- package/dist/messages/ai.js.map +1 -1
- package/dist/messages/base.cjs +3 -2
- package/dist/messages/base.cjs.map +1 -1
- package/dist/messages/base.js +3 -2
- package/dist/messages/base.js.map +1 -1
- package/dist/messages/index.cjs +4 -2
- package/dist/messages/index.d.cts +2 -2
- package/dist/messages/index.d.ts +2 -2
- package/dist/messages/index.js +5 -4
- package/dist/messages/transformers.cjs +2 -2
- package/dist/messages/transformers.js +2 -2
- package/dist/messages/utils.cjs +77 -4
- package/dist/messages/utils.cjs.map +1 -1
- package/dist/messages/utils.d.cts +33 -2
- package/dist/messages/utils.d.ts +33 -2
- package/dist/messages/utils.js +77 -5
- package/dist/messages/utils.js.map +1 -1
- package/dist/prompts/chat.cjs +2 -2
- package/dist/prompts/chat.js +2 -2
- package/dist/runnables/base.cjs +3 -3
- package/dist/runnables/base.cjs.map +1 -1
- package/dist/runnables/base.js +1 -1
- package/dist/runnables/base.js.map +1 -1
- package/dist/runnables/graph_mermaid.cjs +2 -1
- package/dist/runnables/graph_mermaid.cjs.map +1 -1
- package/dist/runnables/graph_mermaid.js +3 -1
- package/dist/runnables/graph_mermaid.js.map +1 -1
- package/dist/runnables/history.cjs +1 -1
- package/dist/runnables/history.js +1 -1
- package/dist/runnables/utils.cjs +5 -0
- package/dist/runnables/utils.cjs.map +1 -1
- package/dist/runnables/utils.js +5 -1
- package/dist/runnables/utils.js.map +1 -1
- package/dist/utils/async_caller.cjs +2 -7
- package/dist/utils/async_caller.cjs.map +1 -1
- package/dist/utils/async_caller.js +1 -6
- package/dist/utils/async_caller.js.map +1 -1
- package/dist/utils/is-network-error/index.cjs +27 -0
- package/dist/utils/is-network-error/index.cjs.map +1 -0
- package/dist/utils/is-network-error/index.js +26 -0
- package/dist/utils/is-network-error/index.js.map +1 -0
- package/dist/utils/p-retry/index.cjs +141 -0
- package/dist/utils/p-retry/index.cjs.map +1 -0
- package/dist/utils/p-retry/index.js +141 -0
- package/dist/utils/p-retry/index.js.map +1 -0
- package/dist/utils/testing/message_history.cjs +1 -1
- package/dist/utils/testing/message_history.js +1 -1
- package/dist/utils/types/index.cjs +4 -0
- package/dist/utils/types/index.d.cts +2 -2
- package/dist/utils/types/index.d.ts +2 -2
- package/dist/utils/types/index.js +4 -2
- package/dist/utils/types/zod.cjs +24 -0
- package/dist/utils/types/zod.cjs.map +1 -1
- package/dist/utils/types/zod.d.cts +4 -1
- package/dist/utils/types/zod.d.ts +4 -1
- package/dist/utils/types/zod.js +23 -1
- package/dist/utils/types/zod.js.map +1 -1
- package/package.json +1 -2
package/dist/messages/utils.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { _isMessageFieldWithRole, isBaseMessage } from "./base.js";
|
|
2
2
|
import { ToolMessage } from "./tool.js";
|
|
3
|
-
import {
|
|
3
|
+
import { addLangChainErrorFields } from "../errors/index.js";
|
|
4
|
+
import { _isToolCall } from "../tools/utils.js";
|
|
5
|
+
import { parsePartialJson } from "../utils/json.js";
|
|
4
6
|
import { ChatMessage, ChatMessageChunk } from "./chat.js";
|
|
5
7
|
import { FunctionMessage, FunctionMessageChunk } from "./function.js";
|
|
6
8
|
import { HumanMessage, HumanMessageChunk } from "./human.js";
|
|
7
|
-
import { SystemMessage, SystemMessageChunk } from "./system.js";
|
|
8
|
-
import { addLangChainErrorFields } from "../errors/index.js";
|
|
9
|
-
import { _isToolCall } from "../tools/utils.js";
|
|
10
9
|
import { RemoveMessage } from "./modifier.js";
|
|
10
|
+
import { SystemMessage, SystemMessageChunk } from "./system.js";
|
|
11
|
+
import { AIMessage, AIMessageChunk } from "./ai.js";
|
|
11
12
|
|
|
12
13
|
//#region src/messages/utils.ts
|
|
13
14
|
/**
|
|
@@ -196,7 +197,78 @@ function convertToChunk(message) {
|
|
|
196
197
|
else if (ChatMessage.isInstance(message)) return new ChatMessageChunk({ ...message });
|
|
197
198
|
else throw new Error("Unknown message type.");
|
|
198
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* Collapses an array of tool call chunks into complete tool calls.
|
|
202
|
+
*
|
|
203
|
+
* This function groups tool call chunks by their id and/or index, then attempts to
|
|
204
|
+
* parse and validate the accumulated arguments for each group. Successfully parsed
|
|
205
|
+
* tool calls are returned as valid `ToolCall` objects, while malformed ones are
|
|
206
|
+
* returned as `InvalidToolCall` objects.
|
|
207
|
+
*
|
|
208
|
+
* @param chunks - An array of `ToolCallChunk` objects to collapse
|
|
209
|
+
* @returns An object containing:
|
|
210
|
+
* - `tool_call_chunks`: The original input chunks
|
|
211
|
+
* - `tool_calls`: An array of successfully parsed and validated tool calls
|
|
212
|
+
* - `invalid_tool_calls`: An array of tool calls that failed parsing or validation
|
|
213
|
+
*
|
|
214
|
+
* @remarks
|
|
215
|
+
* Chunks are grouped using the following matching logic:
|
|
216
|
+
* - If a chunk has both an id and index, it matches chunks with the same id and index
|
|
217
|
+
* - If a chunk has only an id, it matches chunks with the same id
|
|
218
|
+
* - If a chunk has only an index, it matches chunks with the same index
|
|
219
|
+
*
|
|
220
|
+
* For each group, the function:
|
|
221
|
+
* 1. Concatenates all `args` strings from the chunks
|
|
222
|
+
* 2. Attempts to parse the concatenated string as JSON
|
|
223
|
+
* 3. Validates that the result is a non-null object with a valid id
|
|
224
|
+
* 4. Creates either a `ToolCall` (if valid) or `InvalidToolCall` (if invalid)
|
|
225
|
+
*/
|
|
226
|
+
function collapseToolCallChunks(chunks) {
|
|
227
|
+
const groupedToolCallChunks = chunks.reduce((acc, chunk) => {
|
|
228
|
+
const matchedChunkIndex = acc.findIndex(([match]) => {
|
|
229
|
+
if ("id" in chunk && chunk.id && "index" in chunk && chunk.index !== void 0) return chunk.id === match.id && chunk.index === match.index;
|
|
230
|
+
if ("id" in chunk && chunk.id) return chunk.id === match.id;
|
|
231
|
+
if ("index" in chunk && chunk.index !== void 0) return chunk.index === match.index;
|
|
232
|
+
return false;
|
|
233
|
+
});
|
|
234
|
+
if (matchedChunkIndex !== -1) acc[matchedChunkIndex].push(chunk);
|
|
235
|
+
else acc.push([chunk]);
|
|
236
|
+
return acc;
|
|
237
|
+
}, []);
|
|
238
|
+
const toolCalls = [];
|
|
239
|
+
const invalidToolCalls = [];
|
|
240
|
+
for (const chunks$1 of groupedToolCallChunks) {
|
|
241
|
+
let parsedArgs = null;
|
|
242
|
+
const name = chunks$1[0]?.name ?? "";
|
|
243
|
+
const joinedArgs = chunks$1.map((c) => c.args || "").join("").trim();
|
|
244
|
+
const argsStr = joinedArgs.length ? joinedArgs : "{}";
|
|
245
|
+
const id = chunks$1[0]?.id;
|
|
246
|
+
try {
|
|
247
|
+
parsedArgs = parsePartialJson(argsStr);
|
|
248
|
+
if (!id || parsedArgs === null || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) throw new Error("Malformed tool call chunk args.");
|
|
249
|
+
toolCalls.push({
|
|
250
|
+
name,
|
|
251
|
+
args: parsedArgs,
|
|
252
|
+
id,
|
|
253
|
+
type: "tool_call"
|
|
254
|
+
});
|
|
255
|
+
} catch {
|
|
256
|
+
invalidToolCalls.push({
|
|
257
|
+
name,
|
|
258
|
+
args: argsStr,
|
|
259
|
+
id,
|
|
260
|
+
error: "Malformed args.",
|
|
261
|
+
type: "invalid_tool_call"
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return {
|
|
266
|
+
tool_call_chunks: chunks,
|
|
267
|
+
tool_calls: toolCalls,
|
|
268
|
+
invalid_tool_calls: invalidToolCalls
|
|
269
|
+
};
|
|
270
|
+
}
|
|
199
271
|
|
|
200
272
|
//#endregion
|
|
201
|
-
export { coerceMessageLikeToMessage, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
|
|
273
|
+
export { coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
|
|
202
274
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["fn: () => T","toolCall: ToolCall | Record<string, unknown>","x: unknown","params:\n | (BaseMessageFields & { type: string } & Record<string, unknown>)\n | SerializedConstructor","type: string","rest: BaseMessageFields & Record<string, unknown>","messageLike: BaseMessageLike","messages: BaseMessage[]","string_messages: string[]","role: string","message: StoredMessage | StoredMessageV1","message: StoredMessage","messages: StoredMessage[]","message: BaseMessage","aiChunkFields: AIMessageChunkFields"],"sources":["../../src/messages/utils.ts"],"sourcesContent":["import { addLangChainErrorFields } from \"../errors/index.js\";\nimport { SerializedConstructor } from \"../load/serializable.js\";\nimport { _isToolCall } from \"../tools/utils.js\";\nimport { AIMessage, AIMessageChunk, AIMessageChunkFields } from \"./ai.js\";\nimport {\n BaseMessageLike,\n BaseMessage,\n isBaseMessage,\n StoredMessage,\n StoredMessageV1,\n BaseMessageFields,\n _isMessageFieldWithRole,\n} from \"./base.js\";\nimport { ChatMessage, ChatMessageFields, ChatMessageChunk } from \"./chat.js\";\nimport {\n FunctionMessage,\n FunctionMessageChunk,\n FunctionMessageFields,\n} from \"./function.js\";\nimport { HumanMessage, HumanMessageChunk } from \"./human.js\";\nimport { RemoveMessage } from \"./modifier.js\";\nimport { SystemMessage, SystemMessageChunk } from \"./system.js\";\nimport { ToolCall, ToolMessage, ToolMessageFields } from \"./tool.js\";\n\nexport type $Expand<T> = T extends infer U ? { [K in keyof U]: U[K] } : never;\n\n/**\n * Extracts the explicitly declared keys from a type T.\n *\n * @template T - The type to extract keys from\n * @returns A union of keys that are not string, number, or symbol\n */\ntype $KnownKeys<T> = {\n [K in keyof T]: string extends K\n ? never\n : number extends K\n ? never\n : symbol extends K\n ? never\n : K;\n}[keyof T];\n\n/**\n * Detects if T has an index signature.\n *\n * @template T - The type to check for index signatures\n * @returns True if T has an index signature, false otherwise\n */\ntype $HasIndexSignature<T> = string extends keyof T\n ? true\n : number extends keyof T\n ? true\n : symbol extends keyof T\n ? true\n : false;\n\n/**\n * Detects if T has an index signature and no known keys.\n *\n * @template T - The type to check for index signatures and no known keys\n * @returns True if T has an index signature and no known keys, false otherwise\n */\ntype $OnlyIndexSignatures<T> = $HasIndexSignature<T> extends true\n ? [$KnownKeys<T>] extends [never]\n ? true\n : false\n : false;\n\n/**\n * Recursively merges two object types T and U, with U taking precedence over T.\n *\n * This utility type performs a deep merge of two object types:\n * - For keys that exist in both T and U:\n * - If both values are objects (Record<string, unknown>), recursively merge them\n * - Otherwise, U's value takes precedence\n * - For keys that exist only in T, use T's value\n * - For keys that exist only in U, use U's value\n *\n * @template T - The first object type to merge\n * @template U - The second object type to merge (takes precedence over T)\n *\n * @example\n * ```ts\n * type ObjectA = {\n * shared: { a: string; b: number };\n * onlyInA: boolean;\n * };\n *\n * type ObjectB = {\n * shared: { b: string; c: Date };\n * onlyInB: symbol;\n * };\n *\n * type Merged = $MergeObjects<ObjectA, ObjectB>;\n * // Result: {\n * // shared: { a: string; b: string; c: Date };\n * // onlyInA: boolean;\n * // onlyInB: symbol;\n * // }\n * ```\n */\nexport type $MergeObjects<T, U> =\n // If U is purely index-signature based, prefer U as a whole\n $OnlyIndexSignatures<U> extends true\n ? U\n : // If T is purely index-signature based, prefer U as a whole (prevents leaking broad index signatures)\n $OnlyIndexSignatures<T> extends true\n ? U\n : {\n [K in keyof T | keyof U]: K extends keyof T\n ? K extends keyof U\n ? T[K] extends Record<string, unknown>\n ? U[K] extends Record<string, unknown>\n ? $MergeObjects<T[K], U[K]>\n : U[K]\n : U[K]\n : T[K]\n : K extends keyof U\n ? U[K]\n : never;\n };\n\n/**\n * Merges two discriminated unions A and B based on a discriminator key (defaults to \"type\").\n * For each possible value of the discriminator across both unions:\n * - If B has a member with that discriminator value, use B's member\n * - Otherwise use A's member with that discriminator value\n * This effectively merges the unions while giving B's members precedence over A's members.\n *\n * @template A - First discriminated union type that extends Record<Key, PropertyKey>\n * @template B - Second discriminated union type that extends Record<Key, PropertyKey>\n * @template Key - The discriminator key property, defaults to \"type\"\n */\nexport type $MergeDiscriminatedUnion<\n A extends Record<Key, PropertyKey>,\n B extends Record<Key, PropertyKey>,\n Key extends PropertyKey = \"type\"\n> = {\n // Create a mapped type over all possible discriminator values from both A and B\n [T in A[Key] | B[Key]]: [Extract<B, Record<Key, T>>] extends [never] // Check if B has a member with this discriminator value\n ? // If B doesn't have this discriminator value, use A's member\n Extract<A, Record<Key, T>>\n : // If B does have this discriminator value, merge A's and B's members (B takes precedence)\n [Extract<A, Record<Key, T>>] extends [never]\n ? Extract<B, Record<Key, T>>\n : $MergeObjects<Extract<A, Record<Key, T>>, Extract<B, Record<Key, T>>>;\n // Index into the mapped type with all possible discriminator values\n // This converts the mapped type back into a union\n}[A[Key] | B[Key]];\n\nexport type Constructor<T> = new (...args: unknown[]) => T;\n\n/**\n * Immediately-invoked function expression.\n *\n * @param fn - The function to execute\n * @returns The result of the function\n */\nexport const iife = <T>(fn: () => T) => fn();\n\nfunction _coerceToolCall(\n toolCall: ToolCall | Record<string, unknown>\n): ToolCall {\n if (_isToolCall(toolCall)) {\n return toolCall;\n } else if (\n typeof toolCall.id === \"string\" &&\n toolCall.type === \"function\" &&\n typeof toolCall.function === \"object\" &&\n toolCall.function !== null &&\n \"arguments\" in toolCall.function &&\n typeof toolCall.function.arguments === \"string\" &&\n \"name\" in toolCall.function &&\n typeof toolCall.function.name === \"string\"\n ) {\n // Handle OpenAI tool call format\n return {\n id: toolCall.id,\n args: JSON.parse(toolCall.function.arguments),\n name: toolCall.function.name,\n type: \"tool_call\",\n };\n } else {\n // TODO: Throw an error?\n return toolCall as unknown as ToolCall;\n }\n}\n\nfunction isSerializedConstructor(x: unknown): x is SerializedConstructor {\n return (\n typeof x === \"object\" &&\n x != null &&\n (x as SerializedConstructor).lc === 1 &&\n Array.isArray((x as SerializedConstructor).id) &&\n (x as SerializedConstructor).kwargs != null &&\n typeof (x as SerializedConstructor).kwargs === \"object\"\n );\n}\n\nfunction _constructMessageFromParams(\n params:\n | (BaseMessageFields & { type: string } & Record<string, unknown>)\n | SerializedConstructor\n) {\n let type: string;\n let rest: BaseMessageFields & Record<string, unknown>;\n // Support serialized messages\n if (isSerializedConstructor(params)) {\n const className = params.id.at(-1);\n if (className === \"HumanMessage\" || className === \"HumanMessageChunk\") {\n type = \"user\";\n } else if (className === \"AIMessage\" || className === \"AIMessageChunk\") {\n type = \"assistant\";\n } else if (\n className === \"SystemMessage\" ||\n className === \"SystemMessageChunk\"\n ) {\n type = \"system\";\n } else if (\n className === \"FunctionMessage\" ||\n className === \"FunctionMessageChunk\"\n ) {\n type = \"function\";\n } else if (\n className === \"ToolMessage\" ||\n className === \"ToolMessageChunk\"\n ) {\n type = \"tool\";\n } else {\n type = \"unknown\";\n }\n rest = params.kwargs as BaseMessageFields;\n } else {\n const { type: extractedType, ...otherParams } = params;\n type = extractedType;\n rest = otherParams;\n }\n if (type === \"human\" || type === \"user\") {\n return new HumanMessage(rest);\n } else if (type === \"ai\" || type === \"assistant\") {\n const { tool_calls: rawToolCalls, ...other } = rest;\n if (!Array.isArray(rawToolCalls)) {\n return new AIMessage(rest);\n }\n const tool_calls = rawToolCalls.map(_coerceToolCall);\n return new AIMessage({ ...other, tool_calls });\n } else if (type === \"system\") {\n return new SystemMessage(rest);\n } else if (type === \"developer\") {\n return new SystemMessage({\n ...rest,\n additional_kwargs: {\n ...rest.additional_kwargs,\n __openai_role__: \"developer\",\n },\n });\n } else if (type === \"tool\" && \"tool_call_id\" in rest) {\n return new ToolMessage({\n ...rest,\n content: rest.content,\n tool_call_id: rest.tool_call_id as string,\n name: rest.name,\n });\n } else if (type === \"remove\" && \"id\" in rest && typeof rest.id === \"string\") {\n return new RemoveMessage({ ...rest, id: rest.id });\n } else {\n const error = addLangChainErrorFields(\n new Error(\n `Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\\n\\nReceived: ${JSON.stringify(\n params,\n null,\n 2\n )}`\n ),\n \"MESSAGE_COERCION_FAILURE\"\n );\n throw error;\n }\n}\n\nexport function coerceMessageLikeToMessage(\n messageLike: BaseMessageLike\n): BaseMessage {\n if (typeof messageLike === \"string\") {\n return new HumanMessage(messageLike);\n } else if (isBaseMessage(messageLike)) {\n return messageLike;\n }\n if (Array.isArray(messageLike)) {\n const [type, content] = messageLike;\n return _constructMessageFromParams({ type, content });\n } else if (_isMessageFieldWithRole(messageLike)) {\n const { role: type, ...rest } = messageLike;\n return _constructMessageFromParams({ ...rest, type });\n } else {\n return _constructMessageFromParams(messageLike);\n }\n}\n\n/**\n * This function is used by memory classes to get a string representation\n * of the chat message history, based on the message content and role.\n */\nexport function getBufferString(\n messages: BaseMessage[],\n humanPrefix = \"Human\",\n aiPrefix = \"AI\"\n): string {\n const string_messages: string[] = [];\n for (const m of messages) {\n let role: string;\n if (m._getType() === \"human\") {\n role = humanPrefix;\n } else if (m._getType() === \"ai\") {\n role = aiPrefix;\n } else if (m._getType() === \"system\") {\n role = \"System\";\n } else if (m._getType() === \"tool\") {\n role = \"Tool\";\n } else if (m._getType() === \"generic\") {\n role = (m as ChatMessage).role;\n } else {\n throw new Error(`Got unsupported message type: ${m._getType()}`);\n }\n const nameStr = m.name ? `${m.name}, ` : \"\";\n const readableContent =\n typeof m.content === \"string\"\n ? m.content\n : JSON.stringify(m.content, null, 2);\n string_messages.push(`${role}: ${nameStr}${readableContent}`);\n }\n return string_messages.join(\"\\n\");\n}\n\n/**\n * Maps messages from an older format (V1) to the current `StoredMessage`\n * format. If the message is already in the `StoredMessage` format, it is\n * returned as is. Otherwise, it transforms the V1 message into a\n * `StoredMessage`. This function is important for maintaining\n * compatibility with older message formats.\n */\nfunction mapV1MessageToStoredMessage(\n message: StoredMessage | StoredMessageV1\n): StoredMessage {\n // TODO: Remove this mapper when we deprecate the old message format.\n if ((message as StoredMessage).data !== undefined) {\n return message as StoredMessage;\n } else {\n const v1Message = message as StoredMessageV1;\n return {\n type: v1Message.type,\n data: {\n content: v1Message.text,\n role: v1Message.role,\n name: undefined,\n tool_call_id: undefined,\n },\n };\n }\n}\n\nexport function mapStoredMessageToChatMessage(message: StoredMessage) {\n const storedMessage = mapV1MessageToStoredMessage(message);\n switch (storedMessage.type) {\n case \"human\":\n return new HumanMessage(storedMessage.data);\n case \"ai\":\n return new AIMessage(storedMessage.data);\n case \"system\":\n return new SystemMessage(storedMessage.data);\n case \"function\":\n if (storedMessage.data.name === undefined) {\n throw new Error(\"Name must be defined for function messages\");\n }\n return new FunctionMessage(storedMessage.data as FunctionMessageFields);\n case \"tool\":\n if (storedMessage.data.tool_call_id === undefined) {\n throw new Error(\"Tool call ID must be defined for tool messages\");\n }\n return new ToolMessage(storedMessage.data as ToolMessageFields);\n case \"generic\": {\n if (storedMessage.data.role === undefined) {\n throw new Error(\"Role must be defined for chat messages\");\n }\n return new ChatMessage(storedMessage.data as ChatMessageFields);\n }\n default:\n throw new Error(`Got unexpected type: ${storedMessage.type}`);\n }\n}\n\n/**\n * Transforms an array of `StoredMessage` instances into an array of\n * `BaseMessage` instances. It uses the `mapV1MessageToStoredMessage`\n * function to ensure all messages are in the `StoredMessage` format, then\n * creates new instances of the appropriate `BaseMessage` subclass based\n * on the type of each message. This function is used to prepare stored\n * messages for use in a chat context.\n */\nexport function mapStoredMessagesToChatMessages(\n messages: StoredMessage[]\n): BaseMessage[] {\n return messages.map(mapStoredMessageToChatMessage);\n}\n\n/**\n * Transforms an array of `BaseMessage` instances into an array of\n * `StoredMessage` instances. It does this by calling the `toDict` method\n * on each `BaseMessage`, which returns a `StoredMessage`. This function\n * is used to prepare chat messages for storage.\n */\nexport function mapChatMessagesToStoredMessages(\n messages: BaseMessage[]\n): StoredMessage[] {\n return messages.map((message) => message.toDict());\n}\n\nexport function convertToChunk(message: BaseMessage) {\n const type = message._getType();\n if (type === \"human\") {\n return new HumanMessageChunk({ ...message });\n } else if (type === \"ai\") {\n let aiChunkFields: AIMessageChunkFields = {\n ...message,\n };\n if (\"tool_calls\" in aiChunkFields) {\n aiChunkFields = {\n ...aiChunkFields,\n tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({\n ...tc,\n type: \"tool_call_chunk\",\n index: undefined,\n args: JSON.stringify(tc.args),\n })),\n };\n }\n return new AIMessageChunk({ ...aiChunkFields });\n } else if (type === \"system\") {\n return new SystemMessageChunk({ ...message });\n } else if (type === \"function\") {\n return new FunctionMessageChunk({ ...message });\n } else if (ChatMessage.isInstance(message)) {\n return new ChatMessageChunk({ ...message });\n } else {\n throw new Error(\"Unknown message type.\");\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8JA,MAAa,OAAO,CAAIA,OAAgB,IAAI;AAE5C,SAAS,gBACPC,UACU;AACV,KAAI,YAAY,SAAS,CACvB,QAAO;UAEP,OAAO,SAAS,OAAO,YACvB,SAAS,SAAS,cAClB,OAAO,SAAS,aAAa,YAC7B,SAAS,aAAa,QACtB,eAAe,SAAS,YACxB,OAAO,SAAS,SAAS,cAAc,YACvC,UAAU,SAAS,YACnB,OAAO,SAAS,SAAS,SAAS,SAGlC,QAAO;EACL,IAAI,SAAS;EACb,MAAM,KAAK,MAAM,SAAS,SAAS,UAAU;EAC7C,MAAM,SAAS,SAAS;EACxB,MAAM;CACP;KAGD,QAAO;AAEV;AAED,SAAS,wBAAwBC,GAAwC;AACvE,QACE,OAAO,MAAM,YACb,KAAK,QACJ,EAA4B,OAAO,KACpC,MAAM,QAAS,EAA4B,GAAG,IAC7C,EAA4B,UAAU,QACvC,OAAQ,EAA4B,WAAW;AAElD;AAED,SAAS,4BACPC,QAGA;CACA,IAAIC;CACJ,IAAIC;AAEJ,KAAI,wBA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AQ,CACxC,QAAO,IAAI,iBAAiB,EAAE,GAAG,QAAS;KAE1C,OAAM,IAAI,MAAM;AAEnB"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":["fn: () => T","toolCall: ToolCall | Record<string, unknown>","x: unknown","params:\n | (BaseMessageFields & { type: string } & Record<string, unknown>)\n | SerializedConstructor","type: string","rest: BaseMessageFields & Record<string, unknown>","messageLike: BaseMessageLike","messages: BaseMessage[]","string_messages: string[]","role: string","message: StoredMessage | StoredMessageV1","message: StoredMessage","messages: StoredMessage[]","message: BaseMessage","aiChunkFields: AIMessageChunkFields","chunks: ToolCallChunk[]","toolCalls: ToolCall[]","invalidToolCalls: InvalidToolCall[]","chunks","parsedArgs: Record<string, unknown> | null"],"sources":["../../src/messages/utils.ts"],"sourcesContent":["import { addLangChainErrorFields } from \"../errors/index.js\";\nimport { SerializedConstructor } from \"../load/serializable.js\";\nimport { _isToolCall } from \"../tools/utils.js\";\nimport { parsePartialJson } from \"../utils/json.js\";\nimport { AIMessage, AIMessageChunk, AIMessageChunkFields } from \"./ai.js\";\nimport {\n BaseMessageLike,\n BaseMessage,\n isBaseMessage,\n StoredMessage,\n StoredMessageV1,\n BaseMessageFields,\n _isMessageFieldWithRole,\n} from \"./base.js\";\nimport { ChatMessage, ChatMessageFields, ChatMessageChunk } from \"./chat.js\";\nimport {\n FunctionMessage,\n FunctionMessageChunk,\n FunctionMessageFields,\n} from \"./function.js\";\nimport { HumanMessage, HumanMessageChunk } from \"./human.js\";\nimport { RemoveMessage } from \"./modifier.js\";\nimport { SystemMessage, SystemMessageChunk } from \"./system.js\";\nimport {\n InvalidToolCall,\n ToolCall,\n ToolCallChunk,\n ToolMessage,\n ToolMessageFields,\n} from \"./tool.js\";\n\nexport type $Expand<T> = T extends infer U ? { [K in keyof U]: U[K] } : never;\n\n/**\n * Extracts the explicitly declared keys from a type T.\n *\n * @template T - The type to extract keys from\n * @returns A union of keys that are not string, number, or symbol\n */\ntype $KnownKeys<T> = {\n [K in keyof T]: string extends K\n ? never\n : number extends K\n ? never\n : symbol extends K\n ? never\n : K;\n}[keyof T];\n\n/**\n * Detects if T has an index signature.\n *\n * @template T - The type to check for index signatures\n * @returns True if T has an index signature, false otherwise\n */\ntype $HasIndexSignature<T> = string extends keyof T\n ? true\n : number extends keyof T\n ? true\n : symbol extends keyof T\n ? true\n : false;\n\n/**\n * Detects if T has an index signature and no known keys.\n *\n * @template T - The type to check for index signatures and no known keys\n * @returns True if T has an index signature and no known keys, false otherwise\n */\ntype $OnlyIndexSignatures<T> = $HasIndexSignature<T> extends true\n ? [$KnownKeys<T>] extends [never]\n ? true\n : false\n : false;\n\n/**\n * Recursively merges two object types T and U, with U taking precedence over T.\n *\n * This utility type performs a deep merge of two object types:\n * - For keys that exist in both T and U:\n * - If both values are objects (Record<string, unknown>), recursively merge them\n * - Otherwise, U's value takes precedence\n * - For keys that exist only in T, use T's value\n * - For keys that exist only in U, use U's value\n *\n * @template T - The first object type to merge\n * @template U - The second object type to merge (takes precedence over T)\n *\n * @example\n * ```ts\n * type ObjectA = {\n * shared: { a: string; b: number };\n * onlyInA: boolean;\n * };\n *\n * type ObjectB = {\n * shared: { b: string; c: Date };\n * onlyInB: symbol;\n * };\n *\n * type Merged = $MergeObjects<ObjectA, ObjectB>;\n * // Result: {\n * // shared: { a: string; b: string; c: Date };\n * // onlyInA: boolean;\n * // onlyInB: symbol;\n * // }\n * ```\n */\nexport type $MergeObjects<T, U> =\n // If U is purely index-signature based, prefer U as a whole\n $OnlyIndexSignatures<U> extends true\n ? U\n : // If T is purely index-signature based, prefer U as a whole (prevents leaking broad index signatures)\n $OnlyIndexSignatures<T> extends true\n ? U\n : {\n [K in keyof T | keyof U]: K extends keyof T\n ? K extends keyof U\n ? T[K] extends Record<string, unknown>\n ? U[K] extends Record<string, unknown>\n ? $MergeObjects<T[K], U[K]>\n : U[K]\n : U[K]\n : T[K]\n : K extends keyof U\n ? U[K]\n : never;\n };\n\n/**\n * Merges two discriminated unions A and B based on a discriminator key (defaults to \"type\").\n * For each possible value of the discriminator across both unions:\n * - If B has a member with that discriminator value, use B's member\n * - Otherwise use A's member with that discriminator value\n * This effectively merges the unions while giving B's members precedence over A's members.\n *\n * @template A - First discriminated union type that extends Record<Key, PropertyKey>\n * @template B - Second discriminated union type that extends Record<Key, PropertyKey>\n * @template Key - The discriminator key property, defaults to \"type\"\n */\nexport type $MergeDiscriminatedUnion<\n A extends Record<Key, PropertyKey>,\n B extends Record<Key, PropertyKey>,\n Key extends PropertyKey = \"type\"\n> = {\n // Create a mapped type over all possible discriminator values from both A and B\n [T in A[Key] | B[Key]]: [Extract<B, Record<Key, T>>] extends [never] // Check if B has a member with this discriminator value\n ? // If B doesn't have this discriminator value, use A's member\n Extract<A, Record<Key, T>>\n : // If B does have this discriminator value, merge A's and B's members (B takes precedence)\n [Extract<A, Record<Key, T>>] extends [never]\n ? Extract<B, Record<Key, T>>\n : $MergeObjects<Extract<A, Record<Key, T>>, Extract<B, Record<Key, T>>>;\n // Index into the mapped type with all possible discriminator values\n // This converts the mapped type back into a union\n}[A[Key] | B[Key]];\n\nexport type Constructor<T> = new (...args: unknown[]) => T;\n\n/**\n * Immediately-invoked function expression.\n *\n * @param fn - The function to execute\n * @returns The result of the function\n */\nexport const iife = <T>(fn: () => T) => fn();\n\nfunction _coerceToolCall(\n toolCall: ToolCall | Record<string, unknown>\n): ToolCall {\n if (_isToolCall(toolCall)) {\n return toolCall;\n } else if (\n typeof toolCall.id === \"string\" &&\n toolCall.type === \"function\" &&\n typeof toolCall.function === \"object\" &&\n toolCall.function !== null &&\n \"arguments\" in toolCall.function &&\n typeof toolCall.function.arguments === \"string\" &&\n \"name\" in toolCall.function &&\n typeof toolCall.function.name === \"string\"\n ) {\n // Handle OpenAI tool call format\n return {\n id: toolCall.id,\n args: JSON.parse(toolCall.function.arguments),\n name: toolCall.function.name,\n type: \"tool_call\",\n };\n } else {\n // TODO: Throw an error?\n return toolCall as unknown as ToolCall;\n }\n}\n\nfunction isSerializedConstructor(x: unknown): x is SerializedConstructor {\n return (\n typeof x === \"object\" &&\n x != null &&\n (x as SerializedConstructor).lc === 1 &&\n Array.isArray((x as SerializedConstructor).id) &&\n (x as SerializedConstructor).kwargs != null &&\n typeof (x as SerializedConstructor).kwargs === \"object\"\n );\n}\n\nfunction _constructMessageFromParams(\n params:\n | (BaseMessageFields & { type: string } & Record<string, unknown>)\n | SerializedConstructor\n) {\n let type: string;\n let rest: BaseMessageFields & Record<string, unknown>;\n // Support serialized messages\n if (isSerializedConstructor(params)) {\n const className = params.id.at(-1);\n if (className === \"HumanMessage\" || className === \"HumanMessageChunk\") {\n type = \"user\";\n } else if (className === \"AIMessage\" || className === \"AIMessageChunk\") {\n type = \"assistant\";\n } else if (\n className === \"SystemMessage\" ||\n className === \"SystemMessageChunk\"\n ) {\n type = \"system\";\n } else if (\n className === \"FunctionMessage\" ||\n className === \"FunctionMessageChunk\"\n ) {\n type = \"function\";\n } else if (\n className === \"ToolMessage\" ||\n className === \"ToolMessageChunk\"\n ) {\n type = \"tool\";\n } else {\n type = \"unknown\";\n }\n rest = params.kwargs as BaseMessageFields;\n } else {\n const { type: extractedType, ...otherParams } = params;\n type = extractedType;\n rest = otherParams;\n }\n if (type === \"human\" || type === \"user\") {\n return new HumanMessage(rest);\n } else if (type === \"ai\" || type === \"assistant\") {\n const { tool_calls: rawToolCalls, ...other } = rest;\n if (!Array.isArray(rawToolCalls)) {\n return new AIMessage(rest);\n }\n const tool_calls = rawToolCalls.map(_coerceToolCall);\n return new AIMessage({ ...other, tool_calls });\n } else if (type === \"system\") {\n return new SystemMessage(rest);\n } else if (type === \"developer\") {\n return new SystemMessage({\n ...rest,\n additional_kwargs: {\n ...rest.additional_kwargs,\n __openai_role__: \"developer\",\n },\n });\n } else if (type === \"tool\" && \"tool_call_id\" in rest) {\n return new ToolMessage({\n ...rest,\n content: rest.content,\n tool_call_id: rest.tool_call_id as string,\n name: rest.name,\n });\n } else if (type === \"remove\" && \"id\" in rest && typeof rest.id === \"string\") {\n return new RemoveMessage({ ...rest, id: rest.id });\n } else {\n const error = addLangChainErrorFields(\n new Error(\n `Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\\n\\nReceived: ${JSON.stringify(\n params,\n null,\n 2\n )}`\n ),\n \"MESSAGE_COERCION_FAILURE\"\n );\n throw error;\n }\n}\n\nexport function coerceMessageLikeToMessage(\n messageLike: BaseMessageLike\n): BaseMessage {\n if (typeof messageLike === \"string\") {\n return new HumanMessage(messageLike);\n } else if (isBaseMessage(messageLike)) {\n return messageLike;\n }\n if (Array.isArray(messageLike)) {\n const [type, content] = messageLike;\n return _constructMessageFromParams({ type, content });\n } else if (_isMessageFieldWithRole(messageLike)) {\n const { role: type, ...rest } = messageLike;\n return _constructMessageFromParams({ ...rest, type });\n } else {\n return _constructMessageFromParams(messageLike);\n }\n}\n\n/**\n * This function is used by memory classes to get a string representation\n * of the chat message history, based on the message content and role.\n */\nexport function getBufferString(\n messages: BaseMessage[],\n humanPrefix = \"Human\",\n aiPrefix = \"AI\"\n): string {\n const string_messages: string[] = [];\n for (const m of messages) {\n let role: string;\n if (m._getType() === \"human\") {\n role = humanPrefix;\n } else if (m._getType() === \"ai\") {\n role = aiPrefix;\n } else if (m._getType() === \"system\") {\n role = \"System\";\n } else if (m._getType() === \"tool\") {\n role = \"Tool\";\n } else if (m._getType() === \"generic\") {\n role = (m as ChatMessage).role;\n } else {\n throw new Error(`Got unsupported message type: ${m._getType()}`);\n }\n const nameStr = m.name ? `${m.name}, ` : \"\";\n const readableContent =\n typeof m.content === \"string\"\n ? m.content\n : JSON.stringify(m.content, null, 2);\n string_messages.push(`${role}: ${nameStr}${readableContent}`);\n }\n return string_messages.join(\"\\n\");\n}\n\n/**\n * Maps messages from an older format (V1) to the current `StoredMessage`\n * format. If the message is already in the `StoredMessage` format, it is\n * returned as is. Otherwise, it transforms the V1 message into a\n * `StoredMessage`. This function is important for maintaining\n * compatibility with older message formats.\n */\nfunction mapV1MessageToStoredMessage(\n message: StoredMessage | StoredMessageV1\n): StoredMessage {\n // TODO: Remove this mapper when we deprecate the old message format.\n if ((message as StoredMessage).data !== undefined) {\n return message as StoredMessage;\n } else {\n const v1Message = message as StoredMessageV1;\n return {\n type: v1Message.type,\n data: {\n content: v1Message.text,\n role: v1Message.role,\n name: undefined,\n tool_call_id: undefined,\n },\n };\n }\n}\n\nexport function mapStoredMessageToChatMessage(message: StoredMessage) {\n const storedMessage = mapV1MessageToStoredMessage(message);\n switch (storedMessage.type) {\n case \"human\":\n return new HumanMessage(storedMessage.data);\n case \"ai\":\n return new AIMessage(storedMessage.data);\n case \"system\":\n return new SystemMessage(storedMessage.data);\n case \"function\":\n if (storedMessage.data.name === undefined) {\n throw new Error(\"Name must be defined for function messages\");\n }\n return new FunctionMessage(storedMessage.data as FunctionMessageFields);\n case \"tool\":\n if (storedMessage.data.tool_call_id === undefined) {\n throw new Error(\"Tool call ID must be defined for tool messages\");\n }\n return new ToolMessage(storedMessage.data as ToolMessageFields);\n case \"generic\": {\n if (storedMessage.data.role === undefined) {\n throw new Error(\"Role must be defined for chat messages\");\n }\n return new ChatMessage(storedMessage.data as ChatMessageFields);\n }\n default:\n throw new Error(`Got unexpected type: ${storedMessage.type}`);\n }\n}\n\n/**\n * Transforms an array of `StoredMessage` instances into an array of\n * `BaseMessage` instances. It uses the `mapV1MessageToStoredMessage`\n * function to ensure all messages are in the `StoredMessage` format, then\n * creates new instances of the appropriate `BaseMessage` subclass based\n * on the type of each message. This function is used to prepare stored\n * messages for use in a chat context.\n */\nexport function mapStoredMessagesToChatMessages(\n messages: StoredMessage[]\n): BaseMessage[] {\n return messages.map(mapStoredMessageToChatMessage);\n}\n\n/**\n * Transforms an array of `BaseMessage` instances into an array of\n * `StoredMessage` instances. It does this by calling the `toDict` method\n * on each `BaseMessage`, which returns a `StoredMessage`. This function\n * is used to prepare chat messages for storage.\n */\nexport function mapChatMessagesToStoredMessages(\n messages: BaseMessage[]\n): StoredMessage[] {\n return messages.map((message) => message.toDict());\n}\n\nexport function convertToChunk(message: BaseMessage) {\n const type = message._getType();\n if (type === \"human\") {\n return new HumanMessageChunk({ ...message });\n } else if (type === \"ai\") {\n let aiChunkFields: AIMessageChunkFields = {\n ...message,\n };\n if (\"tool_calls\" in aiChunkFields) {\n aiChunkFields = {\n ...aiChunkFields,\n tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({\n ...tc,\n type: \"tool_call_chunk\",\n index: undefined,\n args: JSON.stringify(tc.args),\n })),\n };\n }\n return new AIMessageChunk({ ...aiChunkFields });\n } else if (type === \"system\") {\n return new SystemMessageChunk({ ...message });\n } else if (type === \"function\") {\n return new FunctionMessageChunk({ ...message });\n } else if (ChatMessage.isInstance(message)) {\n return new ChatMessageChunk({ ...message });\n } else {\n throw new Error(\"Unknown message type.\");\n }\n}\n\n/**\n * Collapses an array of tool call chunks into complete tool calls.\n *\n * This function groups tool call chunks by their id and/or index, then attempts to\n * parse and validate the accumulated arguments for each group. Successfully parsed\n * tool calls are returned as valid `ToolCall` objects, while malformed ones are\n * returned as `InvalidToolCall` objects.\n *\n * @param chunks - An array of `ToolCallChunk` objects to collapse\n * @returns An object containing:\n * - `tool_call_chunks`: The original input chunks\n * - `tool_calls`: An array of successfully parsed and validated tool calls\n * - `invalid_tool_calls`: An array of tool calls that failed parsing or validation\n *\n * @remarks\n * Chunks are grouped using the following matching logic:\n * - If a chunk has both an id and index, it matches chunks with the same id and index\n * - If a chunk has only an id, it matches chunks with the same id\n * - If a chunk has only an index, it matches chunks with the same index\n *\n * For each group, the function:\n * 1. Concatenates all `args` strings from the chunks\n * 2. Attempts to parse the concatenated string as JSON\n * 3. Validates that the result is a non-null object with a valid id\n * 4. Creates either a `ToolCall` (if valid) or `InvalidToolCall` (if invalid)\n */\nexport function collapseToolCallChunks(chunks: ToolCallChunk[]): {\n tool_call_chunks: ToolCallChunk[];\n tool_calls: ToolCall[];\n invalid_tool_calls: InvalidToolCall[];\n} {\n const groupedToolCallChunks = chunks.reduce((acc, chunk) => {\n const matchedChunkIndex = acc.findIndex(([match]) => {\n // If chunk has an id and index, match if both are present\n if (\n \"id\" in chunk &&\n chunk.id &&\n \"index\" in chunk &&\n chunk.index !== undefined\n ) {\n return chunk.id === match.id && chunk.index === match.index;\n }\n // If chunk has an id, we match on id\n if (\"id\" in chunk && chunk.id) {\n return chunk.id === match.id;\n }\n // If chunk has an index, we match on index\n if (\"index\" in chunk && chunk.index !== undefined) {\n return chunk.index === match.index;\n }\n return false;\n });\n if (matchedChunkIndex !== -1) {\n acc[matchedChunkIndex].push(chunk);\n } else {\n acc.push([chunk]);\n }\n return acc;\n }, [] as ToolCallChunk[][]);\n\n const toolCalls: ToolCall[] = [];\n const invalidToolCalls: InvalidToolCall[] = [];\n for (const chunks of groupedToolCallChunks) {\n let parsedArgs: Record<string, unknown> | null = null;\n const name = chunks[0]?.name ?? \"\";\n const joinedArgs = chunks\n .map((c) => c.args || \"\")\n .join(\"\")\n .trim();\n const argsStr = joinedArgs.length ? joinedArgs : \"{}\";\n const id = chunks[0]?.id;\n try {\n parsedArgs = parsePartialJson(argsStr);\n if (\n !id ||\n parsedArgs === null ||\n typeof parsedArgs !== \"object\" ||\n Array.isArray(parsedArgs)\n ) {\n throw new Error(\"Malformed tool call chunk args.\");\n }\n toolCalls.push({\n name,\n args: parsedArgs,\n id,\n type: \"tool_call\",\n });\n } catch {\n invalidToolCalls.push({\n name,\n args: argsStr,\n id,\n error: \"Malformed args.\",\n type: \"invalid_tool_call\",\n });\n }\n }\n return {\n tool_call_chunks: chunks,\n tool_calls: toolCalls,\n invalid_tool_calls: invalidToolCalls,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqKA,MAAa,OAAO,CAAIA,OAAgB,IAAI;AAE5C,SAAS,gBACPC,UACU;AACV,KAAI,YAAY,SAAS,CACvB,QAAO;UAEP,OAAO,SAAS,OAAO,YACvB,SAAS,SAAS,cAClB,OAAO,SAAS,aAAa,YAC7B,SAAS,aAAa,QACtB,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,IAAI,QAAQ;EAChC,MAAM,aAAaA,SAChB,IAAI,CAAC,MAAM,EAAE,QAAQ,GAAG,CACxB,KAAK,GAAG,CACR,MAAM;EACT,MAAM,UAAU,WAAW,SAAS,aAAa;EACjD,MAAM,KAAKA,SAAO,IAAI;AACtB,MAAI;GACF,aAAa,iBAAiB,QAAQ;AACtC,OACE,CAAC,MACD,eAAe,QACf,OAAO,eAAe,YACtB,MAAM,QAAQ,WAAW,CAEzB,OAAM,IAAI,MAAM;GAElB,UAAU,KAAK;IACb;IACA,MAAM;IACN;IACA,MAAM;GACP,EAAC;EACH,QAAO;GACN,iBAAiB,KAAK;IACpB;IACA,MAAM;IACN;IACA,OAAO;IACP,MAAM;GACP,EAAC;EACH;CACF;AACD,QAAO;EACL,kBAAkB;EAClB,YAAY;EACZ,oBAAoB;CACrB;AACF"}
|
package/dist/prompts/chat.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
const require_base = require('../messages/base.cjs');
|
|
2
|
-
const
|
|
2
|
+
const require_index = require('../errors/index.cjs');
|
|
3
3
|
const require_chat = require('../messages/chat.cjs');
|
|
4
4
|
const require_human = require('../messages/human.cjs');
|
|
5
5
|
const require_system = require('../messages/system.cjs');
|
|
6
|
-
const require_index = require('../errors/index.cjs');
|
|
7
6
|
const require_utils = require('../messages/utils.cjs');
|
|
7
|
+
const require_ai = require('../messages/ai.cjs');
|
|
8
8
|
const require_base$1 = require('../runnables/base.cjs');
|
|
9
9
|
require('../messages/index.cjs');
|
|
10
10
|
const require_prompt_values = require('../prompt_values.cjs');
|
package/dist/prompts/chat.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { BaseMessage, isBaseMessage } from "../messages/base.js";
|
|
2
|
-
import {
|
|
2
|
+
import { addLangChainErrorFields } from "../errors/index.js";
|
|
3
3
|
import { ChatMessage } from "../messages/chat.js";
|
|
4
4
|
import { HumanMessage } from "../messages/human.js";
|
|
5
5
|
import { SystemMessage } from "../messages/system.js";
|
|
6
|
-
import { addLangChainErrorFields } from "../errors/index.js";
|
|
7
6
|
import { coerceMessageLikeToMessage } from "../messages/utils.js";
|
|
7
|
+
import { AIMessage } from "../messages/ai.js";
|
|
8
8
|
import { Runnable } from "../runnables/base.js";
|
|
9
9
|
import "../messages/index.js";
|
|
10
10
|
import { ChatPromptValue } from "../prompt_values.js";
|
package/dist/runnables/base.cjs
CHANGED
|
@@ -8,6 +8,7 @@ const require_signal = require('../utils/signal.cjs');
|
|
|
8
8
|
const require_utils_stream = require('../utils/stream.cjs');
|
|
9
9
|
const require_tracers_log_stream = require('../tracers/log_stream.cjs');
|
|
10
10
|
const require_event_stream = require('../tracers/event_stream.cjs');
|
|
11
|
+
const require_index$1 = require('../utils/p-retry/index.cjs');
|
|
11
12
|
const require_utils_async_caller = require('../utils/async_caller.cjs');
|
|
12
13
|
const require_root_listener = require('../tracers/root_listener.cjs');
|
|
13
14
|
const require_utils$1 = require('./utils.cjs');
|
|
@@ -16,7 +17,6 @@ const require_runnables_graph = require('./graph.cjs');
|
|
|
16
17
|
const require_wrappers = require('./wrappers.cjs');
|
|
17
18
|
const require_iter = require('./iter.cjs');
|
|
18
19
|
const zod_v3 = require_rolldown_runtime.__toESM(require("zod/v3"));
|
|
19
|
-
const p_retry = require_rolldown_runtime.__toESM(require("p-retry"));
|
|
20
20
|
const uuid = require_rolldown_runtime.__toESM(require("uuid"));
|
|
21
21
|
const langsmith_singletons_traceable = require_rolldown_runtime.__toESM(require("langsmith/singletons/traceable"));
|
|
22
22
|
|
|
@@ -836,7 +836,7 @@ var RunnableRetry = class extends RunnableBinding {
|
|
|
836
836
|
return require_config.patchConfig(config, { callbacks: runManager?.getChild(tag) });
|
|
837
837
|
}
|
|
838
838
|
async _invoke(input, config, runManager) {
|
|
839
|
-
return
|
|
839
|
+
return require_index$1.pRetry((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), {
|
|
840
840
|
onFailedAttempt: ({ error }) => this.onFailedAttempt(error, input),
|
|
841
841
|
retries: Math.max(this.maxAttemptNumber - 1, 0),
|
|
842
842
|
randomize: true
|
|
@@ -858,7 +858,7 @@ var RunnableRetry = class extends RunnableBinding {
|
|
|
858
858
|
async _batch(inputs, configs, runManagers, batchOptions) {
|
|
859
859
|
const resultsMap = {};
|
|
860
860
|
try {
|
|
861
|
-
await
|
|
861
|
+
await require_index$1.pRetry(async (attemptNumber) => {
|
|
862
862
|
const remainingIndexes = inputs.map((_, i) => i).filter((i) => resultsMap[i.toString()] === void 0 || resultsMap[i.toString()] instanceof Error);
|
|
863
863
|
const remainingInputs = remainingIndexes.map((i) => inputs[i]);
|
|
864
864
|
const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i]));
|