@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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","names":["firstContent: MessageContent","secondContent: MessageContent","left?: \"success\" | \"error\"","right?: \"success\" | \"error\"","obj: any","depthLimit: number","currentDepth: number","obj","result: Record<string, unknown>","arg:\n | $InferMessageContent<TStructure, TRole>\n | BaseMessageFields<TStructure, TRole>","fields: BaseMessageFields<TStructure, TRole>","blocks: Array<ContentBlock>","blocks","obj: unknown","value: string | undefined","depth: number | null","format: MessageStringFormat","value?: unknown","left: Record<string, any>","right: Record<string, any>","left?: Content[]","right?: Content[]","left: T | undefined","right: T | undefined","x: BaseMessageLike","messageLike?: unknown"],"sources":["../../src/messages/base.ts"],"sourcesContent":["import { Serializable, SerializedConstructor } from \"../load/serializable.js\";\nimport { ContentBlock } from \"./content/index.js\";\nimport { isDataContentBlock } from \"./content/data.js\";\nimport { convertToV1FromAnthropicInput } from \"./block_translators/anthropic.js\";\nimport { convertToV1FromDataContent } from \"./block_translators/data.js\";\nimport { convertToV1FromChatCompletionsInput } from \"./block_translators/openai.js\";\nimport {\n $InferMessageContent,\n $InferResponseMetadata,\n MessageStructure,\n MessageType,\n isMessage,\n Message,\n} from \"./message.js\";\nimport {\n convertToFormattedString,\n type MessageStringFormat,\n} from \"./format.js\";\n\n/** @internal */\nconst MESSAGE_SYMBOL = Symbol.for(\"langchain.message\");\n\nexport interface StoredMessageData {\n content: string;\n role: string | undefined;\n name: string | undefined;\n tool_call_id: string | undefined;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n additional_kwargs?: Record<string, any>;\n /** Response metadata. For example: response headers, logprobs, token counts, model name. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n response_metadata?: Record<string, any>;\n id?: string;\n}\n\nexport interface StoredMessage {\n type: string;\n data: StoredMessageData;\n}\n\nexport interface StoredGeneration {\n text: string;\n message?: StoredMessage;\n}\n\nexport interface StoredMessageV1 {\n type: string;\n role: string | undefined;\n text: string;\n}\n\nexport type MessageContent = string | Array<ContentBlock>;\n\nexport interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n\n /**\n * The name of the function to call.\n */\n name: string;\n}\n\nexport type BaseMessageFields<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType\n> = {\n id?: string;\n name?: string;\n content?: $InferMessageContent<TStructure, TRole>;\n contentBlocks?: Array<ContentBlock.Standard>;\n /** @deprecated */\n additional_kwargs?: {\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n function_call?: FunctionCall;\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n tool_calls?: OpenAIToolCall[];\n [key: string]: unknown;\n };\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n};\n\nexport function mergeContent(\n firstContent: MessageContent,\n secondContent: MessageContent\n): MessageContent {\n // If first content is a string\n if (typeof firstContent === \"string\") {\n if (firstContent === \"\") {\n return secondContent;\n }\n if (typeof secondContent === \"string\") {\n return firstContent + secondContent;\n } else if (Array.isArray(secondContent) && secondContent.length === 0) {\n return firstContent;\n } else if (\n Array.isArray(secondContent) &&\n secondContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n {\n type: \"text\",\n source_type: \"text\",\n text: firstContent,\n },\n ...secondContent,\n ];\n } else {\n return [{ type: \"text\", text: firstContent }, ...secondContent];\n }\n // If both are arrays\n } else if (Array.isArray(secondContent)) {\n return (\n _mergeLists(firstContent, secondContent) ?? [\n ...firstContent,\n ...secondContent,\n ]\n );\n } else {\n if (secondContent === \"\") {\n return firstContent;\n } else if (\n Array.isArray(firstContent) &&\n firstContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n ...firstContent,\n {\n type: \"file\",\n source_type: \"text\",\n text: secondContent,\n },\n ];\n } else {\n return [...firstContent, { type: \"text\", text: secondContent }];\n }\n }\n}\n\n/**\n * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else\n * it will return 'success'.\n *\n * @param {\"success\" | \"error\" | undefined} left The existing value to 'merge' with the new value.\n * @param {\"success\" | \"error\" | undefined} right The new value to 'merge' with the existing value\n * @returns {\"success\" | \"error\"} The 'merged' value.\n */\nexport function _mergeStatus(\n left?: \"success\" | \"error\",\n right?: \"success\" | \"error\"\n): \"success\" | \"error\" | undefined {\n if (left === \"error\" || right === \"error\") {\n return \"error\";\n }\n return \"success\";\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction stringifyWithDepthLimit(obj: any, depthLimit: number): string {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function helper(obj: any, currentDepth: number): any {\n if (typeof obj !== \"object\" || obj === null || obj === undefined) {\n return obj;\n }\n if (currentDepth >= depthLimit) {\n if (Array.isArray(obj)) {\n return \"[Array]\";\n }\n return \"[Object]\";\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => helper(item, currentDepth + 1));\n }\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n result[key] = helper(obj[key], currentDepth + 1);\n }\n return result;\n }\n\n return JSON.stringify(helper(obj, 0), null, 2);\n}\n\n/**\n * Base class for all types of messages in a conversation. It includes\n * properties like `content`, `name`, and `additional_kwargs`. It also\n * includes methods like `toDict()` and `_getType()`.\n */\nexport abstract class BaseMessage<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType\n >\n extends Serializable\n implements Message<TStructure, TRole>\n{\n lc_namespace = [\"langchain_core\", \"messages\"];\n\n lc_serializable = true;\n\n get lc_aliases(): Record<string, string> {\n // exclude snake case conversion to pascal case\n return {\n additional_kwargs: \"additional_kwargs\",\n response_metadata: \"response_metadata\",\n };\n }\n\n readonly [MESSAGE_SYMBOL] = true as const;\n\n abstract readonly type: TRole;\n\n id?: string;\n\n name?: string;\n\n content: $InferMessageContent<TStructure, TRole>;\n\n additional_kwargs: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"additional_kwargs\"]\n >;\n\n response_metadata: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"response_metadata\"]\n >;\n\n /**\n * @deprecated Use .getType() instead or import the proper typeguard.\n * For example:\n *\n * ```ts\n * import { isAIMessage } from \"@langchain/core/messages\";\n *\n * const message = new AIMessage(\"Hello!\");\n * isAIMessage(message); // true\n * ```\n */\n _getType(): MessageType {\n return this.type;\n }\n\n /**\n * @deprecated Use .type instead\n * The type of the message.\n */\n getType(): MessageType {\n return this._getType();\n }\n\n constructor(\n arg:\n | $InferMessageContent<TStructure, TRole>\n | BaseMessageFields<TStructure, TRole>\n ) {\n const fields: BaseMessageFields<TStructure, TRole> =\n typeof arg === \"string\" || Array.isArray(arg) ? { content: arg } : arg;\n if (!fields.additional_kwargs) {\n fields.additional_kwargs = {};\n }\n if (!fields.response_metadata) {\n fields.response_metadata = {};\n }\n super(fields);\n this.name = fields.name;\n if (fields.content === undefined && fields.contentBlocks !== undefined) {\n this.content = fields.contentBlocks as $InferMessageContent<\n TStructure,\n TRole\n >;\n this.response_metadata = {\n output_version: \"v1\",\n ...fields.response_metadata,\n };\n } else if (fields.content !== undefined) {\n this.content = fields.content ?? [];\n this.response_metadata = fields.response_metadata;\n } else {\n this.content = [] as $InferMessageContent<TStructure, TRole>;\n this.response_metadata = fields.response_metadata;\n }\n this.additional_kwargs = fields.additional_kwargs;\n this.id = fields.id;\n }\n\n /** Get text content of the message. */\n get text(): string {\n if (typeof this.content === \"string\") {\n return this.content;\n }\n if (!Array.isArray(this.content)) return \"\";\n return this.content\n .map((c) => {\n if (typeof c === \"string\") return c;\n if (c.type === \"text\") return c.text;\n return \"\";\n })\n .join(\"\");\n }\n\n get contentBlocks(): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock> =\n typeof this.content === \"string\"\n ? [{ type: \"text\", text: this.content }]\n : this.content;\n const parsingSteps = [\n convertToV1FromDataContent,\n convertToV1FromChatCompletionsInput,\n convertToV1FromAnthropicInput,\n ];\n const parsedBlocks = parsingSteps.reduce(\n (blocks, step) => step(blocks),\n blocks\n );\n return parsedBlocks as Array<ContentBlock.Standard>;\n }\n\n toDict(): StoredMessage {\n return {\n type: this.getType(),\n data: (this.toJSON() as SerializedConstructor)\n .kwargs as StoredMessageData,\n };\n }\n\n static lc_name() {\n return \"BaseMessage\";\n }\n\n // Can't be protected for silly reasons\n get _printableFields(): Record<string, unknown> {\n return {\n id: this.id,\n content: this.content,\n name: this.name,\n additional_kwargs: this.additional_kwargs,\n response_metadata: this.response_metadata,\n };\n }\n\n static isInstance(obj: unknown): obj is BaseMessage {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n MESSAGE_SYMBOL in obj &&\n obj[MESSAGE_SYMBOL] === true &&\n isMessage(obj)\n );\n }\n\n // this private method is used to update the ID for the runtime\n // value as well as in lc_kwargs for serialisation\n _updateId(value: string | undefined) {\n this.id = value;\n\n // lc_attributes wouldn't work here, because jest compares the\n // whole object\n this.lc_kwargs.id = value;\n }\n\n get [Symbol.toStringTag]() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (this.constructor as any).lc_name();\n }\n\n // Override the default behavior of console.log\n [Symbol.for(\"nodejs.util.inspect.custom\")](depth: number | null) {\n if (depth === null) {\n return this;\n }\n const printable = stringifyWithDepthLimit(\n this._printableFields,\n Math.max(4, depth)\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return `${(this.constructor as any).lc_name()} ${printable}`;\n }\n\n toFormattedString(format: MessageStringFormat = \"pretty\"): string {\n return convertToFormattedString(this, format);\n }\n}\n\n/**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\nexport type OpenAIToolCall = {\n /**\n * The ID of the tool call.\n */\n id: string;\n\n /**\n * The function that the model called.\n */\n function: FunctionCall;\n\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: \"function\";\n\n index?: number;\n};\n\nexport function isOpenAIToolCallArray(\n value?: unknown\n): value is OpenAIToolCall[] {\n return (\n Array.isArray(value) &&\n value.every((v) => typeof (v as OpenAIToolCall).index === \"number\")\n );\n}\n\nexport function _mergeDicts(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n left: Record<string, any> = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n right: Record<string, any> = {}\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> {\n const merged = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (merged[key] == null) {\n merged[key] = value;\n } else if (value == null) {\n continue;\n } else if (\n typeof merged[key] !== typeof value ||\n Array.isArray(merged[key]) !== Array.isArray(value)\n ) {\n throw new Error(\n `field[${key}] already exists in the message chunk, but with a different type.`\n );\n } else if (typeof merged[key] === \"string\") {\n if (key === \"type\") {\n // Do not merge 'type' fields\n continue;\n } else if (\n [\"id\", \"name\", \"output_version\", \"model_provider\"].includes(key)\n ) {\n // Keep the incoming value for these fields\n merged[key] = value;\n } else {\n merged[key] += value;\n }\n } else if (typeof merged[key] === \"object\" && !Array.isArray(merged[key])) {\n merged[key] = _mergeDicts(merged[key], value);\n } else if (Array.isArray(merged[key])) {\n merged[key] = _mergeLists(merged[key], value);\n } else if (merged[key] === value) {\n continue;\n } else {\n console.warn(\n `field[${key}] already exists in this message chunk and value has unsupported type.`\n );\n }\n }\n return merged;\n}\n\nexport function _mergeLists<Content extends ContentBlock>(\n left?: Content[],\n right?: Content[]\n): Content[] | undefined {\n if (left === undefined && right === undefined) {\n return undefined;\n } else if (left === undefined || right === undefined) {\n return left || right;\n } else {\n const merged = [...left];\n for (const item of right) {\n if (\n typeof item === \"object\" &&\n item !== null &&\n \"index\" in item &&\n typeof item.index === \"number\"\n ) {\n const toMerge = merged.findIndex((leftItem) => {\n const isObject = typeof leftItem === \"object\";\n const indiciesMatch =\n \"index\" in leftItem && leftItem.index === item.index;\n const idsMatch =\n \"id\" in leftItem && \"id\" in item && leftItem?.id === item?.id;\n const eitherItemMissingID =\n !(\"id\" in leftItem) ||\n !leftItem?.id ||\n !(\"id\" in item) ||\n !item?.id;\n return isObject && indiciesMatch && (idsMatch || eitherItemMissingID);\n });\n if (\n toMerge !== -1 &&\n typeof merged[toMerge] === \"object\" &&\n merged[toMerge] !== null\n ) {\n merged[toMerge] = _mergeDicts(\n merged[toMerge] as Record<string, unknown>,\n item as Record<string, unknown>\n ) as Content;\n } else {\n merged.push(item);\n }\n } else if (\n typeof item === \"object\" &&\n item !== null &&\n \"text\" in item &&\n item.text === \"\"\n ) {\n // No-op - skip empty text blocks\n continue;\n } else {\n merged.push(item);\n }\n }\n return merged;\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _mergeObj<T = any>(\n left: T | undefined,\n right: T | undefined\n): T {\n if (!left && !right) {\n throw new Error(\"Cannot merge two undefined objects.\");\n }\n if (!left || !right) {\n return left || (right as T);\n } else if (typeof left !== typeof right) {\n throw new Error(\n `Cannot merge objects of different types.\\nLeft ${typeof left}\\nRight ${typeof right}`\n );\n } else if (typeof left === \"string\" && typeof right === \"string\") {\n return (left + right) as T;\n } else if (Array.isArray(left) && Array.isArray(right)) {\n return _mergeLists(left, right) as T;\n } else if (typeof left === \"object\" && typeof right === \"object\") {\n return _mergeDicts(left, right) as T;\n } else if (left === right) {\n return left;\n } else {\n throw new Error(\n `Can not merge objects of different types.\\nLeft ${left}\\nRight ${right}`\n );\n }\n}\n\n/**\n * Represents a chunk of a message, which can be concatenated with other\n * message chunks. It includes a method `_merge_kwargs_dict()` for merging\n * additional keyword arguments from another `BaseMessageChunk` into this\n * one. It also overrides the `__add__()` method to support concatenation\n * of `BaseMessageChunk` instances.\n */\nexport abstract class BaseMessageChunk<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType\n> extends BaseMessage<TStructure, TRole> {\n abstract concat(chunk: BaseMessageChunk): BaseMessageChunk<TStructure, TRole>;\n\n static isInstance(obj: unknown): obj is BaseMessageChunk {\n if (!super.isInstance(obj)) {\n return false;\n }\n // Check if obj is an instance of BaseMessageChunk by traversing the prototype chain\n let proto = Object.getPrototypeOf(obj);\n while (proto !== null) {\n if (proto === BaseMessageChunk.prototype) {\n return true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n }\n}\n\nexport type MessageFieldWithRole = {\n role: MessageType;\n content: MessageContent;\n name?: string;\n} & Record<string, unknown>;\n\nexport function _isMessageFieldWithRole(\n x: BaseMessageLike\n): x is MessageFieldWithRole {\n return typeof (x as MessageFieldWithRole).role === \"string\";\n}\n\nexport type BaseMessageLike =\n | BaseMessage\n | MessageFieldWithRole\n | [MessageType, MessageContent]\n | string\n /**\n * @deprecated Specifying \"type\" is deprecated and will be removed in 0.4.0.\n */\n | ({\n type: MessageType | \"user\" | \"assistant\" | \"placeholder\";\n } & BaseMessageFields &\n Record<string, unknown>)\n | SerializedConstructor;\n\n/**\n * @deprecated Use {@link BaseMessage.isInstance} instead\n */\nexport function isBaseMessage(\n messageLike?: unknown\n): messageLike is BaseMessage {\n return typeof (messageLike as BaseMessage)?._getType === \"function\";\n}\n\n/**\n * @deprecated Use {@link BaseMessageChunk.isInstance} instead\n */\nexport function isBaseMessageChunk(\n messageLike?: unknown\n): messageLike is BaseMessageChunk {\n return BaseMessageChunk.isInstance(messageLike);\n}\n"],"mappings":";;;;;;;;;;AAoBA,MAAM,iBAAiB,OAAO,IAAI,oBAAoB;AAuEtD,SAAgB,aACdA,cACAC,eACgB;AAEhB,KAAI,OAAO,iBAAiB,UAAU;AACpC,MAAI,iBAAiB,GACnB,QAAO;AAET,MAAI,OAAO,kBAAkB,SAC3B,QAAO,eAAe;WACb,MAAM,QAAQ,cAAc,IAAI,cAAc,WAAW,EAClE,QAAO;WAEP,MAAM,QAAQ,cAAc,IAC5B,cAAc,KAAK,CAAC,MAAM,mBAAmB,EAAE,CAAC,CAEhD,QAAO,CACL;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACP,GACD,GAAG,aACJ;MAED,QAAO,CAAC;GAAE,MAAM;GAAQ,MAAM;EAAc,GAAE,GAAG,aAAc;CAGlE,WAAU,MAAM,QAAQ,cAAc,CACrC,QACE,YAAY,cAAc,cAAc,IAAI,CAC1C,GAAG,cACH,GAAG,aACJ;UAGC,kBAAkB,GACpB,QAAO;UAEP,MAAM,QAAQ,aAAa,IAC3B,aAAa,KAAK,CAAC,MAAM,mBAAmB,EAAE,CAAC,CAE/C,QAAO,CACL,GAAG,cACH;EACE,MAAM;EACN,aAAa;EACb,MAAM;CACP,CACF;KAED,QAAO,CAAC,GAAG,cAAc;EAAE,MAAM;EAAQ,MAAM;CAAe,CAAC;AAGpE;;;;;;;;;AAUD,SAAgB,aACdC,MACAC,OACiC;AACjC,KAAI,SAAS,WAAW,UAAU,QAChC,QAAO;AAET,QAAO;AACR;AAGD,SAAS,wBAAwBC,KAAUC,YAA4B;CAErE,SAAS,OAAOD,OAAUE,cAA2B;AACnD,MAAI,OAAOC,UAAQ,YAAYA,UAAQ,QAAQA,UAAQ,OACrD,QAAOA;AAET,MAAI,gBAAgB,YAAY;AAC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KAAuC;AACvD,MAAI,CAAC,MAAM,WAAW,IAAI,CACxB,QAAO;EAGT,IAAI,QAAQ,OAAO,eAAe,IAAI;AACtC,SAAO,UAAU,MAAM;AACrB,OAAI,UAAU,iBAAiB,UAC7B,QAAO;GAET,QAAQ,OAAO,eAAe,MAAM;EACrC;AACD,SAAO;CACR;AACF;AAQD,SAAgB,wBACdW,GAC2B;AAC3B,QAAO,OAAQ,EAA2B,SAAS;AACpD;;;;AAmBD,SAAgB,cACdC,aAC4B;AAC5B,QAAO,OAAQ,aAA6B,aAAa;AAC1D;;;;AAKD,SAAgB,mBACdA,aACiC;AACjC,QAAO,iBAAiB,WAAW,YAAY;AAChD"}
|
|
1
|
+
{"version":3,"file":"base.js","names":["firstContent: MessageContent","secondContent: MessageContent","left?: \"success\" | \"error\"","right?: \"success\" | \"error\"","obj: any","depthLimit: number","currentDepth: number","obj","result: Record<string, unknown>","arg:\n | $InferMessageContent<TStructure, TRole>\n | BaseMessageFields<TStructure, TRole>","fields: BaseMessageFields<TStructure, TRole>","blocks: Array<ContentBlock>","blocks","obj: unknown","value: string | undefined","depth: number | null","format: MessageStringFormat","value?: unknown","left: Record<string, any>","right: Record<string, any>","left?: Content[]","right?: Content[]","left: T | undefined","right: T | undefined","x: BaseMessageLike","messageLike?: unknown"],"sources":["../../src/messages/base.ts"],"sourcesContent":["import { Serializable, SerializedConstructor } from \"../load/serializable.js\";\nimport { ContentBlock } from \"./content/index.js\";\nimport { isDataContentBlock } from \"./content/data.js\";\nimport { convertToV1FromAnthropicInput } from \"./block_translators/anthropic.js\";\nimport { convertToV1FromDataContent } from \"./block_translators/data.js\";\nimport { convertToV1FromChatCompletionsInput } from \"./block_translators/openai.js\";\nimport {\n $InferMessageContent,\n $InferResponseMetadata,\n MessageStructure,\n MessageType,\n isMessage,\n Message,\n} from \"./message.js\";\nimport {\n convertToFormattedString,\n type MessageStringFormat,\n} from \"./format.js\";\n\n/** @internal */\nconst MESSAGE_SYMBOL = Symbol.for(\"langchain.message\");\n\nexport interface StoredMessageData {\n content: string;\n role: string | undefined;\n name: string | undefined;\n tool_call_id: string | undefined;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n additional_kwargs?: Record<string, any>;\n /** Response metadata. For example: response headers, logprobs, token counts, model name. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n response_metadata?: Record<string, any>;\n id?: string;\n}\n\nexport interface StoredMessage {\n type: string;\n data: StoredMessageData;\n}\n\nexport interface StoredGeneration {\n text: string;\n message?: StoredMessage;\n}\n\nexport interface StoredMessageV1 {\n type: string;\n role: string | undefined;\n text: string;\n}\n\nexport type MessageContent = string | Array<ContentBlock>;\n\nexport interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n\n /**\n * The name of the function to call.\n */\n name: string;\n}\n\nexport type BaseMessageFields<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType\n> = {\n id?: string;\n name?: string;\n content?: $InferMessageContent<TStructure, TRole>;\n contentBlocks?: Array<ContentBlock.Standard>;\n /** @deprecated */\n additional_kwargs?: {\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n function_call?: FunctionCall;\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n tool_calls?: OpenAIToolCall[];\n [key: string]: unknown;\n };\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n};\n\nexport function mergeContent(\n firstContent: MessageContent,\n secondContent: MessageContent\n): MessageContent {\n // If first content is a string\n if (typeof firstContent === \"string\") {\n if (firstContent === \"\") {\n return secondContent;\n }\n if (typeof secondContent === \"string\") {\n return firstContent + secondContent;\n } else if (Array.isArray(secondContent) && secondContent.length === 0) {\n return firstContent;\n } else if (\n Array.isArray(secondContent) &&\n secondContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n {\n type: \"text\",\n source_type: \"text\",\n text: firstContent,\n },\n ...secondContent,\n ];\n } else {\n return [{ type: \"text\", text: firstContent }, ...secondContent];\n }\n // If both are arrays\n } else if (Array.isArray(secondContent)) {\n return (\n _mergeLists(firstContent, secondContent) ?? [\n ...firstContent,\n ...secondContent,\n ]\n );\n } else {\n if (secondContent === \"\") {\n return firstContent;\n } else if (\n Array.isArray(firstContent) &&\n firstContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n ...firstContent,\n {\n type: \"file\",\n source_type: \"text\",\n text: secondContent,\n },\n ];\n } else {\n return [...firstContent, { type: \"text\", text: secondContent }];\n }\n }\n}\n\n/**\n * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else\n * it will return 'success'.\n *\n * @param {\"success\" | \"error\" | undefined} left The existing value to 'merge' with the new value.\n * @param {\"success\" | \"error\" | undefined} right The new value to 'merge' with the existing value\n * @returns {\"success\" | \"error\"} The 'merged' value.\n */\nexport function _mergeStatus(\n left?: \"success\" | \"error\",\n right?: \"success\" | \"error\"\n): \"success\" | \"error\" | undefined {\n if (left === \"error\" || right === \"error\") {\n return \"error\";\n }\n return \"success\";\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction stringifyWithDepthLimit(obj: any, depthLimit: number): string {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function helper(obj: any, currentDepth: number): any {\n if (typeof obj !== \"object\" || obj === null || obj === undefined) {\n return obj;\n }\n if (currentDepth >= depthLimit) {\n if (Array.isArray(obj)) {\n return \"[Array]\";\n }\n return \"[Object]\";\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => helper(item, currentDepth + 1));\n }\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n result[key] = helper(obj[key], currentDepth + 1);\n }\n return result;\n }\n\n return JSON.stringify(helper(obj, 0), null, 2);\n}\n\n/**\n * Base class for all types of messages in a conversation. It includes\n * properties like `content`, `name`, and `additional_kwargs`. It also\n * includes methods like `toDict()` and `_getType()`.\n */\nexport abstract class BaseMessage<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType\n >\n extends Serializable\n implements Message<TStructure, TRole>\n{\n lc_namespace = [\"langchain_core\", \"messages\"];\n\n lc_serializable = true;\n\n get lc_aliases(): Record<string, string> {\n // exclude snake case conversion to pascal case\n return {\n additional_kwargs: \"additional_kwargs\",\n response_metadata: \"response_metadata\",\n };\n }\n\n readonly [MESSAGE_SYMBOL] = true as const;\n\n abstract readonly type: TRole;\n\n id?: string;\n\n name?: string;\n\n content: $InferMessageContent<TStructure, TRole>;\n\n additional_kwargs: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"additional_kwargs\"]\n >;\n\n response_metadata: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"response_metadata\"]\n >;\n\n /**\n * @deprecated Use .getType() instead or import the proper typeguard.\n * For example:\n *\n * ```ts\n * import { isAIMessage } from \"@langchain/core/messages\";\n *\n * const message = new AIMessage(\"Hello!\");\n * isAIMessage(message); // true\n * ```\n */\n _getType(): MessageType {\n return this.type;\n }\n\n /**\n * @deprecated Use .type instead\n * The type of the message.\n */\n getType(): MessageType {\n return this._getType();\n }\n\n constructor(\n arg:\n | $InferMessageContent<TStructure, TRole>\n | BaseMessageFields<TStructure, TRole>\n ) {\n const fields: BaseMessageFields<TStructure, TRole> =\n typeof arg === \"string\" || Array.isArray(arg) ? { content: arg } : arg;\n if (!fields.additional_kwargs) {\n fields.additional_kwargs = {};\n }\n if (!fields.response_metadata) {\n fields.response_metadata = {};\n }\n super(fields);\n this.name = fields.name;\n if (fields.content === undefined && fields.contentBlocks !== undefined) {\n this.content = fields.contentBlocks as $InferMessageContent<\n TStructure,\n TRole\n >;\n this.response_metadata = {\n output_version: \"v1\",\n ...fields.response_metadata,\n };\n } else if (fields.content !== undefined) {\n this.content = fields.content ?? [];\n this.response_metadata = fields.response_metadata;\n } else {\n this.content = [] as $InferMessageContent<TStructure, TRole>;\n this.response_metadata = fields.response_metadata;\n }\n this.additional_kwargs = fields.additional_kwargs;\n this.id = fields.id;\n }\n\n /** Get text content of the message. */\n get text(): string {\n if (typeof this.content === \"string\") {\n return this.content;\n }\n if (!Array.isArray(this.content)) return \"\";\n return this.content\n .map((c) => {\n if (typeof c === \"string\") return c;\n if (c.type === \"text\") return c.text;\n return \"\";\n })\n .join(\"\");\n }\n\n get contentBlocks(): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock> =\n typeof this.content === \"string\"\n ? [{ type: \"text\", text: this.content }]\n : this.content;\n const parsingSteps = [\n convertToV1FromDataContent,\n convertToV1FromChatCompletionsInput,\n convertToV1FromAnthropicInput,\n ];\n const parsedBlocks = parsingSteps.reduce(\n (blocks, step) => step(blocks),\n blocks\n );\n return parsedBlocks as Array<ContentBlock.Standard>;\n }\n\n toDict(): StoredMessage {\n return {\n type: this.getType(),\n data: (this.toJSON() as SerializedConstructor)\n .kwargs as StoredMessageData,\n };\n }\n\n static lc_name() {\n return \"BaseMessage\";\n }\n\n // Can't be protected for silly reasons\n get _printableFields(): Record<string, unknown> {\n return {\n id: this.id,\n content: this.content,\n name: this.name,\n additional_kwargs: this.additional_kwargs,\n response_metadata: this.response_metadata,\n };\n }\n\n static isInstance(obj: unknown): obj is BaseMessage {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n MESSAGE_SYMBOL in obj &&\n obj[MESSAGE_SYMBOL] === true &&\n isMessage(obj)\n );\n }\n\n // this private method is used to update the ID for the runtime\n // value as well as in lc_kwargs for serialisation\n _updateId(value: string | undefined) {\n this.id = value;\n\n // lc_attributes wouldn't work here, because jest compares the\n // whole object\n this.lc_kwargs.id = value;\n }\n\n get [Symbol.toStringTag]() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (this.constructor as any).lc_name();\n }\n\n // Override the default behavior of console.log\n [Symbol.for(\"nodejs.util.inspect.custom\")](depth: number | null) {\n if (depth === null) {\n return this;\n }\n const printable = stringifyWithDepthLimit(\n this._printableFields,\n Math.max(4, depth)\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return `${(this.constructor as any).lc_name()} ${printable}`;\n }\n\n toFormattedString(format: MessageStringFormat = \"pretty\"): string {\n return convertToFormattedString(this, format);\n }\n}\n\n/**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\nexport type OpenAIToolCall = {\n /**\n * The ID of the tool call.\n */\n id: string;\n\n /**\n * The function that the model called.\n */\n function: FunctionCall;\n\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: \"function\";\n\n index?: number;\n};\n\nexport function isOpenAIToolCallArray(\n value?: unknown\n): value is OpenAIToolCall[] {\n return (\n Array.isArray(value) &&\n value.every((v) => typeof (v as OpenAIToolCall).index === \"number\")\n );\n}\n\nexport function _mergeDicts(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n left: Record<string, any> = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n right: Record<string, any> = {}\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> {\n const merged = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (merged[key] == null) {\n merged[key] = value;\n } else if (value == null) {\n continue;\n } else if (\n typeof merged[key] !== typeof value ||\n Array.isArray(merged[key]) !== Array.isArray(value)\n ) {\n throw new Error(\n `field[${key}] already exists in the message chunk, but with a different type.`\n );\n } else if (typeof merged[key] === \"string\") {\n if (key === \"type\") {\n // Do not merge 'type' fields\n continue;\n } else if (\n [\"id\", \"name\", \"output_version\", \"model_provider\"].includes(key)\n ) {\n // Keep the incoming value for these fields if its defined\n if (value) {\n merged[key] = value;\n }\n } else {\n merged[key] += value;\n }\n } else if (typeof merged[key] === \"object\" && !Array.isArray(merged[key])) {\n merged[key] = _mergeDicts(merged[key], value);\n } else if (Array.isArray(merged[key])) {\n merged[key] = _mergeLists(merged[key], value);\n } else if (merged[key] === value) {\n continue;\n } else {\n console.warn(\n `field[${key}] already exists in this message chunk and value has unsupported type.`\n );\n }\n }\n return merged;\n}\n\nexport function _mergeLists<Content extends ContentBlock>(\n left?: Content[],\n right?: Content[]\n): Content[] | undefined {\n if (left === undefined && right === undefined) {\n return undefined;\n } else if (left === undefined || right === undefined) {\n return left || right;\n } else {\n const merged = [...left];\n for (const item of right) {\n if (\n typeof item === \"object\" &&\n item !== null &&\n \"index\" in item &&\n typeof item.index === \"number\"\n ) {\n const toMerge = merged.findIndex((leftItem) => {\n const isObject = typeof leftItem === \"object\";\n const indiciesMatch =\n \"index\" in leftItem && leftItem.index === item.index;\n const idsMatch =\n \"id\" in leftItem && \"id\" in item && leftItem?.id === item?.id;\n const eitherItemMissingID =\n !(\"id\" in leftItem) ||\n !leftItem?.id ||\n !(\"id\" in item) ||\n !item?.id;\n return isObject && indiciesMatch && (idsMatch || eitherItemMissingID);\n });\n if (\n toMerge !== -1 &&\n typeof merged[toMerge] === \"object\" &&\n merged[toMerge] !== null\n ) {\n merged[toMerge] = _mergeDicts(\n merged[toMerge] as Record<string, unknown>,\n item as Record<string, unknown>\n ) as Content;\n } else {\n merged.push(item);\n }\n } else if (\n typeof item === \"object\" &&\n item !== null &&\n \"text\" in item &&\n item.text === \"\"\n ) {\n // No-op - skip empty text blocks\n continue;\n } else {\n merged.push(item);\n }\n }\n return merged;\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _mergeObj<T = any>(\n left: T | undefined,\n right: T | undefined\n): T {\n if (!left && !right) {\n throw new Error(\"Cannot merge two undefined objects.\");\n }\n if (!left || !right) {\n return left || (right as T);\n } else if (typeof left !== typeof right) {\n throw new Error(\n `Cannot merge objects of different types.\\nLeft ${typeof left}\\nRight ${typeof right}`\n );\n } else if (typeof left === \"string\" && typeof right === \"string\") {\n return (left + right) as T;\n } else if (Array.isArray(left) && Array.isArray(right)) {\n return _mergeLists(left, right) as T;\n } else if (typeof left === \"object\" && typeof right === \"object\") {\n return _mergeDicts(left, right) as T;\n } else if (left === right) {\n return left;\n } else {\n throw new Error(\n `Can not merge objects of different types.\\nLeft ${left}\\nRight ${right}`\n );\n }\n}\n\n/**\n * Represents a chunk of a message, which can be concatenated with other\n * message chunks. It includes a method `_merge_kwargs_dict()` for merging\n * additional keyword arguments from another `BaseMessageChunk` into this\n * one. It also overrides the `__add__()` method to support concatenation\n * of `BaseMessageChunk` instances.\n */\nexport abstract class BaseMessageChunk<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType\n> extends BaseMessage<TStructure, TRole> {\n abstract concat(chunk: BaseMessageChunk): BaseMessageChunk<TStructure, TRole>;\n\n static isInstance(obj: unknown): obj is BaseMessageChunk {\n if (!super.isInstance(obj)) {\n return false;\n }\n // Check if obj is an instance of BaseMessageChunk by traversing the prototype chain\n let proto = Object.getPrototypeOf(obj);\n while (proto !== null) {\n if (proto === BaseMessageChunk.prototype) {\n return true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n }\n}\n\nexport type MessageFieldWithRole = {\n role: MessageType;\n content: MessageContent;\n name?: string;\n} & Record<string, unknown>;\n\nexport function _isMessageFieldWithRole(\n x: BaseMessageLike\n): x is MessageFieldWithRole {\n return typeof (x as MessageFieldWithRole).role === \"string\";\n}\n\nexport type BaseMessageLike =\n | BaseMessage\n | MessageFieldWithRole\n | [MessageType, MessageContent]\n | string\n /**\n * @deprecated Specifying \"type\" is deprecated and will be removed in 0.4.0.\n */\n | ({\n type: MessageType | \"user\" | \"assistant\" | \"placeholder\";\n } & BaseMessageFields &\n Record<string, unknown>)\n | SerializedConstructor;\n\n/**\n * @deprecated Use {@link BaseMessage.isInstance} instead\n */\nexport function isBaseMessage(\n messageLike?: unknown\n): messageLike is BaseMessage {\n return typeof (messageLike as BaseMessage)?._getType === \"function\";\n}\n\n/**\n * @deprecated Use {@link BaseMessageChunk.isInstance} instead\n */\nexport function isBaseMessageChunk(\n messageLike?: unknown\n): messageLike is BaseMessageChunk {\n return BaseMessageChunk.isInstance(messageLike);\n}\n"],"mappings":";;;;;;;;;;AAoBA,MAAM,iBAAiB,OAAO,IAAI,oBAAoB;AAuEtD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AO;CACR;AACF;AAQD,SAAgB,wBACdW,GAC2B;AAC3B,QAAO,OAAQ,EAA2B,SAAS;AACpD;;;;AAmBD,SAAgB,cACdC,aAC4B;AAC5B,QAAO,OAAQ,aAA6B,aAAa;AAC1D;;;;AAKD,SAAgB,mBACdA,aACiC;AACjC,QAAO,iBAAiB,WAAW,YAAY;AAChD"}
|
package/dist/messages/index.cjs
CHANGED
|
@@ -4,13 +4,13 @@ const require_message = require('./message.cjs');
|
|
|
4
4
|
const require_base = require('./base.cjs');
|
|
5
5
|
const require_metadata = require('./metadata.cjs');
|
|
6
6
|
const require_messages_tool = require('./tool.cjs');
|
|
7
|
-
const require_ai = require('./ai.cjs');
|
|
8
7
|
const require_chat = require('./chat.cjs');
|
|
9
8
|
const require_function = require('./function.cjs');
|
|
10
9
|
const require_human = require('./human.cjs');
|
|
11
|
-
const require_system = require('./system.cjs');
|
|
12
10
|
const require_modifier = require('./modifier.cjs');
|
|
11
|
+
const require_system = require('./system.cjs');
|
|
13
12
|
const require_utils = require('./utils.cjs');
|
|
13
|
+
const require_ai = require('./ai.cjs');
|
|
14
14
|
const require_transformers = require('./transformers.cjs');
|
|
15
15
|
const require_index = require('./content/index.cjs');
|
|
16
16
|
|
|
@@ -39,6 +39,7 @@ require_rolldown_runtime.__export(messages_exports, {
|
|
|
39
39
|
_mergeObj: () => require_base._mergeObj,
|
|
40
40
|
_mergeStatus: () => require_base._mergeStatus,
|
|
41
41
|
coerceMessageLikeToMessage: () => require_utils.coerceMessageLikeToMessage,
|
|
42
|
+
collapseToolCallChunks: () => require_utils.collapseToolCallChunks,
|
|
42
43
|
convertToChunk: () => require_utils.convertToChunk,
|
|
43
44
|
convertToOpenAIImageBlock: () => require_data.convertToOpenAIImageBlock,
|
|
44
45
|
convertToProviderContentBlock: () => require_data.convertToProviderContentBlock,
|
|
@@ -104,6 +105,7 @@ exports._mergeLists = require_base._mergeLists;
|
|
|
104
105
|
exports._mergeObj = require_base._mergeObj;
|
|
105
106
|
exports._mergeStatus = require_base._mergeStatus;
|
|
106
107
|
exports.coerceMessageLikeToMessage = require_utils.coerceMessageLikeToMessage;
|
|
108
|
+
exports.collapseToolCallChunks = require_utils.collapseToolCallChunks;
|
|
107
109
|
exports.convertToChunk = require_utils.convertToChunk;
|
|
108
110
|
exports.convertToOpenAIImageBlock = require_data.convertToOpenAIImageBlock;
|
|
109
111
|
exports.convertToProviderContentBlock = require_data.convertToProviderContentBlock;
|
|
@@ -8,8 +8,8 @@ import { ChatMessage, ChatMessageChunk, ChatMessageFields, isChatMessage, isChat
|
|
|
8
8
|
import { FunctionMessage, FunctionMessageChunk, FunctionMessageFields, isFunctionMessage, isFunctionMessageChunk } from "./function.cjs";
|
|
9
9
|
import { HumanMessage, HumanMessageChunk, HumanMessageFields, isHumanMessage, isHumanMessageChunk } from "./human.cjs";
|
|
10
10
|
import { SystemMessage, SystemMessageChunk, SystemMessageFields, isSystemMessage, isSystemMessageChunk } from "./system.cjs";
|
|
11
|
-
import { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages } from "./utils.cjs";
|
|
11
|
+
import { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages } from "./utils.cjs";
|
|
12
12
|
import { $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $MergeContentDefinition, $MergeMessageStructure, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, Message, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, StandardMessageStructure, isMessage } from "./message.cjs";
|
|
13
13
|
import { RemoveMessage, RemoveMessageFields } from "./modifier.cjs";
|
|
14
14
|
import { FilterMessagesFields, MessageChunkUnion, MessageTypeOrClass, MessageUnion, TrimMessagesFields, defaultTextSplitter, filterMessages, mergeMessageRuns, trimMessages } from "./transformers.cjs";
|
|
15
|
-
export { $Expand, $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $MergeContentDefinition, $MergeDiscriminatedUnion, $MergeMessageStructure, $MergeObjects, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, AIMessage, AIMessageChunk, AIMessageChunkFields, AIMessageFields, BaseMessage, BaseMessageChunk, BaseMessageFields, BaseMessageLike, ChatMessage, ChatMessageChunk, ChatMessageFields, Constructor, ContentBlock, Data, DirectToolOutput, FilterMessagesFields, FunctionCall, FunctionMessage, FunctionMessageChunk, FunctionMessageFields, HumanMessage, HumanMessageChunk, HumanMessageFields, ImageDetail, InputTokenDetails, InvalidToolCall, KNOWN_BLOCK_TYPES, Message, MessageChunkUnion, MessageContent, MessageContentComplex, MessageContentImageUrl, MessageContentText, MessageFieldWithRole, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, MessageTypeOrClass, MessageUnion, ModalitiesTokenDetails, OpenAIToolCall, OutputTokenDetails, ProviderFormatTypes, RemoveMessage, RemoveMessageFields, ResponseMetadata, StandardContentBlockConverter, StandardMessageStructure, StoredGeneration, StoredMessage, StoredMessageData, StoredMessageV1, SystemMessage, SystemMessageChunk, SystemMessageFields, ToolCall, ToolCallChunk, ToolMessage, ToolMessageChunk, ToolMessageFields, TrimMessagesFields, UsageMetadata, _isMessageFieldWithRole, _mergeDicts, _mergeLists, _mergeObj, _mergeStatus, coerceMessageLikeToMessage, convertToChunk, convertToOpenAIImageBlock, convertToProviderContentBlock, defaultTextSplitter, defaultToolCallParser, filterMessages, getBufferString, iife, isAIMessage, isAIMessageChunk, isBase64ContentBlock, isBaseMessage, isBaseMessageChunk, isChatMessage, isChatMessageChunk, isDataContentBlock, isDirectToolOutput, isFunctionMessage, isFunctionMessageChunk, isHumanMessage, isHumanMessageChunk, isIDContentBlock, isMessage, isOpenAIToolCallArray, isPlainTextContentBlock, isSystemMessage, isSystemMessageChunk, isToolMessage, isToolMessageChunk, isURLContentBlock, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages, mergeContent, mergeMessageRuns, mergeResponseMetadata, mergeUsageMetadata, parseBase64DataUrl, parseMimeType, trimMessages };
|
|
15
|
+
export { $Expand, $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $MergeContentDefinition, $MergeDiscriminatedUnion, $MergeMessageStructure, $MergeObjects, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, AIMessage, AIMessageChunk, AIMessageChunkFields, AIMessageFields, BaseMessage, BaseMessageChunk, BaseMessageFields, BaseMessageLike, ChatMessage, ChatMessageChunk, ChatMessageFields, Constructor, ContentBlock, Data, DirectToolOutput, FilterMessagesFields, FunctionCall, FunctionMessage, FunctionMessageChunk, FunctionMessageFields, HumanMessage, HumanMessageChunk, HumanMessageFields, ImageDetail, InputTokenDetails, InvalidToolCall, KNOWN_BLOCK_TYPES, Message, MessageChunkUnion, MessageContent, MessageContentComplex, MessageContentImageUrl, MessageContentText, MessageFieldWithRole, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, MessageTypeOrClass, MessageUnion, ModalitiesTokenDetails, OpenAIToolCall, OutputTokenDetails, ProviderFormatTypes, RemoveMessage, RemoveMessageFields, ResponseMetadata, StandardContentBlockConverter, StandardMessageStructure, StoredGeneration, StoredMessage, StoredMessageData, StoredMessageV1, SystemMessage, SystemMessageChunk, SystemMessageFields, ToolCall, ToolCallChunk, ToolMessage, ToolMessageChunk, ToolMessageFields, TrimMessagesFields, UsageMetadata, _isMessageFieldWithRole, _mergeDicts, _mergeLists, _mergeObj, _mergeStatus, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, convertToOpenAIImageBlock, convertToProviderContentBlock, defaultTextSplitter, defaultToolCallParser, filterMessages, getBufferString, iife, isAIMessage, isAIMessageChunk, isBase64ContentBlock, isBaseMessage, isBaseMessageChunk, isChatMessage, isChatMessageChunk, isDataContentBlock, isDirectToolOutput, isFunctionMessage, isFunctionMessageChunk, isHumanMessage, isHumanMessageChunk, isIDContentBlock, isMessage, isOpenAIToolCallArray, isPlainTextContentBlock, isSystemMessage, isSystemMessageChunk, isToolMessage, isToolMessageChunk, isURLContentBlock, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages, mergeContent, mergeMessageRuns, mergeResponseMetadata, mergeUsageMetadata, parseBase64DataUrl, parseMimeType, trimMessages };
|
package/dist/messages/index.d.ts
CHANGED
|
@@ -8,8 +8,8 @@ import { ChatMessage, ChatMessageChunk, ChatMessageFields, isChatMessage, isChat
|
|
|
8
8
|
import { FunctionMessage, FunctionMessageChunk, FunctionMessageFields, isFunctionMessage, isFunctionMessageChunk } from "./function.js";
|
|
9
9
|
import { HumanMessage, HumanMessageChunk, HumanMessageFields, isHumanMessage, isHumanMessageChunk } from "./human.js";
|
|
10
10
|
import { SystemMessage, SystemMessageChunk, SystemMessageFields, isSystemMessage, isSystemMessageChunk } from "./system.js";
|
|
11
|
-
import { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages } from "./utils.js";
|
|
11
|
+
import { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages } from "./utils.js";
|
|
12
12
|
import { $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $MergeContentDefinition, $MergeMessageStructure, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, Message, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, StandardMessageStructure, isMessage } from "./message.js";
|
|
13
13
|
import { RemoveMessage, RemoveMessageFields } from "./modifier.js";
|
|
14
14
|
import { FilterMessagesFields, MessageChunkUnion, MessageTypeOrClass, MessageUnion, TrimMessagesFields, defaultTextSplitter, filterMessages, mergeMessageRuns, trimMessages } from "./transformers.js";
|
|
15
|
-
export { $Expand, $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $MergeContentDefinition, $MergeDiscriminatedUnion, $MergeMessageStructure, $MergeObjects, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, AIMessage, AIMessageChunk, AIMessageChunkFields, AIMessageFields, BaseMessage, BaseMessageChunk, BaseMessageFields, BaseMessageLike, ChatMessage, ChatMessageChunk, ChatMessageFields, Constructor, ContentBlock, Data, DirectToolOutput, FilterMessagesFields, FunctionCall, FunctionMessage, FunctionMessageChunk, FunctionMessageFields, HumanMessage, HumanMessageChunk, HumanMessageFields, ImageDetail, InputTokenDetails, InvalidToolCall, KNOWN_BLOCK_TYPES, Message, MessageChunkUnion, MessageContent, MessageContentComplex, MessageContentImageUrl, MessageContentText, MessageFieldWithRole, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, MessageTypeOrClass, MessageUnion, ModalitiesTokenDetails, OpenAIToolCall, OutputTokenDetails, ProviderFormatTypes, RemoveMessage, RemoveMessageFields, ResponseMetadata, StandardContentBlockConverter, StandardMessageStructure, StoredGeneration, StoredMessage, StoredMessageData, StoredMessageV1, SystemMessage, SystemMessageChunk, SystemMessageFields, ToolCall, ToolCallChunk, ToolMessage, ToolMessageChunk, ToolMessageFields, TrimMessagesFields, UsageMetadata, _isMessageFieldWithRole, _mergeDicts, _mergeLists, _mergeObj, _mergeStatus, coerceMessageLikeToMessage, convertToChunk, convertToOpenAIImageBlock, convertToProviderContentBlock, defaultTextSplitter, defaultToolCallParser, filterMessages, getBufferString, iife, isAIMessage, isAIMessageChunk, isBase64ContentBlock, isBaseMessage, isBaseMessageChunk, isChatMessage, isChatMessageChunk, isDataContentBlock, isDirectToolOutput, isFunctionMessage, isFunctionMessageChunk, isHumanMessage, isHumanMessageChunk, isIDContentBlock, isMessage, isOpenAIToolCallArray, isPlainTextContentBlock, isSystemMessage, isSystemMessageChunk, isToolMessage, isToolMessageChunk, isURLContentBlock, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages, mergeContent, mergeMessageRuns, mergeResponseMetadata, mergeUsageMetadata, parseBase64DataUrl, parseMimeType, trimMessages };
|
|
15
|
+
export { $Expand, $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $MergeContentDefinition, $MergeDiscriminatedUnion, $MergeMessageStructure, $MergeObjects, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, AIMessage, AIMessageChunk, AIMessageChunkFields, AIMessageFields, BaseMessage, BaseMessageChunk, BaseMessageFields, BaseMessageLike, ChatMessage, ChatMessageChunk, ChatMessageFields, Constructor, ContentBlock, Data, DirectToolOutput, FilterMessagesFields, FunctionCall, FunctionMessage, FunctionMessageChunk, FunctionMessageFields, HumanMessage, HumanMessageChunk, HumanMessageFields, ImageDetail, InputTokenDetails, InvalidToolCall, KNOWN_BLOCK_TYPES, Message, MessageChunkUnion, MessageContent, MessageContentComplex, MessageContentImageUrl, MessageContentText, MessageFieldWithRole, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, MessageTypeOrClass, MessageUnion, ModalitiesTokenDetails, OpenAIToolCall, OutputTokenDetails, ProviderFormatTypes, RemoveMessage, RemoveMessageFields, ResponseMetadata, StandardContentBlockConverter, StandardMessageStructure, StoredGeneration, StoredMessage, StoredMessageData, StoredMessageV1, SystemMessage, SystemMessageChunk, SystemMessageFields, ToolCall, ToolCallChunk, ToolMessage, ToolMessageChunk, ToolMessageFields, TrimMessagesFields, UsageMetadata, _isMessageFieldWithRole, _mergeDicts, _mergeLists, _mergeObj, _mergeStatus, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, convertToOpenAIImageBlock, convertToProviderContentBlock, defaultTextSplitter, defaultToolCallParser, filterMessages, getBufferString, iife, isAIMessage, isAIMessageChunk, isBase64ContentBlock, isBaseMessage, isBaseMessageChunk, isChatMessage, isChatMessageChunk, isDataContentBlock, isDirectToolOutput, isFunctionMessage, isFunctionMessageChunk, isHumanMessage, isHumanMessageChunk, isIDContentBlock, isMessage, isOpenAIToolCallArray, isPlainTextContentBlock, isSystemMessage, isSystemMessageChunk, isToolMessage, isToolMessageChunk, isURLContentBlock, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages, mergeContent, mergeMessageRuns, mergeResponseMetadata, mergeUsageMetadata, parseBase64DataUrl, parseMimeType, trimMessages };
|
package/dist/messages/index.js
CHANGED
|
@@ -4,13 +4,13 @@ import { isMessage } from "./message.js";
|
|
|
4
4
|
import { BaseMessage, BaseMessageChunk, _isMessageFieldWithRole, _mergeDicts, _mergeLists, _mergeObj, _mergeStatus, isBaseMessage, isBaseMessageChunk, isOpenAIToolCallArray, mergeContent } from "./base.js";
|
|
5
5
|
import { mergeResponseMetadata, mergeUsageMetadata } from "./metadata.js";
|
|
6
6
|
import { ToolMessage, ToolMessageChunk, defaultToolCallParser, isDirectToolOutput, isToolMessage, isToolMessageChunk } from "./tool.js";
|
|
7
|
-
import { AIMessage, AIMessageChunk, isAIMessage, isAIMessageChunk } from "./ai.js";
|
|
8
7
|
import { ChatMessage, ChatMessageChunk, isChatMessage, isChatMessageChunk } from "./chat.js";
|
|
9
8
|
import { FunctionMessage, FunctionMessageChunk, isFunctionMessage, isFunctionMessageChunk } from "./function.js";
|
|
10
9
|
import { HumanMessage, HumanMessageChunk, isHumanMessage, isHumanMessageChunk } from "./human.js";
|
|
11
|
-
import { SystemMessage, SystemMessageChunk, isSystemMessage, isSystemMessageChunk } from "./system.js";
|
|
12
10
|
import { RemoveMessage } from "./modifier.js";
|
|
13
|
-
import {
|
|
11
|
+
import { SystemMessage, SystemMessageChunk, isSystemMessage, isSystemMessageChunk } from "./system.js";
|
|
12
|
+
import { coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages } from "./utils.js";
|
|
13
|
+
import { AIMessage, AIMessageChunk, isAIMessage, isAIMessageChunk } from "./ai.js";
|
|
14
14
|
import { defaultTextSplitter, filterMessages, mergeMessageRuns, trimMessages } from "./transformers.js";
|
|
15
15
|
import { KNOWN_BLOCK_TYPES } from "./content/index.js";
|
|
16
16
|
|
|
@@ -39,6 +39,7 @@ __export(messages_exports, {
|
|
|
39
39
|
_mergeObj: () => _mergeObj,
|
|
40
40
|
_mergeStatus: () => _mergeStatus,
|
|
41
41
|
coerceMessageLikeToMessage: () => coerceMessageLikeToMessage,
|
|
42
|
+
collapseToolCallChunks: () => collapseToolCallChunks,
|
|
42
43
|
convertToChunk: () => convertToChunk,
|
|
43
44
|
convertToOpenAIImageBlock: () => convertToOpenAIImageBlock,
|
|
44
45
|
convertToProviderContentBlock: () => convertToProviderContentBlock,
|
|
@@ -82,5 +83,5 @@ __export(messages_exports, {
|
|
|
82
83
|
});
|
|
83
84
|
|
|
84
85
|
//#endregion
|
|
85
|
-
export { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, ChatMessage, ChatMessageChunk, FunctionMessage, FunctionMessageChunk, HumanMessage, HumanMessageChunk, KNOWN_BLOCK_TYPES, RemoveMessage, SystemMessage, SystemMessageChunk, ToolMessage, ToolMessageChunk, _isMessageFieldWithRole, _mergeDicts, _mergeLists, _mergeObj, _mergeStatus, coerceMessageLikeToMessage, convertToChunk, convertToOpenAIImageBlock, convertToProviderContentBlock, defaultTextSplitter, defaultToolCallParser, filterMessages, getBufferString, iife, isAIMessage, isAIMessageChunk, isBase64ContentBlock, isBaseMessage, isBaseMessageChunk, isChatMessage, isChatMessageChunk, isDataContentBlock, isDirectToolOutput, isFunctionMessage, isFunctionMessageChunk, isHumanMessage, isHumanMessageChunk, isIDContentBlock, isMessage, isOpenAIToolCallArray, isPlainTextContentBlock, isSystemMessage, isSystemMessageChunk, isToolMessage, isToolMessageChunk, isURLContentBlock, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages, mergeContent, mergeMessageRuns, mergeResponseMetadata, mergeUsageMetadata, messages_exports, parseBase64DataUrl, parseMimeType, trimMessages };
|
|
86
|
+
export { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, ChatMessage, ChatMessageChunk, FunctionMessage, FunctionMessageChunk, HumanMessage, HumanMessageChunk, KNOWN_BLOCK_TYPES, RemoveMessage, SystemMessage, SystemMessageChunk, ToolMessage, ToolMessageChunk, _isMessageFieldWithRole, _mergeDicts, _mergeLists, _mergeObj, _mergeStatus, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, convertToOpenAIImageBlock, convertToProviderContentBlock, defaultTextSplitter, defaultToolCallParser, filterMessages, getBufferString, iife, isAIMessage, isAIMessageChunk, isBase64ContentBlock, isBaseMessage, isBaseMessageChunk, isChatMessage, isChatMessageChunk, isDataContentBlock, isDirectToolOutput, isFunctionMessage, isFunctionMessageChunk, isHumanMessage, isHumanMessageChunk, isIDContentBlock, isMessage, isOpenAIToolCallArray, isPlainTextContentBlock, isSystemMessage, isSystemMessageChunk, isToolMessage, isToolMessageChunk, isURLContentBlock, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages, mergeContent, mergeMessageRuns, mergeResponseMetadata, mergeUsageMetadata, messages_exports, parseBase64DataUrl, parseMimeType, trimMessages };
|
|
86
87
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
const require_base = require('./base.cjs');
|
|
2
2
|
const require_messages_tool = require('./tool.cjs');
|
|
3
|
-
const require_ai = require('./ai.cjs');
|
|
4
3
|
const require_chat = require('./chat.cjs');
|
|
5
4
|
const require_function = require('./function.cjs');
|
|
6
5
|
const require_human = require('./human.cjs');
|
|
7
|
-
const require_system = require('./system.cjs');
|
|
8
6
|
const require_modifier = require('./modifier.cjs');
|
|
7
|
+
const require_system = require('./system.cjs');
|
|
9
8
|
const require_utils = require('./utils.cjs');
|
|
9
|
+
const require_ai = require('./ai.cjs');
|
|
10
10
|
const require_base$1 = require('../runnables/base.cjs');
|
|
11
11
|
|
|
12
12
|
//#region src/messages/transformers.ts
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { isBaseMessageChunk } from "./base.js";
|
|
2
2
|
import { ToolMessage, ToolMessageChunk } from "./tool.js";
|
|
3
|
-
import { AIMessage, AIMessageChunk } from "./ai.js";
|
|
4
3
|
import { ChatMessage, ChatMessageChunk } from "./chat.js";
|
|
5
4
|
import { FunctionMessage, FunctionMessageChunk } from "./function.js";
|
|
6
5
|
import { HumanMessage, HumanMessageChunk } from "./human.js";
|
|
7
|
-
import { SystemMessage, SystemMessageChunk } from "./system.js";
|
|
8
6
|
import { RemoveMessage } from "./modifier.js";
|
|
7
|
+
import { SystemMessage, SystemMessageChunk } from "./system.js";
|
|
9
8
|
import { convertToChunk } from "./utils.js";
|
|
9
|
+
import { AIMessage, AIMessageChunk } from "./ai.js";
|
|
10
10
|
import { RunnableLambda } from "../runnables/base.js";
|
|
11
11
|
|
|
12
12
|
//#region src/messages/transformers.ts
|
package/dist/messages/utils.cjs
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
const require_base = require('./base.cjs');
|
|
2
2
|
const require_messages_tool = require('./tool.cjs');
|
|
3
|
-
const
|
|
3
|
+
const require_index = require('../errors/index.cjs');
|
|
4
|
+
const require_utils = require('../tools/utils.cjs');
|
|
5
|
+
const require_json = require('../utils/json.cjs');
|
|
4
6
|
const require_chat = require('./chat.cjs');
|
|
5
7
|
const require_function = require('./function.cjs');
|
|
6
8
|
const require_human = require('./human.cjs');
|
|
7
|
-
const require_system = require('./system.cjs');
|
|
8
|
-
const require_index = require('../errors/index.cjs');
|
|
9
|
-
const require_utils = require('../tools/utils.cjs');
|
|
10
9
|
const require_modifier = require('./modifier.cjs');
|
|
10
|
+
const require_system = require('./system.cjs');
|
|
11
|
+
const require_ai = require('./ai.cjs');
|
|
11
12
|
|
|
12
13
|
//#region src/messages/utils.ts
|
|
13
14
|
/**
|
|
@@ -196,9 +197,81 @@ function convertToChunk(message) {
|
|
|
196
197
|
else if (require_chat.ChatMessage.isInstance(message)) return new require_chat.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 = require_json.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
273
|
exports.coerceMessageLikeToMessage = coerceMessageLikeToMessage;
|
|
274
|
+
exports.collapseToolCallChunks = collapseToolCallChunks;
|
|
202
275
|
exports.convertToChunk = convertToChunk;
|
|
203
276
|
exports.getBufferString = getBufferString;
|
|
204
277
|
exports.iife = iife;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","names":["fn: () => T","toolCall: ToolCall | Record<string, unknown>","_isToolCall","x: unknown","params:\n | (BaseMessageFields & { type: string } & Record<string, unknown>)\n | SerializedConstructor","type: string","rest: BaseMessageFields & Record<string, unknown>","HumanMessage","AIMessage","SystemMessage","ToolMessage","RemoveMessage","addLangChainErrorFields","messageLike: BaseMessageLike","isBaseMessage","_isMessageFieldWithRole","messages: BaseMessage[]","string_messages: string[]","role: string","message: StoredMessage | StoredMessageV1","message: StoredMessage","FunctionMessage","ChatMessage","messages: StoredMessage[]","message: BaseMessage","HumanMessageChunk","aiChunkFields: AIMessageChunkFields","AIMessageChunk","SystemMessageChunk","FunctionMessageChunk","ChatMessageChunk"],"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,KAAIC,0BAAY,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,SAA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ClB,gBAAgB;GACd,GAAG;GACH,kBAAkB,cAAc,YAAY,IAAI,CAAC,QAAQ;IACvD,GAAG;IACH,MAAM;IACN,OAAO;IACP,MAAM,KAAK,UAAU,GAAG,KAAK;GAC9B,GAAE;EACJ;AAEH,SAAO,IAAIC,0BAAe,EAAE,GAAG,cAAe;CAC/C,WAAU,SAAS,SAClB,QAAO,IAAIC,kCAAmB,EAAE,GAAG,QAAS;UACnC,SAAS,WAClB,QAAO,IAAIC,sCAAqB,EAAE,GAAG,QAAS;UACrCP,yBAAY,WAAW,QAAQ,CACxC,QAAO,IAAIQ,8BAAiB,EAAE,GAAG,QAAS;KAE1C,OAAM,IAAI,MAAM;AAEnB"}
|
|
1
|
+
{"version":3,"file":"utils.cjs","names":["fn: () => T","toolCall: ToolCall | Record<string, unknown>","_isToolCall","x: unknown","params:\n | (BaseMessageFields & { type: string } & Record<string, unknown>)\n | SerializedConstructor","type: string","rest: BaseMessageFields & Record<string, unknown>","HumanMessage","AIMessage","SystemMessage","ToolMessage","RemoveMessage","addLangChainErrorFields","messageLike: BaseMessageLike","isBaseMessage","_isMessageFieldWithRole","messages: BaseMessage[]","string_messages: string[]","role: string","message: StoredMessage | StoredMessageV1","message: StoredMessage","FunctionMessage","ChatMessage","messages: StoredMessage[]","message: BaseMessage","HumanMessageChunk","aiChunkFields: AIMessageChunkFields","AIMessageChunk","SystemMessageChunk","FunctionMessageChunk","ChatMessageChunk","chunks: ToolCallChunk[]","toolCalls: ToolCall[]","invalidToolCalls: InvalidToolCall[]","chunks","parsedArgs: Record<string, unknown> | null","parsePartialJson"],"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,KAAIC,0BAAY,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,wBAAwB,OAAO,EAAE;EACnC,MAAM,YAAY,OAAO,GAAG,GAAG,GAAG;AAClC,MAAI,cAAc,kBAAkB,cAAc,qBAChD,OAAO;WACE,cAAc,eAAe,cAAc,kBACpD,OAAO;WAEP,cAAc,mBACd,cAAc,sBAEd,OAAO;WAEP,cAAc,qBACd,cAAc,wBAEd,OAAO;WAEP,cAAc,iBACd,cAAc,oBAEd,OAA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AAM,oBAAoB,IAAI,UAAU,CAAC,CAAC,MAAM,KAAK;AAEnD,OACE,QAAQ,SACR,MAAM,MACN,WAAW,SACX,MAAM,UAAU,OAEhB,QAAO,MAAM,OAAO,MAAM,MAAM,MAAM,UAAU,MAAM;AAGxD,OAAI,QAAQ,SAAS,MAAM,GACzB,QAAO,MAAM,OAAO,MAAM;AAG5B,OAAI,WAAW,SAAS,MAAM,UAAU,OACtC,QAAO,MAAM,UAAU,MAAM;AAE/B,UAAO;EACR,EAAC;AACF,MAAI,sBAAsB,IACxB,IAAI,mBAAmB,KAAK,MAAM;OAElC,IAAI,KAAK,CAAC,KAAM,EAAC;AAEnB,SAAO;CACR,GAAE,CAAE,EAAsB;CAE3B,MAAMC,YAAwB,CAAE;CAChC,MAAMC,mBAAsC,CAAE;AAC9C,MAAK,MAAMC,YAAU,uBAAuB;EAC1C,IAAIC,aAA6C;EACjD,MAAM,OAAOD,SAAO,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,aAAaE,8BAAiB,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"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BaseMessage, BaseMessageLike, StoredMessage } from "./base.cjs";
|
|
2
|
-
import { ToolMessage } from "./tool.cjs";
|
|
2
|
+
import { InvalidToolCall, ToolCall, ToolCallChunk, ToolMessage } from "./tool.cjs";
|
|
3
3
|
import { AIMessage, AIMessageChunk } from "./ai.cjs";
|
|
4
4
|
import { ChatMessage, ChatMessageChunk } from "./chat.cjs";
|
|
5
5
|
import { FunctionMessage, FunctionMessageChunk } from "./function.cjs";
|
|
@@ -111,6 +111,37 @@ declare function mapStoredMessagesToChatMessages(messages: StoredMessage[]): Bas
|
|
|
111
111
|
*/
|
|
112
112
|
declare function mapChatMessagesToStoredMessages(messages: BaseMessage[]): StoredMessage[];
|
|
113
113
|
declare function convertToChunk(message: BaseMessage): AIMessageChunk<MessageStructure> | ChatMessageChunk<MessageStructure> | FunctionMessageChunk<MessageStructure> | HumanMessageChunk<MessageStructure> | SystemMessageChunk<MessageStructure>;
|
|
114
|
+
/**
|
|
115
|
+
* Collapses an array of tool call chunks into complete tool calls.
|
|
116
|
+
*
|
|
117
|
+
* This function groups tool call chunks by their id and/or index, then attempts to
|
|
118
|
+
* parse and validate the accumulated arguments for each group. Successfully parsed
|
|
119
|
+
* tool calls are returned as valid `ToolCall` objects, while malformed ones are
|
|
120
|
+
* returned as `InvalidToolCall` objects.
|
|
121
|
+
*
|
|
122
|
+
* @param chunks - An array of `ToolCallChunk` objects to collapse
|
|
123
|
+
* @returns An object containing:
|
|
124
|
+
* - `tool_call_chunks`: The original input chunks
|
|
125
|
+
* - `tool_calls`: An array of successfully parsed and validated tool calls
|
|
126
|
+
* - `invalid_tool_calls`: An array of tool calls that failed parsing or validation
|
|
127
|
+
*
|
|
128
|
+
* @remarks
|
|
129
|
+
* Chunks are grouped using the following matching logic:
|
|
130
|
+
* - If a chunk has both an id and index, it matches chunks with the same id and index
|
|
131
|
+
* - If a chunk has only an id, it matches chunks with the same id
|
|
132
|
+
* - If a chunk has only an index, it matches chunks with the same index
|
|
133
|
+
*
|
|
134
|
+
* For each group, the function:
|
|
135
|
+
* 1. Concatenates all `args` strings from the chunks
|
|
136
|
+
* 2. Attempts to parse the concatenated string as JSON
|
|
137
|
+
* 3. Validates that the result is a non-null object with a valid id
|
|
138
|
+
* 4. Creates either a `ToolCall` (if valid) or `InvalidToolCall` (if invalid)
|
|
139
|
+
*/
|
|
140
|
+
declare function collapseToolCallChunks(chunks: ToolCallChunk[]): {
|
|
141
|
+
tool_call_chunks: ToolCallChunk[];
|
|
142
|
+
tool_calls: ToolCall[];
|
|
143
|
+
invalid_tool_calls: InvalidToolCall[];
|
|
144
|
+
};
|
|
114
145
|
//#endregion
|
|
115
|
-
export { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
|
|
146
|
+
export { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
|
|
116
147
|
//# sourceMappingURL=utils.d.cts.map
|
package/dist/messages/utils.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BaseMessage, BaseMessageLike, StoredMessage } from "./base.js";
|
|
2
|
-
import { ToolMessage } from "./tool.js";
|
|
2
|
+
import { InvalidToolCall, ToolCall, ToolCallChunk, ToolMessage } from "./tool.js";
|
|
3
3
|
import { AIMessage, AIMessageChunk } from "./ai.js";
|
|
4
4
|
import { ChatMessage, ChatMessageChunk } from "./chat.js";
|
|
5
5
|
import { FunctionMessage, FunctionMessageChunk } from "./function.js";
|
|
@@ -111,6 +111,37 @@ declare function mapStoredMessagesToChatMessages(messages: StoredMessage[]): Bas
|
|
|
111
111
|
*/
|
|
112
112
|
declare function mapChatMessagesToStoredMessages(messages: BaseMessage[]): StoredMessage[];
|
|
113
113
|
declare function convertToChunk(message: BaseMessage): AIMessageChunk<MessageStructure> | ChatMessageChunk<MessageStructure> | FunctionMessageChunk<MessageStructure> | HumanMessageChunk<MessageStructure> | SystemMessageChunk<MessageStructure>;
|
|
114
|
+
/**
|
|
115
|
+
* Collapses an array of tool call chunks into complete tool calls.
|
|
116
|
+
*
|
|
117
|
+
* This function groups tool call chunks by their id and/or index, then attempts to
|
|
118
|
+
* parse and validate the accumulated arguments for each group. Successfully parsed
|
|
119
|
+
* tool calls are returned as valid `ToolCall` objects, while malformed ones are
|
|
120
|
+
* returned as `InvalidToolCall` objects.
|
|
121
|
+
*
|
|
122
|
+
* @param chunks - An array of `ToolCallChunk` objects to collapse
|
|
123
|
+
* @returns An object containing:
|
|
124
|
+
* - `tool_call_chunks`: The original input chunks
|
|
125
|
+
* - `tool_calls`: An array of successfully parsed and validated tool calls
|
|
126
|
+
* - `invalid_tool_calls`: An array of tool calls that failed parsing or validation
|
|
127
|
+
*
|
|
128
|
+
* @remarks
|
|
129
|
+
* Chunks are grouped using the following matching logic:
|
|
130
|
+
* - If a chunk has both an id and index, it matches chunks with the same id and index
|
|
131
|
+
* - If a chunk has only an id, it matches chunks with the same id
|
|
132
|
+
* - If a chunk has only an index, it matches chunks with the same index
|
|
133
|
+
*
|
|
134
|
+
* For each group, the function:
|
|
135
|
+
* 1. Concatenates all `args` strings from the chunks
|
|
136
|
+
* 2. Attempts to parse the concatenated string as JSON
|
|
137
|
+
* 3. Validates that the result is a non-null object with a valid id
|
|
138
|
+
* 4. Creates either a `ToolCall` (if valid) or `InvalidToolCall` (if invalid)
|
|
139
|
+
*/
|
|
140
|
+
declare function collapseToolCallChunks(chunks: ToolCallChunk[]): {
|
|
141
|
+
tool_call_chunks: ToolCallChunk[];
|
|
142
|
+
tool_calls: ToolCall[];
|
|
143
|
+
invalid_tool_calls: InvalidToolCall[];
|
|
144
|
+
};
|
|
114
145
|
//#endregion
|
|
115
|
-
export { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
|
|
146
|
+
export { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
|
|
116
147
|
//# sourceMappingURL=utils.d.ts.map
|