@langchain/core 1.1.5 → 1.2.0-dev-1765937705265

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 (316) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/caches/index.d.cts +2 -2
  3. package/dist/caches/index.d.cts.map +1 -1
  4. package/dist/caches/index.d.ts +2 -2
  5. package/dist/caches/index.d.ts.map +1 -1
  6. package/dist/callbacks/base.d.cts +2 -2
  7. package/dist/callbacks/base.d.cts.map +1 -1
  8. package/dist/callbacks/base.d.ts +2 -2
  9. package/dist/callbacks/base.d.ts.map +1 -1
  10. package/dist/load/index.d.cts.map +1 -1
  11. package/dist/messages/ai.cjs +13 -9
  12. package/dist/messages/ai.cjs.map +1 -1
  13. package/dist/messages/ai.d.cts +25 -5
  14. package/dist/messages/ai.d.cts.map +1 -1
  15. package/dist/messages/ai.d.ts +25 -5
  16. package/dist/messages/ai.d.ts.map +1 -1
  17. package/dist/messages/ai.js +13 -9
  18. package/dist/messages/ai.js.map +1 -1
  19. package/dist/messages/base.cjs +2 -2
  20. package/dist/messages/base.cjs.map +1 -1
  21. package/dist/messages/base.d.cts +1 -1
  22. package/dist/messages/base.d.cts.map +1 -1
  23. package/dist/messages/base.d.ts +1 -1
  24. package/dist/messages/base.d.ts.map +1 -1
  25. package/dist/messages/base.js +2 -2
  26. package/dist/messages/base.js.map +1 -1
  27. package/dist/messages/index.d.cts +2 -2
  28. package/dist/messages/index.d.ts +2 -2
  29. package/dist/messages/message.cjs.map +1 -1
  30. package/dist/messages/message.d.cts +62 -6
  31. package/dist/messages/message.d.cts.map +1 -1
  32. package/dist/messages/message.d.ts +62 -6
  33. package/dist/messages/message.d.ts.map +1 -1
  34. package/dist/messages/message.js.map +1 -1
  35. package/dist/messages/tool.cjs.map +1 -1
  36. package/dist/messages/tool.d.cts +10 -0
  37. package/dist/messages/tool.d.cts.map +1 -1
  38. package/dist/messages/tool.d.ts +10 -0
  39. package/dist/messages/tool.d.ts.map +1 -1
  40. package/dist/messages/tool.js.map +1 -1
  41. package/dist/messages/utils.d.cts +3 -3
  42. package/dist/messages/utils.d.cts.map +1 -1
  43. package/dist/messages/utils.d.ts +3 -3
  44. package/dist/messages/utils.d.ts.map +1 -1
  45. package/dist/prompt_values.d.cts +4 -4
  46. package/dist/prompt_values.d.cts.map +1 -1
  47. package/dist/prompt_values.d.ts +4 -4
  48. package/dist/prompt_values.d.ts.map +1 -1
  49. package/dist/prompts/chat.d.cts +2 -2
  50. package/dist/prompts/chat.d.cts.map +1 -1
  51. package/dist/prompts/chat.d.ts +2 -2
  52. package/dist/prompts/chat.d.ts.map +1 -1
  53. package/dist/stores.d.cts.map +1 -1
  54. package/dist/stores.d.ts.map +1 -1
  55. package/dist/tools/index.cjs +2 -1
  56. package/dist/tools/index.cjs.map +1 -1
  57. package/dist/tools/index.d.cts +17 -12
  58. package/dist/tools/index.d.cts.map +1 -1
  59. package/dist/tools/index.d.ts +17 -12
  60. package/dist/tools/index.d.ts.map +1 -1
  61. package/dist/tools/index.js +2 -1
  62. package/dist/tools/index.js.map +1 -1
  63. package/dist/tracers/event_stream.cjs +5 -1
  64. package/dist/tracers/event_stream.cjs.map +1 -1
  65. package/dist/tracers/event_stream.d.cts.map +1 -1
  66. package/dist/tracers/event_stream.d.ts.map +1 -1
  67. package/dist/tracers/event_stream.js +5 -1
  68. package/dist/tracers/event_stream.js.map +1 -1
  69. package/dist/utils/event_source_parse.d.cts.map +1 -1
  70. package/dist/utils/stream.d.cts.map +1 -1
  71. package/dist/utils/testing/chat_models.cjs +4 -1
  72. package/dist/utils/testing/chat_models.cjs.map +1 -1
  73. package/dist/utils/testing/chat_models.d.cts +5 -5
  74. package/dist/utils/testing/chat_models.d.cts.map +1 -1
  75. package/dist/utils/testing/chat_models.d.ts +5 -5
  76. package/dist/utils/testing/chat_models.d.ts.map +1 -1
  77. package/dist/utils/testing/chat_models.js +4 -1
  78. package/dist/utils/testing/chat_models.js.map +1 -1
  79. package/dist/vectorstores.d.cts.map +1 -1
  80. package/package.json +2 -2
  81. package/agents.cjs +0 -1
  82. package/agents.d.cts +0 -1
  83. package/agents.d.ts +0 -1
  84. package/agents.js +0 -1
  85. package/caches.cjs +0 -1
  86. package/caches.d.cts +0 -1
  87. package/caches.d.ts +0 -1
  88. package/caches.js +0 -1
  89. package/callbacks/base.cjs +0 -1
  90. package/callbacks/base.d.cts +0 -1
  91. package/callbacks/base.d.ts +0 -1
  92. package/callbacks/base.js +0 -1
  93. package/callbacks/dispatch/web.cjs +0 -1
  94. package/callbacks/dispatch/web.d.cts +0 -1
  95. package/callbacks/dispatch/web.d.ts +0 -1
  96. package/callbacks/dispatch/web.js +0 -1
  97. package/callbacks/dispatch.cjs +0 -1
  98. package/callbacks/dispatch.d.cts +0 -1
  99. package/callbacks/dispatch.d.ts +0 -1
  100. package/callbacks/dispatch.js +0 -1
  101. package/callbacks/manager.cjs +0 -1
  102. package/callbacks/manager.d.cts +0 -1
  103. package/callbacks/manager.d.ts +0 -1
  104. package/callbacks/manager.js +0 -1
  105. package/callbacks/promises.cjs +0 -1
  106. package/callbacks/promises.d.cts +0 -1
  107. package/callbacks/promises.d.ts +0 -1
  108. package/callbacks/promises.js +0 -1
  109. package/chat_history.cjs +0 -1
  110. package/chat_history.d.cts +0 -1
  111. package/chat_history.d.ts +0 -1
  112. package/chat_history.js +0 -1
  113. package/context.cjs +0 -1
  114. package/context.d.cts +0 -1
  115. package/context.d.ts +0 -1
  116. package/context.js +0 -1
  117. package/document_loaders/base.cjs +0 -1
  118. package/document_loaders/base.d.cts +0 -1
  119. package/document_loaders/base.d.ts +0 -1
  120. package/document_loaders/base.js +0 -1
  121. package/document_loaders/langsmith.cjs +0 -1
  122. package/document_loaders/langsmith.d.cts +0 -1
  123. package/document_loaders/langsmith.d.ts +0 -1
  124. package/document_loaders/langsmith.js +0 -1
  125. package/documents.cjs +0 -1
  126. package/documents.d.cts +0 -1
  127. package/documents.d.ts +0 -1
  128. package/documents.js +0 -1
  129. package/embeddings.cjs +0 -1
  130. package/embeddings.d.cts +0 -1
  131. package/embeddings.d.ts +0 -1
  132. package/embeddings.js +0 -1
  133. package/example_selectors.cjs +0 -1
  134. package/example_selectors.d.cts +0 -1
  135. package/example_selectors.d.ts +0 -1
  136. package/example_selectors.js +0 -1
  137. package/indexing.cjs +0 -1
  138. package/indexing.d.cts +0 -1
  139. package/indexing.d.ts +0 -1
  140. package/indexing.js +0 -1
  141. package/language_models/base.cjs +0 -1
  142. package/language_models/base.d.cts +0 -1
  143. package/language_models/base.d.ts +0 -1
  144. package/language_models/base.js +0 -1
  145. package/language_models/chat_models.cjs +0 -1
  146. package/language_models/chat_models.d.cts +0 -1
  147. package/language_models/chat_models.d.ts +0 -1
  148. package/language_models/chat_models.js +0 -1
  149. package/language_models/llms.cjs +0 -1
  150. package/language_models/llms.d.cts +0 -1
  151. package/language_models/llms.d.ts +0 -1
  152. package/language_models/llms.js +0 -1
  153. package/language_models/profile.cjs +0 -1
  154. package/language_models/profile.d.cts +0 -1
  155. package/language_models/profile.d.ts +0 -1
  156. package/language_models/profile.js +0 -1
  157. package/load/serializable.cjs +0 -1
  158. package/load/serializable.d.cts +0 -1
  159. package/load/serializable.d.ts +0 -1
  160. package/load/serializable.js +0 -1
  161. package/load.cjs +0 -1
  162. package/load.d.cts +0 -1
  163. package/load.d.ts +0 -1
  164. package/load.js +0 -1
  165. package/memory.cjs +0 -1
  166. package/memory.d.cts +0 -1
  167. package/memory.d.ts +0 -1
  168. package/memory.js +0 -1
  169. package/messages/tool.cjs +0 -1
  170. package/messages/tool.d.cts +0 -1
  171. package/messages/tool.d.ts +0 -1
  172. package/messages/tool.js +0 -1
  173. package/messages.cjs +0 -1
  174. package/messages.d.cts +0 -1
  175. package/messages.d.ts +0 -1
  176. package/messages.js +0 -1
  177. package/output_parsers/openai_functions.cjs +0 -1
  178. package/output_parsers/openai_functions.d.cts +0 -1
  179. package/output_parsers/openai_functions.d.ts +0 -1
  180. package/output_parsers/openai_functions.js +0 -1
  181. package/output_parsers/openai_tools.cjs +0 -1
  182. package/output_parsers/openai_tools.d.cts +0 -1
  183. package/output_parsers/openai_tools.d.ts +0 -1
  184. package/output_parsers/openai_tools.js +0 -1
  185. package/output_parsers.cjs +0 -1
  186. package/output_parsers.d.cts +0 -1
  187. package/output_parsers.d.ts +0 -1
  188. package/output_parsers.js +0 -1
  189. package/outputs.cjs +0 -1
  190. package/outputs.d.cts +0 -1
  191. package/outputs.d.ts +0 -1
  192. package/outputs.js +0 -1
  193. package/prompt_values.cjs +0 -1
  194. package/prompt_values.d.cts +0 -1
  195. package/prompt_values.d.ts +0 -1
  196. package/prompt_values.js +0 -1
  197. package/prompts.cjs +0 -1
  198. package/prompts.d.cts +0 -1
  199. package/prompts.d.ts +0 -1
  200. package/prompts.js +0 -1
  201. package/retrievers/document_compressors.cjs +0 -1
  202. package/retrievers/document_compressors.d.cts +0 -1
  203. package/retrievers/document_compressors.d.ts +0 -1
  204. package/retrievers/document_compressors.js +0 -1
  205. package/retrievers.cjs +0 -1
  206. package/retrievers.d.cts +0 -1
  207. package/retrievers.d.ts +0 -1
  208. package/retrievers.js +0 -1
  209. package/runnables/graph.cjs +0 -1
  210. package/runnables/graph.d.cts +0 -1
  211. package/runnables/graph.d.ts +0 -1
  212. package/runnables/graph.js +0 -1
  213. package/runnables.cjs +0 -1
  214. package/runnables.d.cts +0 -1
  215. package/runnables.d.ts +0 -1
  216. package/runnables.js +0 -1
  217. package/singletons.cjs +0 -1
  218. package/singletons.d.cts +0 -1
  219. package/singletons.d.ts +0 -1
  220. package/singletons.js +0 -1
  221. package/stores.cjs +0 -1
  222. package/stores.d.cts +0 -1
  223. package/stores.d.ts +0 -1
  224. package/stores.js +0 -1
  225. package/structured_query.cjs +0 -1
  226. package/structured_query.d.cts +0 -1
  227. package/structured_query.d.ts +0 -1
  228. package/structured_query.js +0 -1
  229. package/tools.cjs +0 -1
  230. package/tools.d.cts +0 -1
  231. package/tools.d.ts +0 -1
  232. package/tools.js +0 -1
  233. package/tracers/base.cjs +0 -1
  234. package/tracers/base.d.cts +0 -1
  235. package/tracers/base.d.ts +0 -1
  236. package/tracers/base.js +0 -1
  237. package/tracers/console.cjs +0 -1
  238. package/tracers/console.d.cts +0 -1
  239. package/tracers/console.d.ts +0 -1
  240. package/tracers/console.js +0 -1
  241. package/tracers/log_stream.cjs +0 -1
  242. package/tracers/log_stream.d.cts +0 -1
  243. package/tracers/log_stream.d.ts +0 -1
  244. package/tracers/log_stream.js +0 -1
  245. package/tracers/run_collector.cjs +0 -1
  246. package/tracers/run_collector.d.cts +0 -1
  247. package/tracers/run_collector.d.ts +0 -1
  248. package/tracers/run_collector.js +0 -1
  249. package/tracers/tracer_langchain.cjs +0 -1
  250. package/tracers/tracer_langchain.d.cts +0 -1
  251. package/tracers/tracer_langchain.d.ts +0 -1
  252. package/tracers/tracer_langchain.js +0 -1
  253. package/types/stream.cjs +0 -1
  254. package/types/stream.d.cts +0 -1
  255. package/types/stream.d.ts +0 -1
  256. package/types/stream.js +0 -1
  257. package/utils/async_caller.cjs +0 -1
  258. package/utils/async_caller.d.cts +0 -1
  259. package/utils/async_caller.d.ts +0 -1
  260. package/utils/async_caller.js +0 -1
  261. package/utils/chunk_array.cjs +0 -1
  262. package/utils/chunk_array.d.cts +0 -1
  263. package/utils/chunk_array.d.ts +0 -1
  264. package/utils/chunk_array.js +0 -1
  265. package/utils/env.cjs +0 -1
  266. package/utils/env.d.cts +0 -1
  267. package/utils/env.d.ts +0 -1
  268. package/utils/env.js +0 -1
  269. package/utils/event_source_parse.cjs +0 -1
  270. package/utils/event_source_parse.d.cts +0 -1
  271. package/utils/event_source_parse.d.ts +0 -1
  272. package/utils/event_source_parse.js +0 -1
  273. package/utils/format.cjs +0 -1
  274. package/utils/format.d.cts +0 -1
  275. package/utils/format.d.ts +0 -1
  276. package/utils/format.js +0 -1
  277. package/utils/function_calling.cjs +0 -1
  278. package/utils/function_calling.d.cts +0 -1
  279. package/utils/function_calling.d.ts +0 -1
  280. package/utils/function_calling.js +0 -1
  281. package/utils/hash.cjs +0 -1
  282. package/utils/hash.d.cts +0 -1
  283. package/utils/hash.d.ts +0 -1
  284. package/utils/hash.js +0 -1
  285. package/utils/json_patch.cjs +0 -1
  286. package/utils/json_patch.d.cts +0 -1
  287. package/utils/json_patch.d.ts +0 -1
  288. package/utils/json_patch.js +0 -1
  289. package/utils/json_schema.cjs +0 -1
  290. package/utils/json_schema.d.cts +0 -1
  291. package/utils/json_schema.d.ts +0 -1
  292. package/utils/json_schema.js +0 -1
  293. package/utils/math.cjs +0 -1
  294. package/utils/math.d.cts +0 -1
  295. package/utils/math.d.ts +0 -1
  296. package/utils/math.js +0 -1
  297. package/utils/stream.cjs +0 -1
  298. package/utils/stream.d.cts +0 -1
  299. package/utils/stream.d.ts +0 -1
  300. package/utils/stream.js +0 -1
  301. package/utils/testing.cjs +0 -1
  302. package/utils/testing.d.cts +0 -1
  303. package/utils/testing.d.ts +0 -1
  304. package/utils/testing.js +0 -1
  305. package/utils/tiktoken.cjs +0 -1
  306. package/utils/tiktoken.d.cts +0 -1
  307. package/utils/tiktoken.d.ts +0 -1
  308. package/utils/tiktoken.js +0 -1
  309. package/utils/types.cjs +0 -1
  310. package/utils/types.d.cts +0 -1
  311. package/utils/types.d.ts +0 -1
  312. package/utils/types.js +0 -1
  313. package/vectorstores.cjs +0 -1
  314. package/vectorstores.d.cts +0 -1
  315. package/vectorstores.d.ts +0 -1
  316. package/vectorstores.js +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["fields?: ToolParams","input: TInput","config?: TConfig","toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >","enrichedConfig: ToolRunnableConfig","arg: TArg","configArg?: TConfig","tags?: string[]","parsed: SchemaOutputT","z4","result","toolCallId: string | undefined","callbacks?: TConfig","fields: DynamicToolInput<ToolOutputT>","input: string","runManager?: CallbackManagerForToolRun","parentConfig?: ToolRunnableConfig","fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>","arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0]","parentConfig?: RunnableConfig","func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>","fields: ToolWrapperParams<SchemaT>","listener: (() => void) | undefined","params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}","content: unknown"],"sources":["../../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4, ZodError } from \"zod/v4\";\nimport {\n validate,\n type Schema as ValidationSchema,\n} from \"@cfworker/json-schema\";\nimport {\n CallbackManager,\n CallbackManagerForToolRun,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport { BaseLangChain } from \"../language_models/base.js\";\nimport {\n mergeConfigs,\n ensureConfig,\n patchConfig,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"../runnables/config.js\";\nimport type { RunnableFunc } from \"../runnables/base.js\";\nimport { isDirectToolOutput, ToolCall, ToolMessage } from \"../messages/tool.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/index.js\";\nimport type { RunnableToolLike } from \"../runnables/base.js\";\nimport {\n _configHasToolCallId,\n _isToolCall,\n ToolInputParsingException,\n} from \"./utils.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodObject,\n type InteropZodType,\n interopParseAsync,\n isSimpleStringZodSchema,\n isInteropZodError,\n isInteropZodSchema,\n type ZodStringV3,\n type ZodStringV4,\n type ZodObjectV3,\n type ZodObjectV4,\n} from \"../utils/types/zod.js\";\nimport { getAbortSignalError } from \"../utils/signal.js\";\nimport type {\n StructuredToolCallInput,\n ToolInputSchemaBase,\n ToolReturnType,\n ResponseFormat,\n ToolInputSchemaInputType,\n ToolInputSchemaOutputType,\n ToolParams,\n ToolRunnableConfig,\n StructuredToolInterface,\n DynamicToolInput,\n DynamicStructuredToolInput,\n StringInputToolSchema,\n ToolInterface,\n ToolOutputType,\n ToolRuntime,\n} from \"./types.js\";\nimport { type JSONSchema, validatesOnlyStrings } from \"../utils/json_schema.js\";\n\nexport type {\n BaseDynamicToolInput,\n ContentAndArtifact,\n DynamicToolInput,\n DynamicStructuredToolInput,\n ResponseFormat,\n StructuredToolCallInput,\n StructuredToolInterface,\n StructuredToolParams,\n ToolInterface,\n ToolParams,\n ToolReturnType,\n ToolRunnableConfig,\n ToolInputSchemaBase as ToolSchemaBase,\n} from \"./types.js\";\n\nexport {\n isLangChainTool,\n isRunnableToolLike,\n isStructuredTool,\n isStructuredToolParams,\n type ToolRuntime,\n} from \"./types.js\";\n\nexport { ToolInputParsingException };\n/**\n * Base class for Tools that accept input of any shape defined by a Zod schema.\n */\nexport abstract class StructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n >\n extends BaseLangChain<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n >\n implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT>\n{\n abstract name: string;\n\n abstract description: string;\n\n abstract schema: SchemaT;\n\n /**\n * Optional provider-specific extra fields for the tool.\n *\n * This is used to pass provider-specific configuration that doesn't fit into\n * standard tool fields.\n */\n extras?: Record<string, unknown>;\n\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect = false;\n\n verboseParsingErrors = false;\n\n get lc_namespace() {\n return [\"langchain\", \"tools\"];\n }\n\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat = \"content\";\n\n /**\n * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n\n constructor(fields?: ToolParams) {\n super(fields ?? {});\n\n this.verboseParsingErrors =\n fields?.verboseParsingErrors ?? this.verboseParsingErrors;\n this.responseFormat = fields?.responseFormat ?? this.responseFormat;\n this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig;\n this.metadata = fields?.metadata ?? this.metadata;\n this.extras = fields?.extras ?? this.extras;\n }\n\n protected abstract _call(\n arg: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT>;\n\n /**\n * Invokes the tool with the provided input and configuration.\n * @param input The input for the tool.\n * @param config Optional configuration for the tool.\n * @returns A Promise that resolves with the tool's output.\n */\n async invoke<\n TInput extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n input: TInput,\n config?: TConfig\n ): Promise<ToolReturnType<TInput, TConfig, ToolOutputT>> {\n let toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n\n let enrichedConfig: ToolRunnableConfig = ensureConfig(\n mergeConfigs(this.defaultConfig, config)\n );\n if (_isToolCall(input)) {\n toolInput = input.args as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n enrichedConfig = {\n ...enrichedConfig,\n toolCall: input,\n };\n } else {\n toolInput = input as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n }\n\n return this.call(toolInput, enrichedConfig) as Promise<\n ToolReturnType<TInput, TConfig, ToolOutputT>\n >;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument, configuration, and tags. It\n * parses the input according to the schema, handles any errors, and\n * manages callbacks.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration or callbacks for the tool.\n * @param tags Optional tags for the tool.\n * @returns A Promise that resolves with a string.\n */\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>> {\n // Determine the actual input that needs parsing/validation.\n // If arg is a ToolCall, use its args; otherwise, use arg directly.\n const inputForValidation = _isToolCall(arg) ? arg.args : arg;\n\n let parsed: SchemaOutputT; // This will hold the successfully parsed input of the expected output type.\n if (isInteropZodSchema(this.schema)) {\n try {\n // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check\n parsed = await interopParseAsync(\n this.schema as InteropZodType,\n inputForValidation as Exclude<TArg, ToolCall>\n );\n } catch (e) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${(e as Error).message}`;\n }\n if (isInteropZodError(e)) {\n message = `${message}\\n\\n${z4.prettifyError(e as ZodError)}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n } else {\n const result = validate(\n inputForValidation,\n this.schema as ValidationSchema\n );\n if (!result.valid) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${result.errors\n .map((e) => `${e.keywordLocation}: ${e.error}`)\n .join(\"\\n\")}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n // Assign the validated input to parsed\n // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.\n parsed = inputForValidation as SchemaOutputT;\n }\n\n const config = parseCallbackConfigArg(configArg);\n const callbackManager_ = CallbackManager.configure(\n config.callbacks,\n this.callbacks,\n config.tags || tags,\n this.tags,\n config.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const runManager = await callbackManager_?.handleToolStart(\n this.toJSON(),\n // Log the original raw input arg\n typeof arg === \"string\" ? arg : JSON.stringify(arg),\n config.runId,\n undefined,\n undefined,\n undefined,\n config.runName\n );\n delete config.runId;\n let result;\n try {\n // Pass the correctly typed parsed input to _call\n result = await this._call(parsed, runManager, config);\n } catch (e) {\n await runManager?.handleToolError(e);\n throw e;\n }\n let content;\n let artifact;\n if (this.responseFormat === \"content_and_artifact\") {\n if (Array.isArray(result) && result.length === 2) {\n [content, artifact] = result;\n } else {\n throw new Error(\n `Tool response format is \"content_and_artifact\" but the output was not a two-tuple.\\nResult: ${JSON.stringify(\n result\n )}`\n );\n }\n } else {\n content = result;\n }\n\n let toolCallId: string | undefined;\n // Extract toolCallId ONLY if the original arg was a ToolCall\n if (_isToolCall(arg)) {\n toolCallId = arg.id;\n }\n // Or if it was provided in the config's toolCall property\n if (!toolCallId && _configHasToolCallId(config)) {\n toolCallId = config.toolCall.id;\n }\n\n const formattedOutput = _formatToolOutput<ToolOutputT>({\n content,\n artifact,\n toolCallId,\n name: this.name,\n metadata: this.metadata,\n });\n await runManager?.handleToolEnd(formattedOutput);\n return formattedOutput as ToolReturnType<TArg, TConfig, ToolOutputT>;\n }\n}\n\n/**\n * Base class for Tools that accept input as a string.\n */\nexport abstract class Tool<ToolOutputT = ToolOutputType>\n extends StructuredTool<\n StringInputToolSchema,\n ToolInputSchemaOutputType<StringInputToolSchema>,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n implements\n ToolInterface<\n StringInputToolSchema,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n{\n schema = z\n .object({ input: z.string().optional() })\n .transform((obj) => obj.input);\n\n constructor(fields?: ToolParams) {\n super(fields);\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument and callbacks. It handles\n * string inputs specifically.\n * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.\n * @param callbacks Optional callbacks for the tool.\n * @returns A Promise that resolves with a string.\n */\n // Match the base class signature including the generics and conditional return type\n call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n // Prepare the input for the base class call method.\n // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.\n const structuredArg =\n typeof arg === \"string\" || arg == null ? { input: arg } : arg;\n\n // Ensure TConfig is passed to super.call\n return super.call(structuredArg, callbacks);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and description.\n */\nexport class DynamicTool<\n ToolOutputT = ToolOutputType\n> extends Tool<ToolOutputT> {\n static lc_name() {\n return \"DynamicTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicToolInput<ToolOutputT>[\"func\"];\n\n constructor(fields: DynamicToolInput<ToolOutputT>) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n async call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n // Call the Tool class's call method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig);\n }\n\n /** @ignore */\n async _call(\n input: string, // DynamicTool's _call specifically expects a string after schema transformation\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(input, runManager, parentConfig);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and\n * description, designed to work with structured data. It extends the\n * StructuredTool class and overrides the _call method to execute the\n * provided function when the tool is called.\n *\n * Schema can be passed as Zod or JSON schema. The tool will not validate\n * input if JSON schema is passed.\n */\nexport class DynamicStructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT> {\n static lc_name() {\n return \"DynamicStructuredTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>[\"func\"];\n\n schema: SchemaT;\n\n constructor(\n fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>\n ) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n this.schema = fields.schema;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n // Match the base class signature\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n\n // Call the base class method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig, tags);\n }\n\n protected _call(\n arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0],\n runManager?: CallbackManagerForToolRun,\n parentConfig?: RunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(arg, runManager, parentConfig);\n }\n}\n\n/**\n * Abstract base class for toolkits in LangChain. Toolkits are collections\n * of tools that agents can use. Subclasses must implement the `tools`\n * property to provide the specific tools for the toolkit.\n */\nexport abstract class BaseToolkit {\n abstract tools: StructuredToolInterface[];\n\n getTools(): StructuredToolInterface[] {\n return this.tools;\n }\n}\n\n/**\n * Parameters for the tool function.\n * Schema can be provided as Zod or JSON schema.\n * Both schema types will be validated.\n * @template {ToolInputSchemaBase} RunInput The input schema for the tool.\n */\ninterface ToolWrapperParams<RunInput = ToolInputSchemaBase | undefined>\n extends ToolParams {\n /**\n * The name of the tool. If using with an LLM, this\n * will be passed as the tool name.\n */\n name: string;\n /**\n * The description of the tool.\n * @default `${fields.name} tool`\n */\n description?: string;\n /**\n * The input schema for the tool. If using an LLM, this\n * will be passed as the tool schema to generate arguments\n * for.\n */\n schema?: RunInput;\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat;\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect?: boolean;\n}\n\n/**\n * Creates a new StructuredTool instance with the provided function, name, description, and schema.\n *\n * Schema can be provided as Zod or JSON schema, and both will be validated.\n *\n * @function\n * @template {ToolInputSchemaBase} SchemaT The input schema for the tool.\n * @template {ToolReturnType} ToolOutputT The output type of the tool.\n *\n * @param {RunnableFunc<z.output<SchemaT>, ToolOutputT>} func - The function to invoke when the tool is called.\n * @param {ToolWrapperParams<SchemaT>} fields - An object containing the following properties:\n * @param {string} fields.name The name of the tool.\n * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.\n * @param {z.AnyZodObject | z.ZodString | undefined} fields.schema The Zod schema defining the input for the tool. If undefined, it will default to a Zod string schema.\n *\n * @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.\n */\nexport function tool<SchemaT extends ZodStringV3, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<SchemaT extends ZodStringV4, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT>\n):\n | DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>\n | DynamicTool<ToolOutputT>;\n\n// Overloads with ToolRuntime as CallOptions\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n):\n | DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>\n | DynamicTool<ToolOutputT> {\n const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema);\n const isStringJSONSchema = validatesOnlyStrings(fields.schema);\n\n // If the schema is not provided, or it's a simple string schema, create a DynamicTool\n if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) {\n return new DynamicTool<ToolOutputT>({\n ...fields,\n description:\n fields.description ??\n (fields.schema as { description?: string } | undefined)?.description ??\n `${fields.name} tool`,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(func(input as any, childConfig as any));\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n });\n }\n\n const schema = fields.schema as InteropZodObject | JSONSchema;\n\n const description =\n fields.description ??\n (fields.schema as { description?: string }).description ??\n `${fields.name} tool`;\n\n return new DynamicStructuredTool<\n typeof schema,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT\n >({\n ...fields,\n description,\n schema,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n let listener: (() => void) | undefined;\n const cleanup = () => {\n if (config?.signal && listener) {\n config.signal.removeEventListener(\"abort\", listener);\n }\n };\n\n if (config?.signal) {\n listener = () => {\n cleanup();\n reject(getAbortSignalError(config.signal));\n };\n config.signal.addEventListener(\"abort\", listener);\n }\n\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await func(input as any, childConfig as any);\n\n /**\n * If the signal is aborted, we don't want to resolve the promise\n * as the promise is already rejected.\n */\n if (config?.signal?.aborted) {\n cleanup();\n return;\n }\n\n cleanup();\n resolve(result);\n } catch (e) {\n cleanup();\n reject(e);\n }\n }\n );\n });\n },\n }) as DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT\n >;\n}\n\nfunction _formatToolOutput<TOutput extends ToolOutputType>(params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}): ToolMessage | TOutput {\n const { content, artifact, toolCallId, metadata } = params;\n if (toolCallId && !isDirectToolOutput(content)) {\n if (\n typeof content === \"string\" ||\n (Array.isArray(content) &&\n content.every((item) => typeof item === \"object\"))\n ) {\n return new ToolMessage({\n status: \"success\",\n content,\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n } else {\n return new ToolMessage({\n status: \"success\",\n content: _stringify(content),\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n }\n } else {\n return content;\n }\n}\n\nfunction _stringify(content: unknown): string {\n try {\n return JSON.stringify(content, null, 2) ?? \"\";\n } catch (_noOp) {\n return `${content}`;\n }\n}\n\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool =\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,IAAsB,iBAAtB,cAMU,cAKV;;;;;;;CAaE;;;;;;;CAQA,eAAe;CAEf,uBAAuB;CAEvB,IAAI,eAAe;AACjB,SAAO,CAAC,aAAa,OAAQ;CAC9B;;;;;;;;;;CAWD,iBAAkC;;;;CAKlC;CAEA,YAAYA,QAAqB;EAC/B,MAAM,UAAU,CAAE,EAAC;EAEnB,KAAK,uBACH,QAAQ,wBAAwB,KAAK;EACvC,KAAK,iBAAiB,QAAQ,kBAAkB,KAAK;EACrD,KAAK,gBAAgB,QAAQ,iBAAiB,KAAK;EACnD,KAAK,WAAW,QAAQ,YAAY,KAAK;EACzC,KAAK,SAAS,QAAQ,UAAU,KAAK;CACtC;;;;;;;CAcD,MAAM,OAIJC,OACAC,QACuD;EACvD,IAAIC;EAKJ,IAAIC,iBAAqC,aACvC,aAAa,KAAK,eAAe,OAAO,CACzC;AACD,MAAI,YAAY,MAAM,EAAE;GACtB,YAAY,MAAM;GAIlB,iBAAiB;IACf,GAAG;IACH,UAAU;GACX;EACF,OACC,YAAY;AAMd,SAAO,KAAK,KAAK,WAAW,eAAe;CAG5C;;;;;;;;;;;;CAaD,MAAM,KAIJC,KACAC,WAEAC,MACqD;EAGrD,MAAM,qBAAqB,YAAY,IAAI,GAAG,IAAI,OAAO;EAEzD,IAAIC;AACJ,MAAI,mBAAmB,KAAK,OAAO,CACjC,KAAI;GAEF,SAAS,MAAM,kBACb,KAAK,QACL,mBACD;EACF,SAAQ,GAAG;GACV,IAAI,UAAU,CAAC,iDAAiD,CAAC;AACjE,OAAI,KAAK,sBACP,UAAU,GAAG,QAAQ,WAAW,EAAG,EAAY,SAAS;AAE1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SAAS,WAAW;IACnD,IAAIC;IACJ,MAAM,UAAU,MAAM;AACpB,SAAI,QAAQ,UAAU,UACpB,OAAO,OAAO,oBAAoB,SAAS,SAAS;IAEvD;AAED,QAAI,QAAQ,QAAQ;KAClB,WAAW,MAAM;MACf,SAAS;MACT,OAAO,oBAAoB,OAAO,OAAO,CAAC;KAC3C;KACD,OAAO,OAAO,iBAAiB,SAAS,SAAS;IAClD;IAED,MAAM,cAAc,YAAY,QAAQ,EACtC,WAAW,YAAY,UAAU,CAClC,EAAC;IAEG,mCAAmC,cACtC,uBAAuB,YAAY,EACnC,YAAY;AACV,SAAI;MAEF,MAAM,SAAS,MAAM,KAAK,OAAc,YAAmB;;;;;AAM3D,UAAI,QAAQ,QAAQ,SAAS;OAC3B,SAAS;AACT;MACD;MAED,SAAS;MACT,QAAQ,OAAO;KAChB,SAAQ,GAAG;MACV,SAAS;MACT,OAAO,EAAE;KACV;IACF,EACF;GACF;EACF;CACF;AAMF;AAED,SAAS,kBAAkDC,QAMjC;CACxB,MAAM,EAAE,SAAS,UAAU,YAAY,UAAU,GAAG;AACpD,KAAI,cAAc,CAAC,mBAAmB,QAAQ,CAC5C,KACE,OAAO,YAAY,YAClB,MAAM,QAAQ,QAAQ,IACrB,QAAQ,MAAM,CAAC,SAAS,OAAO,SAAS,SAAS,CAEnD,QAAO,IAAI,YAAY;EACrB,QAAQ;EACR;EACA;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAED,QAAO,IAAI,YAAY;EACrB,QAAQ;EACR,SAAS,WAAW,QAAQ;EAC5B;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAGH,QAAO;AAEV;AAED,SAAS,WAAWC,SAA0B;AAC5C,KAAI;AACF,SAAO,KAAK,UAAU,SAAS,MAAM,EAAE,IAAI;CAC5C,SAAQ,OAAO;AACd,SAAO,GAAG,SAAS;CACpB;AACF"}
1
+ {"version":3,"file":"index.js","names":["fields?: ToolParams","input: TInput","config?: TConfig","toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >","enrichedConfig: ToolRunnableConfig","arg: TArg","configArg?: TConfig","tags?: string[]","parsed: SchemaOutputT","z4","result","toolCallId: string | undefined","callbacks?: TConfig","fields: DynamicToolInput<ToolOutputT>","input: string","runManager?: CallbackManagerForToolRun","parentConfig?: ToolRunnableConfig","fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT> & {\n name: NameT;\n }","arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0]","parentConfig?: RunnableConfig","func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>","fields: ToolWrapperParams<SchemaT, NameT>","listener: (() => void) | undefined","params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}","content: unknown"],"sources":["../../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4, ZodError } from \"zod/v4\";\nimport {\n validate,\n type Schema as ValidationSchema,\n} from \"@cfworker/json-schema\";\nimport {\n CallbackManager,\n CallbackManagerForToolRun,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport { BaseLangChain } from \"../language_models/base.js\";\nimport {\n mergeConfigs,\n ensureConfig,\n patchConfig,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"../runnables/config.js\";\nimport type { RunnableFunc } from \"../runnables/base.js\";\nimport { isDirectToolOutput, ToolCall, ToolMessage } from \"../messages/tool.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/index.js\";\nimport type { RunnableToolLike } from \"../runnables/base.js\";\nimport {\n _configHasToolCallId,\n _isToolCall,\n ToolInputParsingException,\n} from \"./utils.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodObject,\n type InteropZodType,\n interopParseAsync,\n isSimpleStringZodSchema,\n isInteropZodError,\n isInteropZodSchema,\n type ZodStringV3,\n type ZodStringV4,\n type ZodObjectV3,\n type ZodObjectV4,\n} from \"../utils/types/zod.js\";\nimport { getAbortSignalError } from \"../utils/signal.js\";\nimport type {\n StructuredToolCallInput,\n ToolInputSchemaBase,\n ToolReturnType,\n ResponseFormat,\n ToolInputSchemaInputType,\n ToolInputSchemaOutputType,\n ToolParams,\n ToolRunnableConfig,\n StructuredToolInterface,\n DynamicToolInput,\n DynamicStructuredToolInput,\n StringInputToolSchema,\n ToolInterface,\n ToolOutputType,\n ToolRuntime,\n} from \"./types.js\";\nimport { type JSONSchema, validatesOnlyStrings } from \"../utils/json_schema.js\";\n\nexport type {\n BaseDynamicToolInput,\n ContentAndArtifact,\n DynamicToolInput,\n DynamicStructuredToolInput,\n ResponseFormat,\n StructuredToolCallInput,\n StructuredToolInterface,\n StructuredToolParams,\n ToolInterface,\n ToolParams,\n ToolReturnType,\n ToolRunnableConfig,\n ToolInputSchemaBase as ToolSchemaBase,\n} from \"./types.js\";\n\nexport {\n isLangChainTool,\n isRunnableToolLike,\n isStructuredTool,\n isStructuredToolParams,\n type ToolRuntime,\n} from \"./types.js\";\n\nexport { ToolInputParsingException };\n/**\n * Base class for Tools that accept input of any shape defined by a Zod schema.\n */\nexport abstract class StructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n >\n extends BaseLangChain<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n >\n implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT>\n{\n abstract name: string;\n\n abstract description: string;\n\n abstract schema: SchemaT;\n\n /**\n * Optional provider-specific extra fields for the tool.\n *\n * This is used to pass provider-specific configuration that doesn't fit into\n * standard tool fields.\n */\n extras?: Record<string, unknown>;\n\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect = false;\n\n verboseParsingErrors = false;\n\n get lc_namespace() {\n return [\"langchain\", \"tools\"];\n }\n\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat = \"content\";\n\n /**\n * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n\n constructor(fields?: ToolParams) {\n super(fields ?? {});\n\n this.verboseParsingErrors =\n fields?.verboseParsingErrors ?? this.verboseParsingErrors;\n this.responseFormat = fields?.responseFormat ?? this.responseFormat;\n this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig;\n this.metadata = fields?.metadata ?? this.metadata;\n this.extras = fields?.extras ?? this.extras;\n }\n\n protected abstract _call(\n arg: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT>;\n\n /**\n * Invokes the tool with the provided input and configuration.\n * @param input The input for the tool.\n * @param config Optional configuration for the tool.\n * @returns A Promise that resolves with the tool's output.\n */\n async invoke<\n TInput extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n input: TInput,\n config?: TConfig\n ): Promise<ToolReturnType<TInput, TConfig, ToolOutputT>> {\n let toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n\n let enrichedConfig: ToolRunnableConfig = ensureConfig(\n mergeConfigs(this.defaultConfig, config)\n );\n if (_isToolCall(input)) {\n toolInput = input.args as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n enrichedConfig = {\n ...enrichedConfig,\n toolCall: input,\n };\n } else {\n toolInput = input as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n }\n\n return this.call(toolInput, enrichedConfig) as Promise<\n ToolReturnType<TInput, TConfig, ToolOutputT>\n >;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument, configuration, and tags. It\n * parses the input according to the schema, handles any errors, and\n * manages callbacks.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration or callbacks for the tool.\n * @param tags Optional tags for the tool.\n * @returns A Promise that resolves with a string.\n */\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>> {\n // Determine the actual input that needs parsing/validation.\n // If arg is a ToolCall, use its args; otherwise, use arg directly.\n const inputForValidation = _isToolCall(arg) ? arg.args : arg;\n\n let parsed: SchemaOutputT; // This will hold the successfully parsed input of the expected output type.\n if (isInteropZodSchema(this.schema)) {\n try {\n // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check\n parsed = await interopParseAsync(\n this.schema as InteropZodType,\n inputForValidation as Exclude<TArg, ToolCall>\n );\n } catch (e) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${(e as Error).message}`;\n }\n if (isInteropZodError(e)) {\n message = `${message}\\n\\n${z4.prettifyError(e as ZodError)}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n } else {\n const result = validate(\n inputForValidation,\n this.schema as ValidationSchema\n );\n if (!result.valid) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${result.errors\n .map((e) => `${e.keywordLocation}: ${e.error}`)\n .join(\"\\n\")}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n // Assign the validated input to parsed\n // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.\n parsed = inputForValidation as SchemaOutputT;\n }\n\n const config = parseCallbackConfigArg(configArg);\n const callbackManager_ = CallbackManager.configure(\n config.callbacks,\n this.callbacks,\n config.tags || tags,\n this.tags,\n config.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const runManager = await callbackManager_?.handleToolStart(\n this.toJSON(),\n // Log the original raw input arg\n typeof arg === \"string\" ? arg : JSON.stringify(arg),\n config.runId,\n undefined,\n undefined,\n undefined,\n config.runName\n );\n delete config.runId;\n let result;\n try {\n // Pass the correctly typed parsed input to _call\n result = await this._call(parsed, runManager, config);\n } catch (e) {\n await runManager?.handleToolError(e);\n throw e;\n }\n let content;\n let artifact;\n if (this.responseFormat === \"content_and_artifact\") {\n if (Array.isArray(result) && result.length === 2) {\n [content, artifact] = result;\n } else {\n throw new Error(\n `Tool response format is \"content_and_artifact\" but the output was not a two-tuple.\\nResult: ${JSON.stringify(\n result\n )}`\n );\n }\n } else {\n content = result;\n }\n\n let toolCallId: string | undefined;\n // Extract toolCallId ONLY if the original arg was a ToolCall\n if (_isToolCall(arg)) {\n toolCallId = arg.id;\n }\n // Or if it was provided in the config's toolCall property\n if (!toolCallId && _configHasToolCallId(config)) {\n toolCallId = config.toolCall.id;\n }\n\n const formattedOutput = _formatToolOutput<ToolOutputT>({\n content,\n artifact,\n toolCallId,\n name: this.name,\n metadata: this.metadata,\n });\n await runManager?.handleToolEnd(formattedOutput);\n return formattedOutput as ToolReturnType<TArg, TConfig, ToolOutputT>;\n }\n}\n\n/**\n * Base class for Tools that accept input as a string.\n */\nexport abstract class Tool<ToolOutputT = ToolOutputType>\n extends StructuredTool<\n StringInputToolSchema,\n ToolInputSchemaOutputType<StringInputToolSchema>,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n implements\n ToolInterface<\n StringInputToolSchema,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n{\n schema = z\n .object({ input: z.string().optional() })\n .transform((obj) => obj.input);\n\n constructor(fields?: ToolParams) {\n super(fields);\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument and callbacks. It handles\n * string inputs specifically.\n * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.\n * @param callbacks Optional callbacks for the tool.\n * @returns A Promise that resolves with a string.\n */\n // Match the base class signature including the generics and conditional return type\n call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n // Prepare the input for the base class call method.\n // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.\n const structuredArg =\n typeof arg === \"string\" || arg == null ? { input: arg } : arg;\n\n // Ensure TConfig is passed to super.call\n return super.call(structuredArg, callbacks);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and description.\n */\nexport class DynamicTool<\n ToolOutputT = ToolOutputType\n> extends Tool<ToolOutputT> {\n static lc_name() {\n return \"DynamicTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicToolInput<ToolOutputT>[\"func\"];\n\n constructor(fields: DynamicToolInput<ToolOutputT>) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n async call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n // Call the Tool class's call method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig);\n }\n\n /** @ignore */\n async _call(\n input: string, // DynamicTool's _call specifically expects a string after schema transformation\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(input, runManager, parentConfig);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and\n * description, designed to work with structured data. It extends the\n * StructuredTool class and overrides the _call method to execute the\n * provided function when the tool is called.\n *\n * Schema can be passed as Zod or JSON schema. The tool will not validate\n * input if JSON schema is passed.\n *\n * @template NameT The literal type of the tool name (for discriminated union support)\n */\nexport class DynamicStructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n NameT extends string = string\n> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT> {\n static lc_name() {\n return \"DynamicStructuredTool\";\n }\n\n declare name: NameT;\n\n description: string;\n\n func: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>[\"func\"];\n\n schema: SchemaT;\n\n constructor(\n fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT> & {\n name: NameT;\n }\n ) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n this.schema = fields.schema;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n // Match the base class signature\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n\n // Call the base class method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig, tags);\n }\n\n protected _call(\n arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0],\n runManager?: CallbackManagerForToolRun,\n parentConfig?: RunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(arg, runManager, parentConfig);\n }\n}\n\n/**\n * Abstract base class for toolkits in LangChain. Toolkits are collections\n * of tools that agents can use. Subclasses must implement the `tools`\n * property to provide the specific tools for the toolkit.\n */\nexport abstract class BaseToolkit {\n abstract tools: StructuredToolInterface[];\n\n getTools(): StructuredToolInterface[] {\n return this.tools;\n }\n}\n\n/**\n * Parameters for the tool function.\n * Schema can be provided as Zod or JSON schema.\n * Both schema types will be validated.\n * @template {ToolInputSchemaBase} RunInput The input schema for the tool.\n * @template {string} NameT The literal name type for discriminated union support.\n */\ninterface ToolWrapperParams<\n RunInput = ToolInputSchemaBase | undefined,\n NameT extends string = string\n> extends ToolParams {\n /**\n * The name of the tool. If using with an LLM, this\n * will be passed as the tool name.\n */\n name: NameT;\n /**\n * The description of the tool.\n * @default `${fields.name} tool`\n */\n description?: string;\n /**\n * The input schema for the tool. If using an LLM, this\n * will be passed as the tool schema to generate arguments\n * for.\n */\n schema?: RunInput;\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat;\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect?: boolean;\n}\n\n/**\n * Creates a new StructuredTool instance with the provided function, name, description, and schema.\n *\n * Schema can be provided as Zod or JSON schema, and both will be validated.\n *\n * @function\n * @template {ToolInputSchemaBase} SchemaT The input schema for the tool.\n * @template {ToolReturnType} ToolOutputT The output type of the tool.\n *\n * @param {RunnableFunc<z.output<SchemaT>, ToolOutputT>} func - The function to invoke when the tool is called.\n * @param {ToolWrapperParams<SchemaT>} fields - An object containing the following properties:\n * @param {string} fields.name The name of the tool.\n * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.\n * @param {z.AnyZodObject | z.ZodString | undefined} fields.schema The Zod schema defining the input for the tool. If undefined, it will default to a Zod string schema.\n *\n * @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.\n */\nexport function tool<SchemaT extends ZodStringV3, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<SchemaT extends ZodStringV4, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >\n | DynamicTool<ToolOutputT>;\n\n// Overloads with ToolRuntime as CallOptions\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >\n | DynamicTool<ToolOutputT> {\n const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema);\n const isStringJSONSchema = validatesOnlyStrings(fields.schema);\n\n // If the schema is not provided, or it's a simple string schema, create a DynamicTool\n if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) {\n return new DynamicTool<ToolOutputT>({\n ...fields,\n description:\n fields.description ??\n (fields.schema as { description?: string } | undefined)?.description ??\n `${fields.name} tool`,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(func(input as any, childConfig as any));\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n });\n }\n\n const schema = fields.schema as InteropZodObject | JSONSchema;\n\n const description =\n fields.description ??\n (fields.schema as { description?: string }).description ??\n `${fields.name} tool`;\n\n return new DynamicStructuredTool<\n typeof schema,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >({\n ...fields,\n description,\n schema,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n let listener: (() => void) | undefined;\n const cleanup = () => {\n if (config?.signal && listener) {\n config.signal.removeEventListener(\"abort\", listener);\n }\n };\n\n if (config?.signal) {\n listener = () => {\n cleanup();\n reject(getAbortSignalError(config.signal));\n };\n config.signal.addEventListener(\"abort\", listener);\n }\n\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await func(input as any, childConfig as any);\n\n /**\n * If the signal is aborted, we don't want to resolve the promise\n * as the promise is already rejected.\n */\n if (config?.signal?.aborted) {\n cleanup();\n return;\n }\n\n cleanup();\n resolve(result);\n } catch (e) {\n cleanup();\n reject(e);\n }\n }\n );\n });\n },\n }) as DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >;\n}\n\nfunction _formatToolOutput<TOutput extends ToolOutputType>(params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}): ToolMessage | TOutput {\n const { content, artifact, toolCallId, metadata } = params;\n if (toolCallId && !isDirectToolOutput(content)) {\n if (\n typeof content === \"string\" ||\n (Array.isArray(content) &&\n content.every((item) => typeof item === \"object\"))\n ) {\n return new ToolMessage({\n status: \"success\",\n content,\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n } else {\n return new ToolMessage({\n status: \"success\",\n content: _stringify(content),\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n }\n } else {\n return content;\n }\n}\n\nfunction _stringify(content: unknown): string {\n try {\n return JSON.stringify(content, null, 2) ?? \"\";\n } catch (_noOp) {\n return `${content}`;\n }\n}\n\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool =\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,IAAsB,iBAAtB,cAMU,cAKV;;;;;;;CAaE;;;;;;;CAQA,eAAe;CAEf,uBAAuB;CAEvB,IAAI,eAAe;AACjB,SAAO,CAAC,aAAa,OAAQ;CAC9B;;;;;;;;;;CAWD,iBAAkC;;;;CAKlC;CAEA,YAAYA,QAAqB;EAC/B,MAAM,UAAU,CAAE,EAAC;EAEnB,KAAK,uBACH,QAAQ,wBAAwB,KAAK;EACvC,KAAK,iBAAiB,QAAQ,kBAAkB,KAAK;EACrD,KAAK,gBAAgB,QAAQ,iBAAiB,KAAK;EACnD,KAAK,W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ACF;GACF;EACF;CACF;AAOF;AAED,SAAS,kBAAkDC,QAMjC;CACxB,MAAM,EAAE,SAAS,UAAU,YAAY,UAAU,GAAG;AACpD,KAAI,cAAc,CAAC,mBAAmB,QAAQ,CAC5C,KACE,OAAO,YAAY,YAClB,MAAM,QAAQ,QAAQ,IACrB,QAAQ,MAAM,CAAC,SAAS,OAAO,SAAS,SAAS,CAEnD,QAAO,IAAI,YAAY;EACrB,QAAQ;EACR;EACA;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAED,QAAO,IAAI,YAAY;EACrB,QAAQ;EACR,SAAS,WAAW,QAAQ;EAC5B;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAGH,QAAO;AAEV;AAED,SAAS,WAAWC,SAA0B;AAC5C,KAAI;AACF,SAAO,KAAK,UAAU,SAAS,MAAM,EAAE,IAAI;CAC5C,SAAQ,OAAO;AACd,SAAO,GAAG,SAAS;CACpB;AACF"}
@@ -30,6 +30,7 @@ var EventStreamCallbackHandler = class extends require_tracers_base.BaseTracer {
30
30
  transformStream;
31
31
  writer;
32
32
  receiveStream;
33
+ readableStreamClosed = false;
33
34
  name = "event_stream_tracer";
34
35
  lc_prefer_streaming = true;
35
36
  constructor(fields) {
@@ -44,7 +45,9 @@ var EventStreamCallbackHandler = class extends require_tracers_base.BaseTracer {
44
45
  this.excludeNames = fields?.excludeNames;
45
46
  this.excludeTypes = fields?.excludeTypes;
46
47
  this.excludeTags = fields?.excludeTags;
47
- this.transformStream = new TransformStream();
48
+ this.transformStream = new TransformStream({ flush: () => {
49
+ this.readableStreamClosed = true;
50
+ } });
48
51
  this.writer = this.transformStream.writable.getWriter();
49
52
  this.receiveStream = require_utils_stream.IterableReadableStream.fromReadableStream(this.transformStream.readable);
50
53
  }
@@ -112,6 +115,7 @@ var EventStreamCallbackHandler = class extends require_tracers_base.BaseTracer {
112
115
  }
113
116
  }
114
117
  async send(payload, run) {
118
+ if (this.readableStreamClosed) return;
115
119
  if (this._includeRun(run)) await this.writer.write(payload);
116
120
  }
117
121
  async sendEndEvent(payload, run) {
@@ -1 +1 @@
1
- {"version":3,"file":"event_stream.cjs","names":["handler: BaseCallbackHandler","BaseTracer","fields?: EventStreamCallbackHandlerInput","IterableReadableStream","_run: Run","run: RunInfo","runId: string","outputStream: AsyncGenerator<T>","eventType: string","data: unknown","GenerationChunk","tappedPromiseResolver: (() => void) | undefined","event: StreamEvent","payload: StreamEvent","run: Run","token: string","kwargs?: { chunk: any }","AIMessageChunk","eventName: string","generations: ChatGeneration[][] | Generation[][] | undefined","output: BaseMessage | Record<string, any> | undefined","runInfo: RunInfo","eventData: StreamEventData","data: StreamEventData","data: any"],"sources":["../../src/tracers/event_stream.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport {\n BaseCallbackHandler,\n BaseCallbackHandlerInput,\n CallbackHandlerPrefersStreaming,\n} from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\nimport { AIMessageChunk } from \"../messages/ai.js\";\nimport { ChatGeneration, Generation, GenerationChunk } from \"../outputs.js\";\nimport { BaseMessage } from \"../messages/base.js\";\n\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input?: any;\n\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n output?: any;\n\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n chunk?: any;\n};\n\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\n\ntype RunInfo = {\n name: string;\n tags: string[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n runType: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputs?: Record<string, any>;\n};\n\nexport interface EventStreamCallbackHandlerInput\n extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\n\nfunction assignName({\n name,\n serialized,\n}: {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n serialized?: Record<string, any>;\n}): string {\n if (name !== undefined) {\n return name;\n }\n if (serialized?.name !== undefined) {\n return serialized.name;\n } else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) {\n return serialized.id[serialized.id.length - 1];\n }\n return \"Unnamed\";\n}\n\nexport const isStreamEventsHandler = (\n handler: BaseCallbackHandler\n): handler is EventStreamCallbackHandler =>\n handler.name === \"event_stream_tracer\";\n\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport class EventStreamCallbackHandler\n extends BaseTracer\n implements CallbackHandlerPrefersStreaming\n{\n protected autoClose = true;\n\n protected includeNames?: string[];\n\n protected includeTypes?: string[];\n\n protected includeTags?: string[];\n\n protected excludeNames?: string[];\n\n protected excludeTypes?: string[];\n\n protected excludeTags?: string[];\n\n private runInfoMap: Map<string, RunInfo> = new Map();\n\n private tappedPromises: Map<string, Promise<void>> = new Map();\n\n protected transformStream: TransformStream;\n\n public writer: WritableStreamDefaultWriter;\n\n public receiveStream: IterableReadableStream<StreamEvent>;\n\n name = \"event_stream_tracer\";\n\n lc_prefer_streaming = true;\n\n constructor(fields?: EventStreamCallbackHandlerInput) {\n super({ _awaitHandler: true, ...fields });\n this.autoClose = fields?.autoClose ?? true;\n this.includeNames = fields?.includeNames;\n this.includeTypes = fields?.includeTypes;\n this.includeTags = fields?.includeTags;\n this.excludeNames = fields?.excludeNames;\n this.excludeTypes = fields?.excludeTypes;\n this.excludeTags = fields?.excludeTags;\n this.transformStream = new TransformStream();\n this.writer = this.transformStream.writable.getWriter();\n this.receiveStream = IterableReadableStream.fromReadableStream(\n this.transformStream.readable\n );\n }\n\n [Symbol.asyncIterator]() {\n return this.receiveStream;\n }\n\n protected async persistRun(_run: Run): Promise<void> {\n // This is a legacy method only called once for an entire run tree\n // and is therefore not useful here\n }\n\n _includeRun(run: RunInfo): boolean {\n const runTags = run.tags ?? [];\n let include =\n this.includeNames === undefined &&\n this.includeTags === undefined &&\n this.includeTypes === undefined;\n if (this.includeNames !== undefined) {\n include = include || this.includeNames.includes(run.name);\n }\n if (this.includeTypes !== undefined) {\n include = include || this.includeTypes.includes(run.runType);\n }\n if (this.includeTags !== undefined) {\n include =\n include ||\n runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined;\n }\n if (this.excludeNames !== undefined) {\n include = include && !this.excludeNames.includes(run.name);\n }\n if (this.excludeTypes !== undefined) {\n include = include && !this.excludeTypes.includes(run.runType);\n }\n if (this.excludeTags !== undefined) {\n include =\n include && runTags.every((tag) => !this.excludeTags?.includes(tag));\n }\n return include;\n }\n\n async *tapOutputIterable<T>(\n runId: string,\n outputStream: AsyncGenerator<T>\n ): AsyncGenerator<T> {\n const firstChunk = await outputStream.next();\n if (firstChunk.done) {\n return;\n }\n const runInfo = this.runInfoMap.get(runId);\n // Run has finished, don't issue any stream events.\n // An example of this is for runnables that use the default\n // implementation of .stream(), which delegates to .invoke()\n // and calls .onChainEnd() before passing it to the iterator.\n if (runInfo === undefined) {\n yield firstChunk.value;\n return;\n }\n // Match format from handlers below\n function _formatOutputChunk(eventType: string, data: unknown) {\n if (eventType === \"llm\" && typeof data === \"string\") {\n return new GenerationChunk({ text: data });\n }\n return data;\n }\n let tappedPromise = this.tappedPromises.get(runId);\n // if we are the first to tap, issue stream events\n if (tappedPromise === undefined) {\n let tappedPromiseResolver: (() => void) | undefined;\n tappedPromise = new Promise((resolve) => {\n tappedPromiseResolver = resolve;\n });\n this.tappedPromises.set(runId, tappedPromise);\n try {\n const event: StreamEvent = {\n event: `on_${runInfo.runType}_stream`,\n run_id: runId,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data: {},\n };\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, firstChunk.value),\n },\n },\n runInfo\n );\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n // Don't yield tool and retriever stream events\n if (runInfo.runType !== \"tool\" && runInfo.runType !== \"retriever\") {\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, chunk),\n },\n },\n runInfo\n );\n }\n yield chunk;\n }\n } finally {\n tappedPromiseResolver?.();\n // Don't delete from the promises map to keep track of which runs have been tapped.\n }\n } else {\n // otherwise just pass through\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n yield chunk;\n }\n }\n }\n\n async send(payload: StreamEvent, run: RunInfo) {\n if (this._includeRun(run)) {\n await this.writer.write(payload);\n }\n }\n\n async sendEndEvent(payload: StreamEvent, run: RunInfo) {\n const tappedPromise = this.tappedPromises.get(payload.run_id);\n if (tappedPromise !== undefined) {\n // eslint-disable-next-line no-void\n void tappedPromise.then(() => {\n // eslint-disable-next-line no-void\n void this.send(payload, run);\n });\n } else {\n await this.send(payload, run);\n }\n }\n\n async onLLMStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.inputs.messages !== undefined ? \"chat_model\" : \"llm\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: run.inputs,\n };\n this.runInfoMap.set(run.id, runInfo);\n const eventName = `on_${runType}_start`;\n await this.send(\n {\n event: eventName,\n data: {\n input: run.inputs,\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onLLMNewToken(\n run: Run,\n token: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n kwargs?: { chunk: any }\n ): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n let chunk;\n let eventName;\n if (runInfo === undefined) {\n throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`);\n }\n // Top-level streaming events are covered by tapOutputIterable\n if (this.runInfoMap.size === 1) {\n return;\n }\n if (runInfo.runType === \"chat_model\") {\n eventName = \"on_chat_model_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new AIMessageChunk({ content: token, id: `run-${run.id}` });\n } else {\n chunk = kwargs.chunk.message;\n }\n } else if (runInfo.runType === \"llm\") {\n eventName = \"on_llm_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new GenerationChunk({ text: token });\n } else {\n chunk = kwargs.chunk;\n }\n } else {\n throw new Error(`Unexpected run type ${runInfo.runType}`);\n }\n await this.send(\n {\n event: eventName,\n data: {\n chunk,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onLLMEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n let eventName: string;\n if (runInfo === undefined) {\n throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`);\n }\n const generations: ChatGeneration[][] | Generation[][] | undefined =\n run.outputs?.generations;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let output: BaseMessage | Record<string, any> | undefined;\n if (runInfo.runType === \"chat_model\") {\n for (const generation of generations ?? []) {\n if (output !== undefined) {\n break;\n }\n output = (generation[0] as ChatGeneration | undefined)?.message;\n }\n eventName = \"on_chat_model_end\";\n } else if (runInfo.runType === \"llm\") {\n output = {\n generations: generations?.map((generation) => {\n return generation.map((chunk) => {\n return {\n text: chunk.text,\n generationInfo: chunk.generationInfo,\n };\n });\n }),\n llmOutput: run.outputs?.llmOutput ?? {},\n };\n eventName = \"on_llm_end\";\n } else {\n throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`);\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onChainStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.run_type ?? \"chain\";\n const runInfo: RunInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: run.run_type,\n };\n let eventData: StreamEventData = {};\n // Workaround Runnable core code not sending input when transform streaming.\n if (run.inputs.input === \"\" && Object.keys(run.inputs).length === 1) {\n eventData = {};\n runInfo.inputs = {};\n } else if (run.inputs.input !== undefined) {\n eventData.input = run.inputs.input;\n runInfo.inputs = run.inputs.input;\n } else {\n eventData.input = run.inputs;\n runInfo.inputs = run.inputs;\n }\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: `on_${runType}_start`,\n data: eventData,\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onChainEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`);\n }\n const eventName = `on_${run.run_type}_end`;\n const inputs = run.inputs ?? runInfo.inputs ?? {};\n const outputs = run.outputs?.output ?? run.outputs;\n const data: StreamEventData = {\n output: outputs,\n input: inputs,\n };\n if (inputs.input && Object.keys(inputs).length === 1) {\n data.input = inputs.input;\n runInfo.inputs = inputs.input;\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data,\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: \"tool\",\n inputs: run.inputs ?? {},\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_tool_start\",\n data: {\n input: run.inputs ?? {},\n },\n name: runName,\n run_id: run.id,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.inputs === undefined) {\n throw new Error(\n `onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`\n );\n }\n const output =\n run.outputs?.output === undefined ? run.outputs : run.outputs.output;\n await this.sendEndEvent(\n {\n event: \"on_tool_end\",\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onRetrieverStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = \"retriever\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: {\n query: run.inputs.query,\n },\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_retriever_start\",\n data: {\n input: {\n query: run.inputs.query,\n },\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onRetrieverEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`);\n }\n await this.sendEndEvent(\n {\n event: \"on_retriever_end\",\n data: {\n output: run.outputs?.documents ?? run.outputs,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async handleCustomEvent(eventName: string, data: any, runId: string) {\n const runInfo = this.runInfoMap.get(runId);\n if (runInfo === undefined) {\n throw new Error(\n `handleCustomEvent: Run ID ${runId} not found in run map.`\n );\n }\n await this.send(\n {\n event: \"on_custom_event\",\n run_id: runId,\n name: eventName,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data,\n },\n runInfo\n );\n }\n\n async finish() {\n const pendingPromises = [...this.tappedPromises.values()];\n // eslint-disable-next-line no-void\n void Promise.all(pendingPromises).finally(() => {\n // eslint-disable-next-line no-void\n void this.writer.close();\n });\n }\n}\n"],"mappings":";;;;;;AAqHA,SAAS,WAAW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OACd,OAAM,IAAI,MACR,CAAC,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;EAG9D,MAAM,KAAK,KACT;GACE,OAAO;GACP,QAAQ;GACR,MAAM;GACN,MAAM,QAAQ;GACd,UAAU,QAAQ;GAClB;EACD,GACD,QACD;CACF;CAED,MAAM,SAAS;EACb,MAAM,kBAAkB,CAAC,GAAG,KAAK,eAAe,QAAQ,AAAC;EAEpD,QAAQ,IAAI,gBAAgB,CAAC,QAAQ,MAAM;GAEzC,KAAK,OAAO,OAAO;EACzB,EAAC;CACH;AACF"}
1
+ {"version":3,"file":"event_stream.cjs","names":["handler: BaseCallbackHandler","BaseTracer","fields?: EventStreamCallbackHandlerInput","IterableReadableStream","_run: Run","run: RunInfo","runId: string","outputStream: AsyncGenerator<T>","eventType: string","data: unknown","GenerationChunk","tappedPromiseResolver: (() => void) | undefined","event: StreamEvent","payload: StreamEvent","run: Run","token: string","kwargs?: { chunk: any }","AIMessageChunk","eventName: string","generations: ChatGeneration[][] | Generation[][] | undefined","output: BaseMessage | Record<string, any> | undefined","runInfo: RunInfo","eventData: StreamEventData","data: StreamEventData","data: any"],"sources":["../../src/tracers/event_stream.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport {\n BaseCallbackHandler,\n BaseCallbackHandlerInput,\n CallbackHandlerPrefersStreaming,\n} from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\nimport { AIMessageChunk } from \"../messages/ai.js\";\nimport { ChatGeneration, Generation, GenerationChunk } from \"../outputs.js\";\nimport { BaseMessage } from \"../messages/base.js\";\n\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input?: any;\n\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n output?: any;\n\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n chunk?: any;\n};\n\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\n\ntype RunInfo = {\n name: string;\n tags: string[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n runType: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputs?: Record<string, any>;\n};\n\nexport interface EventStreamCallbackHandlerInput\n extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\n\nfunction assignName({\n name,\n serialized,\n}: {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n serialized?: Record<string, any>;\n}): string {\n if (name !== undefined) {\n return name;\n }\n if (serialized?.name !== undefined) {\n return serialized.name;\n } else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) {\n return serialized.id[serialized.id.length - 1];\n }\n return \"Unnamed\";\n}\n\nexport const isStreamEventsHandler = (\n handler: BaseCallbackHandler\n): handler is EventStreamCallbackHandler =>\n handler.name === \"event_stream_tracer\";\n\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport class EventStreamCallbackHandler\n extends BaseTracer\n implements CallbackHandlerPrefersStreaming\n{\n protected autoClose = true;\n\n protected includeNames?: string[];\n\n protected includeTypes?: string[];\n\n protected includeTags?: string[];\n\n protected excludeNames?: string[];\n\n protected excludeTypes?: string[];\n\n protected excludeTags?: string[];\n\n private runInfoMap: Map<string, RunInfo> = new Map();\n\n private tappedPromises: Map<string, Promise<void>> = new Map();\n\n protected transformStream: TransformStream;\n\n public writer: WritableStreamDefaultWriter;\n\n public receiveStream: IterableReadableStream<StreamEvent>;\n\n private readableStreamClosed = false;\n\n name = \"event_stream_tracer\";\n\n lc_prefer_streaming = true;\n\n constructor(fields?: EventStreamCallbackHandlerInput) {\n super({ _awaitHandler: true, ...fields });\n this.autoClose = fields?.autoClose ?? true;\n this.includeNames = fields?.includeNames;\n this.includeTypes = fields?.includeTypes;\n this.includeTags = fields?.includeTags;\n this.excludeNames = fields?.excludeNames;\n this.excludeTypes = fields?.excludeTypes;\n this.excludeTags = fields?.excludeTags;\n this.transformStream = new TransformStream({\n flush: () => {\n this.readableStreamClosed = true;\n },\n });\n this.writer = this.transformStream.writable.getWriter();\n this.receiveStream = IterableReadableStream.fromReadableStream(\n this.transformStream.readable\n );\n }\n\n [Symbol.asyncIterator]() {\n return this.receiveStream;\n }\n\n protected async persistRun(_run: Run): Promise<void> {\n // This is a legacy method only called once for an entire run tree\n // and is therefore not useful here\n }\n\n _includeRun(run: RunInfo): boolean {\n const runTags = run.tags ?? [];\n let include =\n this.includeNames === undefined &&\n this.includeTags === undefined &&\n this.includeTypes === undefined;\n if (this.includeNames !== undefined) {\n include = include || this.includeNames.includes(run.name);\n }\n if (this.includeTypes !== undefined) {\n include = include || this.includeTypes.includes(run.runType);\n }\n if (this.includeTags !== undefined) {\n include =\n include ||\n runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined;\n }\n if (this.excludeNames !== undefined) {\n include = include && !this.excludeNames.includes(run.name);\n }\n if (this.excludeTypes !== undefined) {\n include = include && !this.excludeTypes.includes(run.runType);\n }\n if (this.excludeTags !== undefined) {\n include =\n include && runTags.every((tag) => !this.excludeTags?.includes(tag));\n }\n return include;\n }\n\n async *tapOutputIterable<T>(\n runId: string,\n outputStream: AsyncGenerator<T>\n ): AsyncGenerator<T> {\n const firstChunk = await outputStream.next();\n if (firstChunk.done) {\n return;\n }\n const runInfo = this.runInfoMap.get(runId);\n // Run has finished, don't issue any stream events.\n // An example of this is for runnables that use the default\n // implementation of .stream(), which delegates to .invoke()\n // and calls .onChainEnd() before passing it to the iterator.\n if (runInfo === undefined) {\n yield firstChunk.value;\n return;\n }\n // Match format from handlers below\n function _formatOutputChunk(eventType: string, data: unknown) {\n if (eventType === \"llm\" && typeof data === \"string\") {\n return new GenerationChunk({ text: data });\n }\n return data;\n }\n let tappedPromise = this.tappedPromises.get(runId);\n // if we are the first to tap, issue stream events\n if (tappedPromise === undefined) {\n let tappedPromiseResolver: (() => void) | undefined;\n tappedPromise = new Promise((resolve) => {\n tappedPromiseResolver = resolve;\n });\n this.tappedPromises.set(runId, tappedPromise);\n try {\n const event: StreamEvent = {\n event: `on_${runInfo.runType}_stream`,\n run_id: runId,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data: {},\n };\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, firstChunk.value),\n },\n },\n runInfo\n );\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n // Don't yield tool and retriever stream events\n if (runInfo.runType !== \"tool\" && runInfo.runType !== \"retriever\") {\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, chunk),\n },\n },\n runInfo\n );\n }\n yield chunk;\n }\n } finally {\n tappedPromiseResolver?.();\n // Don't delete from the promises map to keep track of which runs have been tapped.\n }\n } else {\n // otherwise just pass through\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n yield chunk;\n }\n }\n }\n\n async send(payload: StreamEvent, run: RunInfo) {\n if (this.readableStreamClosed) return;\n if (this._includeRun(run)) {\n await this.writer.write(payload);\n }\n }\n\n async sendEndEvent(payload: StreamEvent, run: RunInfo) {\n const tappedPromise = this.tappedPromises.get(payload.run_id);\n if (tappedPromise !== undefined) {\n // eslint-disable-next-line no-void\n void tappedPromise.then(() => {\n // eslint-disable-next-line no-void\n void this.send(payload, run);\n });\n } else {\n await this.send(payload, run);\n }\n }\n\n async onLLMStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.inputs.messages !== undefined ? \"chat_model\" : \"llm\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: run.inputs,\n };\n this.runInfoMap.set(run.id, runInfo);\n const eventName = `on_${runType}_start`;\n await this.send(\n {\n event: eventName,\n data: {\n input: run.inputs,\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onLLMNewToken(\n run: Run,\n token: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n kwargs?: { chunk: any }\n ): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n let chunk;\n let eventName;\n if (runInfo === undefined) {\n throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`);\n }\n // Top-level streaming events are covered by tapOutputIterable\n if (this.runInfoMap.size === 1) {\n return;\n }\n if (runInfo.runType === \"chat_model\") {\n eventName = \"on_chat_model_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new AIMessageChunk({ content: token, id: `run-${run.id}` });\n } else {\n chunk = kwargs.chunk.message;\n }\n } else if (runInfo.runType === \"llm\") {\n eventName = \"on_llm_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new GenerationChunk({ text: token });\n } else {\n chunk = kwargs.chunk;\n }\n } else {\n throw new Error(`Unexpected run type ${runInfo.runType}`);\n }\n await this.send(\n {\n event: eventName,\n data: {\n chunk,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onLLMEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n let eventName: string;\n if (runInfo === undefined) {\n throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`);\n }\n const generations: ChatGeneration[][] | Generation[][] | undefined =\n run.outputs?.generations;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let output: BaseMessage | Record<string, any> | undefined;\n if (runInfo.runType === \"chat_model\") {\n for (const generation of generations ?? []) {\n if (output !== undefined) {\n break;\n }\n output = (generation[0] as ChatGeneration | undefined)?.message;\n }\n eventName = \"on_chat_model_end\";\n } else if (runInfo.runType === \"llm\") {\n output = {\n generations: generations?.map((generation) => {\n return generation.map((chunk) => {\n return {\n text: chunk.text,\n generationInfo: chunk.generationInfo,\n };\n });\n }),\n llmOutput: run.outputs?.llmOutput ?? {},\n };\n eventName = \"on_llm_end\";\n } else {\n throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`);\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onChainStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.run_type ?? \"chain\";\n const runInfo: RunInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: run.run_type,\n };\n let eventData: StreamEventData = {};\n // Workaround Runnable core code not sending input when transform streaming.\n if (run.inputs.input === \"\" && Object.keys(run.inputs).length === 1) {\n eventData = {};\n runInfo.inputs = {};\n } else if (run.inputs.input !== undefined) {\n eventData.input = run.inputs.input;\n runInfo.inputs = run.inputs.input;\n } else {\n eventData.input = run.inputs;\n runInfo.inputs = run.inputs;\n }\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: `on_${runType}_start`,\n data: eventData,\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onChainEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`);\n }\n const eventName = `on_${run.run_type}_end`;\n const inputs = run.inputs ?? runInfo.inputs ?? {};\n const outputs = run.outputs?.output ?? run.outputs;\n const data: StreamEventData = {\n output: outputs,\n input: inputs,\n };\n if (inputs.input && Object.keys(inputs).length === 1) {\n data.input = inputs.input;\n runInfo.inputs = inputs.input;\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data,\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: \"tool\",\n inputs: run.inputs ?? {},\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_tool_start\",\n data: {\n input: run.inputs ?? {},\n },\n name: runName,\n run_id: run.id,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.inputs === undefined) {\n throw new Error(\n `onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`\n );\n }\n const output =\n run.outputs?.output === undefined ? run.outputs : run.outputs.output;\n await this.sendEndEvent(\n {\n event: \"on_tool_end\",\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onRetrieverStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = \"retriever\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: {\n query: run.inputs.query,\n },\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_retriever_start\",\n data: {\n input: {\n query: run.inputs.query,\n },\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onRetrieverEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`);\n }\n await this.sendEndEvent(\n {\n event: \"on_retriever_end\",\n data: {\n output: run.outputs?.documents ?? run.outputs,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async handleCustomEvent(eventName: string, data: any, runId: string) {\n const runInfo = this.runInfoMap.get(runId);\n if (runInfo === undefined) {\n throw new Error(\n `handleCustomEvent: Run ID ${runId} not found in run map.`\n );\n }\n await this.send(\n {\n event: \"on_custom_event\",\n run_id: runId,\n name: eventName,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data,\n },\n runInfo\n );\n }\n\n async finish() {\n const pendingPromises = [...this.tappedPromises.values()];\n // eslint-disable-next-line no-void\n void Promise.all(pendingPromises).finally(() => {\n // eslint-disable-next-line no-void\n void this.writer.close();\n });\n }\n}\n"],"mappings":";;;;;;AAqHA,SAAS,WAAW,EAClB,MACA,YAKD,EAAU;AACT,KAAI,SAAS,OACX,QAAO;AAET,KAAI,YAAY,SAAS,OACvB,QAAO,WAAW;UACT,YAAY,OAAO,UAAa,MAAM,QAAQ,YAAY,GAAG,CACtE,QAAO,WAAW,GAAG,WAAW,GAAG,SAAS;AAE9C,QAAO;AACR;AAED,MAAa,wBAAwB,CACnCA,YAEA,QAAQ,SAAS;;;;;;;AAQnB,IAAa,6BAAb,cACUC,gCAEV;CACE,AAAU,YAAY;CAEtB,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAQ,6BAAmC,IAAI;CAE/C,AAAQ,iCAA6C,IAAI;CAEzD,AAAU;CAEV,AAAO;CAEP,AAAO;CAEP,AAAQ,uBAAuB;CAE/B,OAAO;CAEP,sBAAsB;CAEtB,YAAYC,QAA0C;EACpD,MAAM;GAAE,eAAe;GAAM,GAAG;EAAQ,EAAC;EACzC,KAAK,YAAY,QAAQ,aAAa;EACtC,KAAK,eAAe,QAAQ;EAC5B,KAAK,eAAe,QAAQ;EAC5B,KAAK,cAAc,QAAQ;EAC3B,KAAK,eAAe,QAAQ;EAC5B,KAAK,eAAe,QAAQ;EAC5B,KAAK,cAAc,QAAQ;EAC3B,KAAK,kBAAkB,IAAI,gBAAgB,EACzC,OAAO,MAAM;GACX,KAAK,uBAAuB;EAC7B,EACF;EACD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AU,KAAK,WAAW,IAAI,IAAI,GAAG;EAC3C,KAAK,WAAW,OAAO,IAAI,GAAG;AAC9B,MAAI,YAAY,OACd,OAAM,IAAI,MAAM,CAAC,uBAAuB,EAAE,IAAI,GAAG,sBAAsB,CAAC;EAE1E,MAAM,KAAK,aACT;GACE,OAAO;GACP,MAAM;IACJ,QAAQ,IAAI,SAAS,aAAa,IAAI;IACtC,OAAO,QAAQ;GAChB;GACD,QAAQ,IAAI;GACZ,MAAM,QAAQ;GACd,MAAM,QAAQ;GACd,UAAU,QAAQ;EACnB,GACD,QACD;CACF;CAGD,MAAM,kBAAkBI,WAAmBM,MAAWlB,OAAe;EACnE,MAAM,UAAU,KAAK,WAAW,IAAI,MAAM;AAC1C,MAAI,YAAY,OACd,OAAM,IAAI,MACR,CAAC,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;EAG9D,MAAM,KAAK,KACT;GACE,OAAO;GACP,QAAQ;GACR,MAAM;GACN,MAAM,QAAQ;GACd,UAAU,QAAQ;GAClB;EACD,GACD,QACD;CACF;CAED,MAAM,SAAS;EACb,MAAM,kBAAkB,CAAC,GAAG,KAAK,eAAe,QAAQ,AAAC;EAEpD,QAAQ,IAAI,gBAAgB,CAAC,QAAQ,MAAM;GAEzC,KAAK,OAAO,OAAO;EACzB,EAAC;CACH;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"event_stream.d.cts","names":["BaseTracer","Run","BaseCallbackHandler","BaseCallbackHandlerInput","CallbackHandlerPrefersStreaming","IterableReadableStream","StreamEventData","StreamEvent","Record","RunInfo","EventStreamCallbackHandlerInput","isStreamEventsHandler","EventStreamCallbackHandler","T","TransformStream","WritableStreamDefaultWriter","Symbol","asyncIterator","Promise","AsyncGenerator"],"sources":["../../src/tracers/event_stream.d.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport { BaseCallbackHandler, BaseCallbackHandlerInput, CallbackHandlerPrefersStreaming } from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n input?: any;\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n output?: any;\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n chunk?: any;\n};\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\ntype RunInfo = {\n name: string;\n tags: string[];\n metadata: Record<string, any>;\n runType: string;\n inputs?: Record<string, any>;\n};\nexport interface EventStreamCallbackHandlerInput extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\nexport declare const isStreamEventsHandler: (handler: BaseCallbackHandler) => handler is EventStreamCallbackHandler;\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport declare class EventStreamCallbackHandler extends BaseTracer implements CallbackHandlerPrefersStreaming {\n protected autoClose: boolean;\n protected includeNames?: string[];\n protected includeTypes?: string[];\n protected includeTags?: string[];\n protected excludeNames?: string[];\n protected excludeTypes?: string[];\n protected excludeTags?: string[];\n private runInfoMap;\n private tappedPromises;\n protected transformStream: TransformStream;\n writer: WritableStreamDefaultWriter;\n receiveStream: IterableReadableStream<StreamEvent>;\n name: string;\n lc_prefer_streaming: boolean;\n constructor(fields?: EventStreamCallbackHandlerInput);\n [Symbol.asyncIterator](): IterableReadableStream<StreamEvent>;\n protected persistRun(_run: Run): Promise<void>;\n _includeRun(run: RunInfo): boolean;\n tapOutputIterable<T>(runId: string, outputStream: AsyncGenerator<T>): AsyncGenerator<T>;\n send(payload: StreamEvent, run: RunInfo): Promise<void>;\n sendEndEvent(payload: StreamEvent, run: RunInfo): Promise<void>;\n onLLMStart(run: Run): Promise<void>;\n onLLMNewToken(run: Run, token: string, kwargs?: {\n chunk: any;\n }): Promise<void>;\n onLLMEnd(run: Run): Promise<void>;\n onChainStart(run: Run): Promise<void>;\n onChainEnd(run: Run): Promise<void>;\n onToolStart(run: Run): Promise<void>;\n onToolEnd(run: Run): Promise<void>;\n onRetrieverStart(run: Run): Promise<void>;\n onRetrieverEnd(run: Run): Promise<void>;\n handleCustomEvent(eventName: string, data: any, runId: string): Promise<void>;\n finish(): Promise<void>;\n}\nexport {};\n//# sourceMappingURL=event_stream.d.ts.map"],"mappings":";;;;AAMA;AA8BA;AAmDA;KAjFYM,eAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA8BAC,WAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAoCEC;;;;;;QAMJF;;UASOI,+BAAAA,SAAwCP"}
1
+ {"version":3,"file":"event_stream.d.cts","names":["BaseTracer","Run","BaseCallbackHandler","BaseCallbackHandlerInput","CallbackHandlerPrefersStreaming","IterableReadableStream","StreamEventData","StreamEvent","Record","RunInfo","EventStreamCallbackHandlerInput","isStreamEventsHandler","EventStreamCallbackHandler","T","TransformStream","WritableStreamDefaultWriter","Symbol","asyncIterator","Promise","AsyncGenerator"],"sources":["../../src/tracers/event_stream.d.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport { BaseCallbackHandler, BaseCallbackHandlerInput, CallbackHandlerPrefersStreaming } from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n input?: any;\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n output?: any;\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n chunk?: any;\n};\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\ntype RunInfo = {\n name: string;\n tags: string[];\n metadata: Record<string, any>;\n runType: string;\n inputs?: Record<string, any>;\n};\nexport interface EventStreamCallbackHandlerInput extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\nexport declare const isStreamEventsHandler: (handler: BaseCallbackHandler) => handler is EventStreamCallbackHandler;\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport declare class EventStreamCallbackHandler extends BaseTracer implements CallbackHandlerPrefersStreaming {\n protected autoClose: boolean;\n protected includeNames?: string[];\n protected includeTypes?: string[];\n protected includeTags?: string[];\n protected excludeNames?: string[];\n protected excludeTypes?: string[];\n protected excludeTags?: string[];\n private runInfoMap;\n private tappedPromises;\n protected transformStream: TransformStream;\n writer: WritableStreamDefaultWriter;\n receiveStream: IterableReadableStream<StreamEvent>;\n private readableStreamClosed;\n name: string;\n lc_prefer_streaming: boolean;\n constructor(fields?: EventStreamCallbackHandlerInput);\n [Symbol.asyncIterator](): IterableReadableStream<StreamEvent>;\n protected persistRun(_run: Run): Promise<void>;\n _includeRun(run: RunInfo): boolean;\n tapOutputIterable<T>(runId: string, outputStream: AsyncGenerator<T>): AsyncGenerator<T>;\n send(payload: StreamEvent, run: RunInfo): Promise<void>;\n sendEndEvent(payload: StreamEvent, run: RunInfo): Promise<void>;\n onLLMStart(run: Run): Promise<void>;\n onLLMNewToken(run: Run, token: string, kwargs?: {\n chunk: any;\n }): Promise<void>;\n onLLMEnd(run: Run): Promise<void>;\n onChainStart(run: Run): Promise<void>;\n onChainEnd(run: Run): Promise<void>;\n onToolStart(run: Run): Promise<void>;\n onToolEnd(run: Run): Promise<void>;\n onRetrieverStart(run: Run): Promise<void>;\n onRetrieverEnd(run: Run): Promise<void>;\n handleCustomEvent(eventName: string, data: any, runId: string): Promise<void>;\n finish(): Promise<void>;\n}\nexport {};\n//# sourceMappingURL=event_stream.d.ts.map"],"mappings":";;;;AAMA;AA8BA;AAmDA;KAjFYM,eAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA8BAC,WAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAoCEC;;;;;;QAMJF;;UASOI,+BAAAA,SAAwCP"}
@@ -1 +1 @@
1
- {"version":3,"file":"event_stream.d.ts","names":["BaseTracer","Run","BaseCallbackHandler","BaseCallbackHandlerInput","CallbackHandlerPrefersStreaming","IterableReadableStream","StreamEventData","StreamEvent","Record","RunInfo","EventStreamCallbackHandlerInput","isStreamEventsHandler","EventStreamCallbackHandler","T","TransformStream","WritableStreamDefaultWriter","Symbol","asyncIterator","Promise","AsyncGenerator"],"sources":["../../src/tracers/event_stream.d.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport { BaseCallbackHandler, BaseCallbackHandlerInput, CallbackHandlerPrefersStreaming } from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n input?: any;\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n output?: any;\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n chunk?: any;\n};\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\ntype RunInfo = {\n name: string;\n tags: string[];\n metadata: Record<string, any>;\n runType: string;\n inputs?: Record<string, any>;\n};\nexport interface EventStreamCallbackHandlerInput extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\nexport declare const isStreamEventsHandler: (handler: BaseCallbackHandler) => handler is EventStreamCallbackHandler;\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport declare class EventStreamCallbackHandler extends BaseTracer implements CallbackHandlerPrefersStreaming {\n protected autoClose: boolean;\n protected includeNames?: string[];\n protected includeTypes?: string[];\n protected includeTags?: string[];\n protected excludeNames?: string[];\n protected excludeTypes?: string[];\n protected excludeTags?: string[];\n private runInfoMap;\n private tappedPromises;\n protected transformStream: TransformStream;\n writer: WritableStreamDefaultWriter;\n receiveStream: IterableReadableStream<StreamEvent>;\n name: string;\n lc_prefer_streaming: boolean;\n constructor(fields?: EventStreamCallbackHandlerInput);\n [Symbol.asyncIterator](): IterableReadableStream<StreamEvent>;\n protected persistRun(_run: Run): Promise<void>;\n _includeRun(run: RunInfo): boolean;\n tapOutputIterable<T>(runId: string, outputStream: AsyncGenerator<T>): AsyncGenerator<T>;\n send(payload: StreamEvent, run: RunInfo): Promise<void>;\n sendEndEvent(payload: StreamEvent, run: RunInfo): Promise<void>;\n onLLMStart(run: Run): Promise<void>;\n onLLMNewToken(run: Run, token: string, kwargs?: {\n chunk: any;\n }): Promise<void>;\n onLLMEnd(run: Run): Promise<void>;\n onChainStart(run: Run): Promise<void>;\n onChainEnd(run: Run): Promise<void>;\n onToolStart(run: Run): Promise<void>;\n onToolEnd(run: Run): Promise<void>;\n onRetrieverStart(run: Run): Promise<void>;\n onRetrieverEnd(run: Run): Promise<void>;\n handleCustomEvent(eventName: string, data: any, runId: string): Promise<void>;\n finish(): Promise<void>;\n}\nexport {};\n//# sourceMappingURL=event_stream.d.ts.map"],"mappings":";;;;;;AAMA;AA8BA;AAmDiBU,KAjFLJ,eAAAA,GAiFKI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAnDLH,WAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAoCEC;;;;;;QAMJF;;UASOI,+BAAAA,SAAwCP"}
1
+ {"version":3,"file":"event_stream.d.ts","names":["BaseTracer","Run","BaseCallbackHandler","BaseCallbackHandlerInput","CallbackHandlerPrefersStreaming","IterableReadableStream","StreamEventData","StreamEvent","Record","RunInfo","EventStreamCallbackHandlerInput","isStreamEventsHandler","EventStreamCallbackHandler","T","TransformStream","WritableStreamDefaultWriter","Symbol","asyncIterator","Promise","AsyncGenerator"],"sources":["../../src/tracers/event_stream.d.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport { BaseCallbackHandler, BaseCallbackHandlerInput, CallbackHandlerPrefersStreaming } from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n input?: any;\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n output?: any;\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n chunk?: any;\n};\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\ntype RunInfo = {\n name: string;\n tags: string[];\n metadata: Record<string, any>;\n runType: string;\n inputs?: Record<string, any>;\n};\nexport interface EventStreamCallbackHandlerInput extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\nexport declare const isStreamEventsHandler: (handler: BaseCallbackHandler) => handler is EventStreamCallbackHandler;\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport declare class EventStreamCallbackHandler extends BaseTracer implements CallbackHandlerPrefersStreaming {\n protected autoClose: boolean;\n protected includeNames?: string[];\n protected includeTypes?: string[];\n protected includeTags?: string[];\n protected excludeNames?: string[];\n protected excludeTypes?: string[];\n protected excludeTags?: string[];\n private runInfoMap;\n private tappedPromises;\n protected transformStream: TransformStream;\n writer: WritableStreamDefaultWriter;\n receiveStream: IterableReadableStream<StreamEvent>;\n private readableStreamClosed;\n name: string;\n lc_prefer_streaming: boolean;\n constructor(fields?: EventStreamCallbackHandlerInput);\n [Symbol.asyncIterator](): IterableReadableStream<StreamEvent>;\n protected persistRun(_run: Run): Promise<void>;\n _includeRun(run: RunInfo): boolean;\n tapOutputIterable<T>(runId: string, outputStream: AsyncGenerator<T>): AsyncGenerator<T>;\n send(payload: StreamEvent, run: RunInfo): Promise<void>;\n sendEndEvent(payload: StreamEvent, run: RunInfo): Promise<void>;\n onLLMStart(run: Run): Promise<void>;\n onLLMNewToken(run: Run, token: string, kwargs?: {\n chunk: any;\n }): Promise<void>;\n onLLMEnd(run: Run): Promise<void>;\n onChainStart(run: Run): Promise<void>;\n onChainEnd(run: Run): Promise<void>;\n onToolStart(run: Run): Promise<void>;\n onToolEnd(run: Run): Promise<void>;\n onRetrieverStart(run: Run): Promise<void>;\n onRetrieverEnd(run: Run): Promise<void>;\n handleCustomEvent(eventName: string, data: any, runId: string): Promise<void>;\n finish(): Promise<void>;\n}\nexport {};\n//# sourceMappingURL=event_stream.d.ts.map"],"mappings":";;;;;;AAMA;AA8BA;AAmDiBU,KAjFLJ,eAAAA,GAiFKI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAnDLH,WAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAoCEC;;;;;;QAMJF;;UASOI,+BAAAA,SAAwCP"}
@@ -30,6 +30,7 @@ var EventStreamCallbackHandler = class extends BaseTracer {
30
30
  transformStream;
31
31
  writer;
32
32
  receiveStream;
33
+ readableStreamClosed = false;
33
34
  name = "event_stream_tracer";
34
35
  lc_prefer_streaming = true;
35
36
  constructor(fields) {
@@ -44,7 +45,9 @@ var EventStreamCallbackHandler = class extends BaseTracer {
44
45
  this.excludeNames = fields?.excludeNames;
45
46
  this.excludeTypes = fields?.excludeTypes;
46
47
  this.excludeTags = fields?.excludeTags;
47
- this.transformStream = new TransformStream();
48
+ this.transformStream = new TransformStream({ flush: () => {
49
+ this.readableStreamClosed = true;
50
+ } });
48
51
  this.writer = this.transformStream.writable.getWriter();
49
52
  this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable);
50
53
  }
@@ -112,6 +115,7 @@ var EventStreamCallbackHandler = class extends BaseTracer {
112
115
  }
113
116
  }
114
117
  async send(payload, run) {
118
+ if (this.readableStreamClosed) return;
115
119
  if (this._includeRun(run)) await this.writer.write(payload);
116
120
  }
117
121
  async sendEndEvent(payload, run) {
@@ -1 +1 @@
1
- {"version":3,"file":"event_stream.js","names":["handler: BaseCallbackHandler","fields?: EventStreamCallbackHandlerInput","_run: Run","run: RunInfo","runId: string","outputStream: AsyncGenerator<T>","eventType: string","data: unknown","tappedPromiseResolver: (() => void) | undefined","event: StreamEvent","payload: StreamEvent","run: Run","token: string","kwargs?: { chunk: any }","eventName: string","generations: ChatGeneration[][] | Generation[][] | undefined","output: BaseMessage | Record<string, any> | undefined","runInfo: RunInfo","eventData: StreamEventData","data: StreamEventData","data: any"],"sources":["../../src/tracers/event_stream.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport {\n BaseCallbackHandler,\n BaseCallbackHandlerInput,\n CallbackHandlerPrefersStreaming,\n} from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\nimport { AIMessageChunk } from \"../messages/ai.js\";\nimport { ChatGeneration, Generation, GenerationChunk } from \"../outputs.js\";\nimport { BaseMessage } from \"../messages/base.js\";\n\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input?: any;\n\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n output?: any;\n\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n chunk?: any;\n};\n\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\n\ntype RunInfo = {\n name: string;\n tags: string[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n runType: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputs?: Record<string, any>;\n};\n\nexport interface EventStreamCallbackHandlerInput\n extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\n\nfunction assignName({\n name,\n serialized,\n}: {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n serialized?: Record<string, any>;\n}): string {\n if (name !== undefined) {\n return name;\n }\n if (serialized?.name !== undefined) {\n return serialized.name;\n } else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) {\n return serialized.id[serialized.id.length - 1];\n }\n return \"Unnamed\";\n}\n\nexport const isStreamEventsHandler = (\n handler: BaseCallbackHandler\n): handler is EventStreamCallbackHandler =>\n handler.name === \"event_stream_tracer\";\n\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport class EventStreamCallbackHandler\n extends BaseTracer\n implements CallbackHandlerPrefersStreaming\n{\n protected autoClose = true;\n\n protected includeNames?: string[];\n\n protected includeTypes?: string[];\n\n protected includeTags?: string[];\n\n protected excludeNames?: string[];\n\n protected excludeTypes?: string[];\n\n protected excludeTags?: string[];\n\n private runInfoMap: Map<string, RunInfo> = new Map();\n\n private tappedPromises: Map<string, Promise<void>> = new Map();\n\n protected transformStream: TransformStream;\n\n public writer: WritableStreamDefaultWriter;\n\n public receiveStream: IterableReadableStream<StreamEvent>;\n\n name = \"event_stream_tracer\";\n\n lc_prefer_streaming = true;\n\n constructor(fields?: EventStreamCallbackHandlerInput) {\n super({ _awaitHandler: true, ...fields });\n this.autoClose = fields?.autoClose ?? true;\n this.includeNames = fields?.includeNames;\n this.includeTypes = fields?.includeTypes;\n this.includeTags = fields?.includeTags;\n this.excludeNames = fields?.excludeNames;\n this.excludeTypes = fields?.excludeTypes;\n this.excludeTags = fields?.excludeTags;\n this.transformStream = new TransformStream();\n this.writer = this.transformStream.writable.getWriter();\n this.receiveStream = IterableReadableStream.fromReadableStream(\n this.transformStream.readable\n );\n }\n\n [Symbol.asyncIterator]() {\n return this.receiveStream;\n }\n\n protected async persistRun(_run: Run): Promise<void> {\n // This is a legacy method only called once for an entire run tree\n // and is therefore not useful here\n }\n\n _includeRun(run: RunInfo): boolean {\n const runTags = run.tags ?? [];\n let include =\n this.includeNames === undefined &&\n this.includeTags === undefined &&\n this.includeTypes === undefined;\n if (this.includeNames !== undefined) {\n include = include || this.includeNames.includes(run.name);\n }\n if (this.includeTypes !== undefined) {\n include = include || this.includeTypes.includes(run.runType);\n }\n if (this.includeTags !== undefined) {\n include =\n include ||\n runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined;\n }\n if (this.excludeNames !== undefined) {\n include = include && !this.excludeNames.includes(run.name);\n }\n if (this.excludeTypes !== undefined) {\n include = include && !this.excludeTypes.includes(run.runType);\n }\n if (this.excludeTags !== undefined) {\n include =\n include && runTags.every((tag) => !this.excludeTags?.includes(tag));\n }\n return include;\n }\n\n async *tapOutputIterable<T>(\n runId: string,\n outputStream: AsyncGenerator<T>\n ): AsyncGenerator<T> {\n const firstChunk = await outputStream.next();\n if (firstChunk.done) {\n return;\n }\n const runInfo = this.runInfoMap.get(runId);\n // Run has finished, don't issue any stream events.\n // An example of this is for runnables that use the default\n // implementation of .stream(), which delegates to .invoke()\n // and calls .onChainEnd() before passing it to the iterator.\n if (runInfo === undefined) {\n yield firstChunk.value;\n return;\n }\n // Match format from handlers below\n function _formatOutputChunk(eventType: string, data: unknown) {\n if (eventType === \"llm\" && typeof data === \"string\") {\n return new GenerationChunk({ text: data });\n }\n return data;\n }\n let tappedPromise = this.tappedPromises.get(runId);\n // if we are the first to tap, issue stream events\n if (tappedPromise === undefined) {\n let tappedPromiseResolver: (() => void) | undefined;\n tappedPromise = new Promise((resolve) => {\n tappedPromiseResolver = resolve;\n });\n this.tappedPromises.set(runId, tappedPromise);\n try {\n const event: StreamEvent = {\n event: `on_${runInfo.runType}_stream`,\n run_id: runId,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data: {},\n };\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, firstChunk.value),\n },\n },\n runInfo\n );\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n // Don't yield tool and retriever stream events\n if (runInfo.runType !== \"tool\" && runInfo.runType !== \"retriever\") {\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, chunk),\n },\n },\n runInfo\n );\n }\n yield chunk;\n }\n } finally {\n tappedPromiseResolver?.();\n // Don't delete from the promises map to keep track of which runs have been tapped.\n }\n } else {\n // otherwise just pass through\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n yield chunk;\n }\n }\n }\n\n async send(payload: StreamEvent, run: RunInfo) {\n if (this._includeRun(run)) {\n await this.writer.write(payload);\n }\n }\n\n async sendEndEvent(payload: StreamEvent, run: RunInfo) {\n const tappedPromise = this.tappedPromises.get(payload.run_id);\n if (tappedPromise !== undefined) {\n // eslint-disable-next-line no-void\n void tappedPromise.then(() => {\n // eslint-disable-next-line no-void\n void this.send(payload, run);\n });\n } else {\n await this.send(payload, run);\n }\n }\n\n async onLLMStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.inputs.messages !== undefined ? \"chat_model\" : \"llm\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: run.inputs,\n };\n this.runInfoMap.set(run.id, runInfo);\n const eventName = `on_${runType}_start`;\n await this.send(\n {\n event: eventName,\n data: {\n input: run.inputs,\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onLLMNewToken(\n run: Run,\n token: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n kwargs?: { chunk: any }\n ): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n let chunk;\n let eventName;\n if (runInfo === undefined) {\n throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`);\n }\n // Top-level streaming events are covered by tapOutputIterable\n if (this.runInfoMap.size === 1) {\n return;\n }\n if (runInfo.runType === \"chat_model\") {\n eventName = \"on_chat_model_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new AIMessageChunk({ content: token, id: `run-${run.id}` });\n } else {\n chunk = kwargs.chunk.message;\n }\n } else if (runInfo.runType === \"llm\") {\n eventName = \"on_llm_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new GenerationChunk({ text: token });\n } else {\n chunk = kwargs.chunk;\n }\n } else {\n throw new Error(`Unexpected run type ${runInfo.runType}`);\n }\n await this.send(\n {\n event: eventName,\n data: {\n chunk,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onLLMEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n let eventName: string;\n if (runInfo === undefined) {\n throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`);\n }\n const generations: ChatGeneration[][] | Generation[][] | undefined =\n run.outputs?.generations;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let output: BaseMessage | Record<string, any> | undefined;\n if (runInfo.runType === \"chat_model\") {\n for (const generation of generations ?? []) {\n if (output !== undefined) {\n break;\n }\n output = (generation[0] as ChatGeneration | undefined)?.message;\n }\n eventName = \"on_chat_model_end\";\n } else if (runInfo.runType === \"llm\") {\n output = {\n generations: generations?.map((generation) => {\n return generation.map((chunk) => {\n return {\n text: chunk.text,\n generationInfo: chunk.generationInfo,\n };\n });\n }),\n llmOutput: run.outputs?.llmOutput ?? {},\n };\n eventName = \"on_llm_end\";\n } else {\n throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`);\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onChainStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.run_type ?? \"chain\";\n const runInfo: RunInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: run.run_type,\n };\n let eventData: StreamEventData = {};\n // Workaround Runnable core code not sending input when transform streaming.\n if (run.inputs.input === \"\" && Object.keys(run.inputs).length === 1) {\n eventData = {};\n runInfo.inputs = {};\n } else if (run.inputs.input !== undefined) {\n eventData.input = run.inputs.input;\n runInfo.inputs = run.inputs.input;\n } else {\n eventData.input = run.inputs;\n runInfo.inputs = run.inputs;\n }\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: `on_${runType}_start`,\n data: eventData,\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onChainEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`);\n }\n const eventName = `on_${run.run_type}_end`;\n const inputs = run.inputs ?? runInfo.inputs ?? {};\n const outputs = run.outputs?.output ?? run.outputs;\n const data: StreamEventData = {\n output: outputs,\n input: inputs,\n };\n if (inputs.input && Object.keys(inputs).length === 1) {\n data.input = inputs.input;\n runInfo.inputs = inputs.input;\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data,\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: \"tool\",\n inputs: run.inputs ?? {},\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_tool_start\",\n data: {\n input: run.inputs ?? {},\n },\n name: runName,\n run_id: run.id,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.inputs === undefined) {\n throw new Error(\n `onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`\n );\n }\n const output =\n run.outputs?.output === undefined ? run.outputs : run.outputs.output;\n await this.sendEndEvent(\n {\n event: \"on_tool_end\",\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onRetrieverStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = \"retriever\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: {\n query: run.inputs.query,\n },\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_retriever_start\",\n data: {\n input: {\n query: run.inputs.query,\n },\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onRetrieverEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`);\n }\n await this.sendEndEvent(\n {\n event: \"on_retriever_end\",\n data: {\n output: run.outputs?.documents ?? run.outputs,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async handleCustomEvent(eventName: string, data: any, runId: string) {\n const runInfo = this.runInfoMap.get(runId);\n if (runInfo === undefined) {\n throw new Error(\n `handleCustomEvent: Run ID ${runId} not found in run map.`\n );\n }\n await this.send(\n {\n event: \"on_custom_event\",\n run_id: runId,\n name: eventName,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data,\n },\n runInfo\n );\n }\n\n async finish() {\n const pendingPromises = [...this.tappedPromises.values()];\n // eslint-disable-next-line no-void\n void Promise.all(pendingPromises).finally(() => {\n // eslint-disable-next-line no-void\n void this.writer.close();\n });\n }\n}\n"],"mappings":";;;;;;AAqHA,SAAS,WAAW,EAClB,MACA,YAKD,EAAU;AACT,KAAI,SAAS,OACX,QAAO;AAET,KAAI,YAAY,SAAS,OACvB,QAAO,W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AO;GACP,QAAQ;GACR,MAAM;GACN,MAAM,QAAQ;GACd,UAAU,QAAQ;GAClB;EACD,GACD,QACD;CACF;CAED,MAAM,SAAS;EACb,MAAM,kBAAkB,CAAC,GAAG,KAAK,eAAe,QAAQ,AAAC;EAEpD,QAAQ,IAAI,gBAAgB,CAAC,QAAQ,MAAM;GAEzC,KAAK,OAAO,OAAO;EACzB,EAAC;CACH;AACF"}
1
+ {"version":3,"file":"event_stream.js","names":["handler: BaseCallbackHandler","fields?: EventStreamCallbackHandlerInput","_run: Run","run: RunInfo","runId: string","outputStream: AsyncGenerator<T>","eventType: string","data: unknown","tappedPromiseResolver: (() => void) | undefined","event: StreamEvent","payload: StreamEvent","run: Run","token: string","kwargs?: { chunk: any }","eventName: string","generations: ChatGeneration[][] | Generation[][] | undefined","output: BaseMessage | Record<string, any> | undefined","runInfo: RunInfo","eventData: StreamEventData","data: StreamEventData","data: any"],"sources":["../../src/tracers/event_stream.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport {\n BaseCallbackHandler,\n BaseCallbackHandlerInput,\n CallbackHandlerPrefersStreaming,\n} from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\nimport { AIMessageChunk } from \"../messages/ai.js\";\nimport { ChatGeneration, Generation, GenerationChunk } from \"../outputs.js\";\nimport { BaseMessage } from \"../messages/base.js\";\n\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input?: any;\n\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n output?: any;\n\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n chunk?: any;\n};\n\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\n\ntype RunInfo = {\n name: string;\n tags: string[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n runType: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputs?: Record<string, any>;\n};\n\nexport interface EventStreamCallbackHandlerInput\n extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\n\nfunction assignName({\n name,\n serialized,\n}: {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n serialized?: Record<string, any>;\n}): string {\n if (name !== undefined) {\n return name;\n }\n if (serialized?.name !== undefined) {\n return serialized.name;\n } else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) {\n return serialized.id[serialized.id.length - 1];\n }\n return \"Unnamed\";\n}\n\nexport const isStreamEventsHandler = (\n handler: BaseCallbackHandler\n): handler is EventStreamCallbackHandler =>\n handler.name === \"event_stream_tracer\";\n\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport class EventStreamCallbackHandler\n extends BaseTracer\n implements CallbackHandlerPrefersStreaming\n{\n protected autoClose = true;\n\n protected includeNames?: string[];\n\n protected includeTypes?: string[];\n\n protected includeTags?: string[];\n\n protected excludeNames?: string[];\n\n protected excludeTypes?: string[];\n\n protected excludeTags?: string[];\n\n private runInfoMap: Map<string, RunInfo> = new Map();\n\n private tappedPromises: Map<string, Promise<void>> = new Map();\n\n protected transformStream: TransformStream;\n\n public writer: WritableStreamDefaultWriter;\n\n public receiveStream: IterableReadableStream<StreamEvent>;\n\n private readableStreamClosed = false;\n\n name = \"event_stream_tracer\";\n\n lc_prefer_streaming = true;\n\n constructor(fields?: EventStreamCallbackHandlerInput) {\n super({ _awaitHandler: true, ...fields });\n this.autoClose = fields?.autoClose ?? true;\n this.includeNames = fields?.includeNames;\n this.includeTypes = fields?.includeTypes;\n this.includeTags = fields?.includeTags;\n this.excludeNames = fields?.excludeNames;\n this.excludeTypes = fields?.excludeTypes;\n this.excludeTags = fields?.excludeTags;\n this.transformStream = new TransformStream({\n flush: () => {\n this.readableStreamClosed = true;\n },\n });\n this.writer = this.transformStream.writable.getWriter();\n this.receiveStream = IterableReadableStream.fromReadableStream(\n this.transformStream.readable\n );\n }\n\n [Symbol.asyncIterator]() {\n return this.receiveStream;\n }\n\n protected async persistRun(_run: Run): Promise<void> {\n // This is a legacy method only called once for an entire run tree\n // and is therefore not useful here\n }\n\n _includeRun(run: RunInfo): boolean {\n const runTags = run.tags ?? [];\n let include =\n this.includeNames === undefined &&\n this.includeTags === undefined &&\n this.includeTypes === undefined;\n if (this.includeNames !== undefined) {\n include = include || this.includeNames.includes(run.name);\n }\n if (this.includeTypes !== undefined) {\n include = include || this.includeTypes.includes(run.runType);\n }\n if (this.includeTags !== undefined) {\n include =\n include ||\n runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined;\n }\n if (this.excludeNames !== undefined) {\n include = include && !this.excludeNames.includes(run.name);\n }\n if (this.excludeTypes !== undefined) {\n include = include && !this.excludeTypes.includes(run.runType);\n }\n if (this.excludeTags !== undefined) {\n include =\n include && runTags.every((tag) => !this.excludeTags?.includes(tag));\n }\n return include;\n }\n\n async *tapOutputIterable<T>(\n runId: string,\n outputStream: AsyncGenerator<T>\n ): AsyncGenerator<T> {\n const firstChunk = await outputStream.next();\n if (firstChunk.done) {\n return;\n }\n const runInfo = this.runInfoMap.get(runId);\n // Run has finished, don't issue any stream events.\n // An example of this is for runnables that use the default\n // implementation of .stream(), which delegates to .invoke()\n // and calls .onChainEnd() before passing it to the iterator.\n if (runInfo === undefined) {\n yield firstChunk.value;\n return;\n }\n // Match format from handlers below\n function _formatOutputChunk(eventType: string, data: unknown) {\n if (eventType === \"llm\" && typeof data === \"string\") {\n return new GenerationChunk({ text: data });\n }\n return data;\n }\n let tappedPromise = this.tappedPromises.get(runId);\n // if we are the first to tap, issue stream events\n if (tappedPromise === undefined) {\n let tappedPromiseResolver: (() => void) | undefined;\n tappedPromise = new Promise((resolve) => {\n tappedPromiseResolver = resolve;\n });\n this.tappedPromises.set(runId, tappedPromise);\n try {\n const event: StreamEvent = {\n event: `on_${runInfo.runType}_stream`,\n run_id: runId,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data: {},\n };\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, firstChunk.value),\n },\n },\n runInfo\n );\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n // Don't yield tool and retriever stream events\n if (runInfo.runType !== \"tool\" && runInfo.runType !== \"retriever\") {\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, chunk),\n },\n },\n runInfo\n );\n }\n yield chunk;\n }\n } finally {\n tappedPromiseResolver?.();\n // Don't delete from the promises map to keep track of which runs have been tapped.\n }\n } else {\n // otherwise just pass through\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n yield chunk;\n }\n }\n }\n\n async send(payload: StreamEvent, run: RunInfo) {\n if (this.readableStreamClosed) return;\n if (this._includeRun(run)) {\n await this.writer.write(payload);\n }\n }\n\n async sendEndEvent(payload: StreamEvent, run: RunInfo) {\n const tappedPromise = this.tappedPromises.get(payload.run_id);\n if (tappedPromise !== undefined) {\n // eslint-disable-next-line no-void\n void tappedPromise.then(() => {\n // eslint-disable-next-line no-void\n void this.send(payload, run);\n });\n } else {\n await this.send(payload, run);\n }\n }\n\n async onLLMStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.inputs.messages !== undefined ? \"chat_model\" : \"llm\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: run.inputs,\n };\n this.runInfoMap.set(run.id, runInfo);\n const eventName = `on_${runType}_start`;\n await this.send(\n {\n event: eventName,\n data: {\n input: run.inputs,\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onLLMNewToken(\n run: Run,\n token: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n kwargs?: { chunk: any }\n ): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n let chunk;\n let eventName;\n if (runInfo === undefined) {\n throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`);\n }\n // Top-level streaming events are covered by tapOutputIterable\n if (this.runInfoMap.size === 1) {\n return;\n }\n if (runInfo.runType === \"chat_model\") {\n eventName = \"on_chat_model_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new AIMessageChunk({ content: token, id: `run-${run.id}` });\n } else {\n chunk = kwargs.chunk.message;\n }\n } else if (runInfo.runType === \"llm\") {\n eventName = \"on_llm_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new GenerationChunk({ text: token });\n } else {\n chunk = kwargs.chunk;\n }\n } else {\n throw new Error(`Unexpected run type ${runInfo.runType}`);\n }\n await this.send(\n {\n event: eventName,\n data: {\n chunk,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onLLMEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n let eventName: string;\n if (runInfo === undefined) {\n throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`);\n }\n const generations: ChatGeneration[][] | Generation[][] | undefined =\n run.outputs?.generations;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let output: BaseMessage | Record<string, any> | undefined;\n if (runInfo.runType === \"chat_model\") {\n for (const generation of generations ?? []) {\n if (output !== undefined) {\n break;\n }\n output = (generation[0] as ChatGeneration | undefined)?.message;\n }\n eventName = \"on_chat_model_end\";\n } else if (runInfo.runType === \"llm\") {\n output = {\n generations: generations?.map((generation) => {\n return generation.map((chunk) => {\n return {\n text: chunk.text,\n generationInfo: chunk.generationInfo,\n };\n });\n }),\n llmOutput: run.outputs?.llmOutput ?? {},\n };\n eventName = \"on_llm_end\";\n } else {\n throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`);\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onChainStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.run_type ?? \"chain\";\n const runInfo: RunInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: run.run_type,\n };\n let eventData: StreamEventData = {};\n // Workaround Runnable core code not sending input when transform streaming.\n if (run.inputs.input === \"\" && Object.keys(run.inputs).length === 1) {\n eventData = {};\n runInfo.inputs = {};\n } else if (run.inputs.input !== undefined) {\n eventData.input = run.inputs.input;\n runInfo.inputs = run.inputs.input;\n } else {\n eventData.input = run.inputs;\n runInfo.inputs = run.inputs;\n }\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: `on_${runType}_start`,\n data: eventData,\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onChainEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`);\n }\n const eventName = `on_${run.run_type}_end`;\n const inputs = run.inputs ?? runInfo.inputs ?? {};\n const outputs = run.outputs?.output ?? run.outputs;\n const data: StreamEventData = {\n output: outputs,\n input: inputs,\n };\n if (inputs.input && Object.keys(inputs).length === 1) {\n data.input = inputs.input;\n runInfo.inputs = inputs.input;\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data,\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: \"tool\",\n inputs: run.inputs ?? {},\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_tool_start\",\n data: {\n input: run.inputs ?? {},\n },\n name: runName,\n run_id: run.id,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.inputs === undefined) {\n throw new Error(\n `onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`\n );\n }\n const output =\n run.outputs?.output === undefined ? run.outputs : run.outputs.output;\n await this.sendEndEvent(\n {\n event: \"on_tool_end\",\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onRetrieverStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = \"retriever\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: {\n query: run.inputs.query,\n },\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_retriever_start\",\n data: {\n input: {\n query: run.inputs.query,\n },\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onRetrieverEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`);\n }\n await this.sendEndEvent(\n {\n event: \"on_retriever_end\",\n data: {\n output: run.outputs?.documents ?? run.outputs,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async handleCustomEvent(eventName: string, data: any, runId: string) {\n const runInfo = this.runInfoMap.get(runId);\n if (runInfo === undefined) {\n throw new Error(\n `handleCustomEvent: Run ID ${runId} not found in run map.`\n );\n }\n await this.send(\n {\n event: \"on_custom_event\",\n run_id: runId,\n name: eventName,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data,\n },\n runInfo\n );\n }\n\n async finish() {\n const pendingPromises = [...this.tappedPromises.values()];\n // eslint-disable-next-line no-void\n void Promise.all(pendingPromises).finally(() => {\n // eslint-disable-next-line no-void\n void this.writer.close();\n });\n }\n}\n"],"mappings":";;;;;;AAqHA,SAAS,WAAW,EAClB,MACA,YAKD,EAAU;AACT,KAAI,SAAS,OACX,QAAO;AAET,KAAI,YAAY,SAAS,OACvB,QAAO,WAAW;UACT,YAAY,OAAO,UAAa,MAAM,QAAQ,YAAY,GAAG,CACtE,QAAO,WAAW,GAAG,WAAW,GAAG,SAAS;AAE9C,QAAO;AACR;AAED,MAAa,wBAAwB,CACnCA,YAEA,QAAQ,SAAS;;;;;;;AAQnB,IAAa,6BAAb,cACU,WAEV;CACE,AAAU,YAAY;CAEtB,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAQ,6BAAmC,IAAI;CAE/C,AAAQ,iCAA6C,IAAI;CAEzD,AAAU;CAEV,AAAO;CAEP,AAAO;CAEP,AAAQ,uBAAuB;CAE/B,OAAO;CAEP,sBAAsB;CAEtB,YAAYC,QAA0C;EACpD,MAAM;GAAE,eAAe;GAAM,GAAG;EAAQ,EAAC;EACzC,KAAK,YAAY,QAAQ,aAAa;EACtC,KAAK,eAAe,QAAQ;EAC5B,KAAK,eAAe,QAAQ;EAC5B,KAAK,cAAc,QAAQ;EAC3B,KAAK,eAAe,QAAQ;EAC5B,KAAK,eAAe,QAAQ;EAC5B,KAAK,cAAc,QAAQ;EAC3B,KAAK,kBAAkB,IAAI,gBAAgB,EACzC,OAAO,MAAM;GACX,KAAK,uBAAuB;EAC7B,EACF;EACD,KAAK,SAAS,KAAK,gBAAgB,SAAS,WAAW;EACvD,KAAK,gBAAgB,uBAAuB,mBAC1C,KAAK,gBAAgB,SACtB;CACF;CAED,CAAC,OAAO,iBAAiB;AACvB,SAAO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