@langchain/core 1.1.5-dev-1765433794876 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (295) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/agents.cjs +1 -0
  3. package/agents.d.cts +1 -0
  4. package/agents.d.ts +1 -0
  5. package/agents.js +1 -0
  6. package/caches.cjs +1 -0
  7. package/caches.d.cts +1 -0
  8. package/caches.d.ts +1 -0
  9. package/caches.js +1 -0
  10. package/callbacks/base.cjs +1 -0
  11. package/callbacks/base.d.cts +1 -0
  12. package/callbacks/base.d.ts +1 -0
  13. package/callbacks/base.js +1 -0
  14. package/callbacks/dispatch/web.cjs +1 -0
  15. package/callbacks/dispatch/web.d.cts +1 -0
  16. package/callbacks/dispatch/web.d.ts +1 -0
  17. package/callbacks/dispatch/web.js +1 -0
  18. package/callbacks/dispatch.cjs +1 -0
  19. package/callbacks/dispatch.d.cts +1 -0
  20. package/callbacks/dispatch.d.ts +1 -0
  21. package/callbacks/dispatch.js +1 -0
  22. package/callbacks/manager.cjs +1 -0
  23. package/callbacks/manager.d.cts +1 -0
  24. package/callbacks/manager.d.ts +1 -0
  25. package/callbacks/manager.js +1 -0
  26. package/callbacks/promises.cjs +1 -0
  27. package/callbacks/promises.d.cts +1 -0
  28. package/callbacks/promises.d.ts +1 -0
  29. package/callbacks/promises.js +1 -0
  30. package/chat_history.cjs +1 -0
  31. package/chat_history.d.cts +1 -0
  32. package/chat_history.d.ts +1 -0
  33. package/chat_history.js +1 -0
  34. package/context.cjs +1 -0
  35. package/context.d.cts +1 -0
  36. package/context.d.ts +1 -0
  37. package/context.js +1 -0
  38. package/dist/caches/index.d.ts.map +1 -1
  39. package/dist/callbacks/base.d.ts.map +1 -1
  40. package/dist/language_models/chat_models.d.ts.map +1 -1
  41. package/dist/load/index.d.cts.map +1 -1
  42. package/dist/memory.d.ts.map +1 -1
  43. package/dist/messages/base.cjs +2 -2
  44. package/dist/messages/base.cjs.map +1 -1
  45. package/dist/messages/base.d.cts +1 -1
  46. package/dist/messages/base.d.cts.map +1 -1
  47. package/dist/messages/base.d.ts +1 -1
  48. package/dist/messages/base.d.ts.map +1 -1
  49. package/dist/messages/base.js +2 -2
  50. package/dist/messages/base.js.map +1 -1
  51. package/dist/messages/format.cjs +1 -1
  52. package/dist/messages/format.cjs.map +1 -1
  53. package/dist/messages/format.js +1 -1
  54. package/dist/messages/format.js.map +1 -1
  55. package/dist/messages/tool.d.cts.map +1 -1
  56. package/dist/runnables/graph_mermaid.cjs +9 -3
  57. package/dist/runnables/graph_mermaid.cjs.map +1 -1
  58. package/dist/runnables/graph_mermaid.js +9 -3
  59. package/dist/runnables/graph_mermaid.js.map +1 -1
  60. package/dist/tracers/base.cjs +9 -10
  61. package/dist/tracers/base.cjs.map +1 -1
  62. package/dist/tracers/base.js +9 -10
  63. package/dist/tracers/base.js.map +1 -1
  64. package/dist/tracers/event_stream.cjs +5 -1
  65. package/dist/tracers/event_stream.cjs.map +1 -1
  66. package/dist/tracers/event_stream.d.cts.map +1 -1
  67. package/dist/tracers/event_stream.d.ts.map +1 -1
  68. package/dist/tracers/event_stream.js +5 -1
  69. package/dist/tracers/event_stream.js.map +1 -1
  70. package/dist/utils/fast-json-patch/src/core.cjs +10 -0
  71. package/dist/utils/fast-json-patch/src/core.cjs.map +1 -1
  72. package/dist/utils/fast-json-patch/src/core.js +10 -0
  73. package/dist/utils/fast-json-patch/src/core.js.map +1 -1
  74. package/dist/utils/json_schema.cjs +4 -3
  75. package/dist/utils/json_schema.cjs.map +1 -1
  76. package/dist/utils/json_schema.d.cts +5 -2
  77. package/dist/utils/json_schema.d.cts.map +1 -1
  78. package/dist/utils/json_schema.d.ts +5 -2
  79. package/dist/utils/json_schema.d.ts.map +1 -1
  80. package/dist/utils/json_schema.js +4 -3
  81. package/dist/utils/json_schema.js.map +1 -1
  82. package/dist/utils/testing/chat_models.cjs +49 -2
  83. package/dist/utils/testing/chat_models.cjs.map +1 -1
  84. package/dist/utils/testing/chat_models.d.cts +4 -1
  85. package/dist/utils/testing/chat_models.d.cts.map +1 -1
  86. package/dist/utils/testing/chat_models.d.ts +4 -1
  87. package/dist/utils/testing/chat_models.d.ts.map +1 -1
  88. package/dist/utils/testing/chat_models.js +49 -2
  89. package/dist/utils/testing/chat_models.js.map +1 -1
  90. package/dist/utils/types/zod.cjs +1 -1
  91. package/dist/utils/types/zod.cjs.map +1 -1
  92. package/dist/utils/types/zod.js +1 -1
  93. package/dist/utils/types/zod.js.map +1 -1
  94. package/dist/vectorstores.d.cts.map +1 -1
  95. package/document_loaders/base.cjs +1 -0
  96. package/document_loaders/base.d.cts +1 -0
  97. package/document_loaders/base.d.ts +1 -0
  98. package/document_loaders/base.js +1 -0
  99. package/document_loaders/langsmith.cjs +1 -0
  100. package/document_loaders/langsmith.d.cts +1 -0
  101. package/document_loaders/langsmith.d.ts +1 -0
  102. package/document_loaders/langsmith.js +1 -0
  103. package/documents.cjs +1 -0
  104. package/documents.d.cts +1 -0
  105. package/documents.d.ts +1 -0
  106. package/documents.js +1 -0
  107. package/embeddings.cjs +1 -0
  108. package/embeddings.d.cts +1 -0
  109. package/embeddings.d.ts +1 -0
  110. package/embeddings.js +1 -0
  111. package/example_selectors.cjs +1 -0
  112. package/example_selectors.d.cts +1 -0
  113. package/example_selectors.d.ts +1 -0
  114. package/example_selectors.js +1 -0
  115. package/indexing.cjs +1 -0
  116. package/indexing.d.cts +1 -0
  117. package/indexing.d.ts +1 -0
  118. package/indexing.js +1 -0
  119. package/language_models/base.cjs +1 -0
  120. package/language_models/base.d.cts +1 -0
  121. package/language_models/base.d.ts +1 -0
  122. package/language_models/base.js +1 -0
  123. package/language_models/chat_models.cjs +1 -0
  124. package/language_models/chat_models.d.cts +1 -0
  125. package/language_models/chat_models.d.ts +1 -0
  126. package/language_models/chat_models.js +1 -0
  127. package/language_models/llms.cjs +1 -0
  128. package/language_models/llms.d.cts +1 -0
  129. package/language_models/llms.d.ts +1 -0
  130. package/language_models/llms.js +1 -0
  131. package/language_models/profile.cjs +1 -0
  132. package/language_models/profile.d.cts +1 -0
  133. package/language_models/profile.d.ts +1 -0
  134. package/language_models/profile.js +1 -0
  135. package/load/serializable.cjs +1 -0
  136. package/load/serializable.d.cts +1 -0
  137. package/load/serializable.d.ts +1 -0
  138. package/load/serializable.js +1 -0
  139. package/load.cjs +1 -0
  140. package/load.d.cts +1 -0
  141. package/load.d.ts +1 -0
  142. package/load.js +1 -0
  143. package/memory.cjs +1 -0
  144. package/memory.d.cts +1 -0
  145. package/memory.d.ts +1 -0
  146. package/memory.js +1 -0
  147. package/messages/tool.cjs +1 -0
  148. package/messages/tool.d.cts +1 -0
  149. package/messages/tool.d.ts +1 -0
  150. package/messages/tool.js +1 -0
  151. package/messages.cjs +1 -0
  152. package/messages.d.cts +1 -0
  153. package/messages.d.ts +1 -0
  154. package/messages.js +1 -0
  155. package/output_parsers/openai_functions.cjs +1 -0
  156. package/output_parsers/openai_functions.d.cts +1 -0
  157. package/output_parsers/openai_functions.d.ts +1 -0
  158. package/output_parsers/openai_functions.js +1 -0
  159. package/output_parsers/openai_tools.cjs +1 -0
  160. package/output_parsers/openai_tools.d.cts +1 -0
  161. package/output_parsers/openai_tools.d.ts +1 -0
  162. package/output_parsers/openai_tools.js +1 -0
  163. package/output_parsers.cjs +1 -0
  164. package/output_parsers.d.cts +1 -0
  165. package/output_parsers.d.ts +1 -0
  166. package/output_parsers.js +1 -0
  167. package/outputs.cjs +1 -0
  168. package/outputs.d.cts +1 -0
  169. package/outputs.d.ts +1 -0
  170. package/outputs.js +1 -0
  171. package/package.json +1 -1
  172. package/prompt_values.cjs +1 -0
  173. package/prompt_values.d.cts +1 -0
  174. package/prompt_values.d.ts +1 -0
  175. package/prompt_values.js +1 -0
  176. package/prompts.cjs +1 -0
  177. package/prompts.d.cts +1 -0
  178. package/prompts.d.ts +1 -0
  179. package/prompts.js +1 -0
  180. package/retrievers/document_compressors.cjs +1 -0
  181. package/retrievers/document_compressors.d.cts +1 -0
  182. package/retrievers/document_compressors.d.ts +1 -0
  183. package/retrievers/document_compressors.js +1 -0
  184. package/retrievers.cjs +1 -0
  185. package/retrievers.d.cts +1 -0
  186. package/retrievers.d.ts +1 -0
  187. package/retrievers.js +1 -0
  188. package/runnables/graph.cjs +1 -0
  189. package/runnables/graph.d.cts +1 -0
  190. package/runnables/graph.d.ts +1 -0
  191. package/runnables/graph.js +1 -0
  192. package/runnables.cjs +1 -0
  193. package/runnables.d.cts +1 -0
  194. package/runnables.d.ts +1 -0
  195. package/runnables.js +1 -0
  196. package/singletons.cjs +1 -0
  197. package/singletons.d.cts +1 -0
  198. package/singletons.d.ts +1 -0
  199. package/singletons.js +1 -0
  200. package/stores.cjs +1 -0
  201. package/stores.d.cts +1 -0
  202. package/stores.d.ts +1 -0
  203. package/stores.js +1 -0
  204. package/structured_query.cjs +1 -0
  205. package/structured_query.d.cts +1 -0
  206. package/structured_query.d.ts +1 -0
  207. package/structured_query.js +1 -0
  208. package/tools.cjs +1 -0
  209. package/tools.d.cts +1 -0
  210. package/tools.d.ts +1 -0
  211. package/tools.js +1 -0
  212. package/tracers/base.cjs +1 -0
  213. package/tracers/base.d.cts +1 -0
  214. package/tracers/base.d.ts +1 -0
  215. package/tracers/base.js +1 -0
  216. package/tracers/console.cjs +1 -0
  217. package/tracers/console.d.cts +1 -0
  218. package/tracers/console.d.ts +1 -0
  219. package/tracers/console.js +1 -0
  220. package/tracers/log_stream.cjs +1 -0
  221. package/tracers/log_stream.d.cts +1 -0
  222. package/tracers/log_stream.d.ts +1 -0
  223. package/tracers/log_stream.js +1 -0
  224. package/tracers/run_collector.cjs +1 -0
  225. package/tracers/run_collector.d.cts +1 -0
  226. package/tracers/run_collector.d.ts +1 -0
  227. package/tracers/run_collector.js +1 -0
  228. package/tracers/tracer_langchain.cjs +1 -0
  229. package/tracers/tracer_langchain.d.cts +1 -0
  230. package/tracers/tracer_langchain.d.ts +1 -0
  231. package/tracers/tracer_langchain.js +1 -0
  232. package/types/stream.cjs +1 -0
  233. package/types/stream.d.cts +1 -0
  234. package/types/stream.d.ts +1 -0
  235. package/types/stream.js +1 -0
  236. package/utils/async_caller.cjs +1 -0
  237. package/utils/async_caller.d.cts +1 -0
  238. package/utils/async_caller.d.ts +1 -0
  239. package/utils/async_caller.js +1 -0
  240. package/utils/chunk_array.cjs +1 -0
  241. package/utils/chunk_array.d.cts +1 -0
  242. package/utils/chunk_array.d.ts +1 -0
  243. package/utils/chunk_array.js +1 -0
  244. package/utils/env.cjs +1 -0
  245. package/utils/env.d.cts +1 -0
  246. package/utils/env.d.ts +1 -0
  247. package/utils/env.js +1 -0
  248. package/utils/event_source_parse.cjs +1 -0
  249. package/utils/event_source_parse.d.cts +1 -0
  250. package/utils/event_source_parse.d.ts +1 -0
  251. package/utils/event_source_parse.js +1 -0
  252. package/utils/format.cjs +1 -0
  253. package/utils/format.d.cts +1 -0
  254. package/utils/format.d.ts +1 -0
  255. package/utils/format.js +1 -0
  256. package/utils/function_calling.cjs +1 -0
  257. package/utils/function_calling.d.cts +1 -0
  258. package/utils/function_calling.d.ts +1 -0
  259. package/utils/function_calling.js +1 -0
  260. package/utils/hash.cjs +1 -0
  261. package/utils/hash.d.cts +1 -0
  262. package/utils/hash.d.ts +1 -0
  263. package/utils/hash.js +1 -0
  264. package/utils/json_patch.cjs +1 -0
  265. package/utils/json_patch.d.cts +1 -0
  266. package/utils/json_patch.d.ts +1 -0
  267. package/utils/json_patch.js +1 -0
  268. package/utils/json_schema.cjs +1 -0
  269. package/utils/json_schema.d.cts +1 -0
  270. package/utils/json_schema.d.ts +1 -0
  271. package/utils/json_schema.js +1 -0
  272. package/utils/math.cjs +1 -0
  273. package/utils/math.d.cts +1 -0
  274. package/utils/math.d.ts +1 -0
  275. package/utils/math.js +1 -0
  276. package/utils/stream.cjs +1 -0
  277. package/utils/stream.d.cts +1 -0
  278. package/utils/stream.d.ts +1 -0
  279. package/utils/stream.js +1 -0
  280. package/utils/testing.cjs +1 -0
  281. package/utils/testing.d.cts +1 -0
  282. package/utils/testing.d.ts +1 -0
  283. package/utils/testing.js +1 -0
  284. package/utils/tiktoken.cjs +1 -0
  285. package/utils/tiktoken.d.cts +1 -0
  286. package/utils/tiktoken.d.ts +1 -0
  287. package/utils/tiktoken.js +1 -0
  288. package/utils/types.cjs +1 -0
  289. package/utils/types.d.cts +1 -0
  290. package/utils/types.d.ts +1 -0
  291. package/utils/types.js +1 -0
  292. package/vectorstores.cjs +1 -0
  293. package/vectorstores.d.cts +1 -0
  294. package/vectorstores.d.ts +1 -0
  295. package/vectorstores.js +1 -0
@@ -1 +1 @@
1
- {"version":3,"file":"base.d.cts","names":["Serializable","SerializedConstructor","ContentBlock","$InferMessageContent","$InferResponseMetadata","MessageStructure","MessageType","Message","MessageStringFormat","MESSAGE_SYMBOL","StoredMessageData","Record","StoredMessage","StoredGeneration","StoredMessageV1","MessageContent","Array","FunctionCall","BaseMessageFields","TStructure","TRole","Standard","OpenAIToolCall","Partial","mergeContent","_mergeStatus","BaseMessage","NonNullable","Symbol","toStringTag","isOpenAIToolCallArray","_mergeDicts","_mergeLists","Content","_mergeObj","T","BaseMessageChunk","MessageFieldWithRole","_isMessageFieldWithRole","BaseMessageLike","isBaseMessage","isBaseMessageChunk"],"sources":["../../src/messages/base.d.ts"],"sourcesContent":["import { Serializable, SerializedConstructor } from \"../load/serializable.js\";\nimport { ContentBlock } from \"./content/index.js\";\nimport { $InferMessageContent, $InferResponseMetadata, MessageStructure, MessageType, Message } from \"./message.js\";\nimport { type MessageStringFormat } from \"./format.js\";\n/** @internal */\ndeclare const MESSAGE_SYMBOL: unique symbol;\nexport interface StoredMessageData {\n content: string;\n role: string | undefined;\n name: string | undefined;\n tool_call_id: string | undefined;\n additional_kwargs?: Record<string, any>;\n /** Response metadata. For example: response headers, logprobs, token counts, model name. */\n response_metadata?: Record<string, any>;\n id?: string;\n}\nexport interface StoredMessage {\n type: string;\n data: StoredMessageData;\n}\nexport interface StoredGeneration {\n text: string;\n message?: StoredMessage;\n}\nexport interface StoredMessageV1 {\n type: string;\n role: string | undefined;\n text: string;\n}\nexport type MessageContent = string | Array<ContentBlock>;\nexport interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n /**\n * The name of the function to call.\n */\n name: string;\n}\nexport type BaseMessageFields<TStructure extends MessageStructure = MessageStructure, TRole extends MessageType = MessageType> = {\n id?: string;\n name?: string;\n content?: $InferMessageContent<TStructure, TRole>;\n contentBlocks?: Array<ContentBlock.Standard>;\n /** @deprecated */\n additional_kwargs?: {\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n function_call?: FunctionCall;\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n tool_calls?: OpenAIToolCall[];\n [key: string]: unknown;\n };\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n};\nexport declare function mergeContent(firstContent: MessageContent, secondContent: MessageContent): MessageContent;\n/**\n * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else\n * it will return 'success'.\n *\n * @param {\"success\" | \"error\" | undefined} left The existing value to 'merge' with the new value.\n * @param {\"success\" | \"error\" | undefined} right The new value to 'merge' with the existing value\n * @returns {\"success\" | \"error\"} The 'merged' value.\n */\nexport declare function _mergeStatus(left?: \"success\" | \"error\", right?: \"success\" | \"error\"): \"success\" | \"error\" | undefined;\n/**\n * Base class for all types of messages in a conversation. It includes\n * properties like `content`, `name`, and `additional_kwargs`. It also\n * includes methods like `toDict()` and `_getType()`.\n */\nexport declare abstract class BaseMessage<TStructure extends MessageStructure = MessageStructure, TRole extends MessageType = MessageType> extends Serializable implements Message<TStructure, TRole> {\n lc_namespace: string[];\n lc_serializable: boolean;\n get lc_aliases(): Record<string, string>;\n readonly [MESSAGE_SYMBOL]: true;\n abstract readonly type: TRole;\n id?: string;\n name?: string;\n content: $InferMessageContent<TStructure, TRole>;\n additional_kwargs: NonNullable<BaseMessageFields<TStructure, TRole>[\"additional_kwargs\"]>;\n response_metadata: NonNullable<BaseMessageFields<TStructure, TRole>[\"response_metadata\"]>;\n /**\n * @deprecated Use .getType() instead or import the proper typeguard.\n * For example:\n *\n * ```ts\n * import { isAIMessage } from \"@langchain/core/messages\";\n *\n * const message = new AIMessage(\"Hello!\");\n * isAIMessage(message); // true\n * ```\n */\n _getType(): MessageType;\n /**\n * @deprecated Use .type instead\n * The type of the message.\n */\n getType(): MessageType;\n constructor(arg: $InferMessageContent<TStructure, TRole> | BaseMessageFields<TStructure, TRole>);\n /** Get text content of the message. */\n get text(): string;\n get contentBlocks(): Array<ContentBlock.Standard>;\n toDict(): StoredMessage;\n static lc_name(): string;\n get _printableFields(): Record<string, unknown>;\n static isInstance(obj: unknown): obj is BaseMessage;\n _updateId(value: string | undefined): void;\n get [Symbol.toStringTag](): any;\n toFormattedString(format?: MessageStringFormat): string;\n}\n/**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\nexport type OpenAIToolCall = {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The function that the model called.\n */\n function: FunctionCall;\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: \"function\";\n index?: number;\n};\nexport declare function isOpenAIToolCallArray(value?: unknown): value is OpenAIToolCall[];\nexport declare function _mergeDicts(left?: Record<string, any>, right?: Record<string, any>): Record<string, any>;\nexport declare function _mergeLists<Content extends ContentBlock>(left?: Content[], right?: Content[]): Content[] | undefined;\nexport declare function _mergeObj<T = any>(left: T | undefined, right: T | undefined): T;\n/**\n * Represents a chunk of a message, which can be concatenated with other\n * message chunks. It includes a method `_merge_kwargs_dict()` for merging\n * additional keyword arguments from another `BaseMessageChunk` into this\n * one. It also overrides the `__add__()` method to support concatenation\n * of `BaseMessageChunk` instances.\n */\nexport declare abstract class BaseMessageChunk<TStructure extends MessageStructure = MessageStructure, TRole extends MessageType = MessageType> extends BaseMessage<TStructure, TRole> {\n abstract concat(chunk: BaseMessageChunk): BaseMessageChunk<TStructure, TRole>;\n static isInstance(obj: unknown): obj is BaseMessageChunk;\n}\nexport type MessageFieldWithRole = {\n role: MessageType;\n content: MessageContent;\n name?: string;\n} & Record<string, unknown>;\nexport declare function _isMessageFieldWithRole(x: BaseMessageLike): x is MessageFieldWithRole;\nexport type BaseMessageLike = BaseMessage | MessageFieldWithRole | [MessageType, MessageContent] | string\n/**\n * @deprecated Specifying \"type\" is deprecated and will be removed in 0.4.0.\n */\n | ({\n type: MessageType | \"user\" | \"assistant\" | \"placeholder\";\n} & BaseMessageFields & Record<string, unknown>) | SerializedConstructor;\n/**\n * @deprecated Use {@link BaseMessage.isInstance} instead\n */\nexport declare function isBaseMessage(messageLike?: unknown): messageLike is BaseMessage;\n/**\n * @deprecated Use {@link BaseMessageChunk.isInstance} instead\n */\nexport declare function isBaseMessageChunk(messageLike?: unknown): messageLike is BaseMessageChunk;\nexport {};\n//# sourceMappingURL=base.d.ts.map"],"mappings":";;;;;;;cAKcS;AAAAA,UACGC,iBAAAA,CAD0B;EAC1BA,OAAAA,EAAAA,MAAAA;EAUAE,IAAAA,EAAAA,MAAAA,GAAAA,SAAa;EAIbC,IAAAA,EAAAA,MAAAA,GAAAA,SAAgB;EAIhBC,YAAAA,EAAAA,MAAe,GAAA,SAAA;EAKpBC,iBAAc,CAAA,EAlBFJ,MAkBE,CAAA,MAAkBT,EAAAA,GAAAA,CAAAA;EAC3Be;EAaLC,iBAAAA,CAAAA,EA9BYP,MA8BK,CAAAQ,MAAAA,EAAAA,GAAAA,CAAAC;EAAoBf,EAAAA,CAAAA,EAAAA,MAAAA;;AAAmDC,UA3BnFM,aAAAA,CA2BmFN;EAAcA,IAAAA,EAAAA,MAAAA;EAG/Ea,IAAAA,EA5BzBT,iBA4ByBS;;AAArBhB,UA1BGU,gBAAAA,CA0BHV;EACYD,IAAAA,EAAAA,MAAamB;EAAnBL,OAAAA,CAAAA,EAzBN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AAkBb,cAAcW,wBAAwB/B,aAAaS;;;;QAKvET;IACNY,oBAAoBP,2BAA2BV;;;;iBAI3BuC,aAAAA,wCAAqDd;;;;iBAIrDe,kBAAAA,wCAA0DL"}
1
+ {"version":3,"file":"base.d.cts","names":["Serializable","SerializedConstructor","ContentBlock","$InferMessageContent","$InferResponseMetadata","MessageStructure","MessageType","Message","MessageStringFormat","MESSAGE_SYMBOL","StoredMessageData","Record","StoredMessage","StoredGeneration","StoredMessageV1","MessageContent","Array","FunctionCall","BaseMessageFields","TStructure","TRole","Standard","OpenAIToolCall","Partial","mergeContent","_mergeStatus","BaseMessage","NonNullable","Symbol","toStringTag","isOpenAIToolCallArray","_mergeDicts","_mergeLists","Content","_mergeObj","T","BaseMessageChunk","MessageFieldWithRole","_isMessageFieldWithRole","BaseMessageLike","isBaseMessage","isBaseMessageChunk"],"sources":["../../src/messages/base.d.ts"],"sourcesContent":["import { Serializable, SerializedConstructor } from \"../load/serializable.js\";\nimport { ContentBlock } from \"./content/index.js\";\nimport { $InferMessageContent, $InferResponseMetadata, MessageStructure, MessageType, Message } from \"./message.js\";\nimport { type MessageStringFormat } from \"./format.js\";\n/** @internal */\ndeclare const MESSAGE_SYMBOL: unique symbol;\nexport interface StoredMessageData {\n content: string;\n role: string | undefined;\n name: string | undefined;\n tool_call_id: string | undefined;\n additional_kwargs?: Record<string, any>;\n /** Response metadata. For example: response headers, logprobs, token counts, model name. */\n response_metadata?: Record<string, any>;\n id?: string;\n}\nexport interface StoredMessage {\n type: string;\n data: StoredMessageData;\n}\nexport interface StoredGeneration {\n text: string;\n message?: StoredMessage;\n}\nexport interface StoredMessageV1 {\n type: string;\n role: string | undefined;\n text: string;\n}\nexport type MessageContent = string | Array<ContentBlock>;\nexport interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n /**\n * The name of the function to call.\n */\n name: string;\n}\nexport type BaseMessageFields<TStructure extends MessageStructure = MessageStructure, TRole extends MessageType = MessageType> = {\n id?: string;\n name?: string;\n content?: $InferMessageContent<TStructure, TRole>;\n contentBlocks?: Array<ContentBlock.Standard>;\n /** @deprecated */\n additional_kwargs?: {\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n function_call?: FunctionCall;\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n tool_calls?: OpenAIToolCall[];\n [key: string]: unknown;\n };\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n};\nexport declare function mergeContent(firstContent: MessageContent, secondContent: MessageContent): MessageContent;\n/**\n * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else\n * it will return 'success'.\n *\n * @param {\"success\" | \"error\" | undefined} left The existing value to 'merge' with the new value.\n * @param {\"success\" | \"error\" | undefined} right The new value to 'merge' with the existing value\n * @returns {\"success\" | \"error\"} The 'merged' value.\n */\nexport declare function _mergeStatus(left?: \"success\" | \"error\", right?: \"success\" | \"error\"): \"success\" | \"error\" | undefined;\n/**\n * Base class for all types of messages in a conversation. It includes\n * properties like `content`, `name`, and `additional_kwargs`. It also\n * includes methods like `toDict()` and `_getType()`.\n */\nexport declare abstract class BaseMessage<TStructure extends MessageStructure = MessageStructure, TRole extends MessageType = MessageType> extends Serializable implements Message<TStructure, TRole> {\n lc_namespace: string[];\n lc_serializable: boolean;\n get lc_aliases(): Record<string, string>;\n readonly [MESSAGE_SYMBOL]: true;\n abstract readonly type: TRole;\n id?: string;\n name?: string;\n content: $InferMessageContent<TStructure, TRole>;\n additional_kwargs: NonNullable<BaseMessageFields<TStructure, TRole>[\"additional_kwargs\"]>;\n response_metadata: NonNullable<BaseMessageFields<TStructure, TRole>[\"response_metadata\"]>;\n /**\n * @deprecated Use .getType() instead or import the proper typeguard.\n * For example:\n *\n * ```ts\n * import { isAIMessage } from \"@langchain/core/messages\";\n *\n * const message = new AIMessage(\"Hello!\");\n * isAIMessage(message); // true\n * ```\n */\n _getType(): MessageType;\n /**\n * @deprecated Use .type instead\n * The type of the message.\n */\n getType(): MessageType;\n constructor(arg: $InferMessageContent<TStructure, TRole> | BaseMessageFields<TStructure, TRole>);\n /** Get text content of the message. */\n get text(): string;\n get contentBlocks(): Array<ContentBlock.Standard>;\n toDict(): StoredMessage;\n static lc_name(): string;\n get _printableFields(): Record<string, unknown>;\n static isInstance(obj: unknown): obj is BaseMessage;\n _updateId(value: string | undefined): void;\n get [Symbol.toStringTag](): any;\n toFormattedString(format?: MessageStringFormat): string;\n}\n/**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\nexport type OpenAIToolCall = {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The function that the model called.\n */\n function: FunctionCall;\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: \"function\";\n index?: number;\n};\nexport declare function isOpenAIToolCallArray(value?: unknown): value is OpenAIToolCall[];\nexport declare function _mergeDicts(left?: Record<string, any>, right?: Record<string, any>): Record<string, any>;\nexport declare function _mergeLists<Content extends ContentBlock>(left?: Content[], right?: Content[]): Content[] | undefined;\nexport declare function _mergeObj<T = any>(left: T | undefined, right: T | undefined): T | undefined;\n/**\n * Represents a chunk of a message, which can be concatenated with other\n * message chunks. It includes a method `_merge_kwargs_dict()` for merging\n * additional keyword arguments from another `BaseMessageChunk` into this\n * one. It also overrides the `__add__()` method to support concatenation\n * of `BaseMessageChunk` instances.\n */\nexport declare abstract class BaseMessageChunk<TStructure extends MessageStructure = MessageStructure, TRole extends MessageType = MessageType> extends BaseMessage<TStructure, TRole> {\n abstract concat(chunk: BaseMessageChunk): BaseMessageChunk<TStructure, TRole>;\n static isInstance(obj: unknown): obj is BaseMessageChunk;\n}\nexport type MessageFieldWithRole = {\n role: MessageType;\n content: MessageContent;\n name?: string;\n} & Record<string, unknown>;\nexport declare function _isMessageFieldWithRole(x: BaseMessageLike): x is MessageFieldWithRole;\nexport type BaseMessageLike = BaseMessage | MessageFieldWithRole | [MessageType, MessageContent] | string\n/**\n * @deprecated Specifying \"type\" is deprecated and will be removed in 0.4.0.\n */\n | ({\n type: MessageType | \"user\" | \"assistant\" | \"placeholder\";\n} & BaseMessageFields & Record<string, unknown>) | SerializedConstructor;\n/**\n * @deprecated Use {@link BaseMessage.isInstance} instead\n */\nexport declare function isBaseMessage(messageLike?: unknown): messageLike is BaseMessage;\n/**\n * @deprecated Use {@link BaseMessageChunk.isInstance} instead\n */\nexport declare function isBaseMessageChunk(messageLike?: unknown): messageLike is BaseMessageChunk;\nexport {};\n//# sourceMappingURL=base.d.ts.map"],"mappings":";;;;;;;cAKcS;AAAAA,UACGC,iBAAAA,CAD0B;EAC1BA,OAAAA,EAAAA,MAAAA;EAUAE,IAAAA,EAAAA,MAAAA,GAAAA,SAAa;EAIbC,IAAAA,EAAAA,MAAAA,GAAAA,SAAgB;EAIhBC,YAAAA,EAAAA,MAAe,GAAA,SAAA;EAKpBC,iBAAc,CAAA,EAlBFJ,MAkBE,CAAA,MAAkBT,EAAAA,GAAAA,CAAAA;EAC3Be;EAaLC,iBAAAA,CAAAA,EA9BYP,MA8BK,CAAAQ,MAAAA,EAAAA,GAAAA,CAAAC;EAAoBf,EAAAA,CAAAA,EAAAA,MAAAA;;AAAmDC,UA3BnFM,aAAAA,CA2BmFN;EAAcA,IAAAA,EAAAA,MAAAA;EAG/Ea,IAAAA,EA5BzBT,iBA4ByBS;;AAArBhB,UA1BGU,gBAAAA,CA0BHV;EACYD,IAAAA,EAAAA,MAAamB;EAAnBL,OAAAA,CAAAA,EAzBNJ,aAyBMI;;AAUCM,UAjCJR,eAAAA,CAiCIQ;EAGkCH,IAAAA,EAAAA,MAAAA;EAAYC,IAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAnChB,IAAAA,EAAAA,MAAAA;;AAAD,KA/BnBW,cAAAA,GA+BmB,MAAA,GA/BOC,KA+BP,CA/Bad,YA+Bb,CAAA;AAEPsB,UAhCPP,YAAAA,CAgCmB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Cf,CAAAA;EACGS,MAAAA,CAAAA,CAAAA,EA3CCH,aA2CDG;EAETJ,OAAAA,OAAAA,CAAAA,CAAAA,EAAAA,MAAAA;EAAM,IAAA,gBAAA,CAAA,CAAA,EA3CkBA,MA2ClB,CAAA,MAAA,EAAA,OAAA,CAAA;EACc2B,OAAAA,UAAAA,CAAAA,GAAAA,EAAAA,OAAuB,CAAA,EAAA,GAAA,IA3CHZ,WA2COa;EACvCA,SAAAA,CAAAA,KAAAA,EAAAA,MAAe,GAAA,SAAA,CAAA,EAAA,IAAA;EAAGb,KA1CrBE,MAAAA,CAAOC,WAAAA,GA0CcH,EAAAA,GAAAA;EAAcW,iBAAAA,CAAAA,MAAAA,CAAAA,EAzCb7B,mBAyCa6B,CAAAA,EAAAA,MAAAA;;;;;AAMpB1B,KA1CZW,cAAAA,GA0CYX;EAA2BV;AAAqB;AAIxE;EAIwBwC,EAAAA,EAAAA,MAAAA;;;;YA1CVxB;;;;;;;iBAOUa,qBAAAA,4BAAiDR;iBACjDS,WAAAA,QAAmBpB,6BAA6BA,sBAAsBA;iBACtEqB,4BAA4B9B,qBAAqB+B,mBAAmBA,YAAYA;iBAChFC,yBAAyBC,sBAAsBA,gBAAgBA;;;;;;;;uBAQzDC,oCAAoC/B,mBAAmBA,gCAAgCC,cAAcA,qBAAqBoB,YAAYP,YAAYC;yBACrJgB,mBAAmBA,iBAAiBjB,YAAYC;0CAC/BgB;;KAEhCC,oBAAAA;QACF/B;WACGS;;IAETJ;iBACoB2B,uBAAAA,IAA2BC,uBAAuBF;KAC9DE,eAAAA,GAAkBb,cAAcW,wBAAwB/B,aAAaS;;;;QAKvET;IACNY,oBAAoBP,2BAA2BV;;;;iBAI3BuC,aAAAA,wCAAqDd;;;;iBAIrDe,kBAAAA,wCAA0DL"}
@@ -138,7 +138,7 @@ type OpenAIToolCall = {
138
138
  declare function isOpenAIToolCallArray(value?: unknown): value is OpenAIToolCall[];
139
139
  declare function _mergeDicts(left?: Record<string, any>, right?: Record<string, any>): Record<string, any>;
140
140
  declare function _mergeLists<Content extends ContentBlock>(left?: Content[], right?: Content[]): Content[] | undefined;
141
- declare function _mergeObj<T = any>(left: T | undefined, right: T | undefined): T;
141
+ declare function _mergeObj<T = any>(left: T | undefined, right: T | undefined): T | undefined;
142
142
  /**
143
143
  * Represents a chunk of a message, which can be concatenated with other
144
144
  * message chunks. It includes a method `_merge_kwargs_dict()` for merging
@@ -1 +1 @@
1
- {"version":3,"file":"base.d.ts","names":["Serializable","SerializedConstructor","ContentBlock","$InferMessageContent","$InferResponseMetadata","MessageStructure","MessageType","Message","MessageStringFormat","MESSAGE_SYMBOL","StoredMessageData","Record","StoredMessage","StoredGeneration","StoredMessageV1","MessageContent","Array","FunctionCall","BaseMessageFields","TStructure","TRole","Standard","OpenAIToolCall","Partial","mergeContent","_mergeStatus","BaseMessage","NonNullable","Symbol","toStringTag","isOpenAIToolCallArray","_mergeDicts","_mergeLists","Content","_mergeObj","T","BaseMessageChunk","MessageFieldWithRole","_isMessageFieldWithRole","BaseMessageLike","isBaseMessage","isBaseMessageChunk"],"sources":["../../src/messages/base.d.ts"],"sourcesContent":["import { Serializable, SerializedConstructor } from \"../load/serializable.js\";\nimport { ContentBlock } from \"./content/index.js\";\nimport { $InferMessageContent, $InferResponseMetadata, MessageStructure, MessageType, Message } from \"./message.js\";\nimport { type MessageStringFormat } from \"./format.js\";\n/** @internal */\ndeclare const MESSAGE_SYMBOL: unique symbol;\nexport interface StoredMessageData {\n content: string;\n role: string | undefined;\n name: string | undefined;\n tool_call_id: string | undefined;\n additional_kwargs?: Record<string, any>;\n /** Response metadata. For example: response headers, logprobs, token counts, model name. */\n response_metadata?: Record<string, any>;\n id?: string;\n}\nexport interface StoredMessage {\n type: string;\n data: StoredMessageData;\n}\nexport interface StoredGeneration {\n text: string;\n message?: StoredMessage;\n}\nexport interface StoredMessageV1 {\n type: string;\n role: string | undefined;\n text: string;\n}\nexport type MessageContent = string | Array<ContentBlock>;\nexport interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n /**\n * The name of the function to call.\n */\n name: string;\n}\nexport type BaseMessageFields<TStructure extends MessageStructure = MessageStructure, TRole extends MessageType = MessageType> = {\n id?: string;\n name?: string;\n content?: $InferMessageContent<TStructure, TRole>;\n contentBlocks?: Array<ContentBlock.Standard>;\n /** @deprecated */\n additional_kwargs?: {\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n function_call?: FunctionCall;\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n tool_calls?: OpenAIToolCall[];\n [key: string]: unknown;\n };\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n};\nexport declare function mergeContent(firstContent: MessageContent, secondContent: MessageContent): MessageContent;\n/**\n * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else\n * it will return 'success'.\n *\n * @param {\"success\" | \"error\" | undefined} left The existing value to 'merge' with the new value.\n * @param {\"success\" | \"error\" | undefined} right The new value to 'merge' with the existing value\n * @returns {\"success\" | \"error\"} The 'merged' value.\n */\nexport declare function _mergeStatus(left?: \"success\" | \"error\", right?: \"success\" | \"error\"): \"success\" | \"error\" | undefined;\n/**\n * Base class for all types of messages in a conversation. It includes\n * properties like `content`, `name`, and `additional_kwargs`. It also\n * includes methods like `toDict()` and `_getType()`.\n */\nexport declare abstract class BaseMessage<TStructure extends MessageStructure = MessageStructure, TRole extends MessageType = MessageType> extends Serializable implements Message<TStructure, TRole> {\n lc_namespace: string[];\n lc_serializable: boolean;\n get lc_aliases(): Record<string, string>;\n readonly [MESSAGE_SYMBOL]: true;\n abstract readonly type: TRole;\n id?: string;\n name?: string;\n content: $InferMessageContent<TStructure, TRole>;\n additional_kwargs: NonNullable<BaseMessageFields<TStructure, TRole>[\"additional_kwargs\"]>;\n response_metadata: NonNullable<BaseMessageFields<TStructure, TRole>[\"response_metadata\"]>;\n /**\n * @deprecated Use .getType() instead or import the proper typeguard.\n * For example:\n *\n * ```ts\n * import { isAIMessage } from \"@langchain/core/messages\";\n *\n * const message = new AIMessage(\"Hello!\");\n * isAIMessage(message); // true\n * ```\n */\n _getType(): MessageType;\n /**\n * @deprecated Use .type instead\n * The type of the message.\n */\n getType(): MessageType;\n constructor(arg: $InferMessageContent<TStructure, TRole> | BaseMessageFields<TStructure, TRole>);\n /** Get text content of the message. */\n get text(): string;\n get contentBlocks(): Array<ContentBlock.Standard>;\n toDict(): StoredMessage;\n static lc_name(): string;\n get _printableFields(): Record<string, unknown>;\n static isInstance(obj: unknown): obj is BaseMessage;\n _updateId(value: string | undefined): void;\n get [Symbol.toStringTag](): any;\n toFormattedString(format?: MessageStringFormat): string;\n}\n/**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\nexport type OpenAIToolCall = {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The function that the model called.\n */\n function: FunctionCall;\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: \"function\";\n index?: number;\n};\nexport declare function isOpenAIToolCallArray(value?: unknown): value is OpenAIToolCall[];\nexport declare function _mergeDicts(left?: Record<string, any>, right?: Record<string, any>): Record<string, any>;\nexport declare function _mergeLists<Content extends ContentBlock>(left?: Content[], right?: Content[]): Content[] | undefined;\nexport declare function _mergeObj<T = any>(left: T | undefined, right: T | undefined): T;\n/**\n * Represents a chunk of a message, which can be concatenated with other\n * message chunks. It includes a method `_merge_kwargs_dict()` for merging\n * additional keyword arguments from another `BaseMessageChunk` into this\n * one. It also overrides the `__add__()` method to support concatenation\n * of `BaseMessageChunk` instances.\n */\nexport declare abstract class BaseMessageChunk<TStructure extends MessageStructure = MessageStructure, TRole extends MessageType = MessageType> extends BaseMessage<TStructure, TRole> {\n abstract concat(chunk: BaseMessageChunk): BaseMessageChunk<TStructure, TRole>;\n static isInstance(obj: unknown): obj is BaseMessageChunk;\n}\nexport type MessageFieldWithRole = {\n role: MessageType;\n content: MessageContent;\n name?: string;\n} & Record<string, unknown>;\nexport declare function _isMessageFieldWithRole(x: BaseMessageLike): x is MessageFieldWithRole;\nexport type BaseMessageLike = BaseMessage | MessageFieldWithRole | [MessageType, MessageContent] | string\n/**\n * @deprecated Specifying \"type\" is deprecated and will be removed in 0.4.0.\n */\n | ({\n type: MessageType | \"user\" | \"assistant\" | \"placeholder\";\n} & BaseMessageFields & Record<string, unknown>) | SerializedConstructor;\n/**\n * @deprecated Use {@link BaseMessage.isInstance} instead\n */\nexport declare function isBaseMessage(messageLike?: unknown): messageLike is BaseMessage;\n/**\n * @deprecated Use {@link BaseMessageChunk.isInstance} instead\n */\nexport declare function isBaseMessageChunk(messageLike?: unknown): messageLike is BaseMessageChunk;\nexport {};\n//# sourceMappingURL=base.d.ts.map"],"mappings":";;;;;;;cAKcS;AAAAA,UACGC,iBAAAA,CAD0B;EAC1BA,OAAAA,EAAAA,MAAAA;EAUAE,IAAAA,EAAAA,MAAAA,GAAAA,SAAa;EAIbC,IAAAA,EAAAA,MAAAA,GAAAA,SAAgB;EAIhBC,YAAAA,EAAAA,MAAe,GAAA,SAAA;EAKpBC,iBAAc,CAAA,EAlBFJ,MAkBE,CAAA,MAAkBT,EAAAA,GAAAA,CAAAA;EAC3Be;EAaLC,iBAAAA,CAAAA,EA9BYP,MA8BK,CAAAQ,MAAAA,EAAAA,GAAAA,CAAAC;EAAoBf,EAAAA,CAAAA,EAAAA,MAAAA;;AAAmDC,UA3BnFM,aAAAA,CA2BmFN;EAAcA,IAAAA,EAAAA,MAAAA;EAG/Ea,IAAAA,EA5BzBT,iBA4ByBS;;AAArBhB,UA1BGU,gBAAAA,CA0BHV;EACYD,IAAAA,EAAAA,MAAamB;EAAnBL,OAAAA,CAAAA,EAzBNJ,aAyBMI;;AAUCM,UAjCJR,eAAAA,CAiCIQ;EAGkCH,IAAAA,EAAAA,MAAAA;EAAYC,IAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAn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AA0DL"}
1
+ {"version":3,"file":"base.d.ts","names":["Serializable","SerializedConstructor","ContentBlock","$InferMessageContent","$InferResponseMetadata","MessageStructure","MessageType","Message","MessageStringFormat","MESSAGE_SYMBOL","StoredMessageData","Record","StoredMessage","StoredGeneration","StoredMessageV1","MessageContent","Array","FunctionCall","BaseMessageFields","TStructure","TRole","Standard","OpenAIToolCall","Partial","mergeContent","_mergeStatus","BaseMessage","NonNullable","Symbol","toStringTag","isOpenAIToolCallArray","_mergeDicts","_mergeLists","Content","_mergeObj","T","BaseMessageChunk","MessageFieldWithRole","_isMessageFieldWithRole","BaseMessageLike","isBaseMessage","isBaseMessageChunk"],"sources":["../../src/messages/base.d.ts"],"sourcesContent":["import { Serializable, SerializedConstructor } from \"../load/serializable.js\";\nimport { ContentBlock } from \"./content/index.js\";\nimport { $InferMessageContent, $InferResponseMetadata, MessageStructure, MessageType, Message } from \"./message.js\";\nimport { type MessageStringFormat } from \"./format.js\";\n/** @internal */\ndeclare const MESSAGE_SYMBOL: unique symbol;\nexport interface StoredMessageData {\n content: string;\n role: string | undefined;\n name: string | undefined;\n tool_call_id: string | undefined;\n additional_kwargs?: Record<string, any>;\n /** Response metadata. For example: response headers, logprobs, token counts, model name. */\n response_metadata?: Record<string, any>;\n id?: string;\n}\nexport interface StoredMessage {\n type: string;\n data: StoredMessageData;\n}\nexport interface StoredGeneration {\n text: string;\n message?: StoredMessage;\n}\nexport interface StoredMessageV1 {\n type: string;\n role: string | undefined;\n text: string;\n}\nexport type MessageContent = string | Array<ContentBlock>;\nexport interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n /**\n * The name of the function to call.\n */\n name: string;\n}\nexport type BaseMessageFields<TStructure extends MessageStructure = MessageStructure, TRole extends MessageType = MessageType> = {\n id?: string;\n name?: string;\n content?: $InferMessageContent<TStructure, TRole>;\n contentBlocks?: Array<ContentBlock.Standard>;\n /** @deprecated */\n additional_kwargs?: {\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n function_call?: FunctionCall;\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n tool_calls?: OpenAIToolCall[];\n [key: string]: unknown;\n };\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n};\nexport declare function mergeContent(firstContent: MessageContent, secondContent: MessageContent): MessageContent;\n/**\n * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else\n * it will return 'success'.\n *\n * @param {\"success\" | \"error\" | undefined} left The existing value to 'merge' with the new value.\n * @param {\"success\" | \"error\" | undefined} right The new value to 'merge' with the existing value\n * @returns {\"success\" | \"error\"} The 'merged' value.\n */\nexport declare function _mergeStatus(left?: \"success\" | \"error\", right?: \"success\" | \"error\"): \"success\" | \"error\" | undefined;\n/**\n * Base class for all types of messages in a conversation. It includes\n * properties like `content`, `name`, and `additional_kwargs`. It also\n * includes methods like `toDict()` and `_getType()`.\n */\nexport declare abstract class BaseMessage<TStructure extends MessageStructure = MessageStructure, TRole extends MessageType = MessageType> extends Serializable implements Message<TStructure, TRole> {\n lc_namespace: string[];\n lc_serializable: boolean;\n get lc_aliases(): Record<string, string>;\n readonly [MESSAGE_SYMBOL]: true;\n abstract readonly type: TRole;\n id?: string;\n name?: string;\n content: $InferMessageContent<TStructure, TRole>;\n additional_kwargs: NonNullable<BaseMessageFields<TStructure, TRole>[\"additional_kwargs\"]>;\n response_metadata: NonNullable<BaseMessageFields<TStructure, TRole>[\"response_metadata\"]>;\n /**\n * @deprecated Use .getType() instead or import the proper typeguard.\n * For example:\n *\n * ```ts\n * import { isAIMessage } from \"@langchain/core/messages\";\n *\n * const message = new AIMessage(\"Hello!\");\n * isAIMessage(message); // true\n * ```\n */\n _getType(): MessageType;\n /**\n * @deprecated Use .type instead\n * The type of the message.\n */\n getType(): MessageType;\n constructor(arg: $InferMessageContent<TStructure, TRole> | BaseMessageFields<TStructure, TRole>);\n /** Get text content of the message. */\n get text(): string;\n get contentBlocks(): Array<ContentBlock.Standard>;\n toDict(): StoredMessage;\n static lc_name(): string;\n get _printableFields(): Record<string, unknown>;\n static isInstance(obj: unknown): obj is BaseMessage;\n _updateId(value: string | undefined): void;\n get [Symbol.toStringTag](): any;\n toFormattedString(format?: MessageStringFormat): string;\n}\n/**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\nexport type OpenAIToolCall = {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The function that the model called.\n */\n function: FunctionCall;\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: \"function\";\n index?: number;\n};\nexport declare function isOpenAIToolCallArray(value?: unknown): value is OpenAIToolCall[];\nexport declare function _mergeDicts(left?: Record<string, any>, right?: Record<string, any>): Record<string, any>;\nexport declare function _mergeLists<Content extends ContentBlock>(left?: Content[], right?: Content[]): Content[] | undefined;\nexport declare function _mergeObj<T = any>(left: T | undefined, right: T | undefined): T | undefined;\n/**\n * Represents a chunk of a message, which can be concatenated with other\n * message chunks. It includes a method `_merge_kwargs_dict()` for merging\n * additional keyword arguments from another `BaseMessageChunk` into this\n * one. It also overrides the `__add__()` method to support concatenation\n * of `BaseMessageChunk` instances.\n */\nexport declare abstract class BaseMessageChunk<TStructure extends MessageStructure = MessageStructure, TRole extends MessageType = MessageType> extends BaseMessage<TStructure, TRole> {\n abstract concat(chunk: BaseMessageChunk): BaseMessageChunk<TStructure, TRole>;\n static isInstance(obj: unknown): obj is BaseMessageChunk;\n}\nexport type MessageFieldWithRole = {\n role: MessageType;\n content: MessageContent;\n name?: string;\n} & Record<string, unknown>;\nexport declare function _isMessageFieldWithRole(x: BaseMessageLike): x is MessageFieldWithRole;\nexport type BaseMessageLike = BaseMessage | MessageFieldWithRole | [MessageType, MessageContent] | string\n/**\n * @deprecated Specifying \"type\" is deprecated and will be removed in 0.4.0.\n */\n | ({\n type: MessageType | \"user\" | \"assistant\" | \"placeholder\";\n} & BaseMessageFields & Record<string, unknown>) | SerializedConstructor;\n/**\n * @deprecated Use {@link BaseMessage.isInstance} instead\n */\nexport declare function isBaseMessage(messageLike?: unknown): messageLike is BaseMessage;\n/**\n * @deprecated Use {@link BaseMessageChunk.isInstance} instead\n */\nexport declare function isBaseMessageChunk(messageLike?: unknown): messageLike is BaseMessageChunk;\nexport {};\n//# sourceMappingURL=base.d.ts.map"],"mappings":";;;;;;;cAKcS;AAAAA,UACGC,iBAAAA,CAD0B;EAC1BA,OAAAA,EAAAA,MAAAA;EAUAE,IAAAA,EAAAA,MAAAA,GAAAA,SAAa;EAIbC,IAAAA,EAAAA,MAAAA,GAAAA,SAAgB;EAIhBC,YAAAA,EAAAA,MAAe,GAAA,SAAA;EAKpBC,iBAAc,CAAA,EAlBFJ,MAkBE,CAAA,MAAkBT,EAAAA,GAAAA,CAAAA;EAC3Be;EAaLC,iBAAAA,CAAAA,EA9BYP,MA8BK,CAAAQ,MAAAA,EAAAA,GAAAA,CAAAC;EAAoBf,EAAAA,CAAAA,EAAAA,MAAAA;;AAAmDC,UA3BnFM,aAAAA,CA2BmFN;EAAcA,IAAAA,EAAAA,MAAAA;EAG/Ea,IAAAA,EA5BzBT,iBA4ByBS;;AAArBhB,UA1BGU,gBAAAA,CA0BHV;EACYD,IAAAA,EAAAA,MAAamB;EAAnBL,OAAAA,CAAAA,EAzBNJ,aAyBMI;;AAUCM,UAjCJR,eAAAA,CAiCIQ;EAGkCH,IAAAA,EAAAA,MAAAA;EAAYC,IAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAnChB,IAAAA,EAAAA,MAAAA;;AAAD,KA/BnBW,cAAAA,GA+BmB,MAAA,GA/BOC,KA+BP,CA/Bad,YA+Bb,CAAA;AAEPsB,UAhCPP,YAAAA,CAgCmB;EAAeF;;;AAA8D;AASjH;AAMA;EAA6DV,SAAAA,EAAAA,MAAAA;EAAmBA;;;EAAmGc,IAAAA,EAAAA,MAAAA;;AAG7JR,KArCVO,iBAqC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,CAAA,CAAA,EA3CkBA,MA2ClB,CAAA,MAAA,EAAA,OAAA,CAAA;EACc2B,OAAAA,UAAAA,CAAAA,GAAAA,EAAAA,OAAuB,CAAA,EAAA,GAAA,IA3CHZ,WA2COa;EACvCA,SAAAA,CAAAA,KAAAA,EAAAA,MAAe,GAAA,SAAA,CAAA,EAAA,IAAA;EAAGb,KA1CrBE,MAAAA,CAAOC,WAAAA,GA0CcH,EAAAA,GAAAA;EAAcW,iBAAAA,CAAAA,MAAAA,CAAAA,EAzCb7B,mBAyCa6B,CAAAA,EAAAA,MAAAA;;;;;AAMpB1B,KA1CZW,cAAAA,GA0CYX;EAA2BV;AAAqB;AAIxE;EAIwBwC,EAAAA,EAAAA,MAAAA;;;;YA1CVxB;;;;;;;iBAOUa,qBAAAA,4BAAiDR;iBACjDS,WAAAA,QAAmBpB,6BAA6BA,sBAAsBA;iBACtEqB,4BAA4B9B,qBAAqB+B,mBAAmBA,YAAYA;iBAChFC,yBAAyBC,sBAAsBA,gBAAgBA;;;;;;;;uBAQzDC,oCAAoC/B,mBAAmBA,gCAAgCC,cAAcA,qBAAqBoB,YAAYP,YAAYC;yBACrJgB,mBAAmBA,iBAAiBjB,YAAYC;0CAC/BgB;;KAEhCC,oBAAAA;QACF/B;WACGS;;IAETJ;iBACoB2B,uBAAAA,IAA2BC,uBAAuBF;KAC9DE,eAAAA,GAAkBb,cAAcW,wBAAwB/B,aAAaS;;;;QAKvET;IACNY,oBAAoBP,2BAA2BV;;;;iBAI3BuC,aAAAA,wCAAqDd;;;;iBAIrDe,kBAAAA,wCAA0DL"}
@@ -228,8 +228,8 @@ function _mergeLists(left, right) {
228
228
  }
229
229
  }
230
230
  function _mergeObj(left, right) {
231
- if (!left && !right) throw new Error("Cannot merge two undefined objects.");
232
- if (!left || !right) return left || right;
231
+ if (left === void 0 && right === void 0) return void 0;
232
+ if (left === void 0 || right === void 0) return left ?? right;
233
233
  else if (typeof left !== typeof right) throw new Error(`Cannot merge objects of different types.\nLeft ${typeof left}\nRight ${typeof right}`);
234
234
  else if (typeof left === "string" && typeof right === "string") return left + right;
235
235
  else if (Array.isArray(left) && Array.isArray(right)) return _mergeLists(left, right);
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":["firstContent: MessageContent","secondContent: MessageContent","left?: \"success\" | \"error\"","right?: \"success\" | \"error\"","obj: any","depthLimit: number","currentDepth: number","obj","result: Record<string, unknown>","arg:\n | $InferMessageContent<TStructure, TRole>\n | BaseMessageFields<TStructure, TRole>","fields: BaseMessageFields<TStructure, TRole>","blocks: Array<ContentBlock>","blocks","obj: unknown","value: string | undefined","depth: number | null","format: MessageStringFormat","value?: unknown","left: Record<string, any>","right: Record<string, any>","left?: Content[]","right?: Content[]","left: T | undefined","right: T | undefined","x: BaseMessageLike","messageLike?: unknown"],"sources":["../../src/messages/base.ts"],"sourcesContent":["import { Serializable, SerializedConstructor } from \"../load/serializable.js\";\nimport { ContentBlock } from \"./content/index.js\";\nimport { isDataContentBlock } from \"./content/data.js\";\nimport { convertToV1FromAnthropicInput } from \"./block_translators/anthropic.js\";\nimport { convertToV1FromDataContent } from \"./block_translators/data.js\";\nimport { convertToV1FromChatCompletionsInput } from \"./block_translators/openai.js\";\nimport {\n $InferMessageContent,\n $InferResponseMetadata,\n MessageStructure,\n MessageType,\n isMessage,\n Message,\n} from \"./message.js\";\nimport {\n convertToFormattedString,\n type MessageStringFormat,\n} from \"./format.js\";\n\n/** @internal */\nconst MESSAGE_SYMBOL = Symbol.for(\"langchain.message\");\n\nexport interface StoredMessageData {\n content: string;\n role: string | undefined;\n name: string | undefined;\n tool_call_id: string | undefined;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n additional_kwargs?: Record<string, any>;\n /** Response metadata. For example: response headers, logprobs, token counts, model name. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n response_metadata?: Record<string, any>;\n id?: string;\n}\n\nexport interface StoredMessage {\n type: string;\n data: StoredMessageData;\n}\n\nexport interface StoredGeneration {\n text: string;\n message?: StoredMessage;\n}\n\nexport interface StoredMessageV1 {\n type: string;\n role: string | undefined;\n text: string;\n}\n\nexport type MessageContent = string | Array<ContentBlock>;\n\nexport interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n\n /**\n * The name of the function to call.\n */\n name: string;\n}\n\nexport type BaseMessageFields<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType\n> = {\n id?: string;\n name?: string;\n content?: $InferMessageContent<TStructure, TRole>;\n contentBlocks?: Array<ContentBlock.Standard>;\n /** @deprecated */\n additional_kwargs?: {\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n function_call?: FunctionCall;\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n tool_calls?: OpenAIToolCall[];\n [key: string]: unknown;\n };\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n};\n\nexport function mergeContent(\n firstContent: MessageContent,\n secondContent: MessageContent\n): MessageContent {\n // If first content is a string\n if (typeof firstContent === \"string\") {\n if (firstContent === \"\") {\n return secondContent;\n }\n if (typeof secondContent === \"string\") {\n return firstContent + secondContent;\n } else if (Array.isArray(secondContent) && secondContent.length === 0) {\n return firstContent;\n } else if (\n Array.isArray(secondContent) &&\n secondContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n {\n type: \"text\",\n source_type: \"text\",\n text: firstContent,\n },\n ...secondContent,\n ];\n } else {\n return [{ type: \"text\", text: firstContent }, ...secondContent];\n }\n // If both are arrays\n } else if (Array.isArray(secondContent)) {\n return (\n _mergeLists(firstContent, secondContent) ?? [\n ...firstContent,\n ...secondContent,\n ]\n );\n } else {\n if (secondContent === \"\") {\n return firstContent;\n } else if (\n Array.isArray(firstContent) &&\n firstContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n ...firstContent,\n {\n type: \"file\",\n source_type: \"text\",\n text: secondContent,\n },\n ];\n } else {\n return [...firstContent, { type: \"text\", text: secondContent }];\n }\n }\n}\n\n/**\n * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else\n * it will return 'success'.\n *\n * @param {\"success\" | \"error\" | undefined} left The existing value to 'merge' with the new value.\n * @param {\"success\" | \"error\" | undefined} right The new value to 'merge' with the existing value\n * @returns {\"success\" | \"error\"} The 'merged' value.\n */\nexport function _mergeStatus(\n left?: \"success\" | \"error\",\n right?: \"success\" | \"error\"\n): \"success\" | \"error\" | undefined {\n if (left === \"error\" || right === \"error\") {\n return \"error\";\n }\n return \"success\";\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction stringifyWithDepthLimit(obj: any, depthLimit: number): string {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function helper(obj: any, currentDepth: number): any {\n if (typeof obj !== \"object\" || obj === null || obj === undefined) {\n return obj;\n }\n if (currentDepth >= depthLimit) {\n if (Array.isArray(obj)) {\n return \"[Array]\";\n }\n return \"[Object]\";\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => helper(item, currentDepth + 1));\n }\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n result[key] = helper(obj[key], currentDepth + 1);\n }\n return result;\n }\n\n return JSON.stringify(helper(obj, 0), null, 2);\n}\n\n/**\n * Base class for all types of messages in a conversation. It includes\n * properties like `content`, `name`, and `additional_kwargs`. It also\n * includes methods like `toDict()` and `_getType()`.\n */\nexport abstract class BaseMessage<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType\n >\n extends Serializable\n implements Message<TStructure, TRole>\n{\n lc_namespace = [\"langchain_core\", \"messages\"];\n\n lc_serializable = true;\n\n get lc_aliases(): Record<string, string> {\n // exclude snake case conversion to pascal case\n return {\n additional_kwargs: \"additional_kwargs\",\n response_metadata: \"response_metadata\",\n };\n }\n\n readonly [MESSAGE_SYMBOL] = true as const;\n\n abstract readonly type: TRole;\n\n id?: string;\n\n name?: string;\n\n content: $InferMessageContent<TStructure, TRole>;\n\n additional_kwargs: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"additional_kwargs\"]\n >;\n\n response_metadata: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"response_metadata\"]\n >;\n\n /**\n * @deprecated Use .getType() instead or import the proper typeguard.\n * For example:\n *\n * ```ts\n * import { isAIMessage } from \"@langchain/core/messages\";\n *\n * const message = new AIMessage(\"Hello!\");\n * isAIMessage(message); // true\n * ```\n */\n _getType(): MessageType {\n return this.type;\n }\n\n /**\n * @deprecated Use .type instead\n * The type of the message.\n */\n getType(): MessageType {\n return this._getType();\n }\n\n constructor(\n arg:\n | $InferMessageContent<TStructure, TRole>\n | BaseMessageFields<TStructure, TRole>\n ) {\n const fields: BaseMessageFields<TStructure, TRole> =\n typeof arg === \"string\" || Array.isArray(arg) ? { content: arg } : arg;\n if (!fields.additional_kwargs) {\n fields.additional_kwargs = {};\n }\n if (!fields.response_metadata) {\n fields.response_metadata = {};\n }\n super(fields);\n this.name = fields.name;\n if (fields.content === undefined && fields.contentBlocks !== undefined) {\n this.content = fields.contentBlocks as $InferMessageContent<\n TStructure,\n TRole\n >;\n this.response_metadata = {\n output_version: \"v1\",\n ...fields.response_metadata,\n };\n } else if (fields.content !== undefined) {\n this.content = fields.content ?? [];\n this.response_metadata = fields.response_metadata;\n } else {\n this.content = [] as $InferMessageContent<TStructure, TRole>;\n this.response_metadata = fields.response_metadata;\n }\n this.additional_kwargs = fields.additional_kwargs;\n this.id = fields.id;\n }\n\n /** Get text content of the message. */\n get text(): string {\n if (typeof this.content === \"string\") {\n return this.content;\n }\n if (!Array.isArray(this.content)) return \"\";\n return this.content\n .map((c) => {\n if (typeof c === \"string\") return c;\n if (c.type === \"text\") return c.text;\n return \"\";\n })\n .join(\"\");\n }\n\n get contentBlocks(): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock> =\n typeof this.content === \"string\"\n ? [{ type: \"text\", text: this.content }]\n : this.content;\n const parsingSteps = [\n convertToV1FromDataContent,\n convertToV1FromChatCompletionsInput,\n convertToV1FromAnthropicInput,\n ];\n const parsedBlocks = parsingSteps.reduce(\n (blocks, step) => step(blocks),\n blocks\n );\n return parsedBlocks as Array<ContentBlock.Standard>;\n }\n\n toDict(): StoredMessage {\n return {\n type: this.getType(),\n data: (this.toJSON() as SerializedConstructor)\n .kwargs as StoredMessageData,\n };\n }\n\n static lc_name() {\n return \"BaseMessage\";\n }\n\n // Can't be protected for silly reasons\n get _printableFields(): Record<string, unknown> {\n return {\n id: this.id,\n content: this.content,\n name: this.name,\n additional_kwargs: this.additional_kwargs,\n response_metadata: this.response_metadata,\n };\n }\n\n static isInstance(obj: unknown): obj is BaseMessage {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n MESSAGE_SYMBOL in obj &&\n obj[MESSAGE_SYMBOL] === true &&\n isMessage(obj)\n );\n }\n\n // this private method is used to update the ID for the runtime\n // value as well as in lc_kwargs for serialisation\n _updateId(value: string | undefined) {\n this.id = value;\n\n // lc_attributes wouldn't work here, because jest compares the\n // whole object\n this.lc_kwargs.id = value;\n }\n\n get [Symbol.toStringTag]() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (this.constructor as any).lc_name();\n }\n\n // Override the default behavior of console.log\n [Symbol.for(\"nodejs.util.inspect.custom\")](depth: number | null) {\n if (depth === null) {\n return this;\n }\n const printable = stringifyWithDepthLimit(\n this._printableFields,\n Math.max(4, depth)\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return `${(this.constructor as any).lc_name()} ${printable}`;\n }\n\n toFormattedString(format: MessageStringFormat = \"pretty\"): string {\n return convertToFormattedString(this, format);\n }\n}\n\n/**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\nexport type OpenAIToolCall = {\n /**\n * The ID of the tool call.\n */\n id: string;\n\n /**\n * The function that the model called.\n */\n function: FunctionCall;\n\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: \"function\";\n\n index?: number;\n};\n\nexport function isOpenAIToolCallArray(\n value?: unknown\n): value is OpenAIToolCall[] {\n return (\n Array.isArray(value) &&\n value.every((v) => typeof (v as OpenAIToolCall).index === \"number\")\n );\n}\n\nexport function _mergeDicts(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n left: Record<string, any> = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n right: Record<string, any> = {}\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> {\n const merged = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (merged[key] == null) {\n merged[key] = value;\n } else if (value == null) {\n continue;\n } else if (\n typeof merged[key] !== typeof value ||\n Array.isArray(merged[key]) !== Array.isArray(value)\n ) {\n throw new Error(\n `field[${key}] already exists in the message chunk, but with a different type.`\n );\n } else if (typeof merged[key] === \"string\") {\n if (key === \"type\") {\n // Do not merge 'type' fields\n continue;\n } else if (\n [\"id\", \"name\", \"output_version\", \"model_provider\"].includes(key)\n ) {\n // Keep the incoming value for these fields if its defined\n if (value) {\n merged[key] = value;\n }\n } else {\n merged[key] += value;\n }\n } else if (typeof merged[key] === \"object\" && !Array.isArray(merged[key])) {\n merged[key] = _mergeDicts(merged[key], value);\n } else if (Array.isArray(merged[key])) {\n merged[key] = _mergeLists(merged[key], value);\n } else if (merged[key] === value) {\n continue;\n } else {\n console.warn(\n `field[${key}] already exists in this message chunk and value has unsupported type.`\n );\n }\n }\n return merged;\n}\n\nexport function _mergeLists<Content extends ContentBlock>(\n left?: Content[],\n right?: Content[]\n): Content[] | undefined {\n if (left === undefined && right === undefined) {\n return undefined;\n } else if (left === undefined || right === undefined) {\n return left || right;\n } else {\n const merged = [...left];\n for (const item of right) {\n if (\n typeof item === \"object\" &&\n item !== null &&\n \"index\" in item &&\n typeof item.index === \"number\"\n ) {\n const toMerge = merged.findIndex((leftItem) => {\n const isObject = typeof leftItem === \"object\";\n const indiciesMatch =\n \"index\" in leftItem && leftItem.index === item.index;\n const idsMatch =\n \"id\" in leftItem && \"id\" in item && leftItem?.id === item?.id;\n const eitherItemMissingID =\n !(\"id\" in leftItem) ||\n !leftItem?.id ||\n !(\"id\" in item) ||\n !item?.id;\n return isObject && indiciesMatch && (idsMatch || eitherItemMissingID);\n });\n if (\n toMerge !== -1 &&\n typeof merged[toMerge] === \"object\" &&\n merged[toMerge] !== null\n ) {\n merged[toMerge] = _mergeDicts(\n merged[toMerge] as Record<string, unknown>,\n item as Record<string, unknown>\n ) as Content;\n } else {\n merged.push(item);\n }\n } else if (\n typeof item === \"object\" &&\n item !== null &&\n \"text\" in item &&\n item.text === \"\"\n ) {\n // No-op - skip empty text blocks\n continue;\n } else {\n merged.push(item);\n }\n }\n return merged;\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _mergeObj<T = any>(\n left: T | undefined,\n right: T | undefined\n): T {\n if (!left && !right) {\n throw new Error(\"Cannot merge two undefined objects.\");\n }\n if (!left || !right) {\n return left || (right as T);\n } else if (typeof left !== typeof right) {\n throw new Error(\n `Cannot merge objects of different types.\\nLeft ${typeof left}\\nRight ${typeof right}`\n );\n } else if (typeof left === \"string\" && typeof right === \"string\") {\n return (left + right) as T;\n } else if (Array.isArray(left) && Array.isArray(right)) {\n return _mergeLists(left, right) as T;\n } else if (typeof left === \"object\" && typeof right === \"object\") {\n return _mergeDicts(left, right) as T;\n } else if (left === right) {\n return left;\n } else {\n throw new Error(\n `Can not merge objects of different types.\\nLeft ${left}\\nRight ${right}`\n );\n }\n}\n\n/**\n * Represents a chunk of a message, which can be concatenated with other\n * message chunks. It includes a method `_merge_kwargs_dict()` for merging\n * additional keyword arguments from another `BaseMessageChunk` into this\n * one. It also overrides the `__add__()` method to support concatenation\n * of `BaseMessageChunk` instances.\n */\nexport abstract class BaseMessageChunk<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType\n> extends BaseMessage<TStructure, TRole> {\n abstract concat(chunk: BaseMessageChunk): BaseMessageChunk<TStructure, TRole>;\n\n static isInstance(obj: unknown): obj is BaseMessageChunk {\n if (!super.isInstance(obj)) {\n return false;\n }\n // Check if obj is an instance of BaseMessageChunk by traversing the prototype chain\n let proto = Object.getPrototypeOf(obj);\n while (proto !== null) {\n if (proto === BaseMessageChunk.prototype) {\n return true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n }\n}\n\nexport type MessageFieldWithRole = {\n role: MessageType;\n content: MessageContent;\n name?: string;\n} & Record<string, unknown>;\n\nexport function _isMessageFieldWithRole(\n x: BaseMessageLike\n): x is MessageFieldWithRole {\n return typeof (x as MessageFieldWithRole).role === \"string\";\n}\n\nexport type BaseMessageLike =\n | BaseMessage\n | MessageFieldWithRole\n | [MessageType, MessageContent]\n | string\n /**\n * @deprecated Specifying \"type\" is deprecated and will be removed in 0.4.0.\n */\n | ({\n type: MessageType | \"user\" | \"assistant\" | \"placeholder\";\n } & BaseMessageFields &\n Record<string, unknown>)\n | SerializedConstructor;\n\n/**\n * @deprecated Use {@link BaseMessage.isInstance} instead\n */\nexport function isBaseMessage(\n messageLike?: unknown\n): messageLike is BaseMessage {\n return typeof (messageLike as BaseMessage)?._getType === \"function\";\n}\n\n/**\n * @deprecated Use {@link BaseMessageChunk.isInstance} instead\n */\nexport function isBaseMessageChunk(\n messageLike?: unknown\n): messageLike is BaseMessageChunk {\n return BaseMessageChunk.isInstance(messageLike);\n}\n"],"mappings":";;;;;;;;;;AAoBA,MAAM,iBAAiB,OAAO,IAAI,oBAAoB;AAuEtD,SAAgB,aACdA,cACAC,eACgB;AAEhB,KAAI,OAAO,iBAAiB,UAAU;AACpC,MAAI,iBAAiB,GACnB,QAAO;AAET,MAAI,OAAO,kBAAkB,SAC3B,QAAO,eAAe;WACb,MAAM,QAAQ,cAAc,IAAI,cAAc,WAAW,EAClE,QAAO;WAEP,MAAM,QAAQ,cAAc,IAC5B,cAAc,KAAK,CAAC,MAAM,mBAAmB,EAAE,CAAC,CAEhD,QAAO,CACL;GACE,MAAM;GACN,aA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EAEpB,WACC,OAAO,SAAS,YAChB,SAAS,QACT,UAAU,QACV,KAAK,SAAS,GAGd;OAEA,OAAO,KAAK,KAAK;AAGrB,SAAO;CACR;AACF;AAGD,SAAgB,UACdC,MACAC,OACG;AACH,KAAI,CAAC,QAAQ,CAAC,MACZ,OAAM,IAAI,MAAM;AAElB,KAAI,CAAC,QAAQ,CAAC,MACZ,QAAO,QAAS;UACP,OAAO,SAAS,OAAO,MAChC,OAAM,IAAI,MACR,CAAC,+CAA+C,EAAE,OAAO,KAAK,QAAQ,EAAE,OAAO,OAAO;UAE/E,OAAO,SAAS,YAAY,OAAO,UAAU,SACtD,QAAQ,OAAO;UACN,MAAM,QAAQ,KAAK,IAAI,MAAM,QAAQ,MAAM,CACpD,QAAO,YAAY,MAAM,MAAM;UACtB,OAAO,SAAS,YAAY,OAAO,UAAU,SACtD,QAAO,YAAY,MAAM,MAAM;UACtB,SAAS,MAClB,QAAO;KAEP,OAAM,IAAI,MACR,CAAC,gDAAgD,EAAE,KAAK,QAAQ,EAAE,OAAO;AAG9E;;;;;;;;AASD,IAAsB,mBAAtB,MAAsB,yBAGZ,YAA+B;CAGvC,OAAO,WAAWV,KAAuC;AACvD,MAAI,CAAC,MAAM,WAAW,IAAI,CACxB,QAAO;EAGT,IAAI,QAAQ,OAAO,eAAe,IAAI;AACtC,SAAO,UAAU,MAAM;AACrB,OAAI,UAAU,iBAAiB,UAC7B,QAAO;GAET,QAAQ,OAAO,eAAe,MAAM;EACrC;AACD,SAAO;CACR;AACF;AAQD,SAAgB,wBACdW,GAC2B;AAC3B,QAAO,OAAQ,EAA2B,SAAS;AACpD;;;;AAmBD,SAAgB,cACdC,aAC4B;AAC5B,QAAO,OAAQ,aAA6B,aAAa;AAC1D;;;;AAKD,SAAgB,mBACdA,aACiC;AACjC,QAAO,iBAAiB,WAAW,YAAY;AAChD"}
1
+ {"version":3,"file":"base.js","names":["firstContent: MessageContent","secondContent: MessageContent","left?: \"success\" | \"error\"","right?: \"success\" | \"error\"","obj: any","depthLimit: number","currentDepth: number","obj","result: Record<string, unknown>","arg:\n | $InferMessageContent<TStructure, TRole>\n | BaseMessageFields<TStructure, TRole>","fields: BaseMessageFields<TStructure, TRole>","blocks: Array<ContentBlock>","blocks","obj: unknown","value: string | undefined","depth: number | null","format: MessageStringFormat","value?: unknown","left: Record<string, any>","right: Record<string, any>","left?: Content[]","right?: Content[]","left: T | undefined","right: T | undefined","x: BaseMessageLike","messageLike?: unknown"],"sources":["../../src/messages/base.ts"],"sourcesContent":["import { Serializable, SerializedConstructor } from \"../load/serializable.js\";\nimport { ContentBlock } from \"./content/index.js\";\nimport { isDataContentBlock } from \"./content/data.js\";\nimport { convertToV1FromAnthropicInput } from \"./block_translators/anthropic.js\";\nimport { convertToV1FromDataContent } from \"./block_translators/data.js\";\nimport { convertToV1FromChatCompletionsInput } from \"./block_translators/openai.js\";\nimport {\n $InferMessageContent,\n $InferResponseMetadata,\n MessageStructure,\n MessageType,\n isMessage,\n Message,\n} from \"./message.js\";\nimport {\n convertToFormattedString,\n type MessageStringFormat,\n} from \"./format.js\";\n\n/** @internal */\nconst MESSAGE_SYMBOL = Symbol.for(\"langchain.message\");\n\nexport interface StoredMessageData {\n content: string;\n role: string | undefined;\n name: string | undefined;\n tool_call_id: string | undefined;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n additional_kwargs?: Record<string, any>;\n /** Response metadata. For example: response headers, logprobs, token counts, model name. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n response_metadata?: Record<string, any>;\n id?: string;\n}\n\nexport interface StoredMessage {\n type: string;\n data: StoredMessageData;\n}\n\nexport interface StoredGeneration {\n text: string;\n message?: StoredMessage;\n}\n\nexport interface StoredMessageV1 {\n type: string;\n role: string | undefined;\n text: string;\n}\n\nexport type MessageContent = string | Array<ContentBlock>;\n\nexport interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n\n /**\n * The name of the function to call.\n */\n name: string;\n}\n\nexport type BaseMessageFields<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType\n> = {\n id?: string;\n name?: string;\n content?: $InferMessageContent<TStructure, TRole>;\n contentBlocks?: Array<ContentBlock.Standard>;\n /** @deprecated */\n additional_kwargs?: {\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n function_call?: FunctionCall;\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n tool_calls?: OpenAIToolCall[];\n [key: string]: unknown;\n };\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n};\n\nexport function mergeContent(\n firstContent: MessageContent,\n secondContent: MessageContent\n): MessageContent {\n // If first content is a string\n if (typeof firstContent === \"string\") {\n if (firstContent === \"\") {\n return secondContent;\n }\n if (typeof secondContent === \"string\") {\n return firstContent + secondContent;\n } else if (Array.isArray(secondContent) && secondContent.length === 0) {\n return firstContent;\n } else if (\n Array.isArray(secondContent) &&\n secondContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n {\n type: \"text\",\n source_type: \"text\",\n text: firstContent,\n },\n ...secondContent,\n ];\n } else {\n return [{ type: \"text\", text: firstContent }, ...secondContent];\n }\n // If both are arrays\n } else if (Array.isArray(secondContent)) {\n return (\n _mergeLists(firstContent, secondContent) ?? [\n ...firstContent,\n ...secondContent,\n ]\n );\n } else {\n if (secondContent === \"\") {\n return firstContent;\n } else if (\n Array.isArray(firstContent) &&\n firstContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n ...firstContent,\n {\n type: \"file\",\n source_type: \"text\",\n text: secondContent,\n },\n ];\n } else {\n return [...firstContent, { type: \"text\", text: secondContent }];\n }\n }\n}\n\n/**\n * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else\n * it will return 'success'.\n *\n * @param {\"success\" | \"error\" | undefined} left The existing value to 'merge' with the new value.\n * @param {\"success\" | \"error\" | undefined} right The new value to 'merge' with the existing value\n * @returns {\"success\" | \"error\"} The 'merged' value.\n */\nexport function _mergeStatus(\n left?: \"success\" | \"error\",\n right?: \"success\" | \"error\"\n): \"success\" | \"error\" | undefined {\n if (left === \"error\" || right === \"error\") {\n return \"error\";\n }\n return \"success\";\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction stringifyWithDepthLimit(obj: any, depthLimit: number): string {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function helper(obj: any, currentDepth: number): any {\n if (typeof obj !== \"object\" || obj === null || obj === undefined) {\n return obj;\n }\n if (currentDepth >= depthLimit) {\n if (Array.isArray(obj)) {\n return \"[Array]\";\n }\n return \"[Object]\";\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => helper(item, currentDepth + 1));\n }\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n result[key] = helper(obj[key], currentDepth + 1);\n }\n return result;\n }\n\n return JSON.stringify(helper(obj, 0), null, 2);\n}\n\n/**\n * Base class for all types of messages in a conversation. It includes\n * properties like `content`, `name`, and `additional_kwargs`. It also\n * includes methods like `toDict()` and `_getType()`.\n */\nexport abstract class BaseMessage<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType\n >\n extends Serializable\n implements Message<TStructure, TRole>\n{\n lc_namespace = [\"langchain_core\", \"messages\"];\n\n lc_serializable = true;\n\n get lc_aliases(): Record<string, string> {\n // exclude snake case conversion to pascal case\n return {\n additional_kwargs: \"additional_kwargs\",\n response_metadata: \"response_metadata\",\n };\n }\n\n readonly [MESSAGE_SYMBOL] = true as const;\n\n abstract readonly type: TRole;\n\n id?: string;\n\n name?: string;\n\n content: $InferMessageContent<TStructure, TRole>;\n\n additional_kwargs: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"additional_kwargs\"]\n >;\n\n response_metadata: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"response_metadata\"]\n >;\n\n /**\n * @deprecated Use .getType() instead or import the proper typeguard.\n * For example:\n *\n * ```ts\n * import { isAIMessage } from \"@langchain/core/messages\";\n *\n * const message = new AIMessage(\"Hello!\");\n * isAIMessage(message); // true\n * ```\n */\n _getType(): MessageType {\n return this.type;\n }\n\n /**\n * @deprecated Use .type instead\n * The type of the message.\n */\n getType(): MessageType {\n return this._getType();\n }\n\n constructor(\n arg:\n | $InferMessageContent<TStructure, TRole>\n | BaseMessageFields<TStructure, TRole>\n ) {\n const fields: BaseMessageFields<TStructure, TRole> =\n typeof arg === \"string\" || Array.isArray(arg) ? { content: arg } : arg;\n if (!fields.additional_kwargs) {\n fields.additional_kwargs = {};\n }\n if (!fields.response_metadata) {\n fields.response_metadata = {};\n }\n super(fields);\n this.name = fields.name;\n if (fields.content === undefined && fields.contentBlocks !== undefined) {\n this.content = fields.contentBlocks as $InferMessageContent<\n TStructure,\n TRole\n >;\n this.response_metadata = {\n output_version: \"v1\",\n ...fields.response_metadata,\n };\n } else if (fields.content !== undefined) {\n this.content = fields.content ?? [];\n this.response_metadata = fields.response_metadata;\n } else {\n this.content = [] as $InferMessageContent<TStructure, TRole>;\n this.response_metadata = fields.response_metadata;\n }\n this.additional_kwargs = fields.additional_kwargs;\n this.id = fields.id;\n }\n\n /** Get text content of the message. */\n get text(): string {\n if (typeof this.content === \"string\") {\n return this.content;\n }\n if (!Array.isArray(this.content)) return \"\";\n return this.content\n .map((c) => {\n if (typeof c === \"string\") return c;\n if (c.type === \"text\") return c.text;\n return \"\";\n })\n .join(\"\");\n }\n\n get contentBlocks(): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock> =\n typeof this.content === \"string\"\n ? [{ type: \"text\", text: this.content }]\n : this.content;\n const parsingSteps = [\n convertToV1FromDataContent,\n convertToV1FromChatCompletionsInput,\n convertToV1FromAnthropicInput,\n ];\n const parsedBlocks = parsingSteps.reduce(\n (blocks, step) => step(blocks),\n blocks\n );\n return parsedBlocks as Array<ContentBlock.Standard>;\n }\n\n toDict(): StoredMessage {\n return {\n type: this.getType(),\n data: (this.toJSON() as SerializedConstructor)\n .kwargs as StoredMessageData,\n };\n }\n\n static lc_name() {\n return \"BaseMessage\";\n }\n\n // Can't be protected for silly reasons\n get _printableFields(): Record<string, unknown> {\n return {\n id: this.id,\n content: this.content,\n name: this.name,\n additional_kwargs: this.additional_kwargs,\n response_metadata: this.response_metadata,\n };\n }\n\n static isInstance(obj: unknown): obj is BaseMessage {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n MESSAGE_SYMBOL in obj &&\n obj[MESSAGE_SYMBOL] === true &&\n isMessage(obj)\n );\n }\n\n // this private method is used to update the ID for the runtime\n // value as well as in lc_kwargs for serialisation\n _updateId(value: string | undefined) {\n this.id = value;\n\n // lc_attributes wouldn't work here, because jest compares the\n // whole object\n this.lc_kwargs.id = value;\n }\n\n get [Symbol.toStringTag]() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (this.constructor as any).lc_name();\n }\n\n // Override the default behavior of console.log\n [Symbol.for(\"nodejs.util.inspect.custom\")](depth: number | null) {\n if (depth === null) {\n return this;\n }\n const printable = stringifyWithDepthLimit(\n this._printableFields,\n Math.max(4, depth)\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return `${(this.constructor as any).lc_name()} ${printable}`;\n }\n\n toFormattedString(format: MessageStringFormat = \"pretty\"): string {\n return convertToFormattedString(this, format);\n }\n}\n\n/**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\nexport type OpenAIToolCall = {\n /**\n * The ID of the tool call.\n */\n id: string;\n\n /**\n * The function that the model called.\n */\n function: FunctionCall;\n\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: \"function\";\n\n index?: number;\n};\n\nexport function isOpenAIToolCallArray(\n value?: unknown\n): value is OpenAIToolCall[] {\n return (\n Array.isArray(value) &&\n value.every((v) => typeof (v as OpenAIToolCall).index === \"number\")\n );\n}\n\nexport function _mergeDicts(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n left: Record<string, any> = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n right: Record<string, any> = {}\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> {\n const merged = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (merged[key] == null) {\n merged[key] = value;\n } else if (value == null) {\n continue;\n } else if (\n typeof merged[key] !== typeof value ||\n Array.isArray(merged[key]) !== Array.isArray(value)\n ) {\n throw new Error(\n `field[${key}] already exists in the message chunk, but with a different type.`\n );\n } else if (typeof merged[key] === \"string\") {\n if (key === \"type\") {\n // Do not merge 'type' fields\n continue;\n } else if (\n [\"id\", \"name\", \"output_version\", \"model_provider\"].includes(key)\n ) {\n // Keep the incoming value for these fields if its defined\n if (value) {\n merged[key] = value;\n }\n } else {\n merged[key] += value;\n }\n } else if (typeof merged[key] === \"object\" && !Array.isArray(merged[key])) {\n merged[key] = _mergeDicts(merged[key], value);\n } else if (Array.isArray(merged[key])) {\n merged[key] = _mergeLists(merged[key], value);\n } else if (merged[key] === value) {\n continue;\n } else {\n console.warn(\n `field[${key}] already exists in this message chunk and value has unsupported type.`\n );\n }\n }\n return merged;\n}\n\nexport function _mergeLists<Content extends ContentBlock>(\n left?: Content[],\n right?: Content[]\n): Content[] | undefined {\n if (left === undefined && right === undefined) {\n return undefined;\n } else if (left === undefined || right === undefined) {\n return left || right;\n } else {\n const merged = [...left];\n for (const item of right) {\n if (\n typeof item === \"object\" &&\n item !== null &&\n \"index\" in item &&\n typeof item.index === \"number\"\n ) {\n const toMerge = merged.findIndex((leftItem) => {\n const isObject = typeof leftItem === \"object\";\n const indiciesMatch =\n \"index\" in leftItem && leftItem.index === item.index;\n const idsMatch =\n \"id\" in leftItem && \"id\" in item && leftItem?.id === item?.id;\n const eitherItemMissingID =\n !(\"id\" in leftItem) ||\n !leftItem?.id ||\n !(\"id\" in item) ||\n !item?.id;\n return isObject && indiciesMatch && (idsMatch || eitherItemMissingID);\n });\n if (\n toMerge !== -1 &&\n typeof merged[toMerge] === \"object\" &&\n merged[toMerge] !== null\n ) {\n merged[toMerge] = _mergeDicts(\n merged[toMerge] as Record<string, unknown>,\n item as Record<string, unknown>\n ) as Content;\n } else {\n merged.push(item);\n }\n } else if (\n typeof item === \"object\" &&\n item !== null &&\n \"text\" in item &&\n item.text === \"\"\n ) {\n // No-op - skip empty text blocks\n continue;\n } else {\n merged.push(item);\n }\n }\n return merged;\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _mergeObj<T = any>(\n left: T | undefined,\n right: T | undefined\n): T | undefined {\n if (left === undefined && right === undefined) {\n return undefined;\n }\n if (left === undefined || right === undefined) {\n return left ?? right;\n } else if (typeof left !== typeof right) {\n throw new Error(\n `Cannot merge objects of different types.\\nLeft ${typeof left}\\nRight ${typeof right}`\n );\n } else if (typeof left === \"string\" && typeof right === \"string\") {\n return (left + right) as T;\n } else if (Array.isArray(left) && Array.isArray(right)) {\n return _mergeLists(left, right) as T;\n } else if (typeof left === \"object\" && typeof right === \"object\") {\n return _mergeDicts(\n left as Record<string, unknown>,\n right as Record<string, unknown>\n ) as T;\n } else if (left === right) {\n return left;\n } else {\n throw new Error(\n `Can not merge objects of different types.\\nLeft ${left}\\nRight ${right}`\n );\n }\n}\n\n/**\n * Represents a chunk of a message, which can be concatenated with other\n * message chunks. It includes a method `_merge_kwargs_dict()` for merging\n * additional keyword arguments from another `BaseMessageChunk` into this\n * one. It also overrides the `__add__()` method to support concatenation\n * of `BaseMessageChunk` instances.\n */\nexport abstract class BaseMessageChunk<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType\n> extends BaseMessage<TStructure, TRole> {\n abstract concat(chunk: BaseMessageChunk): BaseMessageChunk<TStructure, TRole>;\n\n static isInstance(obj: unknown): obj is BaseMessageChunk {\n if (!super.isInstance(obj)) {\n return false;\n }\n // Check if obj is an instance of BaseMessageChunk by traversing the prototype chain\n let proto = Object.getPrototypeOf(obj);\n while (proto !== null) {\n if (proto === BaseMessageChunk.prototype) {\n return true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n }\n}\n\nexport type MessageFieldWithRole = {\n role: MessageType;\n content: MessageContent;\n name?: string;\n} & Record<string, unknown>;\n\nexport function _isMessageFieldWithRole(\n x: BaseMessageLike\n): x is MessageFieldWithRole {\n return typeof (x as MessageFieldWithRole).role === \"string\";\n}\n\nexport type BaseMessageLike =\n | BaseMessage\n | MessageFieldWithRole\n | [MessageType, MessageContent]\n | string\n /**\n * @deprecated Specifying \"type\" is deprecated and will be removed in 0.4.0.\n */\n | ({\n type: MessageType | \"user\" | \"assistant\" | \"placeholder\";\n } & BaseMessageFields &\n Record<string, unknown>)\n | SerializedConstructor;\n\n/**\n * @deprecated Use {@link BaseMessage.isInstance} instead\n */\nexport function isBaseMessage(\n messageLike?: unknown\n): messageLike is BaseMessage {\n return typeof (messageLike as BaseMessage)?._getType === \"function\";\n}\n\n/**\n * @deprecated Use {@link BaseMessageChunk.isInstance} instead\n */\nexport function isBaseMessageChunk(\n messageLike?: unknown\n): messageLike is BaseMessageChunk {\n return BaseMessageChunk.isInstance(messageLike);\n}\n"],"mappings":";;;;;;;;;;AAoBA,MAAM,iBAAiB,OAAO,IAAI,oBAAoB;AAuEtD,SAAgB,aACdA,cACAC,eACgB;AAEhB,KAAI,OAAO,iBAAiB,UAAU;AACpC,MAAI,iBAAiB,GACnB,QAAO;AAET,MAAI,OAAO,kBAAkB,SAC3B,QAAO,eAAe;WACb,MAAM,QAAQ,cAAc,IAAI,cAAc,WAAW,EAClE,QAAO;WAEP,MAAM,QAAQ,cAAc,IAC5B,cAAc,KAAK,CAAC,MAAM,mBAAmB,EAAE,CAAC,CAEhD,QAAO,CACL;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACP,GACD,GAAG,aACJ;MAED,QAAO,CAAC;GAAE,MAAM;GAAQ,MAAM;EAAc,GAAE,GAAG,aAAc;CAGlE,WAAU,MAAM,QAAQ,cAAc,CACrC,QACE,YAAY,cAAc,cAAc,IAAI,CAC1C,G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ClC,QAAO;AAET,KAAI,SAAS,UAAa,UAAU,OAClC,QAAO,QAAQ;UACN,OAAO,SAAS,OAAO,MAChC,OAAM,IAAI,MACR,CAAC,+CAA+C,EAAE,OAAO,KAAK,QAAQ,EAAE,OAAO,OAAO;UAE/E,OAAO,SAAS,YAAY,OAAO,UAAU,SACtD,QAAQ,OAAO;UACN,MAAM,QAAQ,KAAK,IAAI,MAAM,QAAQ,MAAM,CACpD,QAAO,YAAY,MAAM,MAAM;UACtB,OAAO,SAAS,YAAY,OAAO,UAAU,SACtD,QAAO,YACL,MACA,MACD;UACQ,SAAS,MAClB,QAAO;KAEP,OAAM,IAAI,MACR,CAAC,gDAAgD,EAAE,KAAK,QAAQ,EAAE,OAAO;AAG9E;;;;;;;;AASD,IAAsB,mBAAtB,MAAsB,yBAGZ,YAA+B;CAGvC,OAAO,WAAWV,KAAuC;AACvD,MAAI,CAAC,MAAM,WAAW,IAAI,CACxB,QAAO;EAGT,IAAI,QAAQ,OAAO,eAAe,IAAI;AACtC,SAAO,UAAU,MAAM;AACrB,OAAI,UAAU,iBAAiB,UAC7B,QAAO;GAET,QAAQ,OAAO,eAAe,MAAM;EACrC;AACD,SAAO;CACR;AACF;AAQD,SAAgB,wBACdW,GAC2B;AAC3B,QAAO,OAAQ,EAA2B,SAAS;AACpD;;;;AAmBD,SAAgB,cACdC,aAC4B;AAC5B,QAAO,OAAQ,aAA6B,aAAa;AAC1D;;;;AAKD,SAAgB,mBACdA,aACiC;AACjC,QAAO,iBAAiB,WAAW,YAAY;AAChD"}
@@ -19,7 +19,7 @@ function convertToPrettyString(message) {
19
19
  lines.push(` ${tc.name} (${tc.id})`);
20
20
  lines.push(` Call ID: ${tc.id}`);
21
21
  lines.push(" Args:");
22
- for (const [key, value] of Object.entries(tc.args)) lines.push(` ${key}: ${value}`);
22
+ for (const [key, value] of Object.entries(tc.args)) lines.push(` ${key}: ${typeof value === "object" ? JSON.stringify(value) : value}`);
23
23
  }
24
24
  }
25
25
  }
@@ -1 +1 @@
1
- {"version":3,"file":"format.cjs","names":["message: BaseMessage","format: MessageStringFormat","lines: string[]"],"sources":["../../src/messages/format.ts"],"sourcesContent":["import { type BaseMessage } from \"./base.js\";\nimport { type AIMessage } from \"./ai.js\";\nimport { type ToolMessage } from \"./tool.js\";\n\nexport type MessageStringFormat = \"pretty\";\n\nexport function convertToFormattedString(\n message: BaseMessage,\n format: MessageStringFormat = \"pretty\"\n): string {\n if (format === \"pretty\") return convertToPrettyString(message);\n return JSON.stringify(message);\n}\n\nfunction convertToPrettyString(message: BaseMessage): string {\n const lines: string[] = [];\n const title = ` ${\n message.type.charAt(0).toUpperCase() + message.type.slice(1)\n } Message `;\n const sepLen = Math.floor((80 - title.length) / 2);\n const sep = \"=\".repeat(sepLen);\n const secondSep = title.length % 2 === 0 ? sep : `${sep}=`;\n lines.push(`${sep}${title}${secondSep}`);\n\n // Add message type specific details\n if (message.type === \"ai\") {\n const aiMessage = message as AIMessage;\n if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) {\n lines.push(\"Tool Calls:\");\n for (const tc of aiMessage.tool_calls) {\n lines.push(` ${tc.name} (${tc.id})`);\n lines.push(` Call ID: ${tc.id}`);\n lines.push(\" Args:\");\n for (const [key, value] of Object.entries(tc.args)) {\n lines.push(` ${key}: ${value}`);\n }\n }\n }\n }\n if (message.type === \"tool\") {\n const toolMessage = message as ToolMessage;\n if (toolMessage.name) {\n lines.push(`Name: ${toolMessage.name}`);\n }\n }\n\n // Add content if it's a string and not empty\n if (typeof message.content === \"string\" && message.content.trim()) {\n if (lines.length > 1) {\n lines.push(\"\"); // blank line before content\n }\n lines.push(message.content);\n }\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";;AAMA,SAAgB,yBACdA,SACAC,SAA8B,UACtB;AACR,KAAI,WAAW,SAAU,QAAO,sBAAsB,QAAQ;AAC9D,QAAO,KAAK,UAAU,QAAQ;AAC/B;AAED,SAAS,sBAAsBD,SAA8B;CAC3D,MAAME,QAAkB,CAAE;CAC1B,MAAM,QAAQ,CAAC,CAAC,EACd,QAAQ,KAAK,OAAO,EAAE,CAAC,aAAa,GAAG,QAAQ,KAAK,MAAM,EAAE,CAC7D,SAAS,CAAC;CACX,MAAM,SAAS,KAAK,OAAO,KAAK,MAAM,UAAU,EAAE;CAClD,MAAM,MAAM,IAAI,OAAO,OAAO;CAC9B,MAAM,YAAY,MAAM,SAAS,MAAM,IAAI,MAAM,GAAG,IAAI,CAAC,CAAC;CAC1D,MAAM,KAAK,GAAG,MAAM,QAAQ,WAAW,CAAC;AAGxC,KAAI,QAAQ,SAAS,MAAM;EACzB,MAAM,YAAY;AAClB,MAAI,UAAU,cAAc,UAAU,WAAW,SAAS,GAAG;GAC3D,MAAM,KAAK,cAAc;AACzB,QAAK,MAAM,MAAM,UAAU,YAAY;IACrC,MAAM,KAAK,CAAC,EAAE,EAAE,GAAG,KAAK,EAAE,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;IACrC,MAAM,KAAK,CAAC,UAAU,EAAE,GAAG,IAAI,CAAC;IAChC,MAAM,KAAK,UAAU;AACrB,SAAK,MAAM,CAAC,KAAK,MAAM,IAAI,OAAO,QAAQ,GAAG,KAAK,EAChD,MAAM,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,OAAO,CAAC;GAErC;EACF;CACF;AACD,KAAI,QAAQ,SAAS,QAAQ;EAC3B,MAAM,cAAc;AACpB,MAAI,YAAY,MACd,MAAM,KAAK,CAAC,MAAM,EAAE,YAAY,MAAM,CAAC;CAE1C;AAGD,KAAI,OAAO,QAAQ,YAAY,YAAY,QAAQ,QAAQ,MAAM,EAAE;AACjE,MAAI,MAAM,SAAS,GACjB,MAAM,KAAK,GAAG;EAEhB,MAAM,KAAK,QAAQ,QAAQ;CAC5B;AAED,QAAO,MAAM,KAAK,KAAK;AACxB"}
1
+ {"version":3,"file":"format.cjs","names":["message: BaseMessage","format: MessageStringFormat","lines: string[]"],"sources":["../../src/messages/format.ts"],"sourcesContent":["import { type BaseMessage } from \"./base.js\";\nimport { type AIMessage } from \"./ai.js\";\nimport { type ToolMessage } from \"./tool.js\";\n\nexport type MessageStringFormat = \"pretty\";\n\nexport function convertToFormattedString(\n message: BaseMessage,\n format: MessageStringFormat = \"pretty\"\n): string {\n if (format === \"pretty\") return convertToPrettyString(message);\n return JSON.stringify(message);\n}\n\nfunction convertToPrettyString(message: BaseMessage): string {\n const lines: string[] = [];\n const title = ` ${\n message.type.charAt(0).toUpperCase() + message.type.slice(1)\n } Message `;\n const sepLen = Math.floor((80 - title.length) / 2);\n const sep = \"=\".repeat(sepLen);\n const secondSep = title.length % 2 === 0 ? sep : `${sep}=`;\n lines.push(`${sep}${title}${secondSep}`);\n\n // Add message type specific details\n if (message.type === \"ai\") {\n const aiMessage = message as AIMessage;\n if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) {\n lines.push(\"Tool Calls:\");\n for (const tc of aiMessage.tool_calls) {\n lines.push(` ${tc.name} (${tc.id})`);\n lines.push(` Call ID: ${tc.id}`);\n lines.push(\" Args:\");\n for (const [key, value] of Object.entries(tc.args)) {\n lines.push(\n ` ${key}: ${\n typeof value === \"object\" ? JSON.stringify(value) : value\n }`\n );\n }\n }\n }\n }\n if (message.type === \"tool\") {\n const toolMessage = message as ToolMessage;\n if (toolMessage.name) {\n lines.push(`Name: ${toolMessage.name}`);\n }\n }\n\n // Add content if it's a string and not empty\n if (typeof message.content === \"string\" && message.content.trim()) {\n if (lines.length > 1) {\n lines.push(\"\"); // blank line before content\n }\n lines.push(message.content);\n }\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";;AAMA,SAAgB,yBACdA,SACAC,SAA8B,UACtB;AACR,KAAI,WAAW,SAAU,QAAO,sBAAsB,QAAQ;AAC9D,QAAO,KAAK,UAAU,QAAQ;AAC/B;AAED,SAAS,sBAAsBD,SAA8B;CAC3D,MAAME,QAAkB,CAAE;CAC1B,MAAM,QAAQ,CAAC,CAAC,EACd,QAAQ,KAAK,OAAO,EAAE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");
21
- for (const [key, value] of Object.entries(tc.args)) lines.push(` ${key}: ${value}`);
21
+ for (const [key, value] of Object.entries(tc.args)) lines.push(` ${key}: ${typeof value === "object" ? JSON.stringify(value) : value}`);
22
22
  }
23
23
  }
24
24
  }
@@ -1 +1 @@
1
- {"version":3,"file":"format.js","names":["message: BaseMessage","format: MessageStringFormat","lines: string[]"],"sources":["../../src/messages/format.ts"],"sourcesContent":["import { type BaseMessage } from \"./base.js\";\nimport { type AIMessage } from \"./ai.js\";\nimport { type ToolMessage } from \"./tool.js\";\n\nexport type MessageStringFormat = \"pretty\";\n\nexport function convertToFormattedString(\n message: BaseMessage,\n format: MessageStringFormat = \"pretty\"\n): string {\n if (format === \"pretty\") return convertToPrettyString(message);\n return JSON.stringify(message);\n}\n\nfunction convertToPrettyString(message: BaseMessage): string {\n const lines: string[] = [];\n const title = ` ${\n message.type.charAt(0).toUpperCase() + message.type.slice(1)\n } Message `;\n const sepLen = Math.floor((80 - title.length) / 2);\n const sep = \"=\".repeat(sepLen);\n const secondSep = title.length % 2 === 0 ? sep : `${sep}=`;\n lines.push(`${sep}${title}${secondSep}`);\n\n // Add message type specific details\n if (message.type === \"ai\") {\n const aiMessage = message as AIMessage;\n if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) {\n lines.push(\"Tool Calls:\");\n for (const tc of aiMessage.tool_calls) {\n lines.push(` ${tc.name} (${tc.id})`);\n lines.push(` Call ID: ${tc.id}`);\n lines.push(\" Args:\");\n for (const [key, value] of Object.entries(tc.args)) {\n lines.push(` ${key}: ${value}`);\n }\n }\n }\n }\n if (message.type === \"tool\") {\n const toolMessage = message as ToolMessage;\n if (toolMessage.name) {\n lines.push(`Name: ${toolMessage.name}`);\n }\n }\n\n // Add content if it's a string and not empty\n if (typeof message.content === \"string\" && message.content.trim()) {\n if (lines.length > 1) {\n lines.push(\"\"); // blank line before content\n }\n lines.push(message.content);\n }\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";AAMA,SAAgB,yBACdA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K,QAAQ,QAAQ;CAC5B;AAED,QAAO,MAAM,KAAK,KAAK;AACxB"}
1
+ {"version":3,"file":"format.js","names":["message: BaseMessage","format: MessageStringFormat","lines: string[]"],"sources":["../../src/messages/format.ts"],"sourcesContent":["import { type BaseMessage } from \"./base.js\";\nimport { type AIMessage } from \"./ai.js\";\nimport { type ToolMessage } from \"./tool.js\";\n\nexport type MessageStringFormat = \"pretty\";\n\nexport function convertToFormattedString(\n message: BaseMessage,\n format: MessageStringFormat = \"pretty\"\n): string {\n if (format === \"pretty\") return convertToPrettyString(message);\n return JSON.stringify(message);\n}\n\nfunction convertToPrettyString(message: BaseMessage): string {\n const lines: string[] = [];\n const title = ` ${\n message.type.charAt(0).toUpperCase() + message.type.slice(1)\n } Message `;\n const sepLen = Math.floor((80 - title.length) / 2);\n const sep = \"=\".repeat(sepLen);\n const secondSep = title.length % 2 === 0 ? sep : `${sep}=`;\n lines.push(`${sep}${title}${secondSep}`);\n\n // Add message type specific details\n if (message.type === \"ai\") {\n const aiMessage = message as AIMessage;\n if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) {\n lines.push(\"Tool Calls:\");\n for (const tc of aiMessage.tool_calls) {\n lines.push(` ${tc.name} (${tc.id})`);\n lines.push(` Call ID: ${tc.id}`);\n lines.push(\" Args:\");\n for (const [key, value] of Object.entries(tc.args)) {\n lines.push(\n ` ${key}: ${\n typeof value === \"object\" ? JSON.stringify(value) : value\n }`\n );\n }\n }\n }\n }\n if (message.type === \"tool\") {\n const toolMessage = message as ToolMessage;\n if (toolMessage.name) {\n lines.push(`Name: ${toolMessage.name}`);\n }\n }\n\n // Add content if it's a string and not empty\n if (typeof message.content === \"string\" && message.content.trim()) {\n if (lines.length > 1) {\n lines.push(\"\"); // blank line before content\n }\n lines.push(message.content);\n }\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";AAMA,SAAgB,yBACdA,SACAC,SAA8B,UACtB;AACR,KAAI,WAAW,SAAU,QAAO,sBAAsB,QAAQ;AAC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,QAAO,MAAM,KAAK,KAAK;AACxB"}
@@ -1 +1 @@
1
- {"version":3,"file":"tool.d.cts","names":["BaseMessage","BaseMessageChunk","BaseMessageFields","$InferMessageContent","MessageStructure","ToolMessageFields","TStructure","Record","DirectToolOutput","isDirectToolOutput","ToolMessage","ToolMessageChunk","ToolCall","TName","TArgs","ToolCallChunk","InvalidToolCall","defaultToolCallParser","isToolMessage","isToolMessageChunk"],"sources":["../../src/messages/tool.d.ts"],"sourcesContent":["import { BaseMessage, BaseMessageChunk, type BaseMessageFields } from \"./base.js\";\nimport { $InferMessageContent, MessageStructure } from \"./message.js\";\nexport interface ToolMessageFields<TStructure extends MessageStructure = MessageStructure> extends BaseMessageFields<TStructure, \"tool\"> {\n /**\n * Artifact of the Tool execution which is not meant to be sent to the model.\n *\n * Should only be specified if it is different from the message content, e.g. if only\n * a subset of the full tool output is being passed as message content but the full\n * output is needed in other parts of the code.\n */\n artifact?: any;\n tool_call_id: string;\n status?: \"success\" | \"error\";\n metadata?: Record<string, unknown>;\n}\n/**\n * Marker parameter for objects that tools can return directly.\n *\n * If a custom BaseTool is invoked with a ToolCall and the output of custom code is\n * not an instance of DirectToolOutput, the output will automatically be coerced to\n * a string and wrapped in a ToolMessage.\n */\nexport interface DirectToolOutput {\n readonly lc_direct_tool_output: true;\n}\nexport declare function isDirectToolOutput(x: unknown): x is DirectToolOutput;\n/**\n * Represents a tool message in a conversation.\n */\nexport declare class ToolMessage<TStructure extends MessageStructure = MessageStructure> extends BaseMessage<TStructure, \"tool\"> implements DirectToolOutput {\n static lc_name(): string;\n get lc_aliases(): Record<string, string>;\n lc_direct_tool_output: true;\n readonly type: \"tool\";\n /**\n * Status of the tool invocation.\n * @version 0.2.19\n */\n status?: \"success\" | \"error\";\n tool_call_id: string;\n metadata?: Record<string, unknown>;\n /**\n * Artifact of the Tool execution which is not meant to be sent to the model.\n *\n * Should only be specified if it is different from the message content, e.g. if only\n * a subset of the full tool output is being passed as message content but the full\n * output is needed in other parts of the code.\n */\n artifact?: any;\n constructor(fields: $InferMessageContent<TStructure, \"tool\"> | ToolMessageFields, tool_call_id: string, name?: string);\n constructor(fields: ToolMessageFields<TStructure>);\n static isInstance(message: unknown): message is ToolMessage;\n get _printableFields(): Record<string, unknown>;\n}\n/**\n * Represents a chunk of a tool message, which can be concatenated\n * with other tool message chunks.\n */\nexport declare class ToolMessageChunk<TStructure extends MessageStructure = MessageStructure> extends BaseMessageChunk<TStructure, \"tool\"> {\n readonly type: \"tool\";\n tool_call_id: string;\n /**\n * Status of the tool invocation.\n * @version 0.2.19\n */\n status?: \"success\" | \"error\";\n /**\n * Artifact of the Tool execution which is not meant to be sent to the model.\n *\n * Should only be specified if it is different from the message content, e.g. if only\n * a subset of the full tool output is being passed as message content but the full\n * output is needed in other parts of the code.\n */\n artifact?: any;\n constructor(fields: ToolMessageFields<TStructure>);\n static lc_name(): string;\n concat(chunk: ToolMessageChunk<TStructure>): this;\n get _printableFields(): Record<string, unknown>;\n}\nexport interface ToolCall<TName extends string = string, TArgs extends Record<string, any> = Record<string, any>> {\n readonly type?: \"tool_call\";\n /**\n * If provided, an identifier associated with the tool call\n */\n id?: string;\n /**\n * The name of the tool being called\n */\n name: TName;\n /**\n * The arguments to the tool call\n */\n args: TArgs;\n}\n/**\n * A chunk of a tool call (e.g., as part of a stream).\n * When merging ToolCallChunks (e.g., via AIMessageChunk.__add__),\n * all string attributes are concatenated. Chunks are only merged if their\n * values of `index` are equal and not None.\n *\n * @example\n * ```ts\n * const leftChunks = [\n * {\n * name: \"foo\",\n * args: '{\"a\":',\n * index: 0\n * }\n * ];\n *\n * const leftAIMessageChunk = new AIMessageChunk({\n * content: \"\",\n * tool_call_chunks: leftChunks\n * });\n *\n * const rightChunks = [\n * {\n * name: undefined,\n * args: '1}',\n * index: 0\n * }\n * ];\n *\n * const rightAIMessageChunk = new AIMessageChunk({\n * content: \"\",\n * tool_call_chunks: rightChunks\n * });\n *\n * const result = leftAIMessageChunk.concat(rightAIMessageChunk);\n * // result.tool_call_chunks is equal to:\n * // [\n * // {\n * // name: \"foo\",\n * // args: '{\"a\":1}'\n * // index: 0\n * // }\n * // ]\n * ```\n */\nexport interface ToolCallChunk<TName extends string = string> {\n readonly type?: \"tool_call_chunk\";\n /**\n * If provided, a substring of an identifier for the tool call\n */\n id?: string;\n /**\n * If provided, a substring of the name of the tool to be called\n */\n name?: TName;\n /**\n * If provided, a JSON substring of the arguments to the tool call\n */\n args?: string;\n /**\n * If provided, the index of the tool call in a sequence\n */\n index?: number;\n}\nexport interface InvalidToolCall<TName extends string = string> {\n readonly type?: \"invalid_tool_call\";\n /**\n * If provided, an identifier associated with the tool call\n */\n id?: string;\n /**\n /**\n * The name of the tool being called\n */\n name?: TName;\n /**\n * The arguments to the tool call\n */\n args?: string;\n /**\n * An error message associated with the tool call\n */\n error?: string;\n /**\n * Index of block in aggregate response\n */\n index?: string | number;\n}\nexport declare function defaultToolCallParser(rawToolCalls: Record<string, any>[]): [ToolCall[], InvalidToolCall[]];\n/**\n * @deprecated Use {@link ToolMessage.isInstance} instead\n */\nexport declare function isToolMessage(x: unknown): x is ToolMessage;\n/**\n * @deprecated Use {@link ToolMessageChunk.isInstance} instead\n */\nexport declare function isToolMessageChunk(x: BaseMessageChunk): x is ToolMessageChunk;\n//# sourceMappingURL=tool.d.ts.map"],"mappings":";;;;UAEiBK,qCAAqCD,mBAAmBA,0BAA0BF,kBAAkBI;;AAArH;;;;;;EAAoH,QAAA,CAAA,EAAA,GAAA;EAoBnGE,YAAAA,EAAAA,MAAgB;EAGTC,MAAAA,CAAAA,EAAAA,SAAAA,GAAkB,OAAA;EAIrBC,QAAAA,CAAAA,EAhBNH,MAgBiB,CAAA,MAAAD,EAAAA,OAAAA,CAAAA;;;;;;;;;AAqBUA,UA5BzBE,gBAAAA,CA4ByBF;EAAlBD,SAAAA,qBAAAA,EAAAA,IAAAA;;AAEIE,iBA3BJE,kBAAAA,CA2BIF,CAAAA,EAAAA,OAAAA,CAAAA,EAAAA,CA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;QASnFM;;;;QAIAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA+COC;;;;;;;;;SASNF;;;;;;;;;;UAUMG;;;;;;;;;;SAUNH;;;;;;;;;;;;;;iBAcaI,qBAAAA,eAAoCV,yBAAyBK,YAAYI;;;;iBAIzEE,aAAAA,mBAAgCR;;;;iBAIhCS,kBAAAA,IAAsBlB,wBAAwBU"}
1
+ {"version":3,"file":"tool.d.cts","names":["BaseMessage","BaseMessageChunk","BaseMessageFields","$InferMessageContent","MessageStructure","ToolMessageFields","TStructure","Record","DirectToolOutput","isDirectToolOutput","ToolMessage","ToolMessageChunk","ToolCall","TName","TArgs","ToolCallChunk","InvalidToolCall","defaultToolCallParser","isToolMessage","isToolMessageChunk"],"sources":["../../src/messages/tool.d.ts"],"sourcesContent":["import { BaseMessage, BaseMessageChunk, type BaseMessageFields } from \"./base.js\";\nimport { $InferMessageContent, MessageStructure } from \"./message.js\";\nexport interface ToolMessageFields<TStructure extends MessageStructure = MessageStructure> extends BaseMessageFields<TStructure, \"tool\"> {\n /**\n * Artifact of the Tool execution which is not meant to be sent to the model.\n *\n * Should only be specified if it is different from the message content, e.g. if only\n * a subset of the full tool output is being passed as message content but the full\n * output is needed in other parts of the code.\n */\n artifact?: any;\n tool_call_id: string;\n status?: \"success\" | \"error\";\n metadata?: Record<string, unknown>;\n}\n/**\n * Marker parameter for objects that tools can return directly.\n *\n * If a custom BaseTool is invoked with a ToolCall and the output of custom code is\n * not an instance of DirectToolOutput, the output will automatically be coerced to\n * a string and wrapped in a ToolMessage.\n */\nexport interface DirectToolOutput {\n readonly lc_direct_tool_output: true;\n}\nexport declare function isDirectToolOutput(x: unknown): x is DirectToolOutput;\n/**\n * Represents a tool message in a conversation.\n */\nexport declare class ToolMessage<TStructure extends MessageStructure = MessageStructure> extends BaseMessage<TStructure, \"tool\"> implements DirectToolOutput {\n static lc_name(): string;\n get lc_aliases(): Record<string, string>;\n lc_direct_tool_output: true;\n readonly type: \"tool\";\n /**\n * Status of the tool invocation.\n * @version 0.2.19\n */\n status?: \"success\" | \"error\";\n tool_call_id: string;\n metadata?: Record<string, unknown>;\n /**\n * Artifact of the Tool execution which is not meant to be sent to the model.\n *\n * Should only be specified if it is different from the message content, e.g. if only\n * a subset of the full tool output is being passed as message content but the full\n * output is needed in other parts of the code.\n */\n artifact?: any;\n constructor(fields: $InferMessageContent<TStructure, \"tool\"> | ToolMessageFields, tool_call_id: string, name?: string);\n constructor(fields: ToolMessageFields<TStructure>);\n static isInstance(message: unknown): message is ToolMessage;\n get _printableFields(): Record<string, unknown>;\n}\n/**\n * Represents a chunk of a tool message, which can be concatenated\n * with other tool message chunks.\n */\nexport declare class ToolMessageChunk<TStructure extends MessageStructure = MessageStructure> extends BaseMessageChunk<TStructure, \"tool\"> {\n readonly type: \"tool\";\n tool_call_id: string;\n /**\n * Status of the tool invocation.\n * @version 0.2.19\n */\n status?: \"success\" | \"error\";\n /**\n * Artifact of the Tool execution which is not meant to be sent to the model.\n *\n * Should only be specified if it is different from the message content, e.g. if only\n * a subset of the full tool output is being passed as message content but the full\n * output is needed in other parts of the code.\n */\n artifact?: any;\n constructor(fields: ToolMessageFields<TStructure>);\n static lc_name(): string;\n concat(chunk: ToolMessageChunk<TStructure>): this;\n get _printableFields(): Record<string, unknown>;\n}\nexport interface ToolCall<TName extends string = string, TArgs extends Record<string, any> = Record<string, any>> {\n readonly type?: \"tool_call\";\n /**\n * If provided, an identifier associated with the tool call\n */\n id?: string;\n /**\n * The name of the tool being called\n */\n name: TName;\n /**\n * The arguments to the tool call\n */\n args: TArgs;\n}\n/**\n * A chunk of a tool call (e.g., as part of a stream).\n * When merging ToolCallChunks (e.g., via AIMessageChunk.__add__),\n * all string attributes are concatenated. Chunks are only merged if their\n * values of `index` are equal and not None.\n *\n * @example\n * ```ts\n * const leftChunks = [\n * {\n * name: \"foo\",\n * args: '{\"a\":',\n * index: 0\n * }\n * ];\n *\n * const leftAIMessageChunk = new AIMessageChunk({\n * content: \"\",\n * tool_call_chunks: leftChunks\n * });\n *\n * const rightChunks = [\n * {\n * name: undefined,\n * args: '1}',\n * index: 0\n * }\n * ];\n *\n * const rightAIMessageChunk = new AIMessageChunk({\n * content: \"\",\n * tool_call_chunks: rightChunks\n * });\n *\n * const result = leftAIMessageChunk.concat(rightAIMessageChunk);\n * // result.tool_call_chunks is equal to:\n * // [\n * // {\n * // name: \"foo\",\n * // args: '{\"a\":1}'\n * // index: 0\n * // }\n * // ]\n * ```\n */\nexport interface ToolCallChunk<TName extends string = string> {\n readonly type?: \"tool_call_chunk\";\n /**\n * If provided, a substring of an identifier for the tool call\n */\n id?: string;\n /**\n * If provided, a substring of the name of the tool to be called\n */\n name?: TName;\n /**\n * If provided, a JSON substring of the arguments to the tool call\n */\n args?: string;\n /**\n * If provided, the index of the tool call in a sequence\n */\n index?: number;\n}\nexport interface InvalidToolCall<TName extends string = string> {\n readonly type?: \"invalid_tool_call\";\n /**\n * If provided, an identifier associated with the tool call\n */\n id?: string;\n /**\n /**\n * The name of the tool being called\n */\n name?: TName;\n /**\n * The arguments to the tool call\n */\n args?: string;\n /**\n * An error message associated with the tool call\n */\n error?: string;\n /**\n * Index of block in aggregate response\n */\n index?: string | number;\n}\nexport declare function defaultToolCallParser(rawToolCalls: Record<string, any>[]): [ToolCall[], InvalidToolCall[]];\n/**\n * @deprecated Use {@link ToolMessage.isInstance} instead\n */\nexport declare function isToolMessage(x: unknown): x is ToolMessage;\n/**\n * @deprecated Use {@link ToolMessageChunk.isInstance} instead\n */\nexport declare function isToolMessageChunk(x: BaseMessageChunk): x is ToolMessageChunk;\n//# sourceMappingURL=tool.d.ts.map"],"mappings":";;;;UAEiBK,qCAAqCD,mBAAmBA,0BAA0BF,kBAAkBI;;AAArH;;;;;;EAAoH,QAAA,CAAA,EAAA,GAAA;EAoBnGE,YAAAA,EAAAA,MAAgB;EAGTC,MAAAA,CAAAA,EAAAA,SAAAA,GAAkB,OAAA;EAIrBC,QAAAA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AAA,EAlIpFT,MAkIoF,CAAA,MAAA,EAAA,OAAA,CAAA;AAIhH;AAIA;;;;cApIqBI,oCAAoCP,mBAAmBA,0BAA0BH,iBAAiBK;;;;;;;;;;;;;;;;sBAgB/FD,kBAAkBC;;gBAExBK,iBAAiBL;0BACPC;;UAEXK,sDAAsDL,sBAAsBA;;;;;;;;;QASnFM;;;;QAIAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA+COC;;;;;;;;;SASNF;;;;;;;;;;UAUMG;;;;;;;;;;SAUNH;;;;;;;;;;;;;;iBAcaI,qBAAAA,eAAoCV,yBAAyBK,YAAYI;;;;iBAIzEE,aAAAA,mBAAgCR;;;;iBAIhCS,kBAAAA,IAAsBlB,wBAAwBU"}
@@ -43,14 +43,21 @@ function drawMermaid(nodes, edges, config) {
43
43
  edgeGroups[commonPrefix].push(edge);
44
44
  }
45
45
  const seenSubgraphs = /* @__PURE__ */ new Set();
46
+ function sortPrefixesByDepth(prefixes) {
47
+ return [...prefixes].sort((a, b) => {
48
+ return a.split(":").length - b.split(":").length;
49
+ });
50
+ }
46
51
  function addSubgraph(edges$1, prefix) {
47
52
  const selfLoop = edges$1.length === 1 && edges$1[0].source === edges$1[0].target;
48
53
  if (prefix && !selfLoop) {
49
54
  const subgraph = prefix.split(":").pop();
50
- if (seenSubgraphs.has(subgraph)) throw new Error(`Found duplicate subgraph '${subgraph}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);
51
- seenSubgraphs.add(subgraph);
55
+ if (seenSubgraphs.has(prefix)) throw new Error(`Found duplicate subgraph '${subgraph}' at '${prefix} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);
56
+ seenSubgraphs.add(prefix);
52
57
  mermaidGraph += `\tsubgraph ${subgraph}\n`;
53
58
  }
59
+ const nestedPrefixes = sortPrefixesByDepth(Object.keys(edgeGroups).filter((nestedPrefix) => nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix && nestedPrefix.split(":").length === prefix.split(":").length + 1));
60
+ for (const nestedPrefix of nestedPrefixes) addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);
54
61
  for (const edge of edges$1) {
55
62
  const { source, target, data, conditional } = edge;
56
63
  let edgeLabel = "";
@@ -62,7 +69,6 @@ function drawMermaid(nodes, edges, config) {
62
69
  } else edgeLabel = conditional ? " -.-> " : " --> ";
63
70
  mermaidGraph += `\t${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)};\n`;
64
71
  }
65
- for (const nestedPrefix in edgeGroups) if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);
66
72
  if (prefix && !selfLoop) mermaidGraph += " end\n";
67
73
  }
68
74
  addSubgraph(edgeGroups[""] ?? [], "");
@@ -1 +1 @@
1
- {"version":3,"file":"graph_mermaid.cjs","names":["nodeLabel: string","nodeColors: Record<string, string>","nodes: Record<string, Node>","edges: Edge[]","config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }","formatDict: Record<string, string>","edgeGroups: Record<string, Edge[]>","prefix: string","edges","mermaidSyntax: string","config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }","toBase64Url"],"sources":["../../src/runnables/graph_mermaid.ts"],"sourcesContent":["import { Edge, Node } from \"./types.js\";\nimport { toBase64Url } from \"./utils.js\";\n\nfunction _escapeNodeLabel(nodeLabel: string): string {\n // Escapes the node label for Mermaid syntax.\n return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, \"_\");\n}\n\nconst MARKDOWN_SPECIAL_CHARS = [\"*\", \"_\", \"`\"];\n\nfunction _generateMermaidGraphStyles(\n nodeColors: Record<string, string>\n): string {\n let styles = \"\";\n for (const [className, color] of Object.entries(nodeColors)) {\n styles += `\\tclassDef ${className} ${color};\\n`;\n }\n return styles;\n}\n\n/**\n * Draws a Mermaid graph using the provided graph data\n */\nexport function drawMermaid(\n nodes: Record<string, Node>,\n edges: Edge[],\n config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }\n): string {\n const {\n firstNode,\n lastNode,\n nodeColors,\n withStyles = true,\n curveStyle = \"linear\",\n wrapLabelNWords = 9,\n } = config ?? {};\n // Initialize Mermaid graph configuration\n let mermaidGraph = withStyles\n ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\\ngraph TD;\\n`\n : \"graph TD;\\n\";\n if (withStyles) {\n // Node formatting templates\n const defaultClassLabel = \"default\";\n const formatDict: Record<string, string> = {\n [defaultClassLabel]: \"{0}({1})\",\n };\n if (firstNode !== undefined) {\n formatDict[firstNode] = \"{0}([{1}]):::first\";\n }\n if (lastNode !== undefined) {\n formatDict[lastNode] = \"{0}([{1}]):::last\";\n }\n\n // Add nodes to the graph\n for (const [key, node] of Object.entries(nodes)) {\n const nodeName = node.name.split(\":\").pop() ?? \"\";\n const label = MARKDOWN_SPECIAL_CHARS.some(\n (char) => nodeName.startsWith(char) && nodeName.endsWith(char)\n )\n ? `<p>${nodeName}</p>`\n : nodeName;\n\n let finalLabel = label;\n if (Object.keys(node.metadata ?? {}).length) {\n finalLabel += `<hr/><small><em>${Object.entries(node.metadata ?? {})\n .map(([k, v]) => `${k} = ${v}`)\n .join(\"\\n\")}</em></small>`;\n }\n\n const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel])\n .replace(\"{0}\", _escapeNodeLabel(key))\n .replace(\"{1}\", finalLabel);\n\n mermaidGraph += `\\t${nodeLabel}\\n`;\n }\n }\n\n // Group edges by their common prefixes\n const edgeGroups: Record<string, Edge[]> = {};\n for (const edge of edges) {\n const srcParts = edge.source.split(\":\");\n const tgtParts = edge.target.split(\":\");\n const commonPrefix = srcParts\n .filter((src, i) => src === tgtParts[i])\n .join(\":\");\n if (!edgeGroups[commonPrefix]) {\n edgeGroups[commonPrefix] = [];\n }\n edgeGroups[commonPrefix].push(edge);\n }\n\n const seenSubgraphs = new Set<string>();\n\n function addSubgraph(edges: Edge[], prefix: string): void {\n const selfLoop = edges.length === 1 && edges[0].source === edges[0].target;\n if (prefix && !selfLoop) {\n const subgraph = prefix.split(\":\").pop()!;\n if (seenSubgraphs.has(subgraph)) {\n throw new Error(\n `Found duplicate subgraph '${subgraph}' -- this likely means that ` +\n \"you're reusing a subgraph node with the same name. \" +\n \"Please adjust your graph to have subgraph nodes with unique names.\"\n );\n }\n\n seenSubgraphs.add(subgraph);\n mermaidGraph += `\\tsubgraph ${subgraph}\\n`;\n }\n\n for (const edge of edges) {\n const { source, target, data, conditional } = edge;\n\n let edgeLabel = \"\";\n if (data !== undefined) {\n let edgeData = data;\n const words = edgeData.split(\" \");\n if (words.length > wrapLabelNWords) {\n edgeData = Array.from(\n { length: Math.ceil(words.length / wrapLabelNWords) },\n (_, i) =>\n words\n .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords)\n .join(\" \")\n ).join(\"&nbsp;<br>&nbsp;\");\n }\n edgeLabel = conditional\n ? ` -. &nbsp;${edgeData}&nbsp; .-> `\n : ` -- &nbsp;${edgeData}&nbsp; --> `;\n } else {\n edgeLabel = conditional ? \" -.-> \" : \" --> \";\n }\n\n mermaidGraph += `\\t${_escapeNodeLabel(\n source\n )}${edgeLabel}${_escapeNodeLabel(target)};\\n`;\n }\n\n // Recursively add nested subgraphs\n for (const nestedPrefix in edgeGroups) {\n if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) {\n addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);\n }\n }\n\n if (prefix && !selfLoop) {\n mermaidGraph += \"\\tend\\n\";\n }\n }\n\n // Start with the top-level edges (no common prefix)\n addSubgraph(edgeGroups[\"\"] ?? [], \"\");\n\n // Add remaining subgraphs\n for (const prefix in edgeGroups) {\n if (!prefix.includes(\":\") && prefix !== \"\") {\n addSubgraph(edgeGroups[prefix], prefix);\n }\n }\n\n // Add custom styles for nodes\n if (withStyles) {\n mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {});\n }\n\n return mermaidGraph;\n}\n\n/**\n * Renders Mermaid graph using the Mermaid.INK API.\n *\n * @example\n * ```javascript\n * const image = await drawMermaidImage(mermaidSyntax, {\n * backgroundColor: \"white\",\n * imageType: \"png\",\n * });\n * fs.writeFileSync(\"image.png\", image);\n * ```\n *\n * @param mermaidSyntax - The Mermaid syntax to render.\n * @param config - The configuration for the image.\n * @returns The image as a Blob.\n */\nexport async function drawMermaidImage(\n mermaidSyntax: string,\n config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }\n) {\n let backgroundColor = config?.backgroundColor ?? \"white\";\n const imageType = config?.imageType ?? \"png\";\n\n const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax);\n\n // Check if the background color is a hexadecimal color code using regex\n if (backgroundColor !== undefined) {\n const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;\n if (!hexColorPattern.test(backgroundColor)) {\n backgroundColor = `!${backgroundColor}`;\n }\n }\n const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`;\n const res = await fetch(imageUrl);\n if (!res.ok) {\n throw new Error(\n [\n `Failed to render the graph using the Mermaid.INK API.`,\n `Status code: ${res.status}`,\n `Status text: ${res.statusText}`,\n ].join(\"\\n\")\n );\n }\n const content = await res.blob();\n return content;\n}\n"],"mappings":";;;AAGA,SAAS,iBAAiBA,WAA2B;AAEnD,QAAO,UAAU,QAAQ,mBAAmB,IAAI;AACjD;AAED,MAAM,yBAAyB;CAAC;CAAK;CAAK;AAAI;AAE9C,SAAS,4BACPC,YACQ;CACR,IAAI,SAAS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,YAAY,iBAAiB,OAAO,CAAC,GAAG,CAAC;EAC9C;AAGD,OAAK,MAAM,gBAAgB,WACzB,KAAI,aAAa,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,iBAAiB,QAC5D,YAAY,WAAW,eAAe,aAAa;AAIvD,MAAI,UAAU,CAAC,UACb,gBAAgB;CAEnB;CAGD,YAAY,WAAW,OAAO,CAAE,GAAE,GAAG;AAGrC,MAAK,MAAM,UAAU,WACnB,KAAI,CAAC,OAAO,SAAS,IAAI,IAAI,WAAW,IACtC,YAAY,WAAW,SAAS,OAAO;AAK3C,KAAI,YACF,gBAAgB,4BAA4B,cAAc,CAAE,EAAC;AAG/D,QAAO;AACR;;;;;;;;;;;;;;;;;AAkBD,eAAsB,iBACpBC,eACAC,QAQA;CACA,IAAI,kBAAkB,QAAQ,mBAAmB;CACjD,MAAM,YAAY,QAAQ,aAAa;CAEvC,MAAM,uBAAuBC,0BAAY,cAAc;AAGvD,KAAI,oBAAoB,QAAW;EACjC,MAAM,kBAAkB;AACxB,MAAI,CAAC,gBAAgB,KAAK,gBAAgB,EACxC,kBAAkB,CAAC,CAAC,EAAE,iBAAiB;CAE1C;CACD,MAAM,WAAW,CAAC,wBAAwB,EAAE,qBAAqB,SAAS,EAAE,gBAAgB,MAAM,EAAE,WAAW;CAC/G,MAAM,MAAM,MAAM,MAAM,SAAS;AACjC,KAAI,CAAC,IAAI,GACP,OAAM,IAAI,MACR;EACE,CAAC,qDAAqD,CAAC;EACvD,CAAC,aAAa,EAAE,IAAI,QAAQ;EAC5B,CAAC,aAAa,EAAE,IAAI,YAAY;CACjC,EAAC,KAAK,KAAK;CAGhB,MAAM,UAAU,MAAM,IAAI,MAAM;AAChC,QAAO;AACR"}
1
+ {"version":3,"file":"graph_mermaid.cjs","names":["nodeLabel: string","nodeColors: Record<string, string>","nodes: Record<string, Node>","edges: Edge[]","config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }","formatDict: Record<string, string>","edgeGroups: Record<string, Edge[]>","prefixes: string[]","prefix: string","edges","mermaidSyntax: string","config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }","toBase64Url"],"sources":["../../src/runnables/graph_mermaid.ts"],"sourcesContent":["import { Edge, Node } from \"./types.js\";\nimport { toBase64Url } from \"./utils.js\";\n\nfunction _escapeNodeLabel(nodeLabel: string): string {\n // Escapes the node label for Mermaid syntax.\n return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, \"_\");\n}\n\nconst MARKDOWN_SPECIAL_CHARS = [\"*\", \"_\", \"`\"];\n\nfunction _generateMermaidGraphStyles(\n nodeColors: Record<string, string>\n): string {\n let styles = \"\";\n for (const [className, color] of Object.entries(nodeColors)) {\n styles += `\\tclassDef ${className} ${color};\\n`;\n }\n return styles;\n}\n\n/**\n * Draws a Mermaid graph using the provided graph data\n */\nexport function drawMermaid(\n nodes: Record<string, Node>,\n edges: Edge[],\n config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }\n): string {\n const {\n firstNode,\n lastNode,\n nodeColors,\n withStyles = true,\n curveStyle = \"linear\",\n wrapLabelNWords = 9,\n } = config ?? {};\n // Initialize Mermaid graph configuration\n let mermaidGraph = withStyles\n ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\\ngraph TD;\\n`\n : \"graph TD;\\n\";\n if (withStyles) {\n // Node formatting templates\n const defaultClassLabel = \"default\";\n const formatDict: Record<string, string> = {\n [defaultClassLabel]: \"{0}({1})\",\n };\n if (firstNode !== undefined) {\n formatDict[firstNode] = \"{0}([{1}]):::first\";\n }\n if (lastNode !== undefined) {\n formatDict[lastNode] = \"{0}([{1}]):::last\";\n }\n\n // Add nodes to the graph\n for (const [key, node] of Object.entries(nodes)) {\n const nodeName = node.name.split(\":\").pop() ?? \"\";\n const label = MARKDOWN_SPECIAL_CHARS.some(\n (char) => nodeName.startsWith(char) && nodeName.endsWith(char)\n )\n ? `<p>${nodeName}</p>`\n : nodeName;\n\n let finalLabel = label;\n if (Object.keys(node.metadata ?? {}).length) {\n finalLabel += `<hr/><small><em>${Object.entries(node.metadata ?? {})\n .map(([k, v]) => `${k} = ${v}`)\n .join(\"\\n\")}</em></small>`;\n }\n\n const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel])\n .replace(\"{0}\", _escapeNodeLabel(key))\n .replace(\"{1}\", finalLabel);\n\n mermaidGraph += `\\t${nodeLabel}\\n`;\n }\n }\n\n // Group edges by their common prefixes\n const edgeGroups: Record<string, Edge[]> = {};\n for (const edge of edges) {\n const srcParts = edge.source.split(\":\");\n const tgtParts = edge.target.split(\":\");\n const commonPrefix = srcParts\n .filter((src, i) => src === tgtParts[i])\n .join(\":\");\n if (!edgeGroups[commonPrefix]) {\n edgeGroups[commonPrefix] = [];\n }\n edgeGroups[commonPrefix].push(edge);\n }\n\n const seenSubgraphs = new Set<string>();\n\n // sort prefixes by path length for correct nesting\n function sortPrefixesByDepth(prefixes: string[]): string[] {\n return [...prefixes].sort((a, b) => {\n return a.split(\":\").length - b.split(\":\").length;\n });\n }\n\n function addSubgraph(edges: Edge[], prefix: string): void {\n const selfLoop = edges.length === 1 && edges[0].source === edges[0].target;\n if (prefix && !selfLoop) {\n const subgraph = prefix.split(\":\").pop()!;\n\n if (seenSubgraphs.has(prefix)) {\n throw new Error(\n `Found duplicate subgraph '${subgraph}' at '${prefix} -- this likely means that ` +\n \"you're reusing a subgraph node with the same name. \" +\n \"Please adjust your graph to have subgraph nodes with unique names.\"\n );\n }\n\n seenSubgraphs.add(prefix);\n mermaidGraph += `\\tsubgraph ${subgraph}\\n`;\n }\n\n // all nested prefixes for this level, sorted by depth\n const nestedPrefixes = sortPrefixesByDepth(\n Object.keys(edgeGroups).filter(\n (nestedPrefix) =>\n nestedPrefix.startsWith(`${prefix}:`) &&\n nestedPrefix !== prefix &&\n nestedPrefix.split(\":\").length === prefix.split(\":\").length + 1\n )\n );\n\n for (const nestedPrefix of nestedPrefixes) {\n addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);\n }\n\n for (const edge of edges) {\n const { source, target, data, conditional } = edge;\n\n let edgeLabel = \"\";\n if (data !== undefined) {\n let edgeData = data;\n const words = edgeData.split(\" \");\n if (words.length > wrapLabelNWords) {\n edgeData = Array.from(\n { length: Math.ceil(words.length / wrapLabelNWords) },\n (_, i) =>\n words\n .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords)\n .join(\" \")\n ).join(\"&nbsp;<br>&nbsp;\");\n }\n edgeLabel = conditional\n ? ` -. &nbsp;${edgeData}&nbsp; .-> `\n : ` -- &nbsp;${edgeData}&nbsp; --> `;\n } else {\n edgeLabel = conditional ? \" -.-> \" : \" --> \";\n }\n\n mermaidGraph += `\\t${_escapeNodeLabel(\n source\n )}${edgeLabel}${_escapeNodeLabel(target)};\\n`;\n }\n\n if (prefix && !selfLoop) {\n mermaidGraph += \"\\tend\\n\";\n }\n }\n\n // Start with the top-level edges (no common prefix)\n addSubgraph(edgeGroups[\"\"] ?? [], \"\");\n\n // Add remaining top-level subgraphs\n for (const prefix in edgeGroups) {\n if (!prefix.includes(\":\") && prefix !== \"\") {\n addSubgraph(edgeGroups[prefix], prefix);\n }\n }\n\n // Add custom styles for nodes\n if (withStyles) {\n mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {});\n }\n\n return mermaidGraph;\n}\n\n/**\n * Renders Mermaid graph using the Mermaid.INK API.\n *\n * @example\n * ```javascript\n * const image = await drawMermaidImage(mermaidSyntax, {\n * backgroundColor: \"white\",\n * imageType: \"png\",\n * });\n * fs.writeFileSync(\"image.png\", image);\n * ```\n *\n * @param mermaidSyntax - The Mermaid syntax to render.\n * @param config - The configuration for the image.\n * @returns The image as a Blob.\n */\nexport async function drawMermaidImage(\n mermaidSyntax: string,\n config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }\n) {\n let backgroundColor = config?.backgroundColor ?? \"white\";\n const imageType = config?.imageType ?? \"png\";\n\n const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax);\n\n // Check if the background color is a hexadecimal color code using regex\n if (backgroundColor !== undefined) {\n const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;\n if (!hexColorPattern.test(backgroundColor)) {\n backgroundColor = `!${backgroundColor}`;\n }\n }\n const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`;\n const res = await fetch(imageUrl);\n if (!res.ok) {\n throw new Error(\n [\n `Failed to render the graph using the Mermaid.INK API.`,\n `Status code: ${res.status}`,\n `Status text: ${res.statusText}`,\n ].join(\"\\n\")\n );\n }\n const content = await res.blob();\n return content;\n}\n"],"mappings":";;;AAGA,SAAS,iBAAiBA,WAA2B;AAEnD,QAAO,UAAU,QAAQ,mBAAmB,IAAI;AACjD;AAED,MAAM,yBAAyB;CAAC;CAAK;CAAK;AAAI;AAE9C,SAAS,4BACPC,YACQ;CACR,IAAI,SAAS;AACb,MAAK,MAAM,CAAC,WAAW,MAAM,IAAI,OAAO,QAAQ,WAAW,EACzD,UAAU,CAAC,WAAW,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,CAAC;AAEjD,QAAO;AACR;;;;AAKD,SAAgB,YACdC,OACAC,OACAC,QAQQ;CACR,MAAM,EACJ,WACA,UACA,YACA,aAAa,MACb,aAAa,UACb,kBAAkB,GACnB,GAAG,UAAU,CAAE;CAEhB,IAAI,eAAe,aACf,CAAC,kCAAkC,EAAE,WAAW,mBAAmB,CAAC,GACpE;AACJ,KAAI,YAAY;EAEd,MAAM,oBAAoB;EAC1B,MAAMC,aAAqC,GACxC,oBAAoB,WACtB;AACD,MAAI,cAAc,QAChB,WAAW,aAAa;A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BAAiB,OAAO,CAAC,GAAG,CAAC;EAC9C;AAED,MAAI,UAAU,CAAC,UACb,gBAAgB;CAEnB;CAGD,YAAY,WAAW,OAAO,CAAE,GAAE,GAAG;AAGrC,MAAK,MAAM,UAAU,WACnB,KAAI,CAAC,OAAO,SAAS,IAAI,IAAI,WAAW,IACtC,YAAY,WAAW,SAAS,OAAO;AAK3C,KAAI,YACF,gBAAgB,4BAA4B,cAAc,CAAE,EAAC;AAG/D,QAAO;AACR;;;;;;;;;;;;;;;;;AAkBD,eAAsB,iBACpBC,eACAC,QAQA;CACA,IAAI,kBAAkB,QAAQ,mBAAmB;CACjD,MAAM,YAAY,QAAQ,aAAa;CAEvC,MAAM,uBAAuBC,0BAAY,cAAc;AAGvD,KAAI,oBAAoB,QAAW;EACjC,MAAM,kBAAkB;AACxB,MAAI,CAAC,gBAAgB,KAAK,gBAAgB,EACxC,kBAAkB,CAAC,CAAC,EAAE,iBAAiB;CAE1C;CACD,MAAM,WAAW,CAAC,wBAAwB,EAAE,qBAAqB,SAAS,EAAE,gBAAgB,MAAM,EAAE,WAAW;CAC/G,MAAM,MAAM,MAAM,MAAM,SAAS;AACjC,KAAI,CAAC,IAAI,GACP,OAAM,IAAI,MACR;EACE,CAAC,qDAAqD,CAAC;EACvD,CAAC,aAAa,EAAE,IAAI,QAAQ;EAC5B,CAAC,aAAa,EAAE,IAAI,YAAY;CACjC,EAAC,KAAK,KAAK;CAGhB,MAAM,UAAU,MAAM,IAAI,MAAM;AAChC,QAAO;AACR"}
@@ -43,14 +43,21 @@ function drawMermaid(nodes, edges, config) {
43
43
  edgeGroups[commonPrefix].push(edge);
44
44
  }
45
45
  const seenSubgraphs = /* @__PURE__ */ new Set();
46
+ function sortPrefixesByDepth(prefixes) {
47
+ return [...prefixes].sort((a, b) => {
48
+ return a.split(":").length - b.split(":").length;
49
+ });
50
+ }
46
51
  function addSubgraph(edges$1, prefix) {
47
52
  const selfLoop = edges$1.length === 1 && edges$1[0].source === edges$1[0].target;
48
53
  if (prefix && !selfLoop) {
49
54
  const subgraph = prefix.split(":").pop();
50
- if (seenSubgraphs.has(subgraph)) throw new Error(`Found duplicate subgraph '${subgraph}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);
51
- seenSubgraphs.add(subgraph);
55
+ if (seenSubgraphs.has(prefix)) throw new Error(`Found duplicate subgraph '${subgraph}' at '${prefix} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);
56
+ seenSubgraphs.add(prefix);
52
57
  mermaidGraph += `\tsubgraph ${subgraph}\n`;
53
58
  }
59
+ const nestedPrefixes = sortPrefixesByDepth(Object.keys(edgeGroups).filter((nestedPrefix) => nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix && nestedPrefix.split(":").length === prefix.split(":").length + 1));
60
+ for (const nestedPrefix of nestedPrefixes) addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);
54
61
  for (const edge of edges$1) {
55
62
  const { source, target, data, conditional } = edge;
56
63
  let edgeLabel = "";
@@ -62,7 +69,6 @@ function drawMermaid(nodes, edges, config) {
62
69
  } else edgeLabel = conditional ? " -.-> " : " --> ";
63
70
  mermaidGraph += `\t${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)};\n`;
64
71
  }
65
- for (const nestedPrefix in edgeGroups) if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);
66
72
  if (prefix && !selfLoop) mermaidGraph += " end\n";
67
73
  }
68
74
  addSubgraph(edgeGroups[""] ?? [], "");
@@ -1 +1 @@
1
- {"version":3,"file":"graph_mermaid.js","names":["nodeLabel: string","nodeColors: Record<string, string>","nodes: Record<string, Node>","edges: Edge[]","config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }","formatDict: Record<string, string>","edgeGroups: Record<string, Edge[]>","prefix: string","edges","mermaidSyntax: string","config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }"],"sources":["../../src/runnables/graph_mermaid.ts"],"sourcesContent":["import { Edge, Node } from \"./types.js\";\nimport { toBase64Url } from \"./utils.js\";\n\nfunction _escapeNodeLabel(nodeLabel: string): string {\n // Escapes the node label for Mermaid syntax.\n return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, \"_\");\n}\n\nconst MARKDOWN_SPECIAL_CHARS = [\"*\", \"_\", \"`\"];\n\nfunction _generateMermaidGraphStyles(\n nodeColors: Record<string, string>\n): string {\n let styles = \"\";\n for (const [className, color] of Object.entries(nodeColors)) {\n styles += `\\tclassDef ${className} ${color};\\n`;\n }\n return styles;\n}\n\n/**\n * Draws a Mermaid graph using the provided graph data\n */\nexport function drawMermaid(\n nodes: Record<string, Node>,\n edges: Edge[],\n config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }\n): string {\n const {\n firstNode,\n lastNode,\n nodeColors,\n withStyles = true,\n curveStyle = \"linear\",\n wrapLabelNWords = 9,\n } = config ?? {};\n // Initialize Mermaid graph configuration\n let mermaidGraph = withStyles\n ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\\ngraph TD;\\n`\n : \"graph TD;\\n\";\n if (withStyles) {\n // Node formatting templates\n const defaultClassLabel = \"default\";\n const formatDict: Record<string, string> = {\n [defaultClassLabel]: \"{0}({1})\",\n };\n if (firstNode !== undefined) {\n formatDict[firstNode] = \"{0}([{1}]):::first\";\n }\n if (lastNode !== undefined) {\n formatDict[lastNode] = \"{0}([{1}]):::last\";\n }\n\n // Add nodes to the graph\n for (const [key, node] of Object.entries(nodes)) {\n const nodeName = node.name.split(\":\").pop() ?? \"\";\n const label = MARKDOWN_SPECIAL_CHARS.some(\n (char) => nodeName.startsWith(char) && nodeName.endsWith(char)\n )\n ? `<p>${nodeName}</p>`\n : nodeName;\n\n let finalLabel = label;\n if (Object.keys(node.metadata ?? {}).length) {\n finalLabel += `<hr/><small><em>${Object.entries(node.metadata ?? {})\n .map(([k, v]) => `${k} = ${v}`)\n .join(\"\\n\")}</em></small>`;\n }\n\n const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel])\n .replace(\"{0}\", _escapeNodeLabel(key))\n .replace(\"{1}\", finalLabel);\n\n mermaidGraph += `\\t${nodeLabel}\\n`;\n }\n }\n\n // Group edges by their common prefixes\n const edgeGroups: Record<string, Edge[]> = {};\n for (const edge of edges) {\n const srcParts = edge.source.split(\":\");\n const tgtParts = edge.target.split(\":\");\n const commonPrefix = srcParts\n .filter((src, i) => src === tgtParts[i])\n .join(\":\");\n if (!edgeGroups[commonPrefix]) {\n edgeGroups[commonPrefix] = [];\n }\n edgeGroups[commonPrefix].push(edge);\n }\n\n const seenSubgraphs = new Set<string>();\n\n function addSubgraph(edges: Edge[], prefix: string): void {\n const selfLoop = edges.length === 1 && edges[0].source === edges[0].target;\n if (prefix && !selfLoop) {\n const subgraph = prefix.split(\":\").pop()!;\n if (seenSubgraphs.has(subgraph)) {\n throw new Error(\n `Found duplicate subgraph '${subgraph}' -- this likely means that ` +\n \"you're reusing a subgraph node with the same name. \" +\n \"Please adjust your graph to have subgraph nodes with unique names.\"\n );\n }\n\n seenSubgraphs.add(subgraph);\n mermaidGraph += `\\tsubgraph ${subgraph}\\n`;\n }\n\n for (const edge of edges) {\n const { source, target, data, conditional } = edge;\n\n let edgeLabel = \"\";\n if (data !== undefined) {\n let edgeData = data;\n const words = edgeData.split(\" \");\n if (words.length > wrapLabelNWords) {\n edgeData = Array.from(\n { length: Math.ceil(words.length / wrapLabelNWords) },\n (_, i) =>\n words\n .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords)\n .join(\" \")\n ).join(\"&nbsp;<br>&nbsp;\");\n }\n edgeLabel = conditional\n ? ` -. &nbsp;${edgeData}&nbsp; .-> `\n : ` -- &nbsp;${edgeData}&nbsp; --> `;\n } else {\n edgeLabel = conditional ? \" -.-> \" : \" --> \";\n }\n\n mermaidGraph += `\\t${_escapeNodeLabel(\n source\n )}${edgeLabel}${_escapeNodeLabel(target)};\\n`;\n }\n\n // Recursively add nested subgraphs\n for (const nestedPrefix in edgeGroups) {\n if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) {\n addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);\n }\n }\n\n if (prefix && !selfLoop) {\n mermaidGraph += \"\\tend\\n\";\n }\n }\n\n // Start with the top-level edges (no common prefix)\n addSubgraph(edgeGroups[\"\"] ?? [], \"\");\n\n // Add remaining subgraphs\n for (const prefix in edgeGroups) {\n if (!prefix.includes(\":\") && prefix !== \"\") {\n addSubgraph(edgeGroups[prefix], prefix);\n }\n }\n\n // Add custom styles for nodes\n if (withStyles) {\n mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {});\n }\n\n return mermaidGraph;\n}\n\n/**\n * Renders Mermaid graph using the Mermaid.INK API.\n *\n * @example\n * ```javascript\n * const image = await drawMermaidImage(mermaidSyntax, {\n * backgroundColor: \"white\",\n * imageType: \"png\",\n * });\n * fs.writeFileSync(\"image.png\", image);\n * ```\n *\n * @param mermaidSyntax - The Mermaid syntax to render.\n * @param config - The configuration for the image.\n * @returns The image as a Blob.\n */\nexport async function drawMermaidImage(\n mermaidSyntax: string,\n config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }\n) {\n let backgroundColor = config?.backgroundColor ?? \"white\";\n const imageType = config?.imageType ?? \"png\";\n\n const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax);\n\n // Check if the background color is a hexadecimal color code using regex\n if (backgroundColor !== undefined) {\n const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;\n if (!hexColorPattern.test(backgroundColor)) {\n backgroundColor = `!${backgroundColor}`;\n }\n }\n const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`;\n const res = await fetch(imageUrl);\n if (!res.ok) {\n throw new Error(\n [\n `Failed to render the graph using the Mermaid.INK API.`,\n `Status code: ${res.status}`,\n `Status text: ${res.statusText}`,\n ].join(\"\\n\")\n );\n }\n const content = await res.blob();\n return content;\n}\n"],"mappings":";;;AAGA,SAAS,iBAAiBA,WAA2B;AAEnD,QAAO,UAAU,QAAQ,mBAAmB,IAAI;AACjD;AAED,MAAM,yBAAyB;CAAC;CAAK;CAAK;AAAI;AAE9C,SAAS,4BACPC,YACQ;CACR,IAAI,SAAS;AACb,MAAK,MAAM,CAAC,WAAW,MAAM,IAAI,OAAO,QAAQ,WAAW,EACzD,UAAU,CAAC,WAAW,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,CAAC;AAEjD,QAAO;AACR;;;;AAKD,SAAgB,YACdC,OACAC,OACAC,QAQQ;CACR,MAAM,EACJ,WACA,UACA,YACA,aAAa,MACb,aAAa,UACb,kBAAkB,GACnB,GAAG,UAAU,CAAE;CAEhB,IAAI,eAAe,aACf,CAAC,kCAAkC,EAAE,WAAW,mBAAmB,CAAC,GACpE;AACJ,KAAI,YAAY;EAEd,MAAM,oBAAoB;EAC1B,MAAMC,aAAqC,GACxC,oBAAoB,WACtB;AACD,MAAI,cAAc,QAChB,WAAW,aAAa;AAE1B,MAAI,aAAa,QACf,WAAW,YAAY;AAIzB,OAAK,MAAM,CAAC,KAAK,KAAK,IAAI,OAAO,QAAQ,MAAM,EAAE;GAC/C,MAAM,WAAW,KAAK,KAAK,MAAM,IAAI,CAAC,KAAK,IAAI;GAC/C,MAAM,QAAQ,uBAAuB,KACnC,CAAC,SAAS,SAAS,WAAW,KAAK,IAAI,SAAS,SAAS,KAAK,CAC/D,GACG,CAAC,GAAG,EAAE,SAAS,IAAI,CAAC,GACpB;GAEJ,IAAI,aAA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BAAgB,MAAM,EAAE,WAAW;CAC/G,MAAM,MAAM,MAAM,MAAM,SAAS;AACjC,KAAI,CAAC,IAAI,GACP,OAAM,IAAI,MACR;EACE,CAAC,qDAAqD,CAAC;EACvD,CAAC,aAAa,EAAE,IAAI,QAAQ;EAC5B,CAAC,aAAa,EAAE,IAAI,YAAY;CACjC,EAAC,KAAK,KAAK;CAGhB,MAAM,UAAU,MAAM,IAAI,MAAM;AAChC,QAAO;AACR"}
1
+ {"version":3,"file":"graph_mermaid.js","names":["nodeLabel: string","nodeColors: Record<string, string>","nodes: Record<string, Node>","edges: Edge[]","config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }","formatDict: Record<string, string>","edgeGroups: Record<string, Edge[]>","prefixes: string[]","prefix: string","edges","mermaidSyntax: string","config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }"],"sources":["../../src/runnables/graph_mermaid.ts"],"sourcesContent":["import { Edge, Node } from \"./types.js\";\nimport { toBase64Url } from \"./utils.js\";\n\nfunction _escapeNodeLabel(nodeLabel: string): string {\n // Escapes the node label for Mermaid syntax.\n return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, \"_\");\n}\n\nconst MARKDOWN_SPECIAL_CHARS = [\"*\", \"_\", \"`\"];\n\nfunction _generateMermaidGraphStyles(\n nodeColors: Record<string, string>\n): string {\n let styles = \"\";\n for (const [className, color] of Object.entries(nodeColors)) {\n styles += `\\tclassDef ${className} ${color};\\n`;\n }\n return styles;\n}\n\n/**\n * Draws a Mermaid graph using the provided graph data\n */\nexport function drawMermaid(\n nodes: Record<string, Node>,\n edges: Edge[],\n config?: {\n firstNode?: string;\n lastNode?: string;\n curveStyle?: string;\n withStyles?: boolean;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }\n): string {\n const {\n firstNode,\n lastNode,\n nodeColors,\n withStyles = true,\n curveStyle = \"linear\",\n wrapLabelNWords = 9,\n } = config ?? {};\n // Initialize Mermaid graph configuration\n let mermaidGraph = withStyles\n ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\\ngraph TD;\\n`\n : \"graph TD;\\n\";\n if (withStyles) {\n // Node formatting templates\n const defaultClassLabel = \"default\";\n const formatDict: Record<string, string> = {\n [defaultClassLabel]: \"{0}({1})\",\n };\n if (firstNode !== undefined) {\n formatDict[firstNode] = \"{0}([{1}]):::first\";\n }\n if (lastNode !== undefined) {\n formatDict[lastNode] = \"{0}([{1}]):::last\";\n }\n\n // Add nodes to the graph\n for (const [key, node] of Object.entries(nodes)) {\n const nodeName = node.name.split(\":\").pop() ?? \"\";\n const label = MARKDOWN_SPECIAL_CHARS.some(\n (char) => nodeName.startsWith(char) && nodeName.endsWith(char)\n )\n ? `<p>${nodeName}</p>`\n : nodeName;\n\n let finalLabel = label;\n if (Object.keys(node.metadata ?? {}).length) {\n finalLabel += `<hr/><small><em>${Object.entries(node.metadata ?? {})\n .map(([k, v]) => `${k} = ${v}`)\n .join(\"\\n\")}</em></small>`;\n }\n\n const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel])\n .replace(\"{0}\", _escapeNodeLabel(key))\n .replace(\"{1}\", finalLabel);\n\n mermaidGraph += `\\t${nodeLabel}\\n`;\n }\n }\n\n // Group edges by their common prefixes\n const edgeGroups: Record<string, Edge[]> = {};\n for (const edge of edges) {\n const srcParts = edge.source.split(\":\");\n const tgtParts = edge.target.split(\":\");\n const commonPrefix = srcParts\n .filter((src, i) => src === tgtParts[i])\n .join(\":\");\n if (!edgeGroups[commonPrefix]) {\n edgeGroups[commonPrefix] = [];\n }\n edgeGroups[commonPrefix].push(edge);\n }\n\n const seenSubgraphs = new Set<string>();\n\n // sort prefixes by path length for correct nesting\n function sortPrefixesByDepth(prefixes: string[]): string[] {\n return [...prefixes].sort((a, b) => {\n return a.split(\":\").length - b.split(\":\").length;\n });\n }\n\n function addSubgraph(edges: Edge[], prefix: string): void {\n const selfLoop = edges.length === 1 && edges[0].source === edges[0].target;\n if (prefix && !selfLoop) {\n const subgraph = prefix.split(\":\").pop()!;\n\n if (seenSubgraphs.has(prefix)) {\n throw new Error(\n `Found duplicate subgraph '${subgraph}' at '${prefix} -- this likely means that ` +\n \"you're reusing a subgraph node with the same name. \" +\n \"Please adjust your graph to have subgraph nodes with unique names.\"\n );\n }\n\n seenSubgraphs.add(prefix);\n mermaidGraph += `\\tsubgraph ${subgraph}\\n`;\n }\n\n // all nested prefixes for this level, sorted by depth\n const nestedPrefixes = sortPrefixesByDepth(\n Object.keys(edgeGroups).filter(\n (nestedPrefix) =>\n nestedPrefix.startsWith(`${prefix}:`) &&\n nestedPrefix !== prefix &&\n nestedPrefix.split(\":\").length === prefix.split(\":\").length + 1\n )\n );\n\n for (const nestedPrefix of nestedPrefixes) {\n addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);\n }\n\n for (const edge of edges) {\n const { source, target, data, conditional } = edge;\n\n let edgeLabel = \"\";\n if (data !== undefined) {\n let edgeData = data;\n const words = edgeData.split(\" \");\n if (words.length > wrapLabelNWords) {\n edgeData = Array.from(\n { length: Math.ceil(words.length / wrapLabelNWords) },\n (_, i) =>\n words\n .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords)\n .join(\" \")\n ).join(\"&nbsp;<br>&nbsp;\");\n }\n edgeLabel = conditional\n ? ` -. &nbsp;${edgeData}&nbsp; .-> `\n : ` -- &nbsp;${edgeData}&nbsp; --> `;\n } else {\n edgeLabel = conditional ? \" -.-> \" : \" --> \";\n }\n\n mermaidGraph += `\\t${_escapeNodeLabel(\n source\n )}${edgeLabel}${_escapeNodeLabel(target)};\\n`;\n }\n\n if (prefix && !selfLoop) {\n mermaidGraph += \"\\tend\\n\";\n }\n }\n\n // Start with the top-level edges (no common prefix)\n addSubgraph(edgeGroups[\"\"] ?? [], \"\");\n\n // Add remaining top-level subgraphs\n for (const prefix in edgeGroups) {\n if (!prefix.includes(\":\") && prefix !== \"\") {\n addSubgraph(edgeGroups[prefix], prefix);\n }\n }\n\n // Add custom styles for nodes\n if (withStyles) {\n mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {});\n }\n\n return mermaidGraph;\n}\n\n/**\n * Renders Mermaid graph using the Mermaid.INK API.\n *\n * @example\n * ```javascript\n * const image = await drawMermaidImage(mermaidSyntax, {\n * backgroundColor: \"white\",\n * imageType: \"png\",\n * });\n * fs.writeFileSync(\"image.png\", image);\n * ```\n *\n * @param mermaidSyntax - The Mermaid syntax to render.\n * @param config - The configuration for the image.\n * @returns The image as a Blob.\n */\nexport async function drawMermaidImage(\n mermaidSyntax: string,\n config?: {\n /**\n * The type of image to render.\n * @default \"png\"\n */\n imageType?: \"png\" | \"jpeg\" | \"webp\";\n backgroundColor?: string;\n }\n) {\n let backgroundColor = config?.backgroundColor ?? \"white\";\n const imageType = config?.imageType ?? \"png\";\n\n const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax);\n\n // Check if the background color is a hexadecimal color code using regex\n if (backgroundColor !== undefined) {\n const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;\n if (!hexColorPattern.test(backgroundColor)) {\n backgroundColor = `!${backgroundColor}`;\n }\n }\n const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`;\n const res = await fetch(imageUrl);\n if (!res.ok) {\n throw new Error(\n [\n `Failed to render the graph using the Mermaid.INK API.`,\n `Status code: ${res.status}`,\n `Status text: ${res.statusText}`,\n ].join(\"\\n\")\n );\n }\n const content = await res.blob();\n return content;\n}\n"],"mappings":";;;AAGA,SAAS,iBAAiBA,WAA2B;AAEnD,QAAO,UAAU,QAAQ,mBAAmB,IAAI;AACjD;AAED,MAAM,yBAAyB;CAAC;CAAK;CAAK;AAAI;AAE9C,SAAS,4BACPC,YACQ;CACR,IAAI,SAAS;AACb,MAAK,MAAM,CAAC,WAA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