@langchain/core 1.1.47 → 1.1.48
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 +25 -0
- package/dist/callbacks/base.cjs +2 -3
- package/dist/callbacks/base.cjs.map +1 -1
- package/dist/callbacks/base.js +1 -2
- package/dist/callbacks/base.js.map +1 -1
- package/dist/callbacks/manager.cjs +7 -8
- package/dist/callbacks/manager.cjs.map +1 -1
- package/dist/callbacks/manager.js +1 -2
- package/dist/callbacks/manager.js.map +1 -1
- package/dist/indexing/base.cjs +3 -4
- package/dist/indexing/base.cjs.map +1 -1
- package/dist/indexing/base.js +1 -2
- package/dist/indexing/base.js.map +1 -1
- package/dist/language_models/base.cjs +1 -1
- package/dist/language_models/base.js +1 -1
- package/dist/messages/block_translators/index.cjs +2 -0
- package/dist/messages/block_translators/index.cjs.map +1 -1
- package/dist/messages/block_translators/index.js +2 -0
- package/dist/messages/block_translators/index.js.map +1 -1
- package/dist/messages/block_translators/openrouter.cjs +101 -0
- package/dist/messages/block_translators/openrouter.cjs.map +1 -0
- package/dist/messages/block_translators/openrouter.js +101 -0
- package/dist/messages/block_translators/openrouter.js.map +1 -0
- package/dist/messages/index.d.cts +2 -2
- package/dist/messages/index.d.ts +2 -2
- package/dist/messages/utils.cjs +16 -2
- package/dist/messages/utils.cjs.map +1 -1
- package/dist/messages/utils.d.cts +9 -1
- package/dist/messages/utils.d.cts.map +1 -1
- package/dist/messages/utils.d.ts +9 -1
- package/dist/messages/utils.d.ts.map +1 -1
- package/dist/messages/utils.js +16 -2
- package/dist/messages/utils.js.map +1 -1
- package/dist/runnables/base.cjs +2 -3
- package/dist/runnables/base.cjs.map +1 -1
- package/dist/runnables/base.js +1 -2
- package/dist/runnables/base.js.map +1 -1
- package/dist/runnables/graph.cjs +6 -8
- package/dist/runnables/graph.cjs.map +1 -1
- package/dist/runnables/graph.js +1 -3
- package/dist/runnables/graph.js.map +1 -1
- package/dist/utils/uuid/index.cjs +33 -22
- package/dist/utils/uuid/index.cjs.map +1 -1
- package/dist/utils/uuid/index.d.cts +25 -12
- package/dist/utils/uuid/index.d.cts.map +1 -0
- package/dist/utils/uuid/index.d.ts +25 -12
- package/dist/utils/uuid/index.d.ts.map +1 -0
- package/dist/utils/uuid/index.js +23 -12
- package/dist/utils/uuid/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/utils/uuid/max.d.cts +0 -5
- package/dist/utils/uuid/max.d.cts.map +0 -1
- package/dist/utils/uuid/max.d.ts +0 -5
- package/dist/utils/uuid/max.d.ts.map +0 -1
- package/dist/utils/uuid/nil.d.cts +0 -5
- package/dist/utils/uuid/nil.d.cts.map +0 -1
- package/dist/utils/uuid/nil.d.ts +0 -5
- package/dist/utils/uuid/nil.d.ts.map +0 -1
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
const require_utils = require("./utils.cjs");
|
|
2
|
+
//#region src/messages/block_translators/openrouter.ts
|
|
3
|
+
/**
|
|
4
|
+
* Converts an OpenRouter AI message to an array of v1 standard content blocks.
|
|
5
|
+
*
|
|
6
|
+
* OpenRouter returns reasoning output through two places on the Chat
|
|
7
|
+
* Completions response:
|
|
8
|
+
*
|
|
9
|
+
* 1. `message.reasoning` / `delta.reasoning` — a flat string that summarizes
|
|
10
|
+
* the model's chain of thought. The `@langchain/openrouter` converter
|
|
11
|
+
* normalizes this into `additional_kwargs.reasoning_content` so it matches
|
|
12
|
+
* the DeepSeek convention already used elsewhere in LangChain.
|
|
13
|
+
* 2. `message.reasoning_details` / `delta.reasoning_details` — a structured
|
|
14
|
+
* array of provider-specific reasoning artifacts (see the
|
|
15
|
+
* `reasoning.summary` / `reasoning.encrypted` / `reasoning.text` union in
|
|
16
|
+
* the OpenRouter API types). The converter preserves these verbatim under
|
|
17
|
+
* `additional_kwargs.reasoning_details` for round-tripping back to the
|
|
18
|
+
* provider on subsequent turns (e.g. Anthropic extended thinking requires
|
|
19
|
+
* the original `signature` to be echoed back).
|
|
20
|
+
*
|
|
21
|
+
* When `reasoning_details` is present, visible blocks are emitted from
|
|
22
|
+
* `reasoning.summary` / `reasoning.text` entries. If the array contains only
|
|
23
|
+
* opaque artifacts (e.g. `reasoning.encrypted`), the flat `reasoning_content`
|
|
24
|
+
* string is used as a fallback when available.
|
|
25
|
+
*
|
|
26
|
+
* @param message - The AI message containing OpenRouter-formatted content
|
|
27
|
+
* @returns Array of content blocks in v1 standard format
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```typescript
|
|
31
|
+
* const message = new AIMessage({
|
|
32
|
+
* content: "The answer is 42",
|
|
33
|
+
* additional_kwargs: { reasoning_content: "Let me think about this..." },
|
|
34
|
+
* response_metadata: { model_provider: "openrouter" },
|
|
35
|
+
* });
|
|
36
|
+
* message.contentBlocks;
|
|
37
|
+
* // [
|
|
38
|
+
* // { type: "reasoning", reasoning: "Let me think about this..." },
|
|
39
|
+
* // { type: "text", text: "The answer is 42" }
|
|
40
|
+
* // ]
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
function convertToV1FromOpenRouterMessage(message) {
|
|
44
|
+
const blocks = [];
|
|
45
|
+
const reasoningDetails = message.additional_kwargs?.reasoning_details;
|
|
46
|
+
let hasVisibleReasoningFromDetails = false;
|
|
47
|
+
if (Array.isArray(reasoningDetails) && reasoningDetails.length > 0) for (const detail of reasoningDetails) {
|
|
48
|
+
if (detail == null || typeof detail !== "object") continue;
|
|
49
|
+
const type = detail.type;
|
|
50
|
+
if (type === "reasoning.summary") {
|
|
51
|
+
const summary = detail.summary;
|
|
52
|
+
if (require_utils._isString(summary) && summary.length > 0) {
|
|
53
|
+
blocks.push({
|
|
54
|
+
type: "reasoning",
|
|
55
|
+
reasoning: summary
|
|
56
|
+
});
|
|
57
|
+
hasVisibleReasoningFromDetails = true;
|
|
58
|
+
}
|
|
59
|
+
} else if (type === "reasoning.text") {
|
|
60
|
+
const text = detail.text;
|
|
61
|
+
if (require_utils._isString(text) && text.length > 0) {
|
|
62
|
+
blocks.push({
|
|
63
|
+
type: "reasoning",
|
|
64
|
+
reasoning: text
|
|
65
|
+
});
|
|
66
|
+
hasVisibleReasoningFromDetails = true;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (!hasVisibleReasoningFromDetails) {
|
|
71
|
+
const reasoningContent = message.additional_kwargs?.reasoning_content;
|
|
72
|
+
if (require_utils._isString(reasoningContent) && reasoningContent.length > 0) blocks.push({
|
|
73
|
+
type: "reasoning",
|
|
74
|
+
reasoning: reasoningContent
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
if (typeof message.content === "string") {
|
|
78
|
+
if (message.content.length > 0) blocks.push({
|
|
79
|
+
type: "text",
|
|
80
|
+
text: message.content
|
|
81
|
+
});
|
|
82
|
+
} else for (const block of message.content) if (typeof block === "object" && "type" in block && block.type === "text" && "text" in block && require_utils._isString(block.text)) blocks.push({
|
|
83
|
+
type: "text",
|
|
84
|
+
text: block.text
|
|
85
|
+
});
|
|
86
|
+
for (const toolCall of message.tool_calls ?? []) blocks.push({
|
|
87
|
+
type: "tool_call",
|
|
88
|
+
id: toolCall.id,
|
|
89
|
+
name: toolCall.name,
|
|
90
|
+
args: toolCall.args
|
|
91
|
+
});
|
|
92
|
+
return blocks;
|
|
93
|
+
}
|
|
94
|
+
const ChatOpenRouterTranslator = {
|
|
95
|
+
translateContent: convertToV1FromOpenRouterMessage,
|
|
96
|
+
translateContentChunk: convertToV1FromOpenRouterMessage
|
|
97
|
+
};
|
|
98
|
+
//#endregion
|
|
99
|
+
exports.ChatOpenRouterTranslator = ChatOpenRouterTranslator;
|
|
100
|
+
|
|
101
|
+
//# sourceMappingURL=openrouter.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openrouter.cjs","names":["_isString"],"sources":["../../../src/messages/block_translators/openrouter.ts"],"sourcesContent":["import { AIMessage } from \"../ai.js\";\nimport { ContentBlock } from \"../content/index.js\";\nimport type { StandardContentBlockTranslator } from \"./index.js\";\nimport { _isString } from \"./utils.js\";\n\n/**\n * Converts an OpenRouter AI message to an array of v1 standard content blocks.\n *\n * OpenRouter returns reasoning output through two places on the Chat\n * Completions response:\n *\n * 1. `message.reasoning` / `delta.reasoning` — a flat string that summarizes\n * the model's chain of thought. The `@langchain/openrouter` converter\n * normalizes this into `additional_kwargs.reasoning_content` so it matches\n * the DeepSeek convention already used elsewhere in LangChain.\n * 2. `message.reasoning_details` / `delta.reasoning_details` — a structured\n * array of provider-specific reasoning artifacts (see the\n * `reasoning.summary` / `reasoning.encrypted` / `reasoning.text` union in\n * the OpenRouter API types). The converter preserves these verbatim under\n * `additional_kwargs.reasoning_details` for round-tripping back to the\n * provider on subsequent turns (e.g. Anthropic extended thinking requires\n * the original `signature` to be echoed back).\n *\n * When `reasoning_details` is present, visible blocks are emitted from\n * `reasoning.summary` / `reasoning.text` entries. If the array contains only\n * opaque artifacts (e.g. `reasoning.encrypted`), the flat `reasoning_content`\n * string is used as a fallback when available.\n *\n * @param message - The AI message containing OpenRouter-formatted content\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage({\n * content: \"The answer is 42\",\n * additional_kwargs: { reasoning_content: \"Let me think about this...\" },\n * response_metadata: { model_provider: \"openrouter\" },\n * });\n * message.contentBlocks;\n * // [\n * // { type: \"reasoning\", reasoning: \"Let me think about this...\" },\n * // { type: \"text\", text: \"The answer is 42\" }\n * // ]\n * ```\n */\nexport function convertToV1FromOpenRouterMessage(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n\n // Prefer structured reasoning_details when present — they can carry\n // multiple distinct reasoning artifacts (summary, encrypted, text).\n const reasoningDetails = message.additional_kwargs?.reasoning_details;\n let hasVisibleReasoningFromDetails = false;\n if (Array.isArray(reasoningDetails) && reasoningDetails.length > 0) {\n for (const detail of reasoningDetails) {\n if (detail == null || typeof detail !== \"object\") continue;\n const type = (detail as { type?: unknown }).type;\n if (type === \"reasoning.summary\") {\n const summary = (detail as { summary?: unknown }).summary;\n if (_isString(summary) && summary.length > 0) {\n blocks.push({ type: \"reasoning\", reasoning: summary });\n hasVisibleReasoningFromDetails = true;\n }\n } else if (type === \"reasoning.text\") {\n const text = (detail as { text?: unknown }).text;\n if (_isString(text) && text.length > 0) {\n blocks.push({ type: \"reasoning\", reasoning: text });\n hasVisibleReasoningFromDetails = true;\n }\n }\n // `reasoning.encrypted` details carry no human-readable text (only an\n // opaque `data` blob that must be echoed back to the provider), so they\n // do not become visible reasoning blocks. They stay in\n // `additional_kwargs.reasoning_details` for round-tripping.\n }\n }\n\n if (!hasVisibleReasoningFromDetails) {\n const reasoningContent = message.additional_kwargs?.reasoning_content;\n if (_isString(reasoningContent) && reasoningContent.length > 0) {\n blocks.push({\n type: \"reasoning\",\n reasoning: reasoningContent,\n });\n }\n }\n\n // Handle text content (string or multi-block array).\n if (typeof message.content === \"string\") {\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n for (const block of message.content) {\n if (\n typeof block === \"object\" &&\n \"type\" in block &&\n block.type === \"text\" &&\n \"text\" in block &&\n _isString(block.text)\n ) {\n blocks.push({\n type: \"text\",\n text: block.text,\n });\n }\n }\n }\n\n // Add tool calls if present.\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n\n return blocks;\n}\n\nexport const ChatOpenRouterTranslator: StandardContentBlockTranslator = {\n translateContent: convertToV1FromOpenRouterMessage,\n translateContentChunk: convertToV1FromOpenRouterMessage,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,iCACd,SAC8B;CAC9B,MAAM,SAAuC,EAAE;CAI/C,MAAM,mBAAmB,QAAQ,mBAAmB;CACpD,IAAI,iCAAiC;AACrC,KAAI,MAAM,QAAQ,i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
|
2
|
+
//#region src/messages/block_translators/openrouter.ts
|
|
3
|
+
/**
|
|
4
|
+
* Converts an OpenRouter AI message to an array of v1 standard content blocks.
|
|
5
|
+
*
|
|
6
|
+
* OpenRouter returns reasoning output through two places on the Chat
|
|
7
|
+
* Completions response:
|
|
8
|
+
*
|
|
9
|
+
* 1. `message.reasoning` / `delta.reasoning` — a flat string that summarizes
|
|
10
|
+
* the model's chain of thought. The `@langchain/openrouter` converter
|
|
11
|
+
* normalizes this into `additional_kwargs.reasoning_content` so it matches
|
|
12
|
+
* the DeepSeek convention already used elsewhere in LangChain.
|
|
13
|
+
* 2. `message.reasoning_details` / `delta.reasoning_details` — a structured
|
|
14
|
+
* array of provider-specific reasoning artifacts (see the
|
|
15
|
+
* `reasoning.summary` / `reasoning.encrypted` / `reasoning.text` union in
|
|
16
|
+
* the OpenRouter API types). The converter preserves these verbatim under
|
|
17
|
+
* `additional_kwargs.reasoning_details` for round-tripping back to the
|
|
18
|
+
* provider on subsequent turns (e.g. Anthropic extended thinking requires
|
|
19
|
+
* the original `signature` to be echoed back).
|
|
20
|
+
*
|
|
21
|
+
* When `reasoning_details` is present, visible blocks are emitted from
|
|
22
|
+
* `reasoning.summary` / `reasoning.text` entries. If the array contains only
|
|
23
|
+
* opaque artifacts (e.g. `reasoning.encrypted`), the flat `reasoning_content`
|
|
24
|
+
* string is used as a fallback when available.
|
|
25
|
+
*
|
|
26
|
+
* @param message - The AI message containing OpenRouter-formatted content
|
|
27
|
+
* @returns Array of content blocks in v1 standard format
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```typescript
|
|
31
|
+
* const message = new AIMessage({
|
|
32
|
+
* content: "The answer is 42",
|
|
33
|
+
* additional_kwargs: { reasoning_content: "Let me think about this..." },
|
|
34
|
+
* response_metadata: { model_provider: "openrouter" },
|
|
35
|
+
* });
|
|
36
|
+
* message.contentBlocks;
|
|
37
|
+
* // [
|
|
38
|
+
* // { type: "reasoning", reasoning: "Let me think about this..." },
|
|
39
|
+
* // { type: "text", text: "The answer is 42" }
|
|
40
|
+
* // ]
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
function convertToV1FromOpenRouterMessage(message) {
|
|
44
|
+
const blocks = [];
|
|
45
|
+
const reasoningDetails = message.additional_kwargs?.reasoning_details;
|
|
46
|
+
let hasVisibleReasoningFromDetails = false;
|
|
47
|
+
if (Array.isArray(reasoningDetails) && reasoningDetails.length > 0) for (const detail of reasoningDetails) {
|
|
48
|
+
if (detail == null || typeof detail !== "object") continue;
|
|
49
|
+
const type = detail.type;
|
|
50
|
+
if (type === "reasoning.summary") {
|
|
51
|
+
const summary = detail.summary;
|
|
52
|
+
if (_isString(summary) && summary.length > 0) {
|
|
53
|
+
blocks.push({
|
|
54
|
+
type: "reasoning",
|
|
55
|
+
reasoning: summary
|
|
56
|
+
});
|
|
57
|
+
hasVisibleReasoningFromDetails = true;
|
|
58
|
+
}
|
|
59
|
+
} else if (type === "reasoning.text") {
|
|
60
|
+
const text = detail.text;
|
|
61
|
+
if (_isString(text) && text.length > 0) {
|
|
62
|
+
blocks.push({
|
|
63
|
+
type: "reasoning",
|
|
64
|
+
reasoning: text
|
|
65
|
+
});
|
|
66
|
+
hasVisibleReasoningFromDetails = true;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (!hasVisibleReasoningFromDetails) {
|
|
71
|
+
const reasoningContent = message.additional_kwargs?.reasoning_content;
|
|
72
|
+
if (_isString(reasoningContent) && reasoningContent.length > 0) blocks.push({
|
|
73
|
+
type: "reasoning",
|
|
74
|
+
reasoning: reasoningContent
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
if (typeof message.content === "string") {
|
|
78
|
+
if (message.content.length > 0) blocks.push({
|
|
79
|
+
type: "text",
|
|
80
|
+
text: message.content
|
|
81
|
+
});
|
|
82
|
+
} else for (const block of message.content) if (typeof block === "object" && "type" in block && block.type === "text" && "text" in block && _isString(block.text)) blocks.push({
|
|
83
|
+
type: "text",
|
|
84
|
+
text: block.text
|
|
85
|
+
});
|
|
86
|
+
for (const toolCall of message.tool_calls ?? []) blocks.push({
|
|
87
|
+
type: "tool_call",
|
|
88
|
+
id: toolCall.id,
|
|
89
|
+
name: toolCall.name,
|
|
90
|
+
args: toolCall.args
|
|
91
|
+
});
|
|
92
|
+
return blocks;
|
|
93
|
+
}
|
|
94
|
+
const ChatOpenRouterTranslator = {
|
|
95
|
+
translateContent: convertToV1FromOpenRouterMessage,
|
|
96
|
+
translateContentChunk: convertToV1FromOpenRouterMessage
|
|
97
|
+
};
|
|
98
|
+
//#endregion
|
|
99
|
+
export { ChatOpenRouterTranslator };
|
|
100
|
+
|
|
101
|
+
//# sourceMappingURL=openrouter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openrouter.js","names":[],"sources":["../../../src/messages/block_translators/openrouter.ts"],"sourcesContent":["import { AIMessage } from \"../ai.js\";\nimport { ContentBlock } from \"../content/index.js\";\nimport type { StandardContentBlockTranslator } from \"./index.js\";\nimport { _isString } from \"./utils.js\";\n\n/**\n * Converts an OpenRouter AI message to an array of v1 standard content blocks.\n *\n * OpenRouter returns reasoning output through two places on the Chat\n * Completions response:\n *\n * 1. `message.reasoning` / `delta.reasoning` — a flat string that summarizes\n * the model's chain of thought. The `@langchain/openrouter` converter\n * normalizes this into `additional_kwargs.reasoning_content` so it matches\n * the DeepSeek convention already used elsewhere in LangChain.\n * 2. `message.reasoning_details` / `delta.reasoning_details` — a structured\n * array of provider-specific reasoning artifacts (see the\n * `reasoning.summary` / `reasoning.encrypted` / `reasoning.text` union in\n * the OpenRouter API types). The converter preserves these verbatim under\n * `additional_kwargs.reasoning_details` for round-tripping back to the\n * provider on subsequent turns (e.g. Anthropic extended thinking requires\n * the original `signature` to be echoed back).\n *\n * When `reasoning_details` is present, visible blocks are emitted from\n * `reasoning.summary` / `reasoning.text` entries. If the array contains only\n * opaque artifacts (e.g. `reasoning.encrypted`), the flat `reasoning_content`\n * string is used as a fallback when available.\n *\n * @param message - The AI message containing OpenRouter-formatted content\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage({\n * content: \"The answer is 42\",\n * additional_kwargs: { reasoning_content: \"Let me think about this...\" },\n * response_metadata: { model_provider: \"openrouter\" },\n * });\n * message.contentBlocks;\n * // [\n * // { type: \"reasoning\", reasoning: \"Let me think about this...\" },\n * // { type: \"text\", text: \"The answer is 42\" }\n * // ]\n * ```\n */\nexport function convertToV1FromOpenRouterMessage(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n\n // Prefer structured reasoning_details when present — they can carry\n // multiple distinct reasoning artifacts (summary, encrypted, text).\n const reasoningDetails = message.additional_kwargs?.reasoning_details;\n let hasVisibleReasoningFromDetails = false;\n if (Array.isArray(reasoningDetails) && reasoningDetails.length > 0) {\n for (const detail of reasoningDetails) {\n if (detail == null || typeof detail !== \"object\") continue;\n const type = (detail as { type?: unknown }).type;\n if (type === \"reasoning.summary\") {\n const summary = (detail as { summary?: unknown }).summary;\n if (_isString(summary) && summary.length > 0) {\n blocks.push({ type: \"reasoning\", reasoning: summary });\n hasVisibleReasoningFromDetails = true;\n }\n } else if (type === \"reasoning.text\") {\n const text = (detail as { text?: unknown }).text;\n if (_isString(text) && text.length > 0) {\n blocks.push({ type: \"reasoning\", reasoning: text });\n hasVisibleReasoningFromDetails = true;\n }\n }\n // `reasoning.encrypted` details carry no human-readable text (only an\n // opaque `data` blob that must be echoed back to the provider), so they\n // do not become visible reasoning blocks. They stay in\n // `additional_kwargs.reasoning_details` for round-tripping.\n }\n }\n\n if (!hasVisibleReasoningFromDetails) {\n const reasoningContent = message.additional_kwargs?.reasoning_content;\n if (_isString(reasoningContent) && reasoningContent.length > 0) {\n blocks.push({\n type: \"reasoning\",\n reasoning: reasoningContent,\n });\n }\n }\n\n // Handle text content (string or multi-block array).\n if (typeof message.content === \"string\") {\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n for (const block of message.content) {\n if (\n typeof block === \"object\" &&\n \"type\" in block &&\n block.type === \"text\" &&\n \"text\" in block &&\n _isString(block.text)\n ) {\n blocks.push({\n type: \"text\",\n text: block.text,\n });\n }\n }\n }\n\n // Add tool calls if present.\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n\n return blocks;\n}\n\nexport const ChatOpenRouterTranslator: StandardContentBlockTranslator = {\n translateContent: convertToV1FromOpenRouterMessage,\n translateContentChunk: convertToV1FromOpenRouterMessage,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,iCACd,SAC8B;CAC9B,MAAM,SAAuC,EAAE;CAI/C,MAAM,mBAAmB,QAAQ,mBAAmB;CACpD,IAAI,iCAAiC;AACrC,KAAI,MAAM,QAAQ,iBAAiB,IAAI,iBAAiB,SAAS,EAC/D,MAAK,MAAM,UAAU,kBAAkB;AACrC,MAAI,UAAU,QAAQ,OAAO,WAAW,SAAU;EAClD,MAAM,OAAQ,OAA8B;AAC5C,MAAI,SAAS,qBAAqB;GAChC,MAAM,UAAW,OAAiC;AAClD,OAAI,UAAU,QAAQ,IAAI,QAAQ,SAAS,GAAG;AAC5C,WAAO,KAAK;KAAE,MAAM;KAAa,WAAW;KAAS,CAAC;AACtD,qCAAiC;;aAE1B,SAAS,kBAAkB;GACpC,MAAM,OAAQ,OAA8B;AAC5C,OAAI,UAAU,KAAK,IAAI,KAAK,SAAS,GAAG;AACtC,WAAO,KAAK;KAAE,MAAM;KAAa,WAAW;KAAM,CAAC;AACnD,qCAAiC;;;;AAUzC,KAAI,CAAC,gCAAgC;EACnC,MAAM,mBAAmB,QAAQ,mBAAmB;AACpD,MAAI,UAAU,iBAAiB,IAAI,iBAAiB,SAAS,EAC3D,QAAO,KAAK;GACV,MAAM;GACN,WAAW;GACZ,CAAC;;AAKN,KAAI,OAAO,QAAQ,YAAY;MACzB,QAAQ,QAAQ,SAAS,EAC3B,QAAO,KAAK;GACV,MAAM;GACN,MAAM,QAAQ;GACf,CAAC;OAGJ,MAAK,MAAM,SAAS,QAAQ,QAC1B,KACE,OAAO,UAAU,YACjB,UAAU,SACV,MAAM,SAAS,UACf,UAAU,SACV,UAAU,MAAM,KAAK,CAErB,QAAO,KAAK;EACV,MAAM;EACN,MAAM,MAAM;EACb,CAAC;AAMR,MAAK,MAAM,YAAY,QAAQ,cAAc,EAAE,CAC7C,QAAO,KAAK;EACV,MAAM;EACN,IAAI,SAAS;EACb,MAAM,SAAS;EACf,MAAM,SAAS;EAChB,CAAC;AAGJ,QAAO;;AAGT,MAAa,2BAA2D;CACtE,kBAAkB;CAClB,uBAAuB;CACxB"}
|
|
@@ -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, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages } from "./utils.cjs";
|
|
11
|
+
import { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, RawInputToolCallChunk, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages } from "./utils.cjs";
|
|
12
12
|
import { $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $InferToolCalls, $InferToolOutputs, $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, $InferToolCalls, $InferToolOutputs, $MergeContentDefinition, $MergeDiscriminatedUnion, $MergeMessageStructure, $MergeObjects, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, AIMessage, AIMessageChunk, AIMessageChunkFields, AIMessageFields, BaseMessage, BaseMessageChunk, BaseMessageFields, BaseMessageLike, ChatMessage, ChatMessageChunk, ChatMessageFields, Constructor, ContentBlock, DEFAULT_MERGE_IGNORE_KEYS, Data, DirectToolOutput, FilterMessagesFields, FunctionCall, FunctionMessage, FunctionMessageChunk, FunctionMessageFields, HumanMessage, HumanMessageChunk, HumanMessageFields, ImageDetail, InputTokenDetails, InvalidToolCall, KNOWN_BLOCK_TYPES, MergeDictsOptions, Message, MessageChunkUnion, MessageContent, MessageContentComplex, MessageContentImageUrl, MessageContentText, MessageFieldWithRole, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, MessageTypeOrClass, MessageUnion, ModalitiesTokenDetails, OpenAIToolCall, OutputTokenDetails, PartialContentBlock, 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 };
|
|
15
|
+
export { $Expand, $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $InferToolCalls, $InferToolOutputs, $MergeContentDefinition, $MergeDiscriminatedUnion, $MergeMessageStructure, $MergeObjects, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, AIMessage, AIMessageChunk, AIMessageChunkFields, AIMessageFields, BaseMessage, BaseMessageChunk, BaseMessageFields, BaseMessageLike, ChatMessage, ChatMessageChunk, ChatMessageFields, Constructor, ContentBlock, DEFAULT_MERGE_IGNORE_KEYS, Data, DirectToolOutput, FilterMessagesFields, FunctionCall, FunctionMessage, FunctionMessageChunk, FunctionMessageFields, HumanMessage, HumanMessageChunk, HumanMessageFields, ImageDetail, InputTokenDetails, InvalidToolCall, KNOWN_BLOCK_TYPES, MergeDictsOptions, Message, MessageChunkUnion, MessageContent, MessageContentComplex, MessageContentImageUrl, MessageContentText, MessageFieldWithRole, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, MessageTypeOrClass, MessageUnion, ModalitiesTokenDetails, OpenAIToolCall, OutputTokenDetails, PartialContentBlock, ProviderFormatTypes, RawInputToolCallChunk, 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, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages } from "./utils.js";
|
|
11
|
+
import { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, RawInputToolCallChunk, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages } from "./utils.js";
|
|
12
12
|
import { $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $InferToolCalls, $InferToolOutputs, $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, $InferToolCalls, $InferToolOutputs, $MergeContentDefinition, $MergeDiscriminatedUnion, $MergeMessageStructure, $MergeObjects, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, AIMessage, AIMessageChunk, AIMessageChunkFields, AIMessageFields, BaseMessage, BaseMessageChunk, BaseMessageFields, BaseMessageLike, ChatMessage, ChatMessageChunk, ChatMessageFields, Constructor, ContentBlock, DEFAULT_MERGE_IGNORE_KEYS, Data, DirectToolOutput, FilterMessagesFields, FunctionCall, FunctionMessage, FunctionMessageChunk, FunctionMessageFields, HumanMessage, HumanMessageChunk, HumanMessageFields, ImageDetail, InputTokenDetails, InvalidToolCall, KNOWN_BLOCK_TYPES, MergeDictsOptions, Message, MessageChunkUnion, MessageContent, MessageContentComplex, MessageContentImageUrl, MessageContentText, MessageFieldWithRole, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, MessageTypeOrClass, MessageUnion, ModalitiesTokenDetails, OpenAIToolCall, OutputTokenDetails, PartialContentBlock, 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 };
|
|
15
|
+
export { $Expand, $InferMessageContent, $InferMessageContentBlocks, $InferMessageProperties, $InferMessageProperty, $InferResponseMetadata, $InferToolCalls, $InferToolOutputs, $MergeContentDefinition, $MergeDiscriminatedUnion, $MergeMessageStructure, $MergeObjects, $MergeOutputVersion, $MessageToolCallBlock, $NormalizedMessageStructure, AIMessage, AIMessageChunk, AIMessageChunkFields, AIMessageFields, BaseMessage, BaseMessageChunk, BaseMessageFields, BaseMessageLike, ChatMessage, ChatMessageChunk, ChatMessageFields, Constructor, ContentBlock, DEFAULT_MERGE_IGNORE_KEYS, Data, DirectToolOutput, FilterMessagesFields, FunctionCall, FunctionMessage, FunctionMessageChunk, FunctionMessageFields, HumanMessage, HumanMessageChunk, HumanMessageFields, ImageDetail, InputTokenDetails, InvalidToolCall, KNOWN_BLOCK_TYPES, MergeDictsOptions, Message, MessageChunkUnion, MessageContent, MessageContentComplex, MessageContentImageUrl, MessageContentText, MessageFieldWithRole, MessageOutputVersion, MessageStructure, MessageToolDefinition, MessageToolSet, MessageType, MessageTypeOrClass, MessageUnion, ModalitiesTokenDetails, OpenAIToolCall, OutputTokenDetails, PartialContentBlock, ProviderFormatTypes, RawInputToolCallChunk, 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/utils.cjs
CHANGED
|
@@ -10,6 +10,9 @@ const require_human = require("./human.cjs");
|
|
|
10
10
|
const require_modifier = require("./modifier.cjs");
|
|
11
11
|
const require_system = require("./system.cjs");
|
|
12
12
|
//#region src/messages/utils.ts
|
|
13
|
+
function chunkUsesRawInputArgs(chunk) {
|
|
14
|
+
return chunk.isCustomTool === true;
|
|
15
|
+
}
|
|
13
16
|
/**
|
|
14
17
|
* Immediately-invoked function expression.
|
|
15
18
|
*
|
|
@@ -278,10 +281,21 @@ function collapseToolCallChunks(chunks) {
|
|
|
278
281
|
const invalidToolCalls = [];
|
|
279
282
|
for (const chunks of groupedToolCallChunks) {
|
|
280
283
|
let parsedArgs = null;
|
|
284
|
+
const usesRawInputArgs = chunks.some(chunkUsesRawInputArgs);
|
|
281
285
|
const name = chunks[0]?.name ?? "";
|
|
282
|
-
const
|
|
286
|
+
const joinedArgsRaw = chunks.map((c) => c.args || "").join("");
|
|
287
|
+
const joinedArgs = usesRawInputArgs ? joinedArgsRaw : joinedArgsRaw.trim();
|
|
283
288
|
const argsStr = joinedArgs.length ? joinedArgs : "{}";
|
|
284
|
-
const id = chunks[0]?.id;
|
|
289
|
+
const id = chunks.find((c) => c.id)?.id ?? chunks[0]?.id;
|
|
290
|
+
if (usesRawInputArgs && id) {
|
|
291
|
+
toolCalls.push({
|
|
292
|
+
name,
|
|
293
|
+
args: { input: joinedArgs },
|
|
294
|
+
id,
|
|
295
|
+
type: "tool_call"
|
|
296
|
+
});
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
285
299
|
try {
|
|
286
300
|
parsedArgs = require_json.parsePartialJson(argsStr);
|
|
287
301
|
if (!id || parsedArgs === null || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) throw new Error("Malformed tool call chunk args.");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","names":["_isToolCall","HumanMessage","AIMessage","SystemMessage","ToolMessage","RemoveMessage","addLangChainErrorFields","isBaseMessage","_isMessageFieldWithRole","FunctionMessage","ChatMessage","HumanMessageChunk","AIMessageChunk","SystemMessageChunk","FunctionMessageChunk","ChatMessageChunk","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> =\n $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 * Renders a single content block to a compact string representation.\n * Text blocks are returned as-is; multimodal blocks (image, audio, video, file)\n * become short placeholders like `[image]` so their existence is preserved\n * without inflating token counts with base64 data or metadata.\n */\nfunction _contentBlockToString(\n block: string | { type?: string; [key: string]: unknown }\n): string {\n if (typeof block === \"string\") return block;\n switch (block.type) {\n case \"text\":\n return (block as { text: string }).text ?? \"\";\n case \"text-plain\":\n return (block as { text?: string }).text ?? \"[text-plain file]\";\n case \"image\":\n case \"image_url\":\n return \"[image]\";\n case \"audio\":\n case \"input_audio\":\n return \"[audio]\";\n case \"video\":\n return \"[video]\";\n case \"file\":\n return \"[file]\";\n case \"reasoning\":\n case \"tool_call\":\n case \"tool_call_chunk\":\n case \"invalid_tool_call\":\n case \"server_tool_call\":\n case \"server_tool_call_chunk\":\n case \"server_tool_call_result\":\n case \"non_standard\":\n return \"\";\n default:\n return block.type ? `[${block.type}]` : \"\";\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 *\n * Produces compact output like:\n * ```\n * Human: What's the weather?\n * AI: Let me check...[tool_calls]\n * Tool: 72°F and sunny\n * ```\n *\n * This avoids token inflation from metadata when stringifying message objects directly.\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.type === \"human\") {\n role = humanPrefix;\n } else if (m.type === \"ai\") {\n role = aiPrefix;\n } else if (m.type === \"system\") {\n role = \"System\";\n } else if (m.type === \"tool\") {\n role = \"Tool\";\n } else if (m.type === \"generic\") {\n role = (m as ChatMessage).role;\n } else {\n throw new Error(`Got unsupported message type: ${m.type}`);\n }\n const nameStr = m.name ? `${m.name}, ` : \"\";\n\n // Render content compactly: text as-is, multimodal blocks as placeholders\n const readableContent =\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? m.content.map(_contentBlockToString).filter(Boolean).join(\"\")\n : \"\";\n\n let message = `${role}: ${nameStr}${readableContent}`;\n\n // Include tool calls for AI messages (matching Python's get_buffer_string behavior)\n if (m.type === \"ai\") {\n const aiMessage = m as AIMessage;\n if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) {\n message += JSON.stringify(aiMessage.tool_calls);\n } else if (\n aiMessage.additional_kwargs &&\n \"function_call\" in aiMessage.additional_kwargs\n ) {\n // Legacy behavior assumes only one function call per message\n message += JSON.stringify(aiMessage.additional_kwargs.function_call);\n }\n }\n\n string_messages.push(message);\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":";;;;;;;;;;;;;;;;;;AAsKA,MAAa,QAAW,OAAgB,IAAI;AAE5C,SAAS,gBACP,UACU;AACV,KAAIA,cAAAA,YAAY,SAAS,CACvB,QAAO;UAEP,OAAO,SAAS,OAAO,YACvB,SAAS,SAAS,cAClB,OAAO,SAAS,aAAa,YAC7B,SAAS,aAAa,QACtB,eAAe,SAAS,YACxB,OAAO,SAAS,SAAS,cAAc,YACvC,UAAU,SAAS,YACnB,OAAO,SAAS,SAAS,SAAS,SAGlC,QAAO;EACL,IAAI,SAAS;EACb,MAAM,KAAK,MAAM,SAAS,SAAS,UAAU;EAC7C,MAAM,SAAS,SAAS;EACxB,MAAM;EACP;KAGD,QAAO;;AAIX,SAAS,wBAAwB,GAAwC;AACvE,QACE,OAAO,MAAM,YACb,KAAK,QACJ,EAA4B,OAAO,KACpC,MAAM,QAAS,EAA4B,GAAG,IAC7C,EAA4B,UAAU,QACvC,OAAQ,EAA4B,WAAW;;AAInD,SAAS,4BACP,QAGA;CACA,IAAI;CACJ,IAAI;AAEJ,KAAI,wBAAwB,OAAO,EAAE;EACnC,MAAM,YAAY,OA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,MAAM,GACzB,QAAO,MAAM,OAAO,MAAM;AAG5B,OAAI,WAAW,SAAS,MAAM,UAAU,KAAA,EACtC,QAAO,MAAM,UAAU,MAAM;AAE/B,UAAO;IACP;AACF,MAAI,sBAAsB,GACxB,KAAI,mBAAmB,KAAK,MAAM;MAElC,KAAI,KAAK,CAAC,MAAM,CAAC;AAEnB,SAAO;IACN,EAAE,CAAsB;CAE3B,MAAM,YAAwB,EAAE;CAChC,MAAM,mBAAsC,EAAE;AAC9C,MAAK,MAAM,UAAU,uBAAuB;EAC1C,IAAI,aAA6C;EACjD,MAAM,OAAO,OAAO,IAAI,QAAQ;EAChC,MAAM,aAAa,OAChB,KAAK,MAAM,EAAE,QAAQ,GAAG,CACxB,KAAK,GAAG,CACR,MAAM;EACT,MAAM,UAAU,WAAW,SAAS,aAAa;EACjD,MAAM,KAAK,OAAO,IAAI;AACtB,MAAI;AACF,gBAAaC,aAAAA,iBAAiB,QAAQ;AACtC,OACE,CAAC,MACD,eAAe,QACf,OAAO,eAAe,YACtB,MAAM,QAAQ,WAAW,CAEzB,OAAM,IAAI,MAAM,kCAAkC;AAEpD,aAAU,KAAK;IACb;IACA,MAAM;IACN;IACA,MAAM;IACP,CAAC;UACI;AACN,oBAAiB,KAAK;IACpB;IACA,MAAM;IACN;IACA,OAAO;IACP,MAAM;IACP,CAAC;;;AAGN,QAAO;EACL,kBAAkB;EAClB,YAAY;EACZ,oBAAoB;EACrB"}
|
|
1
|
+
{"version":3,"file":"utils.cjs","names":["_isToolCall","HumanMessage","AIMessage","SystemMessage","ToolMessage","RemoveMessage","addLangChainErrorFields","isBaseMessage","_isMessageFieldWithRole","FunctionMessage","ChatMessage","HumanMessageChunk","AIMessageChunk","SystemMessageChunk","FunctionMessageChunk","ChatMessageChunk","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 * Provider streaming marker for raw (non-JSON) tool input.\n * Not part of the public {@link ToolCallChunk} type; integrations may attach\n * `isCustomTool` at runtime and pass chunks typed as this alias.\n */\nexport type RawInputToolCallChunk = ToolCallChunk & { isCustomTool?: boolean };\n\nfunction chunkUsesRawInputArgs(chunk: ToolCallChunk): boolean {\n return (chunk as RawInputToolCallChunk).isCustomTool === true;\n}\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> =\n $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 * Renders a single content block to a compact string representation.\n * Text blocks are returned as-is; multimodal blocks (image, audio, video, file)\n * become short placeholders like `[image]` so their existence is preserved\n * without inflating token counts with base64 data or metadata.\n */\nfunction _contentBlockToString(\n block: string | { type?: string; [key: string]: unknown }\n): string {\n if (typeof block === \"string\") return block;\n switch (block.type) {\n case \"text\":\n return (block as { text: string }).text ?? \"\";\n case \"text-plain\":\n return (block as { text?: string }).text ?? \"[text-plain file]\";\n case \"image\":\n case \"image_url\":\n return \"[image]\";\n case \"audio\":\n case \"input_audio\":\n return \"[audio]\";\n case \"video\":\n return \"[video]\";\n case \"file\":\n return \"[file]\";\n case \"reasoning\":\n case \"tool_call\":\n case \"tool_call_chunk\":\n case \"invalid_tool_call\":\n case \"server_tool_call\":\n case \"server_tool_call_chunk\":\n case \"server_tool_call_result\":\n case \"non_standard\":\n return \"\";\n default:\n return block.type ? `[${block.type}]` : \"\";\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 *\n * Produces compact output like:\n * ```\n * Human: What's the weather?\n * AI: Let me check...[tool_calls]\n * Tool: 72°F and sunny\n * ```\n *\n * This avoids token inflation from metadata when stringifying message objects directly.\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.type === \"human\") {\n role = humanPrefix;\n } else if (m.type === \"ai\") {\n role = aiPrefix;\n } else if (m.type === \"system\") {\n role = \"System\";\n } else if (m.type === \"tool\") {\n role = \"Tool\";\n } else if (m.type === \"generic\") {\n role = (m as ChatMessage).role;\n } else {\n throw new Error(`Got unsupported message type: ${m.type}`);\n }\n const nameStr = m.name ? `${m.name}, ` : \"\";\n\n // Render content compactly: text as-is, multimodal blocks as placeholders\n const readableContent =\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? m.content.map(_contentBlockToString).filter(Boolean).join(\"\")\n : \"\";\n\n let message = `${role}: ${nameStr}${readableContent}`;\n\n // Include tool calls for AI messages (matching Python's get_buffer_string behavior)\n if (m.type === \"ai\") {\n const aiMessage = m as AIMessage;\n if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) {\n message += JSON.stringify(aiMessage.tool_calls);\n } else if (\n aiMessage.additional_kwargs &&\n \"function_call\" in aiMessage.additional_kwargs\n ) {\n // Legacy behavior assumes only one function call per message\n message += JSON.stringify(aiMessage.additional_kwargs.function_call);\n }\n }\n\n string_messages.push(message);\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 usesRawInputArgs = chunks.some(chunkUsesRawInputArgs);\n const name = chunks[0]?.name ?? \"\";\n const joinedArgsRaw = chunks.map((c) => c.args || \"\").join(\"\");\n const joinedArgs = usesRawInputArgs ? joinedArgsRaw : joinedArgsRaw.trim();\n const argsStr = joinedArgs.length ? joinedArgs : \"{}\";\n const id = chunks.find((c) => c.id)?.id ?? chunks[0]?.id;\n if (usesRawInputArgs && id) {\n toolCalls.push({\n name,\n args: { input: joinedArgs },\n id,\n type: \"tool_call\",\n });\n continue;\n }\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":";;;;;;;;;;;;AAwCA,SAAS,sBAAsB,OAA+B;AAC5D,QAAQ,MAAgC,iBAAiB;;;;;;;;AAwI3D,MAAa,QAAW,OAAgB,IAAI;AAE5C,SAAS,gBACP,UACU;AACV,KAAIA,cAAAA,YAAY,SAAS,CACvB,QAAO;UAEP,OAAO,SAAS,OAAO,YACvB,SAAS,SAAS,cAClB,OAAO,SAAS,aAAa,YAC7B,SAAS,aAAa,QACtB,eAAe,SAAS,YACxB,OAAO,SAAS,SAAS,cAAc,YACvC,UAAU,SAAS,YACnB,OAAO,SAAS,SAAS,SAAS,SAGlC,QAAO;EACL,IAAI,SAAS;EACb,MAAM,KAAK,MAAM,SAAS,SAAS,UAAU;EAC7C,MAAM,SAAS,SAAS;EACxB,MAAM;EACP;KAGD,QAAO;;AAIX,SAAS,wBAAwB,GAAwC;AACvE,QACE,OAAO,MAAM,YACb,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ACA,MAAM;IACN;IACA,OAAO;IACP,MAAM;IACP,CAAC;;;AAGN,QAAO;EACL,kBAAkB;EAClB,YAAY;EACZ,oBAAoB;EACrB"}
|
|
@@ -9,6 +9,14 @@ import { MessageStructure, MessageToolSet } from "./message.cjs";
|
|
|
9
9
|
|
|
10
10
|
//#region src/messages/utils.d.ts
|
|
11
11
|
type $Expand<T> = T extends infer U ? { [K in keyof U]: U[K] } : never;
|
|
12
|
+
/**
|
|
13
|
+
* Provider streaming marker for raw (non-JSON) tool input.
|
|
14
|
+
* Not part of the public {@link ToolCallChunk} type; integrations may attach
|
|
15
|
+
* `isCustomTool` at runtime and pass chunks typed as this alias.
|
|
16
|
+
*/
|
|
17
|
+
type RawInputToolCallChunk = ToolCallChunk & {
|
|
18
|
+
isCustomTool?: boolean;
|
|
19
|
+
};
|
|
12
20
|
/**
|
|
13
21
|
* Extracts the explicitly declared keys from a type T.
|
|
14
22
|
*
|
|
@@ -149,5 +157,5 @@ declare function collapseToolCallChunks(chunks: ToolCallChunk[]): {
|
|
|
149
157
|
invalid_tool_calls: InvalidToolCall[];
|
|
150
158
|
};
|
|
151
159
|
//#endregion
|
|
152
|
-
export { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
|
|
160
|
+
export { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, RawInputToolCallChunk, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
|
|
153
161
|
//# sourceMappingURL=utils.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.cts","names":[],"sources":["../../src/messages/utils.ts"],"mappings":";;;;;;;;;;KA+BY,OAAA,MAAa,CAAA,iCAAkC,CAAA,GAA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EAAQ,aAAA;EAC7C,gBAAA,EAAkB,aAAA;EAClB,UAAA,EAAY,QAAA;EACZ,kBAAA,EAAoB,eAAA;AAAA"}
|
package/dist/messages/utils.d.ts
CHANGED
|
@@ -9,6 +9,14 @@ import { MessageStructure, MessageToolSet } from "./message.js";
|
|
|
9
9
|
|
|
10
10
|
//#region src/messages/utils.d.ts
|
|
11
11
|
type $Expand<T> = T extends infer U ? { [K in keyof U]: U[K] } : never;
|
|
12
|
+
/**
|
|
13
|
+
* Provider streaming marker for raw (non-JSON) tool input.
|
|
14
|
+
* Not part of the public {@link ToolCallChunk} type; integrations may attach
|
|
15
|
+
* `isCustomTool` at runtime and pass chunks typed as this alias.
|
|
16
|
+
*/
|
|
17
|
+
type RawInputToolCallChunk = ToolCallChunk & {
|
|
18
|
+
isCustomTool?: boolean;
|
|
19
|
+
};
|
|
12
20
|
/**
|
|
13
21
|
* Extracts the explicitly declared keys from a type T.
|
|
14
22
|
*
|
|
@@ -149,5 +157,5 @@ declare function collapseToolCallChunks(chunks: ToolCallChunk[]): {
|
|
|
149
157
|
invalid_tool_calls: InvalidToolCall[];
|
|
150
158
|
};
|
|
151
159
|
//#endregion
|
|
152
|
-
export { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
|
|
160
|
+
export { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, RawInputToolCallChunk, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
|
|
153
161
|
//# sourceMappingURL=utils.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","names":[],"sources":["../../src/messages/utils.ts"],"mappings":";;;;;;;;;;KA+BY,OAAA,MAAa,CAAA,iCA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,CAAuB,MAAA,EAAQ,aAAA;EAC7C,gBAAA,EAAkB,aAAA;EAClB,UAAA,EAAY,QAAA;EACZ,kBAAA,EAAoB,eAAA;AAAA"}
|
package/dist/messages/utils.js
CHANGED
|
@@ -10,6 +10,9 @@ import { HumanMessage, HumanMessageChunk } from "./human.js";
|
|
|
10
10
|
import { RemoveMessage } from "./modifier.js";
|
|
11
11
|
import { SystemMessage, SystemMessageChunk } from "./system.js";
|
|
12
12
|
//#region src/messages/utils.ts
|
|
13
|
+
function chunkUsesRawInputArgs(chunk) {
|
|
14
|
+
return chunk.isCustomTool === true;
|
|
15
|
+
}
|
|
13
16
|
/**
|
|
14
17
|
* Immediately-invoked function expression.
|
|
15
18
|
*
|
|
@@ -278,10 +281,21 @@ function collapseToolCallChunks(chunks) {
|
|
|
278
281
|
const invalidToolCalls = [];
|
|
279
282
|
for (const chunks of groupedToolCallChunks) {
|
|
280
283
|
let parsedArgs = null;
|
|
284
|
+
const usesRawInputArgs = chunks.some(chunkUsesRawInputArgs);
|
|
281
285
|
const name = chunks[0]?.name ?? "";
|
|
282
|
-
const
|
|
286
|
+
const joinedArgsRaw = chunks.map((c) => c.args || "").join("");
|
|
287
|
+
const joinedArgs = usesRawInputArgs ? joinedArgsRaw : joinedArgsRaw.trim();
|
|
283
288
|
const argsStr = joinedArgs.length ? joinedArgs : "{}";
|
|
284
|
-
const id = chunks[0]?.id;
|
|
289
|
+
const id = chunks.find((c) => c.id)?.id ?? chunks[0]?.id;
|
|
290
|
+
if (usesRawInputArgs && id) {
|
|
291
|
+
toolCalls.push({
|
|
292
|
+
name,
|
|
293
|
+
args: { input: joinedArgs },
|
|
294
|
+
id,
|
|
295
|
+
type: "tool_call"
|
|
296
|
+
});
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
285
299
|
try {
|
|
286
300
|
parsedArgs = parsePartialJson(argsStr);
|
|
287
301
|
if (!id || parsedArgs === null || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) throw new Error("Malformed tool call chunk args.");
|