@langchain/core 1.1.2 → 1.1.3

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.
Files changed (227) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/agents.d.cts +0 -2
  3. package/dist/agents.d.ts +0 -2
  4. package/dist/callbacks/base.d.cts +22 -60
  5. package/dist/callbacks/base.d.ts +22 -60
  6. package/dist/callbacks/dispatch/index.d.cts +1 -3
  7. package/dist/callbacks/dispatch/index.d.ts +1 -3
  8. package/dist/callbacks/dispatch/web.d.cts +1 -3
  9. package/dist/callbacks/dispatch/web.d.ts +1 -3
  10. package/dist/callbacks/manager.d.cts +2 -12
  11. package/dist/callbacks/manager.d.ts +2 -12
  12. package/dist/chat_history.cjs +1 -1
  13. package/dist/chat_history.d.cts +0 -1
  14. package/dist/chat_history.d.ts +0 -1
  15. package/dist/chat_history.js +1 -1
  16. package/dist/document_loaders/langsmith.d.cts +0 -3
  17. package/dist/document_loaders/langsmith.d.ts +0 -3
  18. package/dist/documents/document.d.cts +3 -12
  19. package/dist/documents/document.d.ts +3 -12
  20. package/dist/example_selectors/length_based.d.cts +1 -1
  21. package/dist/example_selectors/length_based.d.ts +1 -1
  22. package/dist/indexing/base.d.cts +0 -1
  23. package/dist/indexing/base.d.ts +0 -1
  24. package/dist/indexing/record_manager.d.cts +0 -1
  25. package/dist/indexing/record_manager.d.ts +0 -1
  26. package/dist/language_models/base.d.cts +8 -38
  27. package/dist/language_models/base.d.ts +8 -38
  28. package/dist/language_models/chat_models.cjs +1 -1
  29. package/dist/language_models/chat_models.d.cts +6 -33
  30. package/dist/language_models/chat_models.d.ts +6 -33
  31. package/dist/language_models/chat_models.js +1 -1
  32. package/dist/language_models/llms.d.cts +0 -6
  33. package/dist/language_models/llms.d.ts +0 -6
  34. package/dist/load/import_type.d.cts +0 -1
  35. package/dist/load/import_type.d.ts +0 -1
  36. package/dist/load/map_keys.cjs +4 -5
  37. package/dist/load/map_keys.cjs.map +1 -1
  38. package/dist/load/map_keys.d.cts +0 -1
  39. package/dist/load/map_keys.d.ts +0 -1
  40. package/dist/load/map_keys.js +3 -3
  41. package/dist/load/map_keys.js.map +1 -1
  42. package/dist/load/serializable.d.cts +0 -1
  43. package/dist/load/serializable.d.ts +0 -1
  44. package/dist/memory.d.cts +0 -3
  45. package/dist/memory.d.ts +0 -3
  46. package/dist/messages/ai.cjs +6 -48
  47. package/dist/messages/ai.cjs.map +1 -1
  48. package/dist/messages/ai.js +6 -48
  49. package/dist/messages/ai.js.map +1 -1
  50. package/dist/messages/base.cjs +3 -2
  51. package/dist/messages/base.cjs.map +1 -1
  52. package/dist/messages/base.d.cts +1 -13
  53. package/dist/messages/base.d.ts +1 -13
  54. package/dist/messages/base.js +3 -2
  55. package/dist/messages/base.js.map +1 -1
  56. package/dist/messages/content/data.d.cts +2 -7
  57. package/dist/messages/content/data.d.ts +2 -7
  58. package/dist/messages/content/index.d.cts +1 -4
  59. package/dist/messages/content/index.d.ts +1 -4
  60. package/dist/messages/content/multimodal.d.cts +0 -1
  61. package/dist/messages/content/multimodal.d.ts +0 -1
  62. package/dist/messages/content/tools.d.cts +0 -1
  63. package/dist/messages/content/tools.d.ts +0 -1
  64. package/dist/messages/index.cjs +4 -2
  65. package/dist/messages/index.d.cts +2 -2
  66. package/dist/messages/index.d.ts +2 -2
  67. package/dist/messages/index.js +5 -4
  68. package/dist/messages/tool.d.cts +2 -9
  69. package/dist/messages/tool.d.ts +2 -9
  70. package/dist/messages/transformers.cjs +2 -2
  71. package/dist/messages/transformers.d.cts +0 -3
  72. package/dist/messages/transformers.d.ts +0 -3
  73. package/dist/messages/transformers.js +2 -2
  74. package/dist/messages/utils.cjs +77 -4
  75. package/dist/messages/utils.cjs.map +1 -1
  76. package/dist/messages/utils.d.cts +35 -7
  77. package/dist/messages/utils.d.ts +35 -7
  78. package/dist/messages/utils.js +77 -5
  79. package/dist/messages/utils.js.map +1 -1
  80. package/dist/node_modules/.pnpm/ansi-styles@6.2.3/node_modules/ansi-styles/index.cjs +169 -0
  81. package/dist/node_modules/.pnpm/ansi-styles@6.2.3/node_modules/ansi-styles/index.cjs.map +1 -0
  82. package/dist/node_modules/.pnpm/ansi-styles@6.2.3/node_modules/ansi-styles/index.js +168 -0
  83. package/dist/node_modules/.pnpm/ansi-styles@6.2.3/node_modules/ansi-styles/index.js.map +1 -0
  84. package/dist/node_modules/.pnpm/camelcase@9.0.0/node_modules/camelcase/index.cjs +122 -0
  85. package/dist/node_modules/.pnpm/camelcase@9.0.0/node_modules/camelcase/index.cjs.map +1 -0
  86. package/dist/node_modules/.pnpm/camelcase@9.0.0/node_modules/camelcase/index.js +121 -0
  87. package/dist/node_modules/.pnpm/camelcase@9.0.0/node_modules/camelcase/index.js.map +1 -0
  88. package/dist/node_modules/.pnpm/decamelize@6.0.1/node_modules/decamelize/index.cjs +18 -0
  89. package/dist/node_modules/.pnpm/decamelize@6.0.1/node_modules/decamelize/index.cjs.map +1 -0
  90. package/dist/node_modules/.pnpm/decamelize@6.0.1/node_modules/decamelize/index.js +17 -0
  91. package/dist/node_modules/.pnpm/decamelize@6.0.1/node_modules/decamelize/index.js.map +1 -0
  92. package/dist/node_modules/.pnpm/is-network-error@1.3.0/node_modules/is-network-error/index.cjs +27 -0
  93. package/dist/node_modules/.pnpm/is-network-error@1.3.0/node_modules/is-network-error/index.cjs.map +1 -0
  94. package/dist/node_modules/.pnpm/is-network-error@1.3.0/node_modules/is-network-error/index.js +26 -0
  95. package/dist/node_modules/.pnpm/is-network-error@1.3.0/node_modules/is-network-error/index.js.map +1 -0
  96. package/dist/node_modules/.pnpm/p-retry@7.1.0/node_modules/p-retry/index.cjs +141 -0
  97. package/dist/node_modules/.pnpm/p-retry@7.1.0/node_modules/p-retry/index.cjs.map +1 -0
  98. package/dist/node_modules/.pnpm/p-retry@7.1.0/node_modules/p-retry/index.js +141 -0
  99. package/dist/node_modules/.pnpm/p-retry@7.1.0/node_modules/p-retry/index.js.map +1 -0
  100. package/dist/output_parsers/json.d.cts +1 -5
  101. package/dist/output_parsers/json.d.ts +1 -5
  102. package/dist/output_parsers/openai_functions/json_output_functions_parsers.d.cts +2 -6
  103. package/dist/output_parsers/openai_functions/json_output_functions_parsers.d.ts +2 -6
  104. package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.cts +10 -34
  105. package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.ts +10 -34
  106. package/dist/output_parsers/transform.d.cts +0 -1
  107. package/dist/output_parsers/transform.d.ts +0 -1
  108. package/dist/outputs.d.cts +0 -6
  109. package/dist/outputs.d.ts +0 -6
  110. package/dist/prompts/base.d.cts +2 -10
  111. package/dist/prompts/base.d.ts +2 -10
  112. package/dist/prompts/chat.cjs +2 -2
  113. package/dist/prompts/chat.d.cts +13 -51
  114. package/dist/prompts/chat.d.ts +13 -51
  115. package/dist/prompts/chat.js +2 -2
  116. package/dist/prompts/few_shot.d.cts +1 -5
  117. package/dist/prompts/few_shot.d.ts +1 -5
  118. package/dist/prompts/image.d.cts +2 -10
  119. package/dist/prompts/image.d.ts +2 -10
  120. package/dist/prompts/prompt.d.cts +4 -15
  121. package/dist/prompts/prompt.d.ts +4 -16
  122. package/dist/prompts/serde.d.cts +0 -1
  123. package/dist/prompts/serde.d.ts +0 -1
  124. package/dist/prompts/string.d.cts +1 -5
  125. package/dist/prompts/string.d.ts +1 -5
  126. package/dist/prompts/structured.d.cts +3 -16
  127. package/dist/prompts/structured.d.ts +3 -16
  128. package/dist/retrievers/document_compressors/index.d.cts +0 -1
  129. package/dist/retrievers/document_compressors/index.d.ts +0 -1
  130. package/dist/retrievers/index.d.cts +2 -6
  131. package/dist/retrievers/index.d.ts +2 -6
  132. package/dist/runnables/base.cjs +7 -7
  133. package/dist/runnables/base.cjs.map +1 -1
  134. package/dist/runnables/base.d.cts +12 -64
  135. package/dist/runnables/base.d.ts +12 -64
  136. package/dist/runnables/base.js +1 -1
  137. package/dist/runnables/branch.d.cts +0 -2
  138. package/dist/runnables/branch.d.ts +0 -2
  139. package/dist/runnables/config.d.cts +0 -1
  140. package/dist/runnables/config.d.ts +0 -1
  141. package/dist/runnables/graph.d.cts +1 -5
  142. package/dist/runnables/graph.d.ts +1 -5
  143. package/dist/runnables/graph_mermaid.cjs +2 -1
  144. package/dist/runnables/graph_mermaid.cjs.map +1 -1
  145. package/dist/runnables/graph_mermaid.js +3 -1
  146. package/dist/runnables/graph_mermaid.js.map +1 -1
  147. package/dist/runnables/history.cjs +1 -1
  148. package/dist/runnables/history.d.cts +4 -12
  149. package/dist/runnables/history.d.ts +4 -12
  150. package/dist/runnables/history.js +1 -1
  151. package/dist/runnables/passthrough.d.cts +0 -2
  152. package/dist/runnables/passthrough.d.ts +0 -2
  153. package/dist/runnables/router.d.cts +0 -1
  154. package/dist/runnables/router.d.ts +0 -1
  155. package/dist/runnables/types.d.cts +2 -9
  156. package/dist/runnables/types.d.ts +2 -9
  157. package/dist/runnables/utils.cjs +5 -0
  158. package/dist/runnables/utils.cjs.map +1 -1
  159. package/dist/runnables/utils.js +5 -1
  160. package/dist/runnables/utils.js.map +1 -1
  161. package/dist/singletons/async_local_storage/context.d.cts +0 -2
  162. package/dist/singletons/async_local_storage/context.d.ts +0 -2
  163. package/dist/singletons/async_local_storage/globals.d.cts +0 -1
  164. package/dist/singletons/async_local_storage/globals.d.ts +0 -1
  165. package/dist/singletons/callbacks.cjs.map +1 -1
  166. package/dist/singletons/callbacks.js.map +1 -1
  167. package/dist/stores.d.cts +0 -1
  168. package/dist/stores.d.ts +0 -1
  169. package/dist/structured_query/utils.d.cts +1 -4
  170. package/dist/structured_query/utils.d.ts +1 -4
  171. package/dist/tools/index.d.cts +1 -6
  172. package/dist/tools/index.d.ts +1 -6
  173. package/dist/tools/types.d.cts +3 -13
  174. package/dist/tools/types.d.ts +3 -13
  175. package/dist/tracers/base.d.cts +1 -20
  176. package/dist/tracers/base.d.ts +1 -20
  177. package/dist/tracers/console.cjs +3 -3
  178. package/dist/tracers/console.cjs.map +1 -1
  179. package/dist/tracers/console.d.cts +0 -2
  180. package/dist/tracers/console.d.ts +0 -2
  181. package/dist/tracers/console.js +3 -3
  182. package/dist/tracers/console.js.map +1 -1
  183. package/dist/tracers/event_stream.d.cts +0 -4
  184. package/dist/tracers/event_stream.d.ts +0 -4
  185. package/dist/tracers/log_stream.d.cts +0 -6
  186. package/dist/tracers/log_stream.d.ts +0 -6
  187. package/dist/types/_internal.d.cts +0 -3
  188. package/dist/types/_internal.d.ts +0 -3
  189. package/dist/types/type-utils.d.cts +0 -2
  190. package/dist/types/type-utils.d.ts +0 -2
  191. package/dist/utils/async_caller.cjs +2 -7
  192. package/dist/utils/async_caller.cjs.map +1 -1
  193. package/dist/utils/async_caller.d.cts +0 -3
  194. package/dist/utils/async_caller.d.ts +0 -3
  195. package/dist/utils/async_caller.js +1 -6
  196. package/dist/utils/async_caller.js.map +1 -1
  197. package/dist/utils/env.d.cts +0 -4
  198. package/dist/utils/env.d.ts +0 -4
  199. package/dist/utils/event_source_parse.d.cts +1 -4
  200. package/dist/utils/event_source_parse.d.ts +1 -4
  201. package/dist/utils/function_calling.d.cts +1 -3
  202. package/dist/utils/function_calling.d.ts +1 -3
  203. package/dist/utils/json.d.cts +0 -1
  204. package/dist/utils/json.d.ts +0 -1
  205. package/dist/utils/stream.d.cts +1 -13
  206. package/dist/utils/stream.d.ts +1 -13
  207. package/dist/utils/testing/chat_models.d.cts +3 -11
  208. package/dist/utils/testing/chat_models.d.ts +3 -11
  209. package/dist/utils/testing/message_history.cjs +1 -1
  210. package/dist/utils/testing/message_history.js +1 -1
  211. package/dist/utils/testing/retrievers.d.cts +1 -3
  212. package/dist/utils/testing/retrievers.d.ts +1 -3
  213. package/dist/utils/testing/vectorstores.d.cts +0 -1
  214. package/dist/utils/testing/vectorstores.d.ts +0 -1
  215. package/dist/utils/types/index.cjs +4 -0
  216. package/dist/utils/types/index.d.cts +2 -4
  217. package/dist/utils/types/index.d.ts +2 -4
  218. package/dist/utils/types/index.js +4 -2
  219. package/dist/utils/types/zod.cjs +24 -0
  220. package/dist/utils/types/zod.cjs.map +1 -1
  221. package/dist/utils/types/zod.d.cts +4 -4
  222. package/dist/utils/types/zod.d.ts +4 -4
  223. package/dist/utils/types/zod.js +23 -1
  224. package/dist/utils/types/zod.js.map +1 -1
  225. package/dist/vectorstores.d.cts +5 -17
  226. package/dist/vectorstores.d.ts +5 -17
  227. package/package.json +6 -6
@@ -10,7 +10,6 @@ interface ToolMessageFields<TStructure extends MessageStructure = MessageStructu
10
10
  * a subset of the full tool output is being passed as message content but the full
11
11
  * output is needed in other parts of the code.
12
12
  */
13
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
13
  artifact?: any;
15
14
  tool_call_id: string;
16
15
  status?: "success" | "error";
@@ -49,7 +48,6 @@ declare class ToolMessage<TStructure extends MessageStructure = MessageStructure
49
48
  * a subset of the full tool output is being passed as message content but the full
50
49
  * output is needed in other parts of the code.
51
50
  */
52
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
53
51
  artifact?: any;
54
52
  constructor(fields: $InferMessageContent<TStructure, "tool"> | ToolMessageFields, tool_call_id: string, name?: string);
55
53
  constructor(fields: ToolMessageFields<TStructure>);
@@ -75,16 +73,13 @@ declare class ToolMessageChunk<TStructure extends MessageStructure = MessageStru
75
73
  * a subset of the full tool output is being passed as message content but the full
76
74
  * output is needed in other parts of the code.
77
75
  */
78
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
79
76
  artifact?: any;
80
77
  constructor(fields: ToolMessageFields<TStructure>);
81
78
  static lc_name(): string;
82
79
  concat(chunk: ToolMessageChunk<TStructure>): this;
83
80
  get _printableFields(): Record<string, unknown>;
84
81
  }
85
- interface ToolCall<TName extends string = string,
86
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
87
- TArgs extends Record<string, any> = Record<string, any>> {
82
+ interface ToolCall<TName extends string = string, TArgs extends Record<string, any> = Record<string, any>> {
88
83
  readonly type?: "tool_call";
89
84
  /**
90
85
  * If provided, an identifier associated with the tool call
@@ -187,9 +182,7 @@ interface InvalidToolCall<TName extends string = string> {
187
182
  */
188
183
  index?: string | number;
189
184
  }
190
- declare function defaultToolCallParser(
191
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
192
- rawToolCalls: Record<string, any>[]): [ToolCall[], InvalidToolCall[]];
185
+ declare function defaultToolCallParser(rawToolCalls: Record<string, any>[]): [ToolCall[], InvalidToolCall[]];
193
186
  /**
194
187
  * @deprecated Use {@link ToolMessage.isInstance} instead
195
188
  */
@@ -10,7 +10,6 @@ interface ToolMessageFields<TStructure extends MessageStructure = MessageStructu
10
10
  * a subset of the full tool output is being passed as message content but the full
11
11
  * output is needed in other parts of the code.
12
12
  */
13
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
13
  artifact?: any;
15
14
  tool_call_id: string;
16
15
  status?: "success" | "error";
@@ -49,7 +48,6 @@ declare class ToolMessage<TStructure extends MessageStructure = MessageStructure
49
48
  * a subset of the full tool output is being passed as message content but the full
50
49
  * output is needed in other parts of the code.
51
50
  */
52
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
53
51
  artifact?: any;
54
52
  constructor(fields: $InferMessageContent<TStructure, "tool"> | ToolMessageFields, tool_call_id: string, name?: string);
55
53
  constructor(fields: ToolMessageFields<TStructure>);
@@ -75,16 +73,13 @@ declare class ToolMessageChunk<TStructure extends MessageStructure = MessageStru
75
73
  * a subset of the full tool output is being passed as message content but the full
76
74
  * output is needed in other parts of the code.
77
75
  */
78
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
79
76
  artifact?: any;
80
77
  constructor(fields: ToolMessageFields<TStructure>);
81
78
  static lc_name(): string;
82
79
  concat(chunk: ToolMessageChunk<TStructure>): this;
83
80
  get _printableFields(): Record<string, unknown>;
84
81
  }
85
- interface ToolCall<TName extends string = string,
86
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
87
- TArgs extends Record<string, any> = Record<string, any>> {
82
+ interface ToolCall<TName extends string = string, TArgs extends Record<string, any> = Record<string, any>> {
88
83
  readonly type?: "tool_call";
89
84
  /**
90
85
  * If provided, an identifier associated with the tool call
@@ -187,9 +182,7 @@ interface InvalidToolCall<TName extends string = string> {
187
182
  */
188
183
  index?: string | number;
189
184
  }
190
- declare function defaultToolCallParser(
191
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
192
- rawToolCalls: Record<string, any>[]): [ToolCall[], InvalidToolCall[]];
185
+ declare function defaultToolCallParser(rawToolCalls: Record<string, any>[]): [ToolCall[], InvalidToolCall[]];
193
186
  /**
194
187
  * @deprecated Use {@link ToolMessage.isInstance} instead
195
188
  */
@@ -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
@@ -14,7 +14,6 @@ import { RemoveMessage } from "./modifier.cjs";
14
14
  //#region src/messages/transformers.d.ts
15
15
  type MessageUnion = typeof HumanMessage | typeof AIMessage | typeof SystemMessage | typeof ChatMessage | typeof FunctionMessage | typeof ToolMessage | typeof RemoveMessage;
16
16
  type MessageChunkUnion = typeof HumanMessageChunk | typeof AIMessageChunk | typeof SystemMessageChunk | typeof FunctionMessageChunk | typeof ToolMessageChunk | typeof ChatMessageChunk | typeof RemoveMessage;
17
- // RemoveMessage does not have a chunk class.
18
17
  type MessageTypeOrClass = MessageType | MessageUnion | MessageChunkUnion;
19
18
  interface FilterMessagesFields {
20
19
  /**
@@ -145,8 +144,6 @@ declare function filterMessages(messages: BaseMessage[], options?: FilterMessage
145
144
  */
146
145
  declare function mergeMessageRuns(): Runnable<BaseMessage[], BaseMessage[]>;
147
146
  declare function mergeMessageRuns(messages: BaseMessage[]): BaseMessage[];
148
- // Since we can not import from `@langchain/textsplitters` we need
149
- // to reconstruct the interface here.
150
147
  interface _TextSplitterInterface extends BaseDocumentTransformer {
151
148
  splitText(text: string): Promise<string[]>;
152
149
  }
@@ -14,7 +14,6 @@ import { RemoveMessage } from "./modifier.js";
14
14
  //#region src/messages/transformers.d.ts
15
15
  type MessageUnion = typeof HumanMessage | typeof AIMessage | typeof SystemMessage | typeof ChatMessage | typeof FunctionMessage | typeof ToolMessage | typeof RemoveMessage;
16
16
  type MessageChunkUnion = typeof HumanMessageChunk | typeof AIMessageChunk | typeof SystemMessageChunk | typeof FunctionMessageChunk | typeof ToolMessageChunk | typeof ChatMessageChunk | typeof RemoveMessage;
17
- // RemoveMessage does not have a chunk class.
18
17
  type MessageTypeOrClass = MessageType | MessageUnion | MessageChunkUnion;
19
18
  interface FilterMessagesFields {
20
19
  /**
@@ -145,8 +144,6 @@ declare function filterMessages(messages: BaseMessage[], options?: FilterMessage
145
144
  */
146
145
  declare function mergeMessageRuns(): Runnable<BaseMessage[], BaseMessage[]>;
147
146
  declare function mergeMessageRuns(messages: BaseMessage[]): BaseMessage[];
148
- // Since we can not import from `@langchain/textsplitters` we need
149
- // to reconstruct the interface here.
150
147
  interface _TextSplitterInterface extends BaseDocumentTransformer {
151
148
  splitText(text: string): Promise<string[]>;
152
149
  }
@@ -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
@@ -1,13 +1,14 @@
1
1
  const require_base = require('./base.cjs');
2
2
  const require_messages_tool = require('./tool.cjs');
3
- const require_ai = require('./ai.cjs');
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,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,E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AAG,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":";;;;;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F,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";
@@ -63,9 +63,7 @@ type $OnlyIndexSignatures<T$1> = $HasIndexSignature<T$1> extends true ? [$KnownK
63
63
  * // }
64
64
  * ```
65
65
  */
66
- type $MergeObjects<T$1, U$1> =
67
- // If U is purely index-signature based, prefer U as a whole
68
- $OnlyIndexSignatures<U$1> extends true ? U$1 : $OnlyIndexSignatures<T$1> extends true ? U$1 : { [K in keyof T$1 | keyof U$1]: K extends keyof T$1 ? K extends keyof U$1 ? T$1[K] extends Record<string, unknown> ? U$1[K] extends Record<string, unknown> ? $MergeObjects<T$1[K], U$1[K]> : U$1[K] : U$1[K] : T$1[K] : K extends keyof U$1 ? U$1[K] : never };
66
+ type $MergeObjects<T$1, U$1> = $OnlyIndexSignatures<U$1> extends true ? U$1 : $OnlyIndexSignatures<T$1> extends true ? U$1 : { [K in keyof T$1 | keyof U$1]: K extends keyof T$1 ? K extends keyof U$1 ? T$1[K] extends Record<string, unknown> ? U$1[K] extends Record<string, unknown> ? $MergeObjects<T$1[K], U$1[K]> : U$1[K] : U$1[K] : T$1[K] : K extends keyof U$1 ? U$1[K] : never };
69
67
  /**
70
68
  * Merges two discriminated unions A and B based on a discriminator key (defaults to "type").
71
69
  * For each possible value of the discriminator across both unions:
@@ -77,8 +75,7 @@ $OnlyIndexSignatures<U$1> extends true ? U$1 : $OnlyIndexSignatures<T$1> extends
77
75
  * @template B - Second discriminated union type that extends Record<Key, PropertyKey>
78
76
  * @template Key - The discriminator key property, defaults to "type"
79
77
  */
80
- type $MergeDiscriminatedUnion<A extends Record<Key, PropertyKey>, B extends Record<Key, PropertyKey>, Key extends PropertyKey = "type"> = { [T in A[Key] | B[Key]]: [Extract<B, Record<Key, T>>] extends [never] // Check if B has a member with this discriminator value
81
- ? Extract<A, Record<Key, T>> : [Extract<A, Record<Key, T>>] extends [never] ? Extract<B, Record<Key, T>> : $MergeObjects<Extract<A, Record<Key, T>>, Extract<B, Record<Key, T>>> }[A[Key] | B[Key]];
78
+ type $MergeDiscriminatedUnion<A extends Record<Key, PropertyKey>, B extends Record<Key, PropertyKey>, Key extends PropertyKey = "type"> = { [T in A[Key] | B[Key]]: [Extract<B, Record<Key, T>>] extends [never] ? Extract<A, Record<Key, T>> : [Extract<A, Record<Key, T>>] extends [never] ? Extract<B, Record<Key, T>> : $MergeObjects<Extract<A, Record<Key, T>>, Extract<B, Record<Key, T>>> }[A[Key] | B[Key]];
82
79
  type Constructor<T$1> = new (...args: unknown[]) => T$1;
83
80
  /**
84
81
  * Immediately-invoked function expression.
@@ -111,6 +108,37 @@ declare function mapStoredMessagesToChatMessages(messages: StoredMessage[]): Bas
111
108
  */
112
109
  declare function mapChatMessagesToStoredMessages(messages: BaseMessage[]): StoredMessage[];
113
110
  declare function convertToChunk(message: BaseMessage): AIMessageChunk<MessageStructure> | ChatMessageChunk<MessageStructure> | FunctionMessageChunk<MessageStructure> | HumanMessageChunk<MessageStructure> | SystemMessageChunk<MessageStructure>;
111
+ /**
112
+ * Collapses an array of tool call chunks into complete tool calls.
113
+ *
114
+ * This function groups tool call chunks by their id and/or index, then attempts to
115
+ * parse and validate the accumulated arguments for each group. Successfully parsed
116
+ * tool calls are returned as valid `ToolCall` objects, while malformed ones are
117
+ * returned as `InvalidToolCall` objects.
118
+ *
119
+ * @param chunks - An array of `ToolCallChunk` objects to collapse
120
+ * @returns An object containing:
121
+ * - `tool_call_chunks`: The original input chunks
122
+ * - `tool_calls`: An array of successfully parsed and validated tool calls
123
+ * - `invalid_tool_calls`: An array of tool calls that failed parsing or validation
124
+ *
125
+ * @remarks
126
+ * Chunks are grouped using the following matching logic:
127
+ * - If a chunk has both an id and index, it matches chunks with the same id and index
128
+ * - If a chunk has only an id, it matches chunks with the same id
129
+ * - If a chunk has only an index, it matches chunks with the same index
130
+ *
131
+ * For each group, the function:
132
+ * 1. Concatenates all `args` strings from the chunks
133
+ * 2. Attempts to parse the concatenated string as JSON
134
+ * 3. Validates that the result is a non-null object with a valid id
135
+ * 4. Creates either a `ToolCall` (if valid) or `InvalidToolCall` (if invalid)
136
+ */
137
+ declare function collapseToolCallChunks(chunks: ToolCallChunk[]): {
138
+ tool_call_chunks: ToolCallChunk[];
139
+ tool_calls: ToolCall[];
140
+ invalid_tool_calls: InvalidToolCall[];
141
+ };
114
142
  //#endregion
115
- export { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
143
+ export { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
116
144
  //# sourceMappingURL=utils.d.cts.map
@@ -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";
@@ -63,9 +63,7 @@ type $OnlyIndexSignatures<T$1> = $HasIndexSignature<T$1> extends true ? [$KnownK
63
63
  * // }
64
64
  * ```
65
65
  */
66
- type $MergeObjects<T$1, U$1> =
67
- // If U is purely index-signature based, prefer U as a whole
68
- $OnlyIndexSignatures<U$1> extends true ? U$1 : $OnlyIndexSignatures<T$1> extends true ? U$1 : { [K in keyof T$1 | keyof U$1]: K extends keyof T$1 ? K extends keyof U$1 ? T$1[K] extends Record<string, unknown> ? U$1[K] extends Record<string, unknown> ? $MergeObjects<T$1[K], U$1[K]> : U$1[K] : U$1[K] : T$1[K] : K extends keyof U$1 ? U$1[K] : never };
66
+ type $MergeObjects<T$1, U$1> = $OnlyIndexSignatures<U$1> extends true ? U$1 : $OnlyIndexSignatures<T$1> extends true ? U$1 : { [K in keyof T$1 | keyof U$1]: K extends keyof T$1 ? K extends keyof U$1 ? T$1[K] extends Record<string, unknown> ? U$1[K] extends Record<string, unknown> ? $MergeObjects<T$1[K], U$1[K]> : U$1[K] : U$1[K] : T$1[K] : K extends keyof U$1 ? U$1[K] : never };
69
67
  /**
70
68
  * Merges two discriminated unions A and B based on a discriminator key (defaults to "type").
71
69
  * For each possible value of the discriminator across both unions:
@@ -77,8 +75,7 @@ $OnlyIndexSignatures<U$1> extends true ? U$1 : $OnlyIndexSignatures<T$1> extends
77
75
  * @template B - Second discriminated union type that extends Record<Key, PropertyKey>
78
76
  * @template Key - The discriminator key property, defaults to "type"
79
77
  */
80
- type $MergeDiscriminatedUnion<A extends Record<Key, PropertyKey>, B extends Record<Key, PropertyKey>, Key extends PropertyKey = "type"> = { [T in A[Key] | B[Key]]: [Extract<B, Record<Key, T>>] extends [never] // Check if B has a member with this discriminator value
81
- ? Extract<A, Record<Key, T>> : [Extract<A, Record<Key, T>>] extends [never] ? Extract<B, Record<Key, T>> : $MergeObjects<Extract<A, Record<Key, T>>, Extract<B, Record<Key, T>>> }[A[Key] | B[Key]];
78
+ type $MergeDiscriminatedUnion<A extends Record<Key, PropertyKey>, B extends Record<Key, PropertyKey>, Key extends PropertyKey = "type"> = { [T in A[Key] | B[Key]]: [Extract<B, Record<Key, T>>] extends [never] ? Extract<A, Record<Key, T>> : [Extract<A, Record<Key, T>>] extends [never] ? Extract<B, Record<Key, T>> : $MergeObjects<Extract<A, Record<Key, T>>, Extract<B, Record<Key, T>>> }[A[Key] | B[Key]];
82
79
  type Constructor<T$1> = new (...args: unknown[]) => T$1;
83
80
  /**
84
81
  * Immediately-invoked function expression.
@@ -111,6 +108,37 @@ declare function mapStoredMessagesToChatMessages(messages: StoredMessage[]): Bas
111
108
  */
112
109
  declare function mapChatMessagesToStoredMessages(messages: BaseMessage[]): StoredMessage[];
113
110
  declare function convertToChunk(message: BaseMessage): AIMessageChunk<MessageStructure> | ChatMessageChunk<MessageStructure> | FunctionMessageChunk<MessageStructure> | HumanMessageChunk<MessageStructure> | SystemMessageChunk<MessageStructure>;
111
+ /**
112
+ * Collapses an array of tool call chunks into complete tool calls.
113
+ *
114
+ * This function groups tool call chunks by their id and/or index, then attempts to
115
+ * parse and validate the accumulated arguments for each group. Successfully parsed
116
+ * tool calls are returned as valid `ToolCall` objects, while malformed ones are
117
+ * returned as `InvalidToolCall` objects.
118
+ *
119
+ * @param chunks - An array of `ToolCallChunk` objects to collapse
120
+ * @returns An object containing:
121
+ * - `tool_call_chunks`: The original input chunks
122
+ * - `tool_calls`: An array of successfully parsed and validated tool calls
123
+ * - `invalid_tool_calls`: An array of tool calls that failed parsing or validation
124
+ *
125
+ * @remarks
126
+ * Chunks are grouped using the following matching logic:
127
+ * - If a chunk has both an id and index, it matches chunks with the same id and index
128
+ * - If a chunk has only an id, it matches chunks with the same id
129
+ * - If a chunk has only an index, it matches chunks with the same index
130
+ *
131
+ * For each group, the function:
132
+ * 1. Concatenates all `args` strings from the chunks
133
+ * 2. Attempts to parse the concatenated string as JSON
134
+ * 3. Validates that the result is a non-null object with a valid id
135
+ * 4. Creates either a `ToolCall` (if valid) or `InvalidToolCall` (if invalid)
136
+ */
137
+ declare function collapseToolCallChunks(chunks: ToolCallChunk[]): {
138
+ tool_call_chunks: ToolCallChunk[];
139
+ tool_calls: ToolCall[];
140
+ invalid_tool_calls: InvalidToolCall[];
141
+ };
114
142
  //#endregion
115
- export { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
143
+ export { $Expand, $MergeDiscriminatedUnion, $MergeObjects, Constructor, coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
116
144
  //# sourceMappingURL=utils.d.ts.map
@@ -1,13 +1,14 @@
1
1
  import { _isMessageFieldWithRole, isBaseMessage } from "./base.js";
2
2
  import { ToolMessage } from "./tool.js";
3
- import { AIMessage, AIMessageChunk } from "./ai.js";
3
+ import { addLangChainErrorFields } from "../errors/index.js";
4
+ import { _isToolCall } from "../tools/utils.js";
5
+ import { parsePartialJson } from "../utils/json.js";
4
6
  import { ChatMessage, ChatMessageChunk } from "./chat.js";
5
7
  import { FunctionMessage, FunctionMessageChunk } from "./function.js";
6
8
  import { HumanMessage, HumanMessageChunk } from "./human.js";
7
- import { SystemMessage, SystemMessageChunk } from "./system.js";
8
- import { addLangChainErrorFields } from "../errors/index.js";
9
- import { _isToolCall } from "../tools/utils.js";
10
9
  import { RemoveMessage } from "./modifier.js";
10
+ import { SystemMessage, SystemMessageChunk } from "./system.js";
11
+ import { AIMessage, AIMessageChunk } from "./ai.js";
11
12
 
12
13
  //#region src/messages/utils.ts
13
14
  /**
@@ -196,7 +197,78 @@ function convertToChunk(message) {
196
197
  else if (ChatMessage.isInstance(message)) return new ChatMessageChunk({ ...message });
197
198
  else throw new Error("Unknown message type.");
198
199
  }
200
+ /**
201
+ * Collapses an array of tool call chunks into complete tool calls.
202
+ *
203
+ * This function groups tool call chunks by their id and/or index, then attempts to
204
+ * parse and validate the accumulated arguments for each group. Successfully parsed
205
+ * tool calls are returned as valid `ToolCall` objects, while malformed ones are
206
+ * returned as `InvalidToolCall` objects.
207
+ *
208
+ * @param chunks - An array of `ToolCallChunk` objects to collapse
209
+ * @returns An object containing:
210
+ * - `tool_call_chunks`: The original input chunks
211
+ * - `tool_calls`: An array of successfully parsed and validated tool calls
212
+ * - `invalid_tool_calls`: An array of tool calls that failed parsing or validation
213
+ *
214
+ * @remarks
215
+ * Chunks are grouped using the following matching logic:
216
+ * - If a chunk has both an id and index, it matches chunks with the same id and index
217
+ * - If a chunk has only an id, it matches chunks with the same id
218
+ * - If a chunk has only an index, it matches chunks with the same index
219
+ *
220
+ * For each group, the function:
221
+ * 1. Concatenates all `args` strings from the chunks
222
+ * 2. Attempts to parse the concatenated string as JSON
223
+ * 3. Validates that the result is a non-null object with a valid id
224
+ * 4. Creates either a `ToolCall` (if valid) or `InvalidToolCall` (if invalid)
225
+ */
226
+ function collapseToolCallChunks(chunks) {
227
+ const groupedToolCallChunks = chunks.reduce((acc, chunk) => {
228
+ const matchedChunkIndex = acc.findIndex(([match]) => {
229
+ if ("id" in chunk && chunk.id && "index" in chunk && chunk.index !== void 0) return chunk.id === match.id && chunk.index === match.index;
230
+ if ("id" in chunk && chunk.id) return chunk.id === match.id;
231
+ if ("index" in chunk && chunk.index !== void 0) return chunk.index === match.index;
232
+ return false;
233
+ });
234
+ if (matchedChunkIndex !== -1) acc[matchedChunkIndex].push(chunk);
235
+ else acc.push([chunk]);
236
+ return acc;
237
+ }, []);
238
+ const toolCalls = [];
239
+ const invalidToolCalls = [];
240
+ for (const chunks$1 of groupedToolCallChunks) {
241
+ let parsedArgs = null;
242
+ const name = chunks$1[0]?.name ?? "";
243
+ const joinedArgs = chunks$1.map((c) => c.args || "").join("").trim();
244
+ const argsStr = joinedArgs.length ? joinedArgs : "{}";
245
+ const id = chunks$1[0]?.id;
246
+ try {
247
+ parsedArgs = parsePartialJson(argsStr);
248
+ if (!id || parsedArgs === null || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) throw new Error("Malformed tool call chunk args.");
249
+ toolCalls.push({
250
+ name,
251
+ args: parsedArgs,
252
+ id,
253
+ type: "tool_call"
254
+ });
255
+ } catch {
256
+ invalidToolCalls.push({
257
+ name,
258
+ args: argsStr,
259
+ id,
260
+ error: "Malformed args.",
261
+ type: "invalid_tool_call"
262
+ });
263
+ }
264
+ }
265
+ return {
266
+ tool_call_chunks: chunks,
267
+ tool_calls: toolCalls,
268
+ invalid_tool_calls: invalidToolCalls
269
+ };
270
+ }
199
271
 
200
272
  //#endregion
201
- export { coerceMessageLikeToMessage, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
273
+ export { coerceMessageLikeToMessage, collapseToolCallChunks, convertToChunk, getBufferString, iife, mapChatMessagesToStoredMessages, mapStoredMessageToChatMessage, mapStoredMessagesToChatMessages };
202
274
  //# sourceMappingURL=utils.js.map