@langchain/core 0.3.72 → 1.0.0-alpha.2

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 (1382) hide show
  1. package/README.md +3 -3
  2. package/dist/_virtual/rolldown_runtime.cjs +32 -0
  3. package/dist/_virtual/rolldown_runtime.js +11 -0
  4. package/dist/agents.cjs +12 -2
  5. package/dist/agents.cjs.map +1 -0
  6. package/dist/agents.d.cts +19 -0
  7. package/dist/agents.d.cts.map +1 -0
  8. package/dist/agents.d.ts +16 -10
  9. package/dist/agents.d.ts.map +1 -0
  10. package/dist/agents.js +6 -1
  11. package/dist/agents.js.map +1 -0
  12. package/dist/caches/base.cjs +99 -104
  13. package/dist/caches/base.cjs.map +1 -0
  14. package/dist/caches/base.d.cts +83 -0
  15. package/dist/caches/base.d.cts.map +1 -0
  16. package/dist/caches/base.d.ts +60 -45
  17. package/dist/caches/base.d.ts.map +1 -0
  18. package/dist/caches/base.js +91 -98
  19. package/dist/caches/base.js.map +1 -0
  20. package/dist/callbacks/base.cjs +112 -185
  21. package/dist/callbacks/base.cjs.map +1 -0
  22. package/dist/callbacks/base.d.cts +318 -0
  23. package/dist/callbacks/base.d.cts.map +1 -0
  24. package/dist/callbacks/base.d.ts +234 -222
  25. package/dist/callbacks/base.d.ts.map +1 -0
  26. package/dist/callbacks/base.js +107 -149
  27. package/dist/callbacks/base.js.map +1 -0
  28. package/dist/callbacks/dispatch/index.cjs +56 -46
  29. package/dist/callbacks/dispatch/index.cjs.map +1 -0
  30. package/dist/callbacks/dispatch/index.d.cts +43 -0
  31. package/dist/callbacks/dispatch/index.d.cts.map +1 -0
  32. package/dist/callbacks/dispatch/index.d.ts +10 -2
  33. package/dist/callbacks/dispatch/index.d.ts.map +1 -0
  34. package/dist/callbacks/dispatch/index.js +48 -41
  35. package/dist/callbacks/dispatch/index.js.map +1 -0
  36. package/dist/callbacks/dispatch/web.cjs +60 -56
  37. package/dist/callbacks/dispatch/web.cjs.map +1 -0
  38. package/dist/callbacks/dispatch/web.d.cts +40 -0
  39. package/dist/callbacks/dispatch/web.d.cts.map +1 -0
  40. package/dist/callbacks/dispatch/web.d.ts +10 -2
  41. package/dist/callbacks/dispatch/web.d.ts.map +1 -0
  42. package/dist/callbacks/dispatch/web.js +54 -53
  43. package/dist/callbacks/dispatch/web.js.map +1 -0
  44. package/dist/callbacks/manager.cjs +580 -877
  45. package/dist/callbacks/manager.cjs.map +1 -0
  46. package/dist/callbacks/manager.d.cts +192 -0
  47. package/dist/callbacks/manager.d.cts.map +1 -0
  48. package/dist/callbacks/manager.d.ts +146 -133
  49. package/dist/callbacks/manager.d.ts.map +1 -0
  50. package/dist/callbacks/manager.js +564 -863
  51. package/dist/callbacks/manager.js.map +1 -0
  52. package/dist/callbacks/promises.cjs +20 -6
  53. package/dist/callbacks/promises.cjs.map +1 -0
  54. package/dist/callbacks/promises.d.cts +2 -0
  55. package/dist/callbacks/promises.d.ts +1 -1
  56. package/dist/callbacks/promises.js +12 -1
  57. package/dist/callbacks/promises.js.map +1 -0
  58. package/dist/chat_history.cjs +126 -119
  59. package/dist/chat_history.cjs.map +1 -0
  60. package/dist/chat_history.d.cts +99 -0
  61. package/dist/chat_history.d.cts.map +1 -0
  62. package/dist/chat_history.d.ts +82 -75
  63. package/dist/chat_history.d.ts.map +1 -0
  64. package/dist/chat_history.js +118 -113
  65. package/dist/chat_history.js.map +1 -0
  66. package/dist/context.cjs +29 -18
  67. package/dist/context.cjs.map +1 -0
  68. package/dist/context.d.cts +7 -0
  69. package/dist/context.d.cts.map +1 -0
  70. package/dist/context.d.ts +7 -2
  71. package/dist/context.d.ts.map +1 -0
  72. package/dist/context.js +18 -11
  73. package/dist/context.js.map +1 -0
  74. package/dist/document_loaders/base.cjs +31 -22
  75. package/dist/document_loaders/base.cjs.map +1 -0
  76. package/dist/document_loaders/base.d.cts +34 -0
  77. package/dist/document_loaders/base.d.cts.map +1 -0
  78. package/dist/document_loaders/base.d.ts +22 -16
  79. package/dist/document_loaders/base.d.ts.map +1 -0
  80. package/dist/document_loaders/base.js +26 -19
  81. package/dist/document_loaders/base.js.map +1 -0
  82. package/dist/document_loaders/langsmith.cjs +128 -195
  83. package/dist/document_loaders/langsmith.cjs.map +1 -0
  84. package/dist/document_loaders/langsmith.d.cts +103 -0
  85. package/dist/document_loaders/langsmith.d.cts.map +1 -0
  86. package/dist/document_loaders/langsmith.d.ts +52 -45
  87. package/dist/document_loaders/langsmith.d.ts.map +1 -0
  88. package/dist/document_loaders/langsmith.js +121 -190
  89. package/dist/document_loaders/langsmith.js.map +1 -0
  90. package/dist/documents/document.cjs +23 -40
  91. package/dist/documents/document.cjs.map +1 -0
  92. package/dist/documents/document.d.cts +50 -0
  93. package/dist/documents/document.d.cts.map +1 -0
  94. package/dist/documents/document.d.ts +44 -31
  95. package/dist/documents/document.d.ts.map +1 -0
  96. package/dist/documents/document.js +23 -37
  97. package/dist/documents/document.js.map +1 -0
  98. package/dist/documents/index.cjs +23 -18
  99. package/dist/documents/index.cjs.map +1 -0
  100. package/dist/documents/index.d.cts +3 -0
  101. package/dist/documents/index.d.ts +3 -2
  102. package/dist/documents/index.js +15 -2
  103. package/dist/documents/index.js.map +1 -0
  104. package/dist/documents/transformers.cjs +46 -48
  105. package/dist/documents/transformers.cjs.map +1 -0
  106. package/dist/documents/transformers.d.cts +44 -0
  107. package/dist/documents/transformers.d.cts.map +1 -0
  108. package/dist/documents/transformers.d.ts +27 -21
  109. package/dist/documents/transformers.d.ts.map +1 -0
  110. package/dist/documents/transformers.js +45 -43
  111. package/dist/documents/transformers.js.map +1 -0
  112. package/dist/embeddings.cjs +28 -22
  113. package/dist/embeddings.cjs.map +1 -0
  114. package/dist/embeddings.d.cts +56 -0
  115. package/dist/embeddings.d.cts.map +1 -0
  116. package/dist/embeddings.d.ts +45 -39
  117. package/dist/embeddings.d.ts.map +1 -0
  118. package/dist/embeddings.js +22 -18
  119. package/dist/embeddings.js.map +1 -0
  120. package/dist/errors/index.cjs +9 -8
  121. package/dist/errors/index.cjs.map +1 -0
  122. package/dist/errors/index.js +9 -6
  123. package/dist/errors/index.js.map +1 -0
  124. package/dist/example_selectors/base.cjs +15 -17
  125. package/dist/example_selectors/base.cjs.map +1 -0
  126. package/dist/example_selectors/base.d.cts +26 -0
  127. package/dist/example_selectors/base.d.cts.map +1 -0
  128. package/dist/example_selectors/base.d.ts +21 -15
  129. package/dist/example_selectors/base.d.ts.map +1 -0
  130. package/dist/example_selectors/base.js +15 -13
  131. package/dist/example_selectors/base.js.map +1 -0
  132. package/dist/example_selectors/conditional.cjs +56 -68
  133. package/dist/example_selectors/conditional.cjs.map +1 -0
  134. package/dist/example_selectors/conditional.d.cts +62 -0
  135. package/dist/example_selectors/conditional.d.cts.map +1 -0
  136. package/dist/example_selectors/conditional.d.ts +42 -43
  137. package/dist/example_selectors/conditional.d.ts.map +1 -0
  138. package/dist/example_selectors/conditional.js +54 -63
  139. package/dist/example_selectors/conditional.js.map +1 -0
  140. package/dist/example_selectors/index.cjs +33 -20
  141. package/dist/example_selectors/index.cjs.map +1 -0
  142. package/dist/example_selectors/index.d.cts +5 -0
  143. package/dist/example_selectors/index.d.ts +5 -4
  144. package/dist/example_selectors/index.js +21 -4
  145. package/dist/example_selectors/index.js.map +1 -0
  146. package/dist/example_selectors/length_based.cjs +118 -145
  147. package/dist/example_selectors/length_based.cjs.map +1 -0
  148. package/dist/example_selectors/length_based.d.cts +95 -0
  149. package/dist/example_selectors/length_based.d.cts.map +1 -0
  150. package/dist/example_selectors/length_based.d.ts +45 -39
  151. package/dist/example_selectors/length_based.d.ts.map +1 -0
  152. package/dist/example_selectors/length_based.js +118 -141
  153. package/dist/example_selectors/length_based.js.map +1 -0
  154. package/dist/example_selectors/semantic_similarity.cjs +118 -135
  155. package/dist/example_selectors/semantic_similarity.cjs.map +1 -0
  156. package/dist/example_selectors/semantic_similarity.d.cts +97 -0
  157. package/dist/example_selectors/semantic_similarity.d.cts.map +1 -0
  158. package/dist/example_selectors/semantic_similarity.d.ts +59 -53
  159. package/dist/example_selectors/semantic_similarity.d.ts.map +1 -0
  160. package/dist/example_selectors/semantic_similarity.js +117 -130
  161. package/dist/example_selectors/semantic_similarity.js.map +1 -0
  162. package/dist/index.cjs +12 -0
  163. package/dist/index.cjs.map +1 -0
  164. package/dist/index.d.cts +1 -0
  165. package/dist/index.d.ts +1 -0
  166. package/dist/index.js +6 -0
  167. package/dist/index.js.map +1 -0
  168. package/dist/indexing/base.cjs +207 -272
  169. package/dist/indexing/base.cjs.map +1 -0
  170. package/dist/indexing/base.d.cts +125 -0
  171. package/dist/indexing/base.d.cts.map +1 -0
  172. package/dist/indexing/base.d.ts +88 -80
  173. package/dist/indexing/base.d.ts.map +1 -0
  174. package/dist/indexing/base.js +205 -267
  175. package/dist/indexing/base.js.map +1 -0
  176. package/dist/indexing/index.cjs +33 -18
  177. package/dist/indexing/index.cjs.map +1 -0
  178. package/dist/indexing/index.d.cts +3 -0
  179. package/dist/indexing/index.d.ts +3 -2
  180. package/dist/indexing/index.js +20 -2
  181. package/dist/indexing/index.js.map +1 -0
  182. package/dist/indexing/record_manager.cjs +11 -17
  183. package/dist/indexing/record_manager.cjs.map +1 -0
  184. package/dist/indexing/record_manager.d.cts +70 -0
  185. package/dist/indexing/record_manager.d.cts.map +1 -0
  186. package/dist/indexing/record_manager.d.ts +65 -59
  187. package/dist/indexing/record_manager.d.ts.map +1 -0
  188. package/dist/indexing/record_manager.js +10 -13
  189. package/dist/indexing/record_manager.js.map +1 -0
  190. package/dist/language_models/base.cjs +212 -293
  191. package/dist/language_models/base.cjs.map +1 -0
  192. package/dist/language_models/base.d.cts +301 -0
  193. package/dist/language_models/base.d.cts.map +1 -0
  194. package/dist/language_models/base.d.ts +256 -212
  195. package/dist/language_models/base.d.ts.map +1 -0
  196. package/dist/language_models/base.js +202 -285
  197. package/dist/language_models/base.js.map +1 -0
  198. package/dist/language_models/chat_models.cjs +500 -622
  199. package/dist/language_models/chat_models.cjs.map +1 -0
  200. package/dist/language_models/chat_models.d.cts +261 -0
  201. package/dist/language_models/chat_models.d.cts.map +1 -0
  202. package/dist/language_models/chat_models.d.ts +228 -172
  203. package/dist/language_models/chat_models.d.ts.map +1 -0
  204. package/dist/language_models/chat_models.js +492 -616
  205. package/dist/language_models/chat_models.js.map +1 -0
  206. package/dist/language_models/llms.cjs +328 -376
  207. package/dist/language_models/llms.cjs.map +1 -0
  208. package/dist/language_models/llms.d.cts +149 -0
  209. package/dist/language_models/llms.d.cts.map +1 -0
  210. package/dist/language_models/llms.d.ts +135 -115
  211. package/dist/language_models/llms.d.ts.map +1 -0
  212. package/dist/language_models/llms.js +321 -371
  213. package/dist/language_models/llms.js.map +1 -0
  214. package/dist/language_models/utils.cjs +19 -0
  215. package/dist/language_models/utils.cjs.map +1 -0
  216. package/dist/language_models/utils.js +17 -0
  217. package/dist/language_models/utils.js.map +1 -0
  218. package/dist/load/import_constants.cjs +7 -5
  219. package/dist/load/import_constants.cjs.map +1 -0
  220. package/dist/load/import_constants.js +6 -2
  221. package/dist/load/import_constants.js.map +1 -0
  222. package/dist/load/import_map.cjs +138 -79
  223. package/dist/load/import_map.cjs.map +1 -0
  224. package/dist/load/import_map.js +134 -44
  225. package/dist/load/import_map.js.map +1 -0
  226. package/dist/load/import_type.d.cts +7 -0
  227. package/dist/load/import_type.d.cts.map +1 -0
  228. package/dist/load/import_type.d.ts +7 -4
  229. package/dist/load/import_type.d.ts.map +1 -0
  230. package/dist/load/index.cjs +85 -192
  231. package/dist/load/index.cjs.map +1 -0
  232. package/dist/load/index.d.cts +12 -0
  233. package/dist/load/index.d.cts.map +1 -0
  234. package/dist/load/index.d.ts +11 -6
  235. package/dist/load/index.d.ts.map +1 -0
  236. package/dist/load/index.js +84 -155
  237. package/dist/load/index.js.map +1 -0
  238. package/dist/load/map_keys.cjs +16 -19
  239. package/dist/load/map_keys.cjs.map +1 -0
  240. package/dist/load/map_keys.d.cts +8 -0
  241. package/dist/load/map_keys.d.cts.map +1 -0
  242. package/dist/load/map_keys.d.ts +7 -8
  243. package/dist/load/map_keys.d.ts.map +1 -0
  244. package/dist/load/map_keys.js +14 -12
  245. package/dist/load/map_keys.js.map +1 -0
  246. package/dist/load/serializable.cjs +143 -185
  247. package/dist/load/serializable.cjs.map +1 -0
  248. package/dist/load/serializable.d.cts +82 -0
  249. package/dist/load/serializable.d.cts.map +1 -0
  250. package/dist/load/serializable.d.ts +74 -68
  251. package/dist/load/serializable.d.ts.map +1 -0
  252. package/dist/load/serializable.js +136 -180
  253. package/dist/load/serializable.js.map +1 -0
  254. package/dist/memory.cjs +60 -51
  255. package/dist/memory.cjs.map +1 -0
  256. package/dist/memory.d.cts +69 -0
  257. package/dist/memory.d.cts.map +1 -0
  258. package/dist/memory.d.ts +34 -27
  259. package/dist/memory.d.ts.map +1 -0
  260. package/dist/memory.js +54 -47
  261. package/dist/memory.js.map +1 -0
  262. package/dist/messages/ai.cjs +280 -333
  263. package/dist/messages/ai.cjs.map +1 -0
  264. package/dist/messages/ai.d.cts +148 -0
  265. package/dist/messages/ai.d.cts.map +1 -0
  266. package/dist/messages/ai.d.ts +119 -107
  267. package/dist/messages/ai.d.ts.map +1 -0
  268. package/dist/messages/ai.js +279 -328
  269. package/dist/messages/ai.js.map +1 -0
  270. package/dist/messages/base.cjs +225 -364
  271. package/dist/messages/base.cjs.map +1 -0
  272. package/dist/messages/base.d.cts +188 -0
  273. package/dist/messages/base.d.cts.map +1 -0
  274. package/dist/messages/base.d.ts +147 -147
  275. package/dist/messages/base.d.ts.map +1 -0
  276. package/dist/messages/base.js +222 -357
  277. package/dist/messages/base.js.map +1 -0
  278. package/dist/messages/block_translators/anthropic.cjs +320 -0
  279. package/dist/messages/block_translators/anthropic.cjs.map +1 -0
  280. package/dist/messages/block_translators/anthropic.js +319 -0
  281. package/dist/messages/block_translators/anthropic.js.map +1 -0
  282. package/dist/messages/block_translators/data.cjs +71 -0
  283. package/dist/messages/block_translators/data.cjs.map +1 -0
  284. package/dist/messages/block_translators/data.js +69 -0
  285. package/dist/messages/block_translators/data.js.map +1 -0
  286. package/dist/messages/block_translators/index.cjs +12 -0
  287. package/dist/messages/block_translators/index.cjs.map +1 -0
  288. package/dist/messages/block_translators/index.js +12 -0
  289. package/dist/messages/block_translators/index.js.map +1 -0
  290. package/dist/messages/block_translators/openai.cjs +324 -0
  291. package/dist/messages/block_translators/openai.cjs.map +1 -0
  292. package/dist/messages/block_translators/openai.js +323 -0
  293. package/dist/messages/block_translators/openai.js.map +1 -0
  294. package/dist/messages/block_translators/utils.cjs +35 -0
  295. package/dist/messages/block_translators/utils.cjs.map +1 -0
  296. package/dist/messages/block_translators/utils.js +28 -0
  297. package/dist/messages/block_translators/utils.js.map +1 -0
  298. package/dist/messages/chat.cjs +78 -86
  299. package/dist/messages/chat.cjs.map +1 -0
  300. package/dist/messages/chat.d.cts +37 -0
  301. package/dist/messages/chat.d.cts.map +1 -0
  302. package/dist/messages/chat.d.ts +27 -22
  303. package/dist/messages/chat.d.ts.map +1 -0
  304. package/dist/messages/chat.js +77 -81
  305. package/dist/messages/chat.js.map +1 -0
  306. package/dist/messages/content/base.d.cts +20 -0
  307. package/dist/messages/content/base.d.cts.map +1 -0
  308. package/dist/messages/content/base.d.ts +20 -0
  309. package/dist/messages/content/base.d.ts.map +1 -0
  310. package/dist/messages/content/data.cjs +146 -0
  311. package/dist/messages/content/data.cjs.map +1 -0
  312. package/dist/messages/content/data.d.cts +280 -0
  313. package/dist/messages/content/data.d.cts.map +1 -0
  314. package/dist/messages/content/data.d.ts +280 -0
  315. package/dist/messages/content/data.d.ts.map +1 -0
  316. package/dist/messages/content/data.js +137 -0
  317. package/dist/messages/content/data.js.map +1 -0
  318. package/dist/messages/content/index.cjs +14 -0
  319. package/dist/messages/content/index.cjs.map +1 -0
  320. package/dist/messages/content/index.d.cts +101 -0
  321. package/dist/messages/content/index.d.cts.map +1 -0
  322. package/dist/messages/content/index.d.ts +101 -0
  323. package/dist/messages/content/index.d.ts.map +1 -0
  324. package/dist/messages/content/index.js +14 -0
  325. package/dist/messages/content/index.js.map +1 -0
  326. package/dist/messages/content/multimodal.cjs +13 -0
  327. package/dist/messages/content/multimodal.cjs.map +1 -0
  328. package/dist/messages/content/multimodal.d.cts +108 -0
  329. package/dist/messages/content/multimodal.d.cts.map +1 -0
  330. package/dist/messages/content/multimodal.d.ts +108 -0
  331. package/dist/messages/content/multimodal.d.ts.map +1 -0
  332. package/dist/messages/content/multimodal.js +12 -0
  333. package/dist/messages/content/multimodal.js.map +1 -0
  334. package/dist/messages/content/tools.cjs +15 -0
  335. package/dist/messages/content/tools.cjs.map +1 -0
  336. package/dist/messages/content/tools.d.cts +151 -0
  337. package/dist/messages/content/tools.d.cts.map +1 -0
  338. package/dist/messages/content/tools.d.ts +151 -0
  339. package/dist/messages/content/tools.d.ts.map +1 -0
  340. package/dist/messages/content/tools.js +14 -0
  341. package/dist/messages/content/tools.js.map +1 -0
  342. package/dist/messages/function.cjs +49 -49
  343. package/dist/messages/function.cjs.map +1 -0
  344. package/dist/messages/function.d.cts +30 -0
  345. package/dist/messages/function.d.cts.map +1 -0
  346. package/dist/messages/function.d.ts +20 -16
  347. package/dist/messages/function.d.ts.map +1 -0
  348. package/dist/messages/function.js +48 -44
  349. package/dist/messages/function.js.map +1 -0
  350. package/dist/messages/human.cjs +47 -49
  351. package/dist/messages/human.cjs.map +1 -0
  352. package/dist/messages/human.d.cts +31 -0
  353. package/dist/messages/human.d.cts.map +1 -0
  354. package/dist/messages/human.d.ts +22 -22
  355. package/dist/messages/human.d.ts.map +1 -0
  356. package/dist/messages/human.js +46 -44
  357. package/dist/messages/human.js.map +1 -0
  358. package/dist/messages/index.cjs +139 -34
  359. package/dist/messages/index.cjs.map +1 -0
  360. package/dist/messages/index.d.cts +13 -0
  361. package/dist/messages/index.d.ts +13 -11
  362. package/dist/messages/index.js +78 -13
  363. package/dist/messages/index.js.map +1 -0
  364. package/dist/messages/modifier.cjs +30 -33
  365. package/dist/messages/modifier.cjs.map +1 -0
  366. package/dist/messages/modifier.d.cts +24 -0
  367. package/dist/messages/modifier.d.cts.map +1 -0
  368. package/dist/messages/modifier.d.ts +18 -13
  369. package/dist/messages/modifier.d.ts.map +1 -0
  370. package/dist/messages/modifier.js +30 -29
  371. package/dist/messages/modifier.js.map +1 -0
  372. package/dist/messages/system.cjs +47 -49
  373. package/dist/messages/system.cjs.map +1 -0
  374. package/dist/messages/system.d.cts +31 -0
  375. package/dist/messages/system.d.cts.map +1 -0
  376. package/dist/messages/system.d.ts +22 -22
  377. package/dist/messages/system.d.ts.map +1 -0
  378. package/dist/messages/system.js +46 -44
  379. package/dist/messages/system.js.map +1 -0
  380. package/dist/messages/tool.cjs +153 -189
  381. package/dist/messages/tool.cjs.map +1 -0
  382. package/dist/messages/tool.d.cts +173 -0
  383. package/dist/messages/tool.d.cts.map +1 -0
  384. package/dist/messages/tool.d.ts +96 -90
  385. package/dist/messages/tool.d.ts.map +1 -0
  386. package/dist/messages/tool.js +145 -183
  387. package/dist/messages/tool.js.map +1 -0
  388. package/dist/messages/transformers.cjs +287 -431
  389. package/dist/messages/transformers.cjs.map +1 -0
  390. package/dist/messages/transformers.d.cts +472 -0
  391. package/dist/messages/transformers.d.cts.map +1 -0
  392. package/dist/messages/transformers.d.ts +111 -105
  393. package/dist/messages/transformers.d.ts.map +1 -0
  394. package/dist/messages/transformers.js +284 -425
  395. package/dist/messages/transformers.js.map +1 -0
  396. package/dist/messages/utils.cjs +172 -267
  397. package/dist/messages/utils.cjs.map +1 -0
  398. package/dist/messages/utils.d.cts +36 -0
  399. package/dist/messages/utils.d.cts.map +1 -0
  400. package/dist/messages/utils.d.ts +13 -8
  401. package/dist/messages/utils.d.ts.map +1 -0
  402. package/dist/messages/utils.js +170 -262
  403. package/dist/messages/utils.js.map +1 -0
  404. package/dist/output_parsers/base.cjs +104 -120
  405. package/dist/output_parsers/base.cjs.map +1 -0
  406. package/dist/output_parsers/base.d.cts +108 -0
  407. package/dist/output_parsers/base.d.cts.map +1 -0
  408. package/dist/output_parsers/base.d.ts +76 -71
  409. package/dist/output_parsers/base.d.ts.map +1 -0
  410. package/dist/output_parsers/base.js +102 -114
  411. package/dist/output_parsers/base.js.map +1 -0
  412. package/dist/output_parsers/bytes.cjs +27 -39
  413. package/dist/output_parsers/bytes.cjs.map +1 -0
  414. package/dist/output_parsers/bytes.d.cts +19 -0
  415. package/dist/output_parsers/bytes.d.cts.map +1 -0
  416. package/dist/output_parsers/bytes.d.ts +13 -7
  417. package/dist/output_parsers/bytes.d.ts.map +1 -0
  418. package/dist/output_parsers/bytes.js +27 -35
  419. package/dist/output_parsers/bytes.js.map +1 -0
  420. package/dist/output_parsers/index.cjs +66 -24
  421. package/dist/output_parsers/index.cjs.map +1 -0
  422. package/dist/output_parsers/index.d.cts +10 -0
  423. package/dist/output_parsers/index.d.ts +10 -8
  424. package/dist/output_parsers/index.js +40 -8
  425. package/dist/output_parsers/index.js.map +1 -0
  426. package/dist/output_parsers/json.cjs +36 -57
  427. package/dist/output_parsers/json.cjs.map +1 -0
  428. package/dist/output_parsers/json.d.cts +26 -0
  429. package/dist/output_parsers/json.d.cts.map +1 -0
  430. package/dist/output_parsers/json.d.ts +20 -13
  431. package/dist/output_parsers/json.d.ts.map +1 -0
  432. package/dist/output_parsers/json.js +36 -52
  433. package/dist/output_parsers/json.js.map +1 -0
  434. package/dist/output_parsers/list.cjs +155 -239
  435. package/dist/output_parsers/list.cjs.map +1 -0
  436. package/dist/output_parsers/list.d.cts +85 -0
  437. package/dist/output_parsers/list.d.cts.map +1 -0
  438. package/dist/output_parsers/list.d.ts +67 -58
  439. package/dist/output_parsers/list.d.ts.map +1 -0
  440. package/dist/output_parsers/list.js +151 -231
  441. package/dist/output_parsers/list.js.map +1 -0
  442. package/dist/output_parsers/openai_functions/index.cjs +22 -17
  443. package/dist/output_parsers/openai_functions/index.cjs.map +1 -0
  444. package/dist/output_parsers/openai_functions/index.d.cts +2 -0
  445. package/dist/output_parsers/openai_functions/index.d.ts +2 -1
  446. package/dist/output_parsers/openai_functions/index.js +14 -1
  447. package/dist/output_parsers/openai_functions/index.js.map +1 -0
  448. package/dist/output_parsers/openai_functions/json_output_functions_parsers.cjs +140 -203
  449. package/dist/output_parsers/openai_functions/json_output_functions_parsers.cjs.map +1 -0
  450. package/dist/output_parsers/openai_functions/json_output_functions_parsers.d.cts +90 -0
  451. package/dist/output_parsers/openai_functions/json_output_functions_parsers.d.cts.map +1 -0
  452. package/dist/output_parsers/openai_functions/json_output_functions_parsers.d.ts +68 -58
  453. package/dist/output_parsers/openai_functions/json_output_functions_parsers.d.ts.map +1 -0
  454. package/dist/output_parsers/openai_functions/json_output_functions_parsers.js +138 -197
  455. package/dist/output_parsers/openai_functions/json_output_functions_parsers.js.map +1 -0
  456. package/dist/output_parsers/openai_tools/index.cjs +26 -17
  457. package/dist/output_parsers/openai_tools/index.cjs.map +1 -0
  458. package/dist/output_parsers/openai_tools/index.d.cts +2 -0
  459. package/dist/output_parsers/openai_tools/index.d.ts +2 -1
  460. package/dist/output_parsers/openai_tools/index.js +16 -1
  461. package/dist/output_parsers/openai_tools/index.js.map +1 -0
  462. package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs +176 -256
  463. package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs.map +1 -0
  464. package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.cts +120 -0
  465. package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.cts.map +1 -0
  466. package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.ts +98 -70
  467. package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.ts.map +1 -0
  468. package/dist/output_parsers/openai_tools/json_output_tools_parsers.js +173 -249
  469. package/dist/output_parsers/openai_tools/json_output_tools_parsers.js.map +1 -0
  470. package/dist/output_parsers/string.cjs +70 -84
  471. package/dist/output_parsers/string.cjs.map +1 -0
  472. package/dist/output_parsers/string.d.cts +45 -0
  473. package/dist/output_parsers/string.d.cts.map +1 -0
  474. package/dist/output_parsers/string.d.ts +25 -19
  475. package/dist/output_parsers/string.d.ts.map +1 -0
  476. package/dist/output_parsers/string.js +70 -80
  477. package/dist/output_parsers/string.js.map +1 -0
  478. package/dist/output_parsers/structured.cjs +148 -181
  479. package/dist/output_parsers/structured.cjs.map +1 -0
  480. package/dist/output_parsers/structured.d.cts +97 -0
  481. package/dist/output_parsers/structured.d.cts.map +1 -0
  482. package/dist/output_parsers/structured.d.ts +82 -74
  483. package/dist/output_parsers/structured.d.ts.map +1 -0
  484. package/dist/output_parsers/structured.js +144 -174
  485. package/dist/output_parsers/structured.js.map +1 -0
  486. package/dist/output_parsers/transform.cjs +79 -109
  487. package/dist/output_parsers/transform.cjs.map +1 -0
  488. package/dist/output_parsers/transform.d.cts +41 -0
  489. package/dist/output_parsers/transform.d.cts.map +1 -0
  490. package/dist/output_parsers/transform.d.ts +29 -22
  491. package/dist/output_parsers/transform.d.ts.map +1 -0
  492. package/dist/output_parsers/transform.js +77 -104
  493. package/dist/output_parsers/transform.js.map +1 -0
  494. package/dist/output_parsers/xml.cjs +95 -129
  495. package/dist/output_parsers/xml.cjs.map +1 -0
  496. package/dist/output_parsers/xml.d.cts +34 -0
  497. package/dist/output_parsers/xml.d.cts.map +1 -0
  498. package/dist/output_parsers/xml.d.ts +29 -24
  499. package/dist/output_parsers/xml.d.ts.map +1 -0
  500. package/dist/output_parsers/xml.js +93 -124
  501. package/dist/output_parsers/xml.js.map +1 -0
  502. package/dist/outputs.cjs +57 -57
  503. package/dist/outputs.cjs.map +1 -0
  504. package/dist/outputs.d.cts +72 -0
  505. package/dist/outputs.d.cts.map +1 -0
  506. package/dist/outputs.d.ts +55 -44
  507. package/dist/outputs.d.ts.map +1 -0
  508. package/dist/outputs.js +50 -53
  509. package/dist/outputs.js.map +1 -0
  510. package/dist/prompt_values.cjs +101 -148
  511. package/dist/prompt_values.cjs.map +1 -0
  512. package/dist/prompt_values.d.cts +83 -0
  513. package/dist/prompt_values.d.cts.map +1 -0
  514. package/dist/prompt_values.d.ts +53 -48
  515. package/dist/prompt_values.d.ts.map +1 -0
  516. package/dist/prompt_values.js +90 -139
  517. package/dist/prompt_values.js.map +1 -0
  518. package/dist/prompts/base.cjs +106 -173
  519. package/dist/prompts/base.cjs.map +1 -0
  520. package/dist/prompts/base.d.cts +108 -0
  521. package/dist/prompts/base.d.cts.map +1 -0
  522. package/dist/prompts/base.d.ts +98 -85
  523. package/dist/prompts/base.d.ts.map +1 -0
  524. package/dist/prompts/base.js +106 -136
  525. package/dist/prompts/base.js.map +1 -0
  526. package/dist/prompts/chat.cjs +533 -786
  527. package/dist/prompts/chat.cjs.map +1 -0
  528. package/dist/prompts/chat.d.cts +296 -0
  529. package/dist/prompts/chat.d.cts.map +1 -0
  530. package/dist/prompts/chat.d.ts +191 -136
  531. package/dist/prompts/chat.d.ts.map +1 -0
  532. package/dist/prompts/chat.js +522 -771
  533. package/dist/prompts/chat.js.map +1 -0
  534. package/dist/prompts/dict.cjs +60 -110
  535. package/dist/prompts/dict.cjs.map +1 -0
  536. package/dist/prompts/dict.d.cts +23 -0
  537. package/dist/prompts/dict.d.cts.map +1 -0
  538. package/dist/prompts/dict.d.ts +19 -14
  539. package/dist/prompts/dict.d.ts.map +1 -0
  540. package/dist/prompts/dict.js +58 -104
  541. package/dist/prompts/dict.js.map +1 -0
  542. package/dist/prompts/few_shot.cjs +239 -352
  543. package/dist/prompts/few_shot.cjs.map +1 -0
  544. package/dist/prompts/few_shot.d.cts +204 -0
  545. package/dist/prompts/few_shot.d.cts.map +1 -0
  546. package/dist/prompts/few_shot.d.ts +157 -148
  547. package/dist/prompts/few_shot.d.ts.map +1 -0
  548. package/dist/prompts/few_shot.js +237 -346
  549. package/dist/prompts/few_shot.js.map +1 -0
  550. package/dist/prompts/image.cjs +92 -126
  551. package/dist/prompts/image.cjs.map +1 -0
  552. package/dist/prompts/image.d.cts +86 -0
  553. package/dist/prompts/image.d.cts.map +1 -0
  554. package/dist/prompts/image.d.ts +76 -60
  555. package/dist/prompts/image.d.ts.map +1 -0
  556. package/dist/prompts/image.js +92 -122
  557. package/dist/prompts/image.js.map +1 -0
  558. package/dist/prompts/index.cjs +79 -27
  559. package/dist/prompts/index.cjs.map +1 -0
  560. package/dist/prompts/index.d.cts +12 -0
  561. package/dist/prompts/index.d.ts +12 -11
  562. package/dist/prompts/index.js +47 -11
  563. package/dist/prompts/index.js.map +1 -0
  564. package/dist/prompts/pipeline.cjs +128 -142
  565. package/dist/prompts/pipeline.cjs.map +1 -0
  566. package/dist/prompts/pipeline.d.cts +104 -0
  567. package/dist/prompts/pipeline.d.cts.map +1 -0
  568. package/dist/prompts/pipeline.d.ts +48 -42
  569. package/dist/prompts/pipeline.d.ts.map +1 -0
  570. package/dist/prompts/pipeline.js +127 -137
  571. package/dist/prompts/pipeline.js.map +1 -0
  572. package/dist/prompts/prompt.cjs +131 -164
  573. package/dist/prompts/prompt.cjs.map +1 -0
  574. package/dist/prompts/prompt.d.cts +134 -0
  575. package/dist/prompts/prompt.d.cts.map +1 -0
  576. package/dist/prompts/prompt.d.ts +106 -79
  577. package/dist/prompts/prompt.d.ts.map +1 -0
  578. package/dist/prompts/prompt.js +131 -160
  579. package/dist/prompts/prompt.js.map +1 -0
  580. package/dist/prompts/serde.d.cts +50 -0
  581. package/dist/prompts/serde.d.cts.map +1 -0
  582. package/dist/prompts/serde.d.ts +24 -17
  583. package/dist/prompts/serde.d.ts.map +1 -0
  584. package/dist/prompts/string.cjs +23 -23
  585. package/dist/prompts/string.cjs.map +1 -0
  586. package/dist/prompts/string.d.cts +27 -0
  587. package/dist/prompts/string.d.cts.map +1 -0
  588. package/dist/prompts/string.d.ts +21 -11
  589. package/dist/prompts/string.d.ts.map +1 -0
  590. package/dist/prompts/string.js +23 -19
  591. package/dist/prompts/string.js.map +1 -0
  592. package/dist/prompts/structured.cjs +46 -70
  593. package/dist/prompts/structured.cjs.map +1 -0
  594. package/dist/prompts/structured.d.cts +40 -0
  595. package/dist/prompts/structured.d.cts.map +1 -0
  596. package/dist/prompts/structured.d.ts +33 -14
  597. package/dist/prompts/structured.d.ts.map +1 -0
  598. package/dist/prompts/structured.js +46 -66
  599. package/dist/prompts/structured.js.map +1 -0
  600. package/dist/prompts/template.cjs +138 -157
  601. package/dist/prompts/template.cjs.map +1 -0
  602. package/dist/prompts/template.d.cts +48 -0
  603. package/dist/prompts/template.d.cts.map +1 -0
  604. package/dist/prompts/template.d.ts +24 -19
  605. package/dist/prompts/template.d.ts.map +1 -0
  606. package/dist/prompts/template.js +135 -150
  607. package/dist/prompts/template.js.map +1 -0
  608. package/dist/retrievers/document_compressors/base.cjs +21 -11
  609. package/dist/retrievers/document_compressors/base.cjs.map +1 -0
  610. package/dist/retrievers/document_compressors/base.d.cts +25 -0
  611. package/dist/retrievers/document_compressors/base.d.cts.map +1 -0
  612. package/dist/retrievers/document_compressors/base.d.ts +20 -13
  613. package/dist/retrievers/document_compressors/base.d.ts.map +1 -0
  614. package/dist/retrievers/document_compressors/base.js +16 -8
  615. package/dist/retrievers/document_compressors/base.js.map +1 -0
  616. package/dist/retrievers/index.cjs +119 -129
  617. package/dist/retrievers/index.cjs.map +1 -0
  618. package/dist/retrievers/index.d.cts +144 -0
  619. package/dist/retrievers/index.d.cts.map +1 -0
  620. package/dist/retrievers/index.d.ts +98 -88
  621. package/dist/retrievers/index.d.ts.map +1 -0
  622. package/dist/retrievers/index.js +113 -125
  623. package/dist/retrievers/index.js.map +1 -0
  624. package/dist/runnables/base.cjs +1808 -2421
  625. package/dist/runnables/base.cjs.map +1 -0
  626. package/dist/runnables/base.d.cts +990 -0
  627. package/dist/runnables/base.d.cts.map +1 -0
  628. package/dist/runnables/base.d.ts +633 -592
  629. package/dist/runnables/base.d.ts.map +1 -0
  630. package/dist/runnables/base.js +1791 -2396
  631. package/dist/runnables/base.js.map +1 -0
  632. package/dist/runnables/branch.cjs +151 -205
  633. package/dist/runnables/branch.cjs.map +1 -0
  634. package/dist/runnables/branch.d.cts +94 -0
  635. package/dist/runnables/branch.d.cts.map +1 -0
  636. package/dist/runnables/branch.d.ts +50 -51
  637. package/dist/runnables/branch.d.ts.map +1 -0
  638. package/dist/runnables/branch.js +151 -201
  639. package/dist/runnables/branch.js.map +1 -0
  640. package/dist/runnables/config.cjs +136 -212
  641. package/dist/runnables/config.cjs.map +1 -0
  642. package/dist/runnables/config.d.cts +26 -0
  643. package/dist/runnables/config.d.cts.map +1 -0
  644. package/dist/runnables/config.d.ts +18 -7
  645. package/dist/runnables/config.d.ts.map +1 -0
  646. package/dist/runnables/config.js +134 -207
  647. package/dist/runnables/config.js.map +1 -0
  648. package/dist/runnables/graph.cjs +215 -260
  649. package/dist/runnables/graph.cjs.map +1 -0
  650. package/dist/runnables/graph.d.cts +52 -0
  651. package/dist/runnables/graph.d.cts.map +1 -0
  652. package/dist/runnables/graph.d.ts +49 -41
  653. package/dist/runnables/graph.d.ts.map +1 -0
  654. package/dist/runnables/graph.js +206 -253
  655. package/dist/runnables/graph.js.map +1 -0
  656. package/dist/runnables/graph_mermaid.cjs +86 -141
  657. package/dist/runnables/graph_mermaid.cjs.map +1 -0
  658. package/dist/runnables/graph_mermaid.js +86 -139
  659. package/dist/runnables/graph_mermaid.js.map +1 -0
  660. package/dist/runnables/history.cjs +160 -260
  661. package/dist/runnables/history.cjs.map +1 -0
  662. package/dist/runnables/history.d.cts +104 -0
  663. package/dist/runnables/history.d.cts.map +1 -0
  664. package/dist/runnables/history.d.ts +38 -26
  665. package/dist/runnables/history.d.ts.map +1 -0
  666. package/dist/runnables/history.js +160 -256
  667. package/dist/runnables/history.js.map +1 -0
  668. package/dist/runnables/index.cjs +65 -31
  669. package/dist/runnables/index.cjs.map +1 -0
  670. package/dist/runnables/index.d.cts +8 -0
  671. package/dist/runnables/index.d.ts +8 -7
  672. package/dist/runnables/index.js +38 -6
  673. package/dist/runnables/index.js.map +1 -0
  674. package/dist/runnables/iter.cjs +27 -42
  675. package/dist/runnables/iter.cjs.map +1 -0
  676. package/dist/runnables/iter.js +26 -37
  677. package/dist/runnables/iter.js.map +1 -0
  678. package/dist/runnables/passthrough.cjs +97 -125
  679. package/dist/runnables/passthrough.cjs.map +1 -0
  680. package/dist/runnables/passthrough.d.cts +76 -0
  681. package/dist/runnables/passthrough.d.cts.map +1 -0
  682. package/dist/runnables/passthrough.d.ts +46 -40
  683. package/dist/runnables/passthrough.d.ts.map +1 -0
  684. package/dist/runnables/passthrough.js +97 -121
  685. package/dist/runnables/passthrough.js.map +1 -0
  686. package/dist/runnables/remote.cjs +387 -508
  687. package/dist/runnables/remote.cjs.map +1 -0
  688. package/dist/runnables/remote.d.cts +73 -0
  689. package/dist/runnables/remote.d.cts.map +1 -0
  690. package/dist/runnables/remote.d.ts +52 -40
  691. package/dist/runnables/remote.d.ts.map +1 -0
  692. package/dist/runnables/remote.js +379 -502
  693. package/dist/runnables/remote.js.map +1 -0
  694. package/dist/runnables/router.cjs +74 -95
  695. package/dist/runnables/router.cjs.map +1 -0
  696. package/dist/runnables/router.d.cts +58 -0
  697. package/dist/runnables/router.d.cts.map +1 -0
  698. package/dist/runnables/router.d.ts +27 -21
  699. package/dist/runnables/router.d.ts.map +1 -0
  700. package/dist/runnables/router.js +74 -91
  701. package/dist/runnables/router.js.map +1 -0
  702. package/dist/runnables/types.d.cts +81 -0
  703. package/dist/runnables/types.d.cts.map +1 -0
  704. package/dist/runnables/types.d.ts +68 -55
  705. package/dist/runnables/types.d.ts.map +1 -0
  706. package/dist/runnables/utils.cjs +40 -85
  707. package/dist/runnables/utils.cjs.map +1 -0
  708. package/dist/runnables/utils.js +40 -82
  709. package/dist/runnables/utils.js.map +1 -0
  710. package/dist/runnables/wrappers.cjs +14 -15
  711. package/dist/runnables/wrappers.cjs.map +1 -0
  712. package/dist/runnables/wrappers.js +14 -12
  713. package/dist/runnables/wrappers.js.map +1 -0
  714. package/dist/singletons/async_local_storage/context.cjs +167 -177
  715. package/dist/singletons/async_local_storage/context.cjs.map +1 -0
  716. package/dist/singletons/async_local_storage/context.d.cts +163 -0
  717. package/dist/singletons/async_local_storage/context.d.cts.map +1 -0
  718. package/dist/singletons/async_local_storage/context.d.ts +17 -9
  719. package/dist/singletons/async_local_storage/context.d.ts.map +1 -0
  720. package/dist/singletons/async_local_storage/context.js +168 -175
  721. package/dist/singletons/async_local_storage/context.js.map +1 -0
  722. package/dist/singletons/async_local_storage/globals.cjs +11 -8
  723. package/dist/singletons/async_local_storage/globals.cjs.map +1 -0
  724. package/dist/singletons/async_local_storage/globals.d.cts +11 -0
  725. package/dist/singletons/async_local_storage/globals.d.cts.map +1 -0
  726. package/dist/singletons/async_local_storage/globals.d.ts +10 -8
  727. package/dist/singletons/async_local_storage/globals.d.ts.map +1 -0
  728. package/dist/singletons/async_local_storage/globals.js +11 -6
  729. package/dist/singletons/async_local_storage/globals.js.map +1 -0
  730. package/dist/singletons/async_local_storage/index.cjs +55 -65
  731. package/dist/singletons/async_local_storage/index.cjs.map +1 -0
  732. package/dist/singletons/async_local_storage/index.d.cts +18 -0
  733. package/dist/singletons/async_local_storage/index.d.cts.map +1 -0
  734. package/dist/singletons/async_local_storage/index.d.ts +13 -9
  735. package/dist/singletons/async_local_storage/index.d.ts.map +1 -0
  736. package/dist/singletons/async_local_storage/index.js +53 -61
  737. package/dist/singletons/async_local_storage/index.js.map +1 -0
  738. package/dist/singletons/callbacks.cjs +43 -60
  739. package/dist/singletons/callbacks.cjs.map +1 -0
  740. package/dist/singletons/callbacks.d.cts +16 -0
  741. package/dist/singletons/callbacks.d.cts.map +1 -0
  742. package/dist/singletons/callbacks.d.ts +8 -3
  743. package/dist/singletons/callbacks.d.ts.map +1 -0
  744. package/dist/singletons/callbacks.js +43 -54
  745. package/dist/singletons/callbacks.js.map +1 -0
  746. package/dist/singletons/index.cjs +23 -8
  747. package/dist/singletons/index.cjs.map +1 -0
  748. package/dist/singletons/index.d.cts +3 -0
  749. package/dist/singletons/index.d.ts +3 -4
  750. package/dist/singletons/index.js +14 -3
  751. package/dist/singletons/index.js.map +1 -0
  752. package/dist/singletons/tracer.cjs +13 -19
  753. package/dist/singletons/tracer.cjs.map +1 -0
  754. package/dist/singletons/tracer.js +13 -15
  755. package/dist/singletons/tracer.js.map +1 -0
  756. package/dist/stores.cjs +78 -87
  757. package/dist/stores.cjs.map +1 -0
  758. package/dist/stores.d.cts +111 -0
  759. package/dist/stores.d.cts.map +1 -0
  760. package/dist/stores.d.ts +84 -78
  761. package/dist/stores.d.ts.map +1 -0
  762. package/dist/stores.js +71 -82
  763. package/dist/stores.js.map +1 -0
  764. package/dist/structured_query/base.cjs +86 -136
  765. package/dist/structured_query/base.cjs.map +1 -0
  766. package/dist/structured_query/base.d.cts +75 -0
  767. package/dist/structured_query/base.d.cts.map +1 -0
  768. package/dist/structured_query/base.d.ts +53 -47
  769. package/dist/structured_query/base.d.ts.map +1 -0
  770. package/dist/structured_query/base.js +86 -132
  771. package/dist/structured_query/base.js.map +1 -0
  772. package/dist/structured_query/functional.cjs +163 -234
  773. package/dist/structured_query/functional.cjs.map +1 -0
  774. package/dist/structured_query/functional.d.cts +98 -0
  775. package/dist/structured_query/functional.d.cts.map +1 -0
  776. package/dist/structured_query/functional.d.ts +72 -67
  777. package/dist/structured_query/functional.d.ts.map +1 -0
  778. package/dist/structured_query/functional.js +163 -230
  779. package/dist/structured_query/functional.js.map +1 -0
  780. package/dist/structured_query/index.cjs +55 -20
  781. package/dist/structured_query/index.cjs.map +1 -0
  782. package/dist/structured_query/index.d.cts +5 -0
  783. package/dist/structured_query/index.d.ts +5 -4
  784. package/dist/structured_query/index.js +32 -4
  785. package/dist/structured_query/index.js.map +1 -0
  786. package/dist/structured_query/ir.cjs +76 -132
  787. package/dist/structured_query/ir.cjs.map +1 -0
  788. package/dist/structured_query/ir.d.cts +143 -0
  789. package/dist/structured_query/ir.d.cts.map +1 -0
  790. package/dist/structured_query/ir.d.ts +61 -56
  791. package/dist/structured_query/ir.d.ts.map +1 -0
  792. package/dist/structured_query/ir.js +69 -124
  793. package/dist/structured_query/ir.js.map +1 -0
  794. package/dist/structured_query/utils.cjs +58 -83
  795. package/dist/structured_query/utils.cjs.map +1 -0
  796. package/dist/structured_query/utils.d.cts +40 -0
  797. package/dist/structured_query/utils.d.cts.map +1 -0
  798. package/dist/structured_query/utils.d.ts +14 -7
  799. package/dist/structured_query/utils.d.ts.map +1 -0
  800. package/dist/structured_query/utils.js +57 -80
  801. package/dist/structured_query/utils.js.map +1 -0
  802. package/dist/tools/index.cjs +321 -437
  803. package/dist/tools/index.cjs.map +1 -0
  804. package/dist/tools/index.d.cts +209 -0
  805. package/dist/tools/index.d.cts.map +1 -0
  806. package/dist/tools/index.d.ts +153 -149
  807. package/dist/tools/index.d.ts.map +1 -0
  808. package/dist/tools/index.js +305 -424
  809. package/dist/tools/index.js.map +1 -0
  810. package/dist/tools/types.cjs +44 -52
  811. package/dist/tools/types.cjs.map +1 -0
  812. package/dist/tools/types.d.cts +283 -0
  813. package/dist/tools/types.d.cts.map +1 -0
  814. package/dist/tools/types.d.ts +149 -138
  815. package/dist/tools/types.d.ts.map +1 -0
  816. package/dist/tools/types.js +45 -50
  817. package/dist/tools/types.js.map +1 -0
  818. package/dist/tools/utils.cjs +20 -32
  819. package/dist/tools/utils.cjs.map +1 -0
  820. package/dist/tools/utils.d.cts +14 -0
  821. package/dist/tools/utils.d.cts.map +1 -0
  822. package/dist/tools/utils.d.ts +8 -10
  823. package/dist/tools/utils.d.ts.map +1 -0
  824. package/dist/tools/utils.js +20 -29
  825. package/dist/tools/utils.js.map +1 -0
  826. package/dist/tracers/base.cjs +441 -529
  827. package/dist/tracers/base.cjs.map +1 -0
  828. package/dist/tracers/base.d.cts +304 -0
  829. package/dist/tracers/base.d.cts.map +1 -0
  830. package/dist/tracers/base.d.ts +296 -271
  831. package/dist/tracers/base.d.ts.map +1 -0
  832. package/dist/tracers/base.js +435 -525
  833. package/dist/tracers/base.js.map +1 -0
  834. package/dist/tracers/console.cjs +206 -223
  835. package/dist/tracers/console.cjs.map +1 -0
  836. package/dist/tracers/console.d.cts +125 -0
  837. package/dist/tracers/console.d.cts.map +1 -0
  838. package/dist/tracers/console.d.ts +109 -101
  839. package/dist/tracers/console.d.ts.map +1 -0
  840. package/dist/tracers/console.js +199 -215
  841. package/dist/tracers/console.js.map +1 -0
  842. package/dist/tracers/event_stream.cjs +357 -529
  843. package/dist/tracers/event_stream.cjs.map +1 -0
  844. package/dist/tracers/event_stream.d.cts +98 -0
  845. package/dist/tracers/event_stream.d.cts.map +1 -0
  846. package/dist/tracers/event_stream.d.ts +87 -129
  847. package/dist/tracers/event_stream.d.ts.map +1 -0
  848. package/dist/tracers/event_stream.js +355 -523
  849. package/dist/tracers/event_stream.js.map +1 -0
  850. package/dist/tracers/initialize.cjs +40 -29
  851. package/dist/tracers/initialize.cjs.map +1 -0
  852. package/dist/tracers/initialize.d.cts +26 -0
  853. package/dist/tracers/initialize.d.cts.map +1 -0
  854. package/dist/tracers/initialize.d.ts +8 -2
  855. package/dist/tracers/initialize.d.ts.map +1 -0
  856. package/dist/tracers/initialize.js +33 -25
  857. package/dist/tracers/initialize.js.map +1 -0
  858. package/dist/tracers/log_stream.cjs +264 -425
  859. package/dist/tracers/log_stream.cjs.map +1 -0
  860. package/dist/tracers/log_stream.d.cts +129 -0
  861. package/dist/tracers/log_stream.d.cts.map +1 -0
  862. package/dist/tracers/log_stream.d.ts +103 -92
  863. package/dist/tracers/log_stream.d.ts.map +1 -0
  864. package/dist/tracers/log_stream.js +255 -418
  865. package/dist/tracers/log_stream.js.map +1 -0
  866. package/dist/tracers/root_listener.cjs +41 -80
  867. package/dist/tracers/root_listener.cjs.map +1 -0
  868. package/dist/tracers/root_listener.js +41 -76
  869. package/dist/tracers/root_listener.js.map +1 -0
  870. package/dist/tracers/run_collector.cjs +44 -48
  871. package/dist/tracers/run_collector.cjs.map +1 -0
  872. package/dist/tracers/run_collector.d.cts +34 -0
  873. package/dist/tracers/run_collector.d.cts.map +1 -0
  874. package/dist/tracers/run_collector.d.ts +27 -19
  875. package/dist/tracers/run_collector.d.ts.map +1 -0
  876. package/dist/tracers/run_collector.js +38 -44
  877. package/dist/tracers/run_collector.js.map +1 -0
  878. package/dist/tracers/tracer_langchain.cjs +91 -123
  879. package/dist/tracers/tracer_langchain.cjs.map +1 -0
  880. package/dist/tracers/tracer_langchain.d.cts +49 -0
  881. package/dist/tracers/tracer_langchain.d.cts.map +1 -0
  882. package/dist/tracers/tracer_langchain.d.ts +43 -38
  883. package/dist/tracers/tracer_langchain.d.ts.map +1 -0
  884. package/dist/tracers/tracer_langchain.js +84 -118
  885. package/dist/tracers/tracer_langchain.js.map +1 -0
  886. package/dist/tracers/tracer_langchain_v1.cjs +166 -198
  887. package/dist/tracers/tracer_langchain_v1.cjs.map +1 -0
  888. package/dist/tracers/tracer_langchain_v1.d.cts +64 -0
  889. package/dist/tracers/tracer_langchain_v1.d.cts.map +1 -0
  890. package/dist/tracers/tracer_langchain_v1.d.ts +56 -51
  891. package/dist/tracers/tracer_langchain_v1.d.ts.map +1 -0
  892. package/dist/tracers/tracer_langchain_v1.js +158 -192
  893. package/dist/tracers/tracer_langchain_v1.js.map +1 -0
  894. package/dist/types/_internal.d.cts +8 -0
  895. package/dist/types/_internal.d.cts.map +1 -0
  896. package/dist/types/_internal.d.ts +8 -1
  897. package/dist/types/_internal.d.ts.map +1 -0
  898. package/dist/types/stream.cjs +12 -2
  899. package/dist/types/stream.cjs.map +1 -0
  900. package/dist/types/stream.d.cts +3 -0
  901. package/dist/types/stream.d.ts +3 -2
  902. package/dist/types/stream.js +6 -1
  903. package/dist/types/stream.js.map +1 -0
  904. package/dist/types/type-utils.d.cts +7 -0
  905. package/dist/types/type-utils.d.cts.map +1 -0
  906. package/dist/types/type-utils.d.ts +7 -1
  907. package/dist/types/type-utils.d.ts.map +1 -0
  908. package/dist/utils/async_caller.cjs +81 -122
  909. package/dist/utils/async_caller.cjs.map +1 -0
  910. package/dist/utils/async_caller.d.cts +52 -0
  911. package/dist/utils/async_caller.d.cts.map +1 -0
  912. package/dist/utils/async_caller.d.ts +36 -29
  913. package/dist/utils/async_caller.d.ts.map +1 -0
  914. package/dist/utils/async_caller.js +74 -114
  915. package/dist/utils/async_caller.js.map +1 -0
  916. package/dist/utils/callbacks.cjs +14 -14
  917. package/dist/utils/callbacks.cjs.map +1 -0
  918. package/dist/utils/callbacks.js +15 -11
  919. package/dist/utils/callbacks.js.map +1 -0
  920. package/dist/utils/chunk_array.cjs +18 -8
  921. package/dist/utils/chunk_array.cjs.map +1 -0
  922. package/dist/utils/chunk_array.d.cts +5 -0
  923. package/dist/utils/chunk_array.d.cts.map +1 -0
  924. package/dist/utils/chunk_array.d.ts +5 -1
  925. package/dist/utils/chunk_array.d.ts.map +1 -0
  926. package/dist/utils/chunk_array.js +14 -6
  927. package/dist/utils/chunk_array.js.map +1 -0
  928. package/dist/utils/env.cjs +62 -72
  929. package/dist/utils/env.cjs.map +1 -0
  930. package/dist/utils/env.d.cts +36 -0
  931. package/dist/utils/env.d.cts.map +1 -0
  932. package/dist/utils/env.d.ts +30 -22
  933. package/dist/utils/env.d.ts.map +1 -0
  934. package/dist/utils/env.js +54 -66
  935. package/dist/utils/env.js.map +1 -0
  936. package/dist/utils/event_source_parse.cjs +172 -225
  937. package/dist/utils/event_source_parse.cjs.map +1 -0
  938. package/dist/utils/event_source_parse.d.cts +47 -0
  939. package/dist/utils/event_source_parse.d.cts.map +1 -0
  940. package/dist/utils/event_source_parse.d.ts +22 -14
  941. package/dist/utils/event_source_parse.d.ts.map +1 -0
  942. package/dist/utils/event_source_parse.js +164 -220
  943. package/dist/utils/event_source_parse.js.map +1 -0
  944. package/dist/utils/fast-json-patch/index.cjs +14 -58
  945. package/dist/utils/fast-json-patch/index.cjs.map +1 -0
  946. package/dist/utils/fast-json-patch/index.js +14 -15
  947. package/dist/utils/fast-json-patch/index.js.map +1 -0
  948. package/dist/utils/fast-json-patch/src/core.cjs +319 -445
  949. package/dist/utils/fast-json-patch/src/core.cjs.map +1 -0
  950. package/dist/utils/fast-json-patch/src/core.d.cts +80 -0
  951. package/dist/utils/fast-json-patch/src/core.d.cts.map +1 -0
  952. package/dist/utils/fast-json-patch/src/core.d.ts +38 -69
  953. package/dist/utils/fast-json-patch/src/core.d.ts.map +1 -0
  954. package/dist/utils/fast-json-patch/src/core.js +314 -442
  955. package/dist/utils/fast-json-patch/src/core.js.map +1 -0
  956. package/dist/utils/fast-json-patch/src/duplex.cjs +72 -231
  957. package/dist/utils/fast-json-patch/src/duplex.cjs.map +1 -0
  958. package/dist/utils/fast-json-patch/src/duplex.d.cts +11 -0
  959. package/dist/utils/fast-json-patch/src/duplex.d.cts.map +1 -0
  960. package/dist/utils/fast-json-patch/src/duplex.d.ts +7 -19
  961. package/dist/utils/fast-json-patch/src/duplex.d.ts.map +1 -0
  962. package/dist/utils/fast-json-patch/src/duplex.js +73 -226
  963. package/dist/utils/fast-json-patch/src/duplex.js.map +1 -0
  964. package/dist/utils/fast-json-patch/src/helpers.cjs +99 -171
  965. package/dist/utils/fast-json-patch/src/helpers.cjs.map +1 -0
  966. package/dist/utils/fast-json-patch/src/helpers.js +99 -166
  967. package/dist/utils/fast-json-patch/src/helpers.js.map +1 -0
  968. package/dist/utils/function_calling.cjs +62 -59
  969. package/dist/utils/function_calling.cjs.map +1 -0
  970. package/dist/utils/function_calling.d.cts +43 -0
  971. package/dist/utils/function_calling.d.cts.map +1 -0
  972. package/dist/utils/function_calling.d.ts +22 -15
  973. package/dist/utils/function_calling.d.ts.map +1 -0
  974. package/dist/utils/function_calling.js +51 -50
  975. package/dist/utils/function_calling.js.map +1 -0
  976. package/dist/utils/hash.cjs +21 -7
  977. package/dist/utils/hash.cjs.map +1 -0
  978. package/dist/utils/hash.d.cts +14 -0
  979. package/dist/utils/hash.d.cts.map +1 -0
  980. package/dist/utils/hash.d.ts +9 -3
  981. package/dist/utils/hash.d.ts.map +1 -0
  982. package/dist/utils/hash.js +14 -2
  983. package/dist/utils/hash.js.map +1 -0
  984. package/dist/utils/js-sha1/hash.cjs +272 -356
  985. package/dist/utils/js-sha1/hash.cjs.map +1 -0
  986. package/dist/utils/js-sha1/hash.d.cts +9 -0
  987. package/dist/utils/js-sha1/hash.d.cts.map +1 -0
  988. package/dist/utils/js-sha1/hash.d.ts +5 -1
  989. package/dist/utils/js-sha1/hash.d.ts.map +1 -0
  990. package/dist/utils/js-sha1/hash.js +268 -356
  991. package/dist/utils/js-sha1/hash.js.map +1 -0
  992. package/dist/utils/js-sha256/hash.cjs +332 -430
  993. package/dist/utils/js-sha256/hash.cjs.map +1 -0
  994. package/dist/utils/js-sha256/hash.d.cts +5 -0
  995. package/dist/utils/js-sha256/hash.d.cts.map +1 -0
  996. package/dist/utils/js-sha256/hash.d.ts +5 -1
  997. package/dist/utils/js-sha256/hash.d.ts.map +1 -0
  998. package/dist/utils/js-sha256/hash.js +328 -430
  999. package/dist/utils/js-sha256/hash.js.map +1 -0
  1000. package/dist/utils/json.cjs +47 -101
  1001. package/dist/utils/json.cjs.map +1 -0
  1002. package/dist/utils/json.d.cts +8 -0
  1003. package/dist/utils/json.d.cts.map +1 -0
  1004. package/dist/utils/json.d.ts +8 -2
  1005. package/dist/utils/json.d.ts.map +1 -0
  1006. package/dist/utils/json.js +47 -99
  1007. package/dist/utils/json.js.map +1 -0
  1008. package/dist/utils/json_patch.cjs +22 -6
  1009. package/dist/utils/json_patch.cjs.map +1 -0
  1010. package/dist/utils/json_patch.d.cts +3 -0
  1011. package/dist/utils/json_patch.d.ts +3 -1
  1012. package/dist/utils/json_patch.js +15 -1
  1013. package/dist/utils/json_patch.js.map +1 -0
  1014. package/dist/utils/json_schema.cjs +77 -92
  1015. package/dist/utils/json_schema.cjs.map +1 -0
  1016. package/dist/utils/json_schema.d.cts +28 -0
  1017. package/dist/utils/json_schema.d.cts.map +1 -0
  1018. package/dist/utils/json_schema.d.ts +15 -6
  1019. package/dist/utils/json_schema.d.ts.map +1 -0
  1020. package/dist/utils/json_schema.js +58 -85
  1021. package/dist/utils/json_schema.js.map +1 -0
  1022. package/dist/utils/math.cjs +112 -108
  1023. package/dist/utils/math.cjs.map +1 -0
  1024. package/dist/utils/math.d.cts +43 -0
  1025. package/dist/utils/math.d.cts.map +1 -0
  1026. package/dist/utils/math.d.ts +10 -7
  1027. package/dist/utils/math.d.ts.map +1 -0
  1028. package/dist/utils/math.js +103 -102
  1029. package/dist/utils/math.js.map +1 -0
  1030. package/dist/utils/ml-distance/distances.cjs +15 -14
  1031. package/dist/utils/ml-distance/distances.cjs.map +1 -0
  1032. package/dist/utils/ml-distance/distances.js +15 -12
  1033. package/dist/utils/ml-distance/distances.js.map +1 -0
  1034. package/dist/utils/ml-distance/similarities.cjs +20 -17
  1035. package/dist/utils/ml-distance/similarities.cjs.map +1 -0
  1036. package/dist/utils/ml-distance/similarities.d.cts +11 -0
  1037. package/dist/utils/ml-distance/similarities.d.cts.map +1 -0
  1038. package/dist/utils/ml-distance/similarities.d.ts +5 -1
  1039. package/dist/utils/ml-distance/similarities.d.ts.map +1 -0
  1040. package/dist/utils/ml-distance/similarities.js +20 -15
  1041. package/dist/utils/ml-distance/similarities.js.map +1 -0
  1042. package/dist/utils/ml-distance-euclidean/euclidean.cjs +10 -10
  1043. package/dist/utils/ml-distance-euclidean/euclidean.cjs.map +1 -0
  1044. package/dist/utils/ml-distance-euclidean/euclidean.js +11 -8
  1045. package/dist/utils/ml-distance-euclidean/euclidean.js.map +1 -0
  1046. package/dist/utils/sax-js/sax.cjs +1206 -1556
  1047. package/dist/utils/sax-js/sax.cjs.map +1 -0
  1048. package/dist/utils/sax-js/sax.js +1205 -1553
  1049. package/dist/utils/sax-js/sax.js.map +1 -0
  1050. package/dist/utils/signal.cjs +39 -27
  1051. package/dist/utils/signal.cjs.map +1 -0
  1052. package/dist/utils/signal.js +38 -25
  1053. package/dist/utils/signal.js.map +1 -0
  1054. package/dist/utils/stream.cjs +186 -268
  1055. package/dist/utils/stream.cjs.map +1 -0
  1056. package/dist/utils/stream.d.cts +54 -0
  1057. package/dist/utils/stream.d.cts.map +1 -0
  1058. package/dist/utils/stream.d.ts +49 -33
  1059. package/dist/utils/stream.d.ts.map +1 -0
  1060. package/dist/utils/stream.js +177 -261
  1061. package/dist/utils/stream.js.map +1 -0
  1062. package/dist/utils/testing/index.cjs +664 -888
  1063. package/dist/utils/testing/index.cjs.map +1 -0
  1064. package/dist/utils/testing/index.d.cts +383 -0
  1065. package/dist/utils/testing/index.d.cts.map +1 -0
  1066. package/dist/utils/testing/index.d.ts +280 -250
  1067. package/dist/utils/testing/index.d.ts.map +1 -0
  1068. package/dist/utils/testing/index.js +639 -865
  1069. package/dist/utils/testing/index.js.map +1 -0
  1070. package/dist/utils/tiktoken.cjs +28 -19
  1071. package/dist/utils/tiktoken.cjs.map +1 -0
  1072. package/dist/utils/tiktoken.d.cts +8 -0
  1073. package/dist/utils/tiktoken.d.cts.map +1 -0
  1074. package/dist/utils/tiktoken.d.ts +7 -2
  1075. package/dist/utils/tiktoken.d.ts.map +1 -0
  1076. package/dist/utils/tiktoken.js +22 -16
  1077. package/dist/utils/tiktoken.js.map +1 -0
  1078. package/dist/utils/types/index.cjs +60 -17
  1079. package/dist/utils/types/index.cjs.map +1 -0
  1080. package/dist/utils/types/index.d.cts +16 -0
  1081. package/dist/utils/types/index.d.cts.map +1 -0
  1082. package/dist/utils/types/index.d.ts +13 -5
  1083. package/dist/utils/types/index.d.ts.map +1 -0
  1084. package/dist/utils/types/index.js +33 -1
  1085. package/dist/utils/types/index.js.map +1 -0
  1086. package/dist/utils/types/zod.cjs +376 -554
  1087. package/dist/utils/types/zod.cjs.map +1 -0
  1088. package/dist/utils/types/zod.d.cts +213 -0
  1089. package/dist/utils/types/zod.d.cts.map +1 -0
  1090. package/dist/utils/types/zod.d.ts +49 -48
  1091. package/dist/utils/types/zod.d.ts.map +1 -0
  1092. package/dist/utils/types/zod.js +376 -552
  1093. package/dist/utils/types/zod.js.map +1 -0
  1094. package/dist/vectorstores.cjs +391 -424
  1095. package/dist/vectorstores.cjs.map +1 -0
  1096. package/dist/vectorstores.d.cts +661 -0
  1097. package/dist/vectorstores.d.cts.map +1 -0
  1098. package/dist/vectorstores.d.ts +488 -471
  1099. package/dist/vectorstores.d.ts.map +1 -0
  1100. package/dist/vectorstores.js +383 -418
  1101. package/dist/vectorstores.js.map +1 -0
  1102. package/package.json +536 -654
  1103. package/agents.cjs +0 -1
  1104. package/agents.d.cts +0 -1
  1105. package/agents.d.ts +0 -1
  1106. package/agents.js +0 -1
  1107. package/caches.cjs +0 -1
  1108. package/caches.d.cts +0 -1
  1109. package/caches.d.ts +0 -1
  1110. package/caches.js +0 -1
  1111. package/callbacks/base.cjs +0 -1
  1112. package/callbacks/base.d.cts +0 -1
  1113. package/callbacks/base.d.ts +0 -1
  1114. package/callbacks/base.js +0 -1
  1115. package/callbacks/dispatch/web.cjs +0 -1
  1116. package/callbacks/dispatch/web.d.cts +0 -1
  1117. package/callbacks/dispatch/web.d.ts +0 -1
  1118. package/callbacks/dispatch/web.js +0 -1
  1119. package/callbacks/dispatch.cjs +0 -1
  1120. package/callbacks/dispatch.d.cts +0 -1
  1121. package/callbacks/dispatch.d.ts +0 -1
  1122. package/callbacks/dispatch.js +0 -1
  1123. package/callbacks/manager.cjs +0 -1
  1124. package/callbacks/manager.d.cts +0 -1
  1125. package/callbacks/manager.d.ts +0 -1
  1126. package/callbacks/manager.js +0 -1
  1127. package/callbacks/promises.cjs +0 -1
  1128. package/callbacks/promises.d.cts +0 -1
  1129. package/callbacks/promises.d.ts +0 -1
  1130. package/callbacks/promises.js +0 -1
  1131. package/chat_history.cjs +0 -1
  1132. package/chat_history.d.cts +0 -1
  1133. package/chat_history.d.ts +0 -1
  1134. package/chat_history.js +0 -1
  1135. package/context.cjs +0 -1
  1136. package/context.d.cts +0 -1
  1137. package/context.d.ts +0 -1
  1138. package/context.js +0 -1
  1139. package/dist/errors/index.d.ts +0 -2
  1140. package/dist/load/import_constants.d.ts +0 -1
  1141. package/dist/load/import_map.d.ts +0 -43
  1142. package/dist/load/import_type.cjs +0 -3
  1143. package/dist/load/import_type.js +0 -2
  1144. package/dist/messages/content_blocks.cjs +0 -165
  1145. package/dist/messages/content_blocks.d.ts +0 -151
  1146. package/dist/messages/content_blocks.js +0 -154
  1147. package/dist/prompts/serde.cjs +0 -2
  1148. package/dist/prompts/serde.js +0 -1
  1149. package/dist/runnables/graph_mermaid.d.ts +0 -18
  1150. package/dist/runnables/iter.d.ts +0 -6
  1151. package/dist/runnables/types.cjs +0 -2
  1152. package/dist/runnables/types.js +0 -1
  1153. package/dist/runnables/utils.d.ts +0 -27
  1154. package/dist/runnables/wrappers.d.ts +0 -2
  1155. package/dist/singletons/tracer.d.ts +0 -3
  1156. package/dist/tracers/root_listener.d.ts +0 -25
  1157. package/dist/types/_internal.cjs +0 -2
  1158. package/dist/types/_internal.js +0 -1
  1159. package/dist/types/type-utils.cjs +0 -2
  1160. package/dist/types/type-utils.js +0 -1
  1161. package/dist/utils/callbacks.d.ts +0 -1
  1162. package/dist/utils/fast-json-patch/index.d.ts +0 -22
  1163. package/dist/utils/fast-json-patch/src/helpers.d.ts +0 -36
  1164. package/dist/utils/ml-distance/distances.d.ts +0 -8
  1165. package/dist/utils/ml-distance-euclidean/euclidean.d.ts +0 -2
  1166. package/dist/utils/sax-js/sax.d.ts +0 -2
  1167. package/dist/utils/signal.d.ts +0 -1
  1168. package/dist/utils/testing/helpers.cjs +0 -7
  1169. package/dist/utils/testing/helpers.d.ts +0 -3
  1170. package/dist/utils/testing/helpers.js +0 -3
  1171. package/document_loaders/base.cjs +0 -1
  1172. package/document_loaders/base.d.cts +0 -1
  1173. package/document_loaders/base.d.ts +0 -1
  1174. package/document_loaders/base.js +0 -1
  1175. package/document_loaders/langsmith.cjs +0 -1
  1176. package/document_loaders/langsmith.d.cts +0 -1
  1177. package/document_loaders/langsmith.d.ts +0 -1
  1178. package/document_loaders/langsmith.js +0 -1
  1179. package/documents.cjs +0 -1
  1180. package/documents.d.cts +0 -1
  1181. package/documents.d.ts +0 -1
  1182. package/documents.js +0 -1
  1183. package/embeddings.cjs +0 -1
  1184. package/embeddings.d.cts +0 -1
  1185. package/embeddings.d.ts +0 -1
  1186. package/embeddings.js +0 -1
  1187. package/example_selectors.cjs +0 -1
  1188. package/example_selectors.d.cts +0 -1
  1189. package/example_selectors.d.ts +0 -1
  1190. package/example_selectors.js +0 -1
  1191. package/indexing.cjs +0 -1
  1192. package/indexing.d.cts +0 -1
  1193. package/indexing.d.ts +0 -1
  1194. package/indexing.js +0 -1
  1195. package/language_models/base.cjs +0 -1
  1196. package/language_models/base.d.cts +0 -1
  1197. package/language_models/base.d.ts +0 -1
  1198. package/language_models/base.js +0 -1
  1199. package/language_models/chat_models.cjs +0 -1
  1200. package/language_models/chat_models.d.cts +0 -1
  1201. package/language_models/chat_models.d.ts +0 -1
  1202. package/language_models/chat_models.js +0 -1
  1203. package/language_models/llms.cjs +0 -1
  1204. package/language_models/llms.d.cts +0 -1
  1205. package/language_models/llms.d.ts +0 -1
  1206. package/language_models/llms.js +0 -1
  1207. package/load/serializable.cjs +0 -1
  1208. package/load/serializable.d.cts +0 -1
  1209. package/load/serializable.d.ts +0 -1
  1210. package/load/serializable.js +0 -1
  1211. package/load.cjs +0 -1
  1212. package/load.d.cts +0 -1
  1213. package/load.d.ts +0 -1
  1214. package/load.js +0 -1
  1215. package/memory.cjs +0 -1
  1216. package/memory.d.cts +0 -1
  1217. package/memory.d.ts +0 -1
  1218. package/memory.js +0 -1
  1219. package/messages/tool.cjs +0 -1
  1220. package/messages/tool.d.cts +0 -1
  1221. package/messages/tool.d.ts +0 -1
  1222. package/messages/tool.js +0 -1
  1223. package/messages.cjs +0 -1
  1224. package/messages.d.cts +0 -1
  1225. package/messages.d.ts +0 -1
  1226. package/messages.js +0 -1
  1227. package/output_parsers/openai_functions.cjs +0 -1
  1228. package/output_parsers/openai_functions.d.cts +0 -1
  1229. package/output_parsers/openai_functions.d.ts +0 -1
  1230. package/output_parsers/openai_functions.js +0 -1
  1231. package/output_parsers/openai_tools.cjs +0 -1
  1232. package/output_parsers/openai_tools.d.cts +0 -1
  1233. package/output_parsers/openai_tools.d.ts +0 -1
  1234. package/output_parsers/openai_tools.js +0 -1
  1235. package/output_parsers.cjs +0 -1
  1236. package/output_parsers.d.cts +0 -1
  1237. package/output_parsers.d.ts +0 -1
  1238. package/output_parsers.js +0 -1
  1239. package/outputs.cjs +0 -1
  1240. package/outputs.d.cts +0 -1
  1241. package/outputs.d.ts +0 -1
  1242. package/outputs.js +0 -1
  1243. package/prompt_values.cjs +0 -1
  1244. package/prompt_values.d.cts +0 -1
  1245. package/prompt_values.d.ts +0 -1
  1246. package/prompt_values.js +0 -1
  1247. package/prompts.cjs +0 -1
  1248. package/prompts.d.cts +0 -1
  1249. package/prompts.d.ts +0 -1
  1250. package/prompts.js +0 -1
  1251. package/retrievers/document_compressors.cjs +0 -1
  1252. package/retrievers/document_compressors.d.cts +0 -1
  1253. package/retrievers/document_compressors.d.ts +0 -1
  1254. package/retrievers/document_compressors.js +0 -1
  1255. package/retrievers.cjs +0 -1
  1256. package/retrievers.d.cts +0 -1
  1257. package/retrievers.d.ts +0 -1
  1258. package/retrievers.js +0 -1
  1259. package/runnables/graph.cjs +0 -1
  1260. package/runnables/graph.d.cts +0 -1
  1261. package/runnables/graph.d.ts +0 -1
  1262. package/runnables/graph.js +0 -1
  1263. package/runnables/remote.cjs +0 -1
  1264. package/runnables/remote.d.cts +0 -1
  1265. package/runnables/remote.d.ts +0 -1
  1266. package/runnables/remote.js +0 -1
  1267. package/runnables.cjs +0 -1
  1268. package/runnables.d.cts +0 -1
  1269. package/runnables.d.ts +0 -1
  1270. package/runnables.js +0 -1
  1271. package/singletons.cjs +0 -1
  1272. package/singletons.d.cts +0 -1
  1273. package/singletons.d.ts +0 -1
  1274. package/singletons.js +0 -1
  1275. package/stores.cjs +0 -1
  1276. package/stores.d.cts +0 -1
  1277. package/stores.d.ts +0 -1
  1278. package/stores.js +0 -1
  1279. package/structured_query.cjs +0 -1
  1280. package/structured_query.d.cts +0 -1
  1281. package/structured_query.d.ts +0 -1
  1282. package/structured_query.js +0 -1
  1283. package/tools.cjs +0 -1
  1284. package/tools.d.cts +0 -1
  1285. package/tools.d.ts +0 -1
  1286. package/tools.js +0 -1
  1287. package/tracers/base.cjs +0 -1
  1288. package/tracers/base.d.cts +0 -1
  1289. package/tracers/base.d.ts +0 -1
  1290. package/tracers/base.js +0 -1
  1291. package/tracers/console.cjs +0 -1
  1292. package/tracers/console.d.cts +0 -1
  1293. package/tracers/console.d.ts +0 -1
  1294. package/tracers/console.js +0 -1
  1295. package/tracers/initialize.cjs +0 -1
  1296. package/tracers/initialize.d.cts +0 -1
  1297. package/tracers/initialize.d.ts +0 -1
  1298. package/tracers/initialize.js +0 -1
  1299. package/tracers/log_stream.cjs +0 -1
  1300. package/tracers/log_stream.d.cts +0 -1
  1301. package/tracers/log_stream.d.ts +0 -1
  1302. package/tracers/log_stream.js +0 -1
  1303. package/tracers/run_collector.cjs +0 -1
  1304. package/tracers/run_collector.d.cts +0 -1
  1305. package/tracers/run_collector.d.ts +0 -1
  1306. package/tracers/run_collector.js +0 -1
  1307. package/tracers/tracer_langchain.cjs +0 -1
  1308. package/tracers/tracer_langchain.d.cts +0 -1
  1309. package/tracers/tracer_langchain.d.ts +0 -1
  1310. package/tracers/tracer_langchain.js +0 -1
  1311. package/tracers/tracer_langchain_v1.cjs +0 -1
  1312. package/tracers/tracer_langchain_v1.d.cts +0 -1
  1313. package/tracers/tracer_langchain_v1.d.ts +0 -1
  1314. package/tracers/tracer_langchain_v1.js +0 -1
  1315. package/types/stream.cjs +0 -1
  1316. package/types/stream.d.cts +0 -1
  1317. package/types/stream.d.ts +0 -1
  1318. package/types/stream.js +0 -1
  1319. package/utils/async_caller.cjs +0 -1
  1320. package/utils/async_caller.d.cts +0 -1
  1321. package/utils/async_caller.d.ts +0 -1
  1322. package/utils/async_caller.js +0 -1
  1323. package/utils/chunk_array.cjs +0 -1
  1324. package/utils/chunk_array.d.cts +0 -1
  1325. package/utils/chunk_array.d.ts +0 -1
  1326. package/utils/chunk_array.js +0 -1
  1327. package/utils/env.cjs +0 -1
  1328. package/utils/env.d.cts +0 -1
  1329. package/utils/env.d.ts +0 -1
  1330. package/utils/env.js +0 -1
  1331. package/utils/event_source_parse.cjs +0 -1
  1332. package/utils/event_source_parse.d.cts +0 -1
  1333. package/utils/event_source_parse.d.ts +0 -1
  1334. package/utils/event_source_parse.js +0 -1
  1335. package/utils/function_calling.cjs +0 -1
  1336. package/utils/function_calling.d.cts +0 -1
  1337. package/utils/function_calling.d.ts +0 -1
  1338. package/utils/function_calling.js +0 -1
  1339. package/utils/hash/insecure.cjs +0 -1
  1340. package/utils/hash/insecure.d.cts +0 -1
  1341. package/utils/hash/insecure.d.ts +0 -1
  1342. package/utils/hash/insecure.js +0 -1
  1343. package/utils/hash/sha256.cjs +0 -1
  1344. package/utils/hash/sha256.d.cts +0 -1
  1345. package/utils/hash/sha256.d.ts +0 -1
  1346. package/utils/hash/sha256.js +0 -1
  1347. package/utils/hash.cjs +0 -1
  1348. package/utils/hash.d.cts +0 -1
  1349. package/utils/hash.d.ts +0 -1
  1350. package/utils/hash.js +0 -1
  1351. package/utils/json_patch.cjs +0 -1
  1352. package/utils/json_patch.d.cts +0 -1
  1353. package/utils/json_patch.d.ts +0 -1
  1354. package/utils/json_patch.js +0 -1
  1355. package/utils/json_schema.cjs +0 -1
  1356. package/utils/json_schema.d.cts +0 -1
  1357. package/utils/json_schema.d.ts +0 -1
  1358. package/utils/json_schema.js +0 -1
  1359. package/utils/math.cjs +0 -1
  1360. package/utils/math.d.cts +0 -1
  1361. package/utils/math.d.ts +0 -1
  1362. package/utils/math.js +0 -1
  1363. package/utils/stream.cjs +0 -1
  1364. package/utils/stream.d.cts +0 -1
  1365. package/utils/stream.d.ts +0 -1
  1366. package/utils/stream.js +0 -1
  1367. package/utils/testing.cjs +0 -1
  1368. package/utils/testing.d.cts +0 -1
  1369. package/utils/testing.d.ts +0 -1
  1370. package/utils/testing.js +0 -1
  1371. package/utils/tiktoken.cjs +0 -1
  1372. package/utils/tiktoken.d.cts +0 -1
  1373. package/utils/tiktoken.d.ts +0 -1
  1374. package/utils/tiktoken.js +0 -1
  1375. package/utils/types.cjs +0 -1
  1376. package/utils/types.d.cts +0 -1
  1377. package/utils/types.d.ts +0 -1
  1378. package/utils/types.js +0 -1
  1379. package/vectorstores.cjs +0 -1
  1380. package/vectorstores.d.cts +0 -1
  1381. package/vectorstores.d.ts +0 -1
  1382. package/vectorstores.js +0 -1
@@ -1,2442 +1,1829 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.RunnableToolLike = exports.RunnablePick = exports.RunnableAssign = exports.RunnableWithFallbacks = exports.RunnableParallel = exports.RunnableLambda = exports.RunnableTraceable = exports.RunnableMap = exports.RunnableSequence = exports.RunnableRetry = exports.RunnableEach = exports.RunnableBinding = exports.Runnable = void 0;
7
- exports._coerceToDict = _coerceToDict;
8
- exports._coerceToRunnable = _coerceToRunnable;
9
- exports.convertRunnableToTool = convertRunnableToTool;
10
- const v3_1 = require("zod/v3");
11
- const p_retry_1 = __importDefault(require("p-retry"));
12
- const uuid_1 = require("uuid");
13
- const traceable_1 = require("langsmith/singletons/traceable");
14
- const log_stream_js_1 = require("../tracers/log_stream.cjs");
15
- const event_stream_js_1 = require("../tracers/event_stream.cjs");
16
- const serializable_js_1 = require("../load/serializable.cjs");
17
- const stream_js_1 = require("../utils/stream.cjs");
18
- const signal_js_1 = require("../utils/signal.cjs");
19
- const config_js_1 = require("./config.cjs");
20
- const async_caller_js_1 = require("../utils/async_caller.cjs");
21
- const root_listener_js_1 = require("../tracers/root_listener.cjs");
22
- const utils_js_1 = require("./utils.cjs");
23
- const index_js_1 = require("../singletons/index.cjs");
24
- const graph_js_1 = require("./graph.cjs");
25
- const wrappers_js_1 = require("./wrappers.cjs");
26
- const iter_js_1 = require("./iter.cjs");
27
- const utils_js_2 = require("../tools/utils.cjs");
28
- const zod_js_1 = require("../utils/types/zod.cjs");
29
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_load_serializable = require('../load/serializable.cjs');
3
+ const require_utils = require('../tools/utils.cjs');
4
+ const require_index = require('../singletons/async_local_storage/index.cjs');
5
+ require('../singletons/index.cjs');
6
+ const require_config = require('./config.cjs');
7
+ const require_signal = require('../utils/signal.cjs');
8
+ const require_utils_stream = require('../utils/stream.cjs');
9
+ const require_tracers_log_stream = require('../tracers/log_stream.cjs');
10
+ const require_event_stream = require('../tracers/event_stream.cjs');
11
+ const require_utils_async_caller = require('../utils/async_caller.cjs');
12
+ const require_root_listener = require('../tracers/root_listener.cjs');
13
+ const require_utils$1 = require('./utils.cjs');
14
+ const require_zod = require('../utils/types/zod.cjs');
15
+ const require_runnables_graph = require('./graph.cjs');
16
+ const require_wrappers = require('./wrappers.cjs');
17
+ const require_iter = require('./iter.cjs');
18
+ const zod_v3 = require_rolldown_runtime.__toESM(require("zod/v3"));
19
+ const p_retry = require_rolldown_runtime.__toESM(require("p-retry"));
20
+ const uuid = require_rolldown_runtime.__toESM(require("uuid"));
21
+ const langsmith_singletons_traceable = require_rolldown_runtime.__toESM(require("langsmith/singletons/traceable"));
22
+
23
+ //#region src/runnables/base.ts
30
24
  function _coerceToDict(value, defaultKey) {
31
- return value &&
32
- !Array.isArray(value) &&
33
- // eslint-disable-next-line no-instanceof/no-instanceof
34
- !(value instanceof Date) &&
35
- typeof value === "object"
36
- ? value
37
- : { [defaultKey]: value };
25
+ return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value };
38
26
  }
39
27
  /**
40
- * A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or
41
- * transformed.
42
- */
43
- class Runnable extends serializable_js_1.Serializable {
44
- constructor() {
45
- super(...arguments);
46
- Object.defineProperty(this, "lc_runnable", {
47
- enumerable: true,
48
- configurable: true,
49
- writable: true,
50
- value: true
51
- });
52
- Object.defineProperty(this, "name", {
53
- enumerable: true,
54
- configurable: true,
55
- writable: true,
56
- value: void 0
57
- });
58
- }
59
- getName(suffix) {
60
- const name =
61
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
62
- this.name ?? this.constructor.lc_name() ?? this.constructor.name;
63
- return suffix ? `${name}${suffix}` : name;
64
- }
65
- /**
66
- * Bind arguments to a Runnable, returning a new Runnable.
67
- * @param kwargs
68
- * @returns A new RunnableBinding that, when invoked, will apply the bound args.
69
- *
70
- * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release.
71
- */
72
- bind(kwargs) {
73
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
74
- return new RunnableBinding({ bound: this, kwargs, config: {} });
75
- }
76
- /**
77
- * Return a new Runnable that maps a list of inputs to a list of outputs,
78
- * by calling invoke() with each input.
79
- *
80
- * @deprecated This will be removed in the next breaking release.
81
- */
82
- map() {
83
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
84
- return new RunnableEach({ bound: this });
85
- }
86
- /**
87
- * Add retry logic to an existing runnable.
88
- * @param fields.stopAfterAttempt The number of attempts to retry.
89
- * @param fields.onFailedAttempt A function that is called when a retry fails.
90
- * @returns A new RunnableRetry that, when invoked, will retry according to the parameters.
91
- */
92
- withRetry(fields) {
93
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
94
- return new RunnableRetry({
95
- bound: this,
96
- kwargs: {},
97
- config: {},
98
- maxAttemptNumber: fields?.stopAfterAttempt,
99
- ...fields,
100
- });
101
- }
102
- /**
103
- * Bind config to a Runnable, returning a new Runnable.
104
- * @param config New configuration parameters to attach to the new runnable.
105
- * @returns A new RunnableBinding with a config matching what's passed.
106
- */
107
- withConfig(config) {
108
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
109
- return new RunnableBinding({
110
- bound: this,
111
- config,
112
- kwargs: {},
113
- });
114
- }
115
- /**
116
- * Create a new runnable from the current one that will try invoking
117
- * other passed fallback runnables if the initial invocation fails.
118
- * @param fields.fallbacks Other runnables to call if the runnable errors.
119
- * @returns A new RunnableWithFallbacks.
120
- */
121
- withFallbacks(fields) {
122
- const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks;
123
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
124
- return new RunnableWithFallbacks({
125
- runnable: this,
126
- fallbacks,
127
- });
128
- }
129
- _getOptionsList(options, length = 0) {
130
- if (Array.isArray(options) && options.length !== length) {
131
- throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`);
132
- }
133
- if (Array.isArray(options)) {
134
- return options.map(config_js_1.ensureConfig);
135
- }
136
- if (length > 1 && !Array.isArray(options) && options.runId) {
137
- console.warn("Provided runId will be used only for the first element of the batch.");
138
- const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId"));
139
- return Array.from({ length }, (_, i) => (0, config_js_1.ensureConfig)(i === 0 ? options : subsequent));
140
- }
141
- return Array.from({ length }, () => (0, config_js_1.ensureConfig)(options));
142
- }
143
- async batch(inputs, options, batchOptions) {
144
- const configList = this._getOptionsList(options ?? {}, inputs.length);
145
- const maxConcurrency = configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency;
146
- const caller = new async_caller_js_1.AsyncCaller({
147
- maxConcurrency,
148
- onFailedAttempt: (e) => {
149
- throw e;
150
- },
151
- });
152
- const batchCalls = inputs.map((input, i) => caller.call(async () => {
153
- try {
154
- const result = await this.invoke(input, configList[i]);
155
- return result;
156
- }
157
- catch (e) {
158
- if (batchOptions?.returnExceptions) {
159
- return e;
160
- }
161
- throw e;
162
- }
163
- }));
164
- return Promise.all(batchCalls);
165
- }
166
- /**
167
- * Default streaming implementation.
168
- * Subclasses should override this method if they support streaming output.
169
- * @param input
170
- * @param options
171
- */
172
- async *_streamIterator(input, options) {
173
- yield this.invoke(input, options);
174
- }
175
- /**
176
- * Stream output in chunks.
177
- * @param input
178
- * @param options
179
- * @returns A readable stream that is also an iterable.
180
- */
181
- async stream(input, options) {
182
- // Buffer the first streamed chunk to allow for initial errors
183
- // to surface immediately.
184
- const config = (0, config_js_1.ensureConfig)(options);
185
- const wrappedGenerator = new stream_js_1.AsyncGeneratorWithSetup({
186
- generator: this._streamIterator(input, config),
187
- config,
188
- });
189
- await wrappedGenerator.setup;
190
- return stream_js_1.IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
191
- }
192
- _separateRunnableConfigFromCallOptions(options) {
193
- let runnableConfig;
194
- if (options === undefined) {
195
- runnableConfig = (0, config_js_1.ensureConfig)(options);
196
- }
197
- else {
198
- runnableConfig = (0, config_js_1.ensureConfig)({
199
- callbacks: options.callbacks,
200
- tags: options.tags,
201
- metadata: options.metadata,
202
- runName: options.runName,
203
- configurable: options.configurable,
204
- recursionLimit: options.recursionLimit,
205
- maxConcurrency: options.maxConcurrency,
206
- runId: options.runId,
207
- timeout: options.timeout,
208
- signal: options.signal,
209
- });
210
- }
211
- const callOptions = { ...options };
212
- delete callOptions.callbacks;
213
- delete callOptions.tags;
214
- delete callOptions.metadata;
215
- delete callOptions.runName;
216
- delete callOptions.configurable;
217
- delete callOptions.recursionLimit;
218
- delete callOptions.maxConcurrency;
219
- delete callOptions.runId;
220
- delete callOptions.timeout;
221
- delete callOptions.signal;
222
- return [runnableConfig, callOptions];
223
- }
224
- async _callWithConfig(func, input, options) {
225
- const config = (0, config_js_1.ensureConfig)(options);
226
- const callbackManager_ = await (0, config_js_1.getCallbackManagerForConfig)(config);
227
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), config.runId, config?.runType, undefined, undefined, config?.runName ?? this.getName());
228
- delete config.runId;
229
- let output;
230
- try {
231
- const promise = func.call(this, input, config, runManager);
232
- output = await (0, signal_js_1.raceWithSignal)(promise, options?.signal);
233
- }
234
- catch (e) {
235
- await runManager?.handleChainError(e);
236
- throw e;
237
- }
238
- await runManager?.handleChainEnd(_coerceToDict(output, "output"));
239
- return output;
240
- }
241
- /**
242
- * Internal method that handles batching and configuration for a runnable
243
- * It takes a function, input values, and optional configuration, and
244
- * returns a promise that resolves to the output values.
245
- * @param func The function to be executed for each input value.
246
- * @param input The input values to be processed.
247
- * @param config Optional configuration for the function execution.
248
- * @returns A promise that resolves to the output values.
249
- */
250
- async _batchWithConfig(func, inputs, options, batchOptions) {
251
- const optionsList = this._getOptionsList(options ?? {}, inputs.length);
252
- const callbackManagers = await Promise.all(optionsList.map(config_js_1.getCallbackManagerForConfig));
253
- const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => {
254
- const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), optionsList[i].runId, optionsList[i].runType, undefined, undefined, optionsList[i].runName ?? this.getName());
255
- delete optionsList[i].runId;
256
- return handleStartRes;
257
- }));
258
- let outputs;
259
- try {
260
- const promise = func.call(this, inputs, optionsList, runManagers, batchOptions);
261
- outputs = await (0, signal_js_1.raceWithSignal)(promise, optionsList?.[0]?.signal);
262
- }
263
- catch (e) {
264
- await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e)));
265
- throw e;
266
- }
267
- await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict(outputs, "output"))));
268
- return outputs;
269
- }
270
- /** @internal */
271
- _concatOutputChunks(first, second) {
272
- return (0, stream_js_1.concat)(first, second);
273
- }
274
- /**
275
- * Helper method to transform an Iterator of Input values into an Iterator of
276
- * Output values, with callbacks.
277
- * Use this to implement `stream()` or `transform()` in Runnable subclasses.
278
- */
279
- async *_transformStreamWithConfig(inputGenerator, transformer, options) {
280
- let finalInput;
281
- let finalInputSupported = true;
282
- let finalOutput;
283
- let finalOutputSupported = true;
284
- const config = (0, config_js_1.ensureConfig)(options);
285
- const callbackManager_ = await (0, config_js_1.getCallbackManagerForConfig)(config);
286
- const outerThis = this;
287
- async function* wrapInputForTracing() {
288
- for await (const chunk of inputGenerator) {
289
- if (finalInputSupported) {
290
- if (finalInput === undefined) {
291
- finalInput = chunk;
292
- }
293
- else {
294
- try {
295
- finalInput = outerThis._concatOutputChunks(finalInput,
296
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
297
- chunk);
298
- }
299
- catch {
300
- finalInput = undefined;
301
- finalInputSupported = false;
302
- }
303
- }
304
- }
305
- yield chunk;
306
- }
307
- }
308
- let runManager;
309
- try {
310
- const pipe = await (0, stream_js_1.pipeGeneratorWithSetup)(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config.runId, config.runType, undefined, undefined, config.runName ?? this.getName()), options?.signal, config);
311
- delete config.runId;
312
- runManager = pipe.setup;
313
- const streamEventsHandler = runManager?.handlers.find(event_stream_js_1.isStreamEventsHandler);
314
- let iterator = pipe.output;
315
- if (streamEventsHandler !== undefined && runManager !== undefined) {
316
- iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator);
317
- }
318
- const streamLogHandler = runManager?.handlers.find(log_stream_js_1.isLogStreamHandler);
319
- if (streamLogHandler !== undefined && runManager !== undefined) {
320
- iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator);
321
- }
322
- for await (const chunk of iterator) {
323
- yield chunk;
324
- if (finalOutputSupported) {
325
- if (finalOutput === undefined) {
326
- finalOutput = chunk;
327
- }
328
- else {
329
- try {
330
- finalOutput = this._concatOutputChunks(finalOutput,
331
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
332
- chunk);
333
- }
334
- catch {
335
- finalOutput = undefined;
336
- finalOutputSupported = false;
337
- }
338
- }
339
- }
340
- }
341
- }
342
- catch (e) {
343
- await runManager?.handleChainError(e, undefined, undefined, undefined, {
344
- inputs: _coerceToDict(finalInput, "input"),
345
- });
346
- throw e;
347
- }
348
- await runManager?.handleChainEnd(finalOutput ?? {}, undefined, undefined, undefined, { inputs: _coerceToDict(finalInput, "input") });
349
- }
350
- getGraph(_) {
351
- const graph = new graph_js_1.Graph();
352
- // TODO: Add input schema for runnables
353
- const inputNode = graph.addNode({
354
- name: `${this.getName()}Input`,
355
- schema: v3_1.z.any(),
356
- });
357
- const runnableNode = graph.addNode(this);
358
- // TODO: Add output schemas for runnables
359
- const outputNode = graph.addNode({
360
- name: `${this.getName()}Output`,
361
- schema: v3_1.z.any(),
362
- });
363
- graph.addEdge(inputNode, runnableNode);
364
- graph.addEdge(runnableNode, outputNode);
365
- return graph;
366
- }
367
- /**
368
- * Create a new runnable sequence that runs each individual runnable in series,
369
- * piping the output of one runnable into another runnable or runnable-like.
370
- * @param coerceable A runnable, function, or object whose values are functions or runnables.
371
- * @returns A new runnable sequence.
372
- */
373
- pipe(coerceable) {
374
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
375
- return new RunnableSequence({
376
- first: this,
377
- last: _coerceToRunnable(coerceable),
378
- });
379
- }
380
- /**
381
- * Pick keys from the dict output of this runnable. Returns a new runnable.
382
- */
383
- pick(keys) {
384
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
385
- return this.pipe(new RunnablePick(keys));
386
- }
387
- /**
388
- * Assigns new fields to the dict output of this runnable. Returns a new runnable.
389
- */
390
- assign(mapping) {
391
- return this.pipe(
392
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
393
- new RunnableAssign(
394
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
395
- new RunnableMap({ steps: mapping })));
396
- }
397
- /**
398
- * Default implementation of transform, which buffers input and then calls stream.
399
- * Subclasses should override this method if they can start producing output while
400
- * input is still being generated.
401
- * @param generator
402
- * @param options
403
- */
404
- async *transform(generator, options) {
405
- let finalChunk;
406
- for await (const chunk of generator) {
407
- if (finalChunk === undefined) {
408
- finalChunk = chunk;
409
- }
410
- else {
411
- // Make a best effort to gather, for any type that supports concat.
412
- // This method should throw an error if gathering fails.
413
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
414
- finalChunk = this._concatOutputChunks(finalChunk, chunk);
415
- }
416
- }
417
- yield* this._streamIterator(finalChunk, (0, config_js_1.ensureConfig)(options));
418
- }
419
- /**
420
- * Stream all output from a runnable, as reported to the callback system.
421
- * This includes all inner runs of LLMs, Retrievers, Tools, etc.
422
- * Output is streamed as Log objects, which include a list of
423
- * jsonpatch ops that describe how the state of the run has changed in each
424
- * step, and the final state of the run.
425
- * The jsonpatch ops can be applied in order to construct state.
426
- * @param input
427
- * @param options
428
- * @param streamOptions
429
- */
430
- async *streamLog(input, options, streamOptions) {
431
- const logStreamCallbackHandler = new log_stream_js_1.LogStreamCallbackHandler({
432
- ...streamOptions,
433
- autoClose: false,
434
- _schemaFormat: "original",
435
- });
436
- const config = (0, config_js_1.ensureConfig)(options);
437
- yield* this._streamLog(input, logStreamCallbackHandler, config);
438
- }
439
- async *_streamLog(input, logStreamCallbackHandler, config) {
440
- const { callbacks } = config;
441
- if (callbacks === undefined) {
442
- // eslint-disable-next-line no-param-reassign
443
- config.callbacks = [logStreamCallbackHandler];
444
- }
445
- else if (Array.isArray(callbacks)) {
446
- // eslint-disable-next-line no-param-reassign
447
- config.callbacks = callbacks.concat([logStreamCallbackHandler]);
448
- }
449
- else {
450
- const copiedCallbacks = callbacks.copy();
451
- copiedCallbacks.addHandler(logStreamCallbackHandler, true);
452
- // eslint-disable-next-line no-param-reassign
453
- config.callbacks = copiedCallbacks;
454
- }
455
- const runnableStreamPromise = this.stream(input, config);
456
- async function consumeRunnableStream() {
457
- try {
458
- const runnableStream = await runnableStreamPromise;
459
- for await (const chunk of runnableStream) {
460
- const patch = new log_stream_js_1.RunLogPatch({
461
- ops: [
462
- {
463
- op: "add",
464
- path: "/streamed_output/-",
465
- value: chunk,
466
- },
467
- ],
468
- });
469
- await logStreamCallbackHandler.writer.write(patch);
470
- }
471
- }
472
- finally {
473
- await logStreamCallbackHandler.writer.close();
474
- }
475
- }
476
- const runnableStreamConsumePromise = consumeRunnableStream();
477
- try {
478
- for await (const log of logStreamCallbackHandler) {
479
- yield log;
480
- }
481
- }
482
- finally {
483
- await runnableStreamConsumePromise;
484
- }
485
- }
486
- streamEvents(input, options, streamOptions) {
487
- let stream;
488
- if (options.version === "v1") {
489
- stream = this._streamEventsV1(input, options, streamOptions);
490
- }
491
- else if (options.version === "v2") {
492
- stream = this._streamEventsV2(input, options, streamOptions);
493
- }
494
- else {
495
- throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`);
496
- }
497
- if (options.encoding === "text/event-stream") {
498
- return (0, wrappers_js_1.convertToHttpEventStream)(stream);
499
- }
500
- else {
501
- return stream_js_1.IterableReadableStream.fromAsyncGenerator(stream);
502
- }
503
- }
504
- async *_streamEventsV2(input, options, streamOptions) {
505
- const eventStreamer = new event_stream_js_1.EventStreamCallbackHandler({
506
- ...streamOptions,
507
- autoClose: false,
508
- });
509
- const config = (0, config_js_1.ensureConfig)(options);
510
- const runId = config.runId ?? (0, uuid_1.v4)();
511
- config.runId = runId;
512
- const callbacks = config.callbacks;
513
- if (callbacks === undefined) {
514
- config.callbacks = [eventStreamer];
515
- }
516
- else if (Array.isArray(callbacks)) {
517
- config.callbacks = callbacks.concat(eventStreamer);
518
- }
519
- else {
520
- const copiedCallbacks = callbacks.copy();
521
- copiedCallbacks.addHandler(eventStreamer, true);
522
- // eslint-disable-next-line no-param-reassign
523
- config.callbacks = copiedCallbacks;
524
- }
525
- const abortController = new AbortController();
526
- // Call the runnable in streaming mode,
527
- // add each chunk to the output stream
528
- const outerThis = this;
529
- async function consumeRunnableStream() {
530
- let signal;
531
- let listener = null;
532
- try {
533
- if (options?.signal) {
534
- if ("any" in AbortSignal) {
535
- // Use native AbortSignal.any() if available (Node 19+)
536
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
537
- signal = AbortSignal.any([
538
- abortController.signal,
539
- options.signal,
540
- ]);
541
- }
542
- else {
543
- // Fallback for Node 18 and below - just use the provided signal
544
- signal = options.signal;
545
- // Ensure we still abort our controller when the parent signal aborts
546
- listener = () => {
547
- abortController.abort();
548
- };
549
- options.signal.addEventListener("abort", listener, { once: true });
550
- }
551
- }
552
- else {
553
- signal = abortController.signal;
554
- }
555
- const runnableStream = await outerThis.stream(input, {
556
- ...config,
557
- signal,
558
- });
559
- const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream);
560
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
561
- for await (const _ of tappedStream) {
562
- // Just iterate so that the callback handler picks up events
563
- if (abortController.signal.aborted)
564
- break;
565
- }
566
- }
567
- finally {
568
- await eventStreamer.finish();
569
- if (signal && listener) {
570
- signal.removeEventListener("abort", listener);
571
- }
572
- }
573
- }
574
- const runnableStreamConsumePromise = consumeRunnableStream();
575
- let firstEventSent = false;
576
- let firstEventRunId;
577
- try {
578
- for await (const event of eventStreamer) {
579
- // This is a work-around an issue where the inputs into the
580
- // chain are not available until the entire input is consumed.
581
- // As a temporary solution, we'll modify the input to be the input
582
- // that was passed into the chain.
583
- if (!firstEventSent) {
584
- event.data.input = input;
585
- firstEventSent = true;
586
- firstEventRunId = event.run_id;
587
- yield event;
588
- continue;
589
- }
590
- if (event.run_id === firstEventRunId && event.event.endsWith("_end")) {
591
- // If it's the end event corresponding to the root runnable
592
- // we dont include the input in the event since it's guaranteed
593
- // to be included in the first event.
594
- if (event.data?.input) {
595
- delete event.data.input;
596
- }
597
- }
598
- yield event;
599
- }
600
- }
601
- finally {
602
- abortController.abort();
603
- await runnableStreamConsumePromise;
604
- }
605
- }
606
- async *_streamEventsV1(input, options, streamOptions) {
607
- let runLog;
608
- let hasEncounteredStartEvent = false;
609
- const config = (0, config_js_1.ensureConfig)(options);
610
- const rootTags = config.tags ?? [];
611
- const rootMetadata = config.metadata ?? {};
612
- const rootName = config.runName ?? this.getName();
613
- const logStreamCallbackHandler = new log_stream_js_1.LogStreamCallbackHandler({
614
- ...streamOptions,
615
- autoClose: false,
616
- _schemaFormat: "streaming_events",
617
- });
618
- const rootEventFilter = new utils_js_1._RootEventFilter({
619
- ...streamOptions,
620
- });
621
- const logStream = this._streamLog(input, logStreamCallbackHandler, config);
622
- for await (const log of logStream) {
623
- if (!runLog) {
624
- runLog = log_stream_js_1.RunLog.fromRunLogPatch(log);
625
- }
626
- else {
627
- runLog = runLog.concat(log);
628
- }
629
- if (runLog.state === undefined) {
630
- throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`);
631
- }
632
- // Yield the start event for the root runnable if it hasn't been seen.
633
- // The root run is never filtered out
634
- if (!hasEncounteredStartEvent) {
635
- hasEncounteredStartEvent = true;
636
- const state = { ...runLog.state };
637
- const event = {
638
- run_id: state.id,
639
- event: `on_${state.type}_start`,
640
- name: rootName,
641
- tags: rootTags,
642
- metadata: rootMetadata,
643
- data: {
644
- input,
645
- },
646
- };
647
- if (rootEventFilter.includeEvent(event, state.type)) {
648
- yield event;
649
- }
650
- }
651
- const paths = log.ops
652
- .filter((op) => op.path.startsWith("/logs/"))
653
- .map((op) => op.path.split("/")[2]);
654
- const dedupedPaths = [...new Set(paths)];
655
- for (const path of dedupedPaths) {
656
- let eventType;
657
- let data = {};
658
- const logEntry = runLog.state.logs[path];
659
- if (logEntry.end_time === undefined) {
660
- if (logEntry.streamed_output.length > 0) {
661
- eventType = "stream";
662
- }
663
- else {
664
- eventType = "start";
665
- }
666
- }
667
- else {
668
- eventType = "end";
669
- }
670
- if (eventType === "start") {
671
- // Include the inputs with the start event if they are available.
672
- // Usually they will NOT be available for components that operate
673
- // on streams, since those components stream the input and
674
- // don't know its final value until the end of the stream.
675
- if (logEntry.inputs !== undefined) {
676
- data.input = logEntry.inputs;
677
- }
678
- }
679
- else if (eventType === "end") {
680
- if (logEntry.inputs !== undefined) {
681
- data.input = logEntry.inputs;
682
- }
683
- data.output = logEntry.final_output;
684
- }
685
- else if (eventType === "stream") {
686
- const chunkCount = logEntry.streamed_output.length;
687
- if (chunkCount !== 1) {
688
- throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`);
689
- }
690
- data = { chunk: logEntry.streamed_output[0] };
691
- // Clean up the stream, we don't need it anymore.
692
- // And this avoids duplicates as well!
693
- logEntry.streamed_output = [];
694
- }
695
- yield {
696
- event: `on_${logEntry.type}_${eventType}`,
697
- name: logEntry.name,
698
- run_id: logEntry.id,
699
- tags: logEntry.tags,
700
- metadata: logEntry.metadata,
701
- data,
702
- };
703
- }
704
- // Finally, we take care of the streaming output from the root chain
705
- // if there is any.
706
- const { state } = runLog;
707
- if (state.streamed_output.length > 0) {
708
- const chunkCount = state.streamed_output.length;
709
- if (chunkCount !== 1) {
710
- throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state.name}"`);
711
- }
712
- const data = { chunk: state.streamed_output[0] };
713
- // Clean up the stream, we don't need it anymore.
714
- state.streamed_output = [];
715
- const event = {
716
- event: `on_${state.type}_stream`,
717
- run_id: state.id,
718
- tags: rootTags,
719
- metadata: rootMetadata,
720
- name: rootName,
721
- data,
722
- };
723
- if (rootEventFilter.includeEvent(event, state.type)) {
724
- yield event;
725
- }
726
- }
727
- }
728
- const state = runLog?.state;
729
- if (state !== undefined) {
730
- // Finally, yield the end event for the root runnable.
731
- const event = {
732
- event: `on_${state.type}_end`,
733
- name: rootName,
734
- run_id: state.id,
735
- tags: rootTags,
736
- metadata: rootMetadata,
737
- data: {
738
- output: state.final_output,
739
- },
740
- };
741
- if (rootEventFilter.includeEvent(event, state.type))
742
- yield event;
743
- }
744
- }
745
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
746
- static isRunnable(thing) {
747
- return (0, utils_js_1.isRunnableInterface)(thing);
748
- }
749
- /**
750
- * Bind lifecycle listeners to a Runnable, returning a new Runnable.
751
- * The Run object contains information about the run, including its id,
752
- * type, input, output, error, startTime, endTime, and any tags or metadata
753
- * added to the run.
754
- *
755
- * @param {Object} params - The object containing the callback functions.
756
- * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.
757
- * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.
758
- * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.
759
- */
760
- withListeners({ onStart, onEnd, onError, }) {
761
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
762
- return new RunnableBinding({
763
- bound: this,
764
- config: {},
765
- configFactories: [
766
- (config) => ({
767
- callbacks: [
768
- new root_listener_js_1.RootListenersTracer({
769
- config,
770
- onStart,
771
- onEnd,
772
- onError,
773
- }),
774
- ],
775
- }),
776
- ],
777
- });
778
- }
779
- /**
780
- * Convert a runnable to a tool. Return a new instance of `RunnableToolLike`
781
- * which contains the runnable, name, description and schema.
782
- *
783
- * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable.
784
- *
785
- * @param fields
786
- * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.
787
- * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided.
788
- * @param {z.ZodType<T>} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.
789
- * @returns {RunnableToolLike<z.ZodType<T>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.
790
- */
791
- asTool(fields) {
792
- return convertRunnableToTool(this, fields);
793
- }
794
- }
795
- exports.Runnable = Runnable;
28
+ * A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or
29
+ * transformed.
30
+ */
31
+ var Runnable = class extends require_load_serializable.Serializable {
32
+ lc_runnable = true;
33
+ name;
34
+ getName(suffix) {
35
+ const name = this.name ?? this.constructor.lc_name() ?? this.constructor.name;
36
+ return suffix ? `${name}${suffix}` : name;
37
+ }
38
+ /**
39
+ * Bind arguments to a Runnable, returning a new Runnable.
40
+ * @param kwargs
41
+ * @returns A new RunnableBinding that, when invoked, will apply the bound args.
42
+ *
43
+ * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release.
44
+ */
45
+ bind(kwargs) {
46
+ return new RunnableBinding({
47
+ bound: this,
48
+ kwargs,
49
+ config: {}
50
+ });
51
+ }
52
+ /**
53
+ * Return a new Runnable that maps a list of inputs to a list of outputs,
54
+ * by calling invoke() with each input.
55
+ *
56
+ * @deprecated This will be removed in the next breaking release.
57
+ */
58
+ map() {
59
+ return new RunnableEach({ bound: this });
60
+ }
61
+ /**
62
+ * Add retry logic to an existing runnable.
63
+ * @param fields.stopAfterAttempt The number of attempts to retry.
64
+ * @param fields.onFailedAttempt A function that is called when a retry fails.
65
+ * @returns A new RunnableRetry that, when invoked, will retry according to the parameters.
66
+ */
67
+ withRetry(fields) {
68
+ return new RunnableRetry({
69
+ bound: this,
70
+ kwargs: {},
71
+ config: {},
72
+ maxAttemptNumber: fields?.stopAfterAttempt,
73
+ ...fields
74
+ });
75
+ }
76
+ /**
77
+ * Bind config to a Runnable, returning a new Runnable.
78
+ * @param config New configuration parameters to attach to the new runnable.
79
+ * @returns A new RunnableBinding with a config matching what's passed.
80
+ */
81
+ withConfig(config) {
82
+ return new RunnableBinding({
83
+ bound: this,
84
+ config,
85
+ kwargs: {}
86
+ });
87
+ }
88
+ /**
89
+ * Create a new runnable from the current one that will try invoking
90
+ * other passed fallback runnables if the initial invocation fails.
91
+ * @param fields.fallbacks Other runnables to call if the runnable errors.
92
+ * @returns A new RunnableWithFallbacks.
93
+ */
94
+ withFallbacks(fields) {
95
+ const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks;
96
+ return new RunnableWithFallbacks({
97
+ runnable: this,
98
+ fallbacks
99
+ });
100
+ }
101
+ _getOptionsList(options, length = 0) {
102
+ if (Array.isArray(options) && options.length !== length) throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`);
103
+ if (Array.isArray(options)) return options.map(require_config.ensureConfig);
104
+ if (length > 1 && !Array.isArray(options) && options.runId) {
105
+ console.warn("Provided runId will be used only for the first element of the batch.");
106
+ const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId"));
107
+ return Array.from({ length }, (_, i) => require_config.ensureConfig(i === 0 ? options : subsequent));
108
+ }
109
+ return Array.from({ length }, () => require_config.ensureConfig(options));
110
+ }
111
+ async batch(inputs, options, batchOptions) {
112
+ const configList = this._getOptionsList(options ?? {}, inputs.length);
113
+ const maxConcurrency = configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency;
114
+ const caller = new require_utils_async_caller.AsyncCaller({
115
+ maxConcurrency,
116
+ onFailedAttempt: (e) => {
117
+ throw e;
118
+ }
119
+ });
120
+ const batchCalls = inputs.map((input, i) => caller.call(async () => {
121
+ try {
122
+ const result = await this.invoke(input, configList[i]);
123
+ return result;
124
+ } catch (e) {
125
+ if (batchOptions?.returnExceptions) return e;
126
+ throw e;
127
+ }
128
+ }));
129
+ return Promise.all(batchCalls);
130
+ }
131
+ /**
132
+ * Default streaming implementation.
133
+ * Subclasses should override this method if they support streaming output.
134
+ * @param input
135
+ * @param options
136
+ */
137
+ async *_streamIterator(input, options) {
138
+ yield this.invoke(input, options);
139
+ }
140
+ /**
141
+ * Stream output in chunks.
142
+ * @param input
143
+ * @param options
144
+ * @returns A readable stream that is also an iterable.
145
+ */
146
+ async stream(input, options) {
147
+ const config = require_config.ensureConfig(options);
148
+ const wrappedGenerator = new require_utils_stream.AsyncGeneratorWithSetup({
149
+ generator: this._streamIterator(input, config),
150
+ config
151
+ });
152
+ await wrappedGenerator.setup;
153
+ return require_utils_stream.IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
154
+ }
155
+ _separateRunnableConfigFromCallOptions(options) {
156
+ let runnableConfig;
157
+ if (options === void 0) runnableConfig = require_config.ensureConfig(options);
158
+ else runnableConfig = require_config.ensureConfig({
159
+ callbacks: options.callbacks,
160
+ tags: options.tags,
161
+ metadata: options.metadata,
162
+ runName: options.runName,
163
+ configurable: options.configurable,
164
+ recursionLimit: options.recursionLimit,
165
+ maxConcurrency: options.maxConcurrency,
166
+ runId: options.runId,
167
+ timeout: options.timeout,
168
+ signal: options.signal
169
+ });
170
+ const callOptions = { ...options };
171
+ delete callOptions.callbacks;
172
+ delete callOptions.tags;
173
+ delete callOptions.metadata;
174
+ delete callOptions.runName;
175
+ delete callOptions.configurable;
176
+ delete callOptions.recursionLimit;
177
+ delete callOptions.maxConcurrency;
178
+ delete callOptions.runId;
179
+ delete callOptions.timeout;
180
+ delete callOptions.signal;
181
+ return [runnableConfig, callOptions];
182
+ }
183
+ async _callWithConfig(func, input, options) {
184
+ const config = require_config.ensureConfig(options);
185
+ const callbackManager_ = await require_config.getCallbackManagerForConfig(config);
186
+ const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), config.runId, config?.runType, void 0, void 0, config?.runName ?? this.getName());
187
+ delete config.runId;
188
+ let output;
189
+ try {
190
+ const promise = func.call(this, input, config, runManager);
191
+ output = await require_signal.raceWithSignal(promise, options?.signal);
192
+ } catch (e) {
193
+ await runManager?.handleChainError(e);
194
+ throw e;
195
+ }
196
+ await runManager?.handleChainEnd(_coerceToDict(output, "output"));
197
+ return output;
198
+ }
199
+ /**
200
+ * Internal method that handles batching and configuration for a runnable
201
+ * It takes a function, input values, and optional configuration, and
202
+ * returns a promise that resolves to the output values.
203
+ * @param func The function to be executed for each input value.
204
+ * @param input The input values to be processed.
205
+ * @param config Optional configuration for the function execution.
206
+ * @returns A promise that resolves to the output values.
207
+ */
208
+ async _batchWithConfig(func, inputs, options, batchOptions) {
209
+ const optionsList = this._getOptionsList(options ?? {}, inputs.length);
210
+ const callbackManagers = await Promise.all(optionsList.map(require_config.getCallbackManagerForConfig));
211
+ const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => {
212
+ const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), optionsList[i].runId, optionsList[i].runType, void 0, void 0, optionsList[i].runName ?? this.getName());
213
+ delete optionsList[i].runId;
214
+ return handleStartRes;
215
+ }));
216
+ let outputs;
217
+ try {
218
+ const promise = func.call(this, inputs, optionsList, runManagers, batchOptions);
219
+ outputs = await require_signal.raceWithSignal(promise, optionsList?.[0]?.signal);
220
+ } catch (e) {
221
+ await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e)));
222
+ throw e;
223
+ }
224
+ await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict(outputs, "output"))));
225
+ return outputs;
226
+ }
227
+ /**
228
+ * Helper method to transform an Iterator of Input values into an Iterator of
229
+ * Output values, with callbacks.
230
+ * Use this to implement `stream()` or `transform()` in Runnable subclasses.
231
+ */
232
+ async *_transformStreamWithConfig(inputGenerator, transformer, options) {
233
+ let finalInput;
234
+ let finalInputSupported = true;
235
+ let finalOutput;
236
+ let finalOutputSupported = true;
237
+ const config = require_config.ensureConfig(options);
238
+ const callbackManager_ = await require_config.getCallbackManagerForConfig(config);
239
+ async function* wrapInputForTracing() {
240
+ for await (const chunk of inputGenerator) {
241
+ if (finalInputSupported) if (finalInput === void 0) finalInput = chunk;
242
+ else try {
243
+ finalInput = require_utils_stream.concat(finalInput, chunk);
244
+ } catch {
245
+ finalInput = void 0;
246
+ finalInputSupported = false;
247
+ }
248
+ yield chunk;
249
+ }
250
+ }
251
+ let runManager;
252
+ try {
253
+ const pipe = await require_utils_stream.pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config.runId, config.runType, void 0, void 0, config.runName ?? this.getName()), options?.signal, config);
254
+ delete config.runId;
255
+ runManager = pipe.setup;
256
+ const streamEventsHandler = runManager?.handlers.find(require_event_stream.isStreamEventsHandler);
257
+ let iterator = pipe.output;
258
+ if (streamEventsHandler !== void 0 && runManager !== void 0) iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator);
259
+ const streamLogHandler = runManager?.handlers.find(require_tracers_log_stream.isLogStreamHandler);
260
+ if (streamLogHandler !== void 0 && runManager !== void 0) iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator);
261
+ for await (const chunk of iterator) {
262
+ yield chunk;
263
+ if (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk;
264
+ else try {
265
+ finalOutput = require_utils_stream.concat(finalOutput, chunk);
266
+ } catch {
267
+ finalOutput = void 0;
268
+ finalOutputSupported = false;
269
+ }
270
+ }
271
+ } catch (e) {
272
+ await runManager?.handleChainError(e, void 0, void 0, void 0, { inputs: _coerceToDict(finalInput, "input") });
273
+ throw e;
274
+ }
275
+ await runManager?.handleChainEnd(finalOutput ?? {}, void 0, void 0, void 0, { inputs: _coerceToDict(finalInput, "input") });
276
+ }
277
+ getGraph(_) {
278
+ const graph = new require_runnables_graph.Graph();
279
+ const inputNode = graph.addNode({
280
+ name: `${this.getName()}Input`,
281
+ schema: zod_v3.z.any()
282
+ });
283
+ const runnableNode = graph.addNode(this);
284
+ const outputNode = graph.addNode({
285
+ name: `${this.getName()}Output`,
286
+ schema: zod_v3.z.any()
287
+ });
288
+ graph.addEdge(inputNode, runnableNode);
289
+ graph.addEdge(runnableNode, outputNode);
290
+ return graph;
291
+ }
292
+ /**
293
+ * Create a new runnable sequence that runs each individual runnable in series,
294
+ * piping the output of one runnable into another runnable or runnable-like.
295
+ * @param coerceable A runnable, function, or object whose values are functions or runnables.
296
+ * @returns A new runnable sequence.
297
+ */
298
+ pipe(coerceable) {
299
+ return new RunnableSequence({
300
+ first: this,
301
+ last: _coerceToRunnable(coerceable)
302
+ });
303
+ }
304
+ /**
305
+ * Pick keys from the dict output of this runnable. Returns a new runnable.
306
+ */
307
+ pick(keys) {
308
+ return this.pipe(new RunnablePick(keys));
309
+ }
310
+ /**
311
+ * Assigns new fields to the dict output of this runnable. Returns a new runnable.
312
+ */
313
+ assign(mapping) {
314
+ return this.pipe(new RunnableAssign(new RunnableMap({ steps: mapping })));
315
+ }
316
+ /**
317
+ * Default implementation of transform, which buffers input and then calls stream.
318
+ * Subclasses should override this method if they can start producing output while
319
+ * input is still being generated.
320
+ * @param generator
321
+ * @param options
322
+ */
323
+ async *transform(generator, options) {
324
+ let finalChunk;
325
+ for await (const chunk of generator) if (finalChunk === void 0) finalChunk = chunk;
326
+ else finalChunk = require_utils_stream.concat(finalChunk, chunk);
327
+ yield* this._streamIterator(finalChunk, require_config.ensureConfig(options));
328
+ }
329
+ /**
330
+ * Stream all output from a runnable, as reported to the callback system.
331
+ * This includes all inner runs of LLMs, Retrievers, Tools, etc.
332
+ * Output is streamed as Log objects, which include a list of
333
+ * jsonpatch ops that describe how the state of the run has changed in each
334
+ * step, and the final state of the run.
335
+ * The jsonpatch ops can be applied in order to construct state.
336
+ * @param input
337
+ * @param options
338
+ * @param streamOptions
339
+ */
340
+ async *streamLog(input, options, streamOptions) {
341
+ const logStreamCallbackHandler = new require_tracers_log_stream.LogStreamCallbackHandler({
342
+ ...streamOptions,
343
+ autoClose: false,
344
+ _schemaFormat: "original"
345
+ });
346
+ const config = require_config.ensureConfig(options);
347
+ yield* this._streamLog(input, logStreamCallbackHandler, config);
348
+ }
349
+ async *_streamLog(input, logStreamCallbackHandler, config) {
350
+ const { callbacks } = config;
351
+ if (callbacks === void 0) config.callbacks = [logStreamCallbackHandler];
352
+ else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat([logStreamCallbackHandler]);
353
+ else {
354
+ const copiedCallbacks = callbacks.copy();
355
+ copiedCallbacks.addHandler(logStreamCallbackHandler, true);
356
+ config.callbacks = copiedCallbacks;
357
+ }
358
+ const runnableStreamPromise = this.stream(input, config);
359
+ async function consumeRunnableStream() {
360
+ try {
361
+ const runnableStream = await runnableStreamPromise;
362
+ for await (const chunk of runnableStream) {
363
+ const patch = new require_tracers_log_stream.RunLogPatch({ ops: [{
364
+ op: "add",
365
+ path: "/streamed_output/-",
366
+ value: chunk
367
+ }] });
368
+ await logStreamCallbackHandler.writer.write(patch);
369
+ }
370
+ } finally {
371
+ await logStreamCallbackHandler.writer.close();
372
+ }
373
+ }
374
+ const runnableStreamConsumePromise = consumeRunnableStream();
375
+ try {
376
+ for await (const log of logStreamCallbackHandler) yield log;
377
+ } finally {
378
+ await runnableStreamConsumePromise;
379
+ }
380
+ }
381
+ streamEvents(input, options, streamOptions) {
382
+ let stream;
383
+ if (options.version === "v1") stream = this._streamEventsV1(input, options, streamOptions);
384
+ else if (options.version === "v2") stream = this._streamEventsV2(input, options, streamOptions);
385
+ else throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`);
386
+ if (options.encoding === "text/event-stream") return require_wrappers.convertToHttpEventStream(stream);
387
+ else return require_utils_stream.IterableReadableStream.fromAsyncGenerator(stream);
388
+ }
389
+ async *_streamEventsV2(input, options, streamOptions) {
390
+ const eventStreamer = new require_event_stream.EventStreamCallbackHandler({
391
+ ...streamOptions,
392
+ autoClose: false
393
+ });
394
+ const config = require_config.ensureConfig(options);
395
+ const runId = config.runId ?? (0, uuid.v4)();
396
+ config.runId = runId;
397
+ const callbacks = config.callbacks;
398
+ if (callbacks === void 0) config.callbacks = [eventStreamer];
399
+ else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(eventStreamer);
400
+ else {
401
+ const copiedCallbacks = callbacks.copy();
402
+ copiedCallbacks.addHandler(eventStreamer, true);
403
+ config.callbacks = copiedCallbacks;
404
+ }
405
+ const abortController = new AbortController();
406
+ const outerThis = this;
407
+ async function consumeRunnableStream() {
408
+ let signal;
409
+ let listener = null;
410
+ try {
411
+ if (options?.signal) if ("any" in AbortSignal) signal = AbortSignal.any([abortController.signal, options.signal]);
412
+ else {
413
+ signal = options.signal;
414
+ listener = () => {
415
+ abortController.abort();
416
+ };
417
+ options.signal.addEventListener("abort", listener, { once: true });
418
+ }
419
+ else signal = abortController.signal;
420
+ const runnableStream = await outerThis.stream(input, {
421
+ ...config,
422
+ signal
423
+ });
424
+ const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream);
425
+ for await (const _ of tappedStream) if (abortController.signal.aborted) break;
426
+ } finally {
427
+ await eventStreamer.finish();
428
+ if (signal && listener) signal.removeEventListener("abort", listener);
429
+ }
430
+ }
431
+ const runnableStreamConsumePromise = consumeRunnableStream();
432
+ let firstEventSent = false;
433
+ let firstEventRunId;
434
+ try {
435
+ for await (const event of eventStreamer) {
436
+ if (!firstEventSent) {
437
+ event.data.input = input;
438
+ firstEventSent = true;
439
+ firstEventRunId = event.run_id;
440
+ yield event;
441
+ continue;
442
+ }
443
+ if (event.run_id === firstEventRunId && event.event.endsWith("_end")) {
444
+ if (event.data?.input) delete event.data.input;
445
+ }
446
+ yield event;
447
+ }
448
+ } finally {
449
+ abortController.abort();
450
+ await runnableStreamConsumePromise;
451
+ }
452
+ }
453
+ async *_streamEventsV1(input, options, streamOptions) {
454
+ let runLog;
455
+ let hasEncounteredStartEvent = false;
456
+ const config = require_config.ensureConfig(options);
457
+ const rootTags = config.tags ?? [];
458
+ const rootMetadata = config.metadata ?? {};
459
+ const rootName = config.runName ?? this.getName();
460
+ const logStreamCallbackHandler = new require_tracers_log_stream.LogStreamCallbackHandler({
461
+ ...streamOptions,
462
+ autoClose: false,
463
+ _schemaFormat: "streaming_events"
464
+ });
465
+ const rootEventFilter = new require_utils$1._RootEventFilter({ ...streamOptions });
466
+ const logStream = this._streamLog(input, logStreamCallbackHandler, config);
467
+ for await (const log of logStream) {
468
+ if (!runLog) runLog = require_tracers_log_stream.RunLog.fromRunLogPatch(log);
469
+ else runLog = runLog.concat(log);
470
+ if (runLog.state === void 0) throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`);
471
+ if (!hasEncounteredStartEvent) {
472
+ hasEncounteredStartEvent = true;
473
+ const state$2 = { ...runLog.state };
474
+ const event = {
475
+ run_id: state$2.id,
476
+ event: `on_${state$2.type}_start`,
477
+ name: rootName,
478
+ tags: rootTags,
479
+ metadata: rootMetadata,
480
+ data: { input }
481
+ };
482
+ if (rootEventFilter.includeEvent(event, state$2.type)) yield event;
483
+ }
484
+ const paths = log.ops.filter((op) => op.path.startsWith("/logs/")).map((op) => op.path.split("/")[2]);
485
+ const dedupedPaths = [...new Set(paths)];
486
+ for (const path of dedupedPaths) {
487
+ let eventType;
488
+ let data = {};
489
+ const logEntry = runLog.state.logs[path];
490
+ if (logEntry.end_time === void 0) if (logEntry.streamed_output.length > 0) eventType = "stream";
491
+ else eventType = "start";
492
+ else eventType = "end";
493
+ if (eventType === "start") {
494
+ if (logEntry.inputs !== void 0) data.input = logEntry.inputs;
495
+ } else if (eventType === "end") {
496
+ if (logEntry.inputs !== void 0) data.input = logEntry.inputs;
497
+ data.output = logEntry.final_output;
498
+ } else if (eventType === "stream") {
499
+ const chunkCount = logEntry.streamed_output.length;
500
+ if (chunkCount !== 1) throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`);
501
+ data = { chunk: logEntry.streamed_output[0] };
502
+ logEntry.streamed_output = [];
503
+ }
504
+ yield {
505
+ event: `on_${logEntry.type}_${eventType}`,
506
+ name: logEntry.name,
507
+ run_id: logEntry.id,
508
+ tags: logEntry.tags,
509
+ metadata: logEntry.metadata,
510
+ data
511
+ };
512
+ }
513
+ const { state: state$1 } = runLog;
514
+ if (state$1.streamed_output.length > 0) {
515
+ const chunkCount = state$1.streamed_output.length;
516
+ if (chunkCount !== 1) throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state$1.name}"`);
517
+ const data = { chunk: state$1.streamed_output[0] };
518
+ state$1.streamed_output = [];
519
+ const event = {
520
+ event: `on_${state$1.type}_stream`,
521
+ run_id: state$1.id,
522
+ tags: rootTags,
523
+ metadata: rootMetadata,
524
+ name: rootName,
525
+ data
526
+ };
527
+ if (rootEventFilter.includeEvent(event, state$1.type)) yield event;
528
+ }
529
+ }
530
+ const state = runLog?.state;
531
+ if (state !== void 0) {
532
+ const event = {
533
+ event: `on_${state.type}_end`,
534
+ name: rootName,
535
+ run_id: state.id,
536
+ tags: rootTags,
537
+ metadata: rootMetadata,
538
+ data: { output: state.final_output }
539
+ };
540
+ if (rootEventFilter.includeEvent(event, state.type)) yield event;
541
+ }
542
+ }
543
+ static isRunnable(thing) {
544
+ return require_utils$1.isRunnableInterface(thing);
545
+ }
546
+ /**
547
+ * Bind lifecycle listeners to a Runnable, returning a new Runnable.
548
+ * The Run object contains information about the run, including its id,
549
+ * type, input, output, error, startTime, endTime, and any tags or metadata
550
+ * added to the run.
551
+ *
552
+ * @param {Object} params - The object containing the callback functions.
553
+ * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.
554
+ * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.
555
+ * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.
556
+ */
557
+ withListeners({ onStart, onEnd, onError }) {
558
+ return new RunnableBinding({
559
+ bound: this,
560
+ config: {},
561
+ configFactories: [(config) => ({ callbacks: [new require_root_listener.RootListenersTracer({
562
+ config,
563
+ onStart,
564
+ onEnd,
565
+ onError
566
+ })] })]
567
+ });
568
+ }
569
+ /**
570
+ * Convert a runnable to a tool. Return a new instance of `RunnableToolLike`
571
+ * which contains the runnable, name, description and schema.
572
+ *
573
+ * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable.
574
+ *
575
+ * @param fields
576
+ * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.
577
+ * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided.
578
+ * @param {z.ZodType<T>} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.
579
+ * @returns {RunnableToolLike<z.ZodType<T>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.
580
+ */
581
+ asTool(fields) {
582
+ return convertRunnableToTool(this, fields);
583
+ }
584
+ };
796
585
  /**
797
- * Wraps a runnable and applies partial config upon invocation.
798
- *
799
- * @example
800
- * ```typescript
801
- * import {
802
- * type RunnableConfig,
803
- * RunnableLambda,
804
- * } from "@langchain/core/runnables";
805
- *
806
- * const enhanceProfile = (
807
- * profile: Record<string, any>,
808
- * config?: RunnableConfig
809
- * ) => {
810
- * if (config?.configurable?.role) {
811
- * return { ...profile, role: config.configurable.role };
812
- * }
813
- * return profile;
814
- * };
815
- *
816
- * const runnable = RunnableLambda.from(enhanceProfile);
817
- *
818
- * // Bind configuration to the runnable to set the user's role dynamically
819
- * const adminRunnable = runnable.bind({ configurable: { role: "Admin" } });
820
- * const userRunnable = runnable.bind({ configurable: { role: "User" } });
821
- *
822
- * const result1 = await adminRunnable.invoke({
823
- * name: "Alice",
824
- * email: "alice@example.com"
825
- * });
826
- *
827
- * // { name: "Alice", email: "alice@example.com", role: "Admin" }
828
- *
829
- * const result2 = await userRunnable.invoke({
830
- * name: "Bob",
831
- * email: "bob@example.com"
832
- * });
833
- *
834
- * // { name: "Bob", email: "bob@example.com", role: "User" }
835
- * ```
836
- */
837
- class RunnableBinding extends Runnable {
838
- static lc_name() {
839
- return "RunnableBinding";
840
- }
841
- constructor(fields) {
842
- super(fields);
843
- Object.defineProperty(this, "lc_namespace", {
844
- enumerable: true,
845
- configurable: true,
846
- writable: true,
847
- value: ["langchain_core", "runnables"]
848
- });
849
- Object.defineProperty(this, "lc_serializable", {
850
- enumerable: true,
851
- configurable: true,
852
- writable: true,
853
- value: true
854
- });
855
- Object.defineProperty(this, "bound", {
856
- enumerable: true,
857
- configurable: true,
858
- writable: true,
859
- value: void 0
860
- });
861
- Object.defineProperty(this, "config", {
862
- enumerable: true,
863
- configurable: true,
864
- writable: true,
865
- value: void 0
866
- });
867
- Object.defineProperty(this, "kwargs", {
868
- enumerable: true,
869
- configurable: true,
870
- writable: true,
871
- value: void 0
872
- });
873
- Object.defineProperty(this, "configFactories", {
874
- enumerable: true,
875
- configurable: true,
876
- writable: true,
877
- value: void 0
878
- });
879
- this.bound = fields.bound;
880
- this.kwargs = fields.kwargs;
881
- this.config = fields.config;
882
- this.configFactories = fields.configFactories;
883
- }
884
- getName(suffix) {
885
- return this.bound.getName(suffix);
886
- }
887
- async _mergeConfig(...options) {
888
- const config = (0, config_js_1.mergeConfigs)(this.config, ...options);
889
- return (0, config_js_1.mergeConfigs)(config, ...(this.configFactories
890
- ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config)))
891
- : []));
892
- }
893
- /**
894
- * Binds the runnable with the specified arguments.
895
- * @param kwargs The arguments to bind the runnable with.
896
- * @returns A new instance of the `RunnableBinding` class that is bound with the specified arguments.
897
- *
898
- * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release.
899
- */
900
- bind(kwargs) {
901
- return new this.constructor({
902
- bound: this.bound,
903
- kwargs: { ...this.kwargs, ...kwargs },
904
- config: this.config,
905
- });
906
- }
907
- withConfig(config) {
908
- return new this.constructor({
909
- bound: this.bound,
910
- kwargs: this.kwargs,
911
- config: { ...this.config, ...config },
912
- });
913
- }
914
- withRetry(fields) {
915
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
916
- return new RunnableRetry({
917
- bound: this.bound,
918
- kwargs: this.kwargs,
919
- config: this.config,
920
- maxAttemptNumber: fields?.stopAfterAttempt,
921
- ...fields,
922
- });
923
- }
924
- async invoke(input, options) {
925
- return this.bound.invoke(input, await this._mergeConfig((0, config_js_1.ensureConfig)(options), this.kwargs));
926
- }
927
- async batch(inputs, options, batchOptions) {
928
- const mergedOptions = Array.isArray(options)
929
- ? await Promise.all(options.map(async (individualOption) => this._mergeConfig((0, config_js_1.ensureConfig)(individualOption), this.kwargs)))
930
- : await this._mergeConfig((0, config_js_1.ensureConfig)(options), this.kwargs);
931
- return this.bound.batch(inputs, mergedOptions, batchOptions);
932
- }
933
- /** @internal */
934
- _concatOutputChunks(first, second) {
935
- return this.bound._concatOutputChunks(first, second);
936
- }
937
- async *_streamIterator(input, options) {
938
- yield* this.bound._streamIterator(input, await this._mergeConfig((0, config_js_1.ensureConfig)(options), this.kwargs));
939
- }
940
- async stream(input, options) {
941
- return this.bound.stream(input, await this._mergeConfig((0, config_js_1.ensureConfig)(options), this.kwargs));
942
- }
943
- async *transform(generator, options) {
944
- yield* this.bound.transform(generator, await this._mergeConfig((0, config_js_1.ensureConfig)(options), this.kwargs));
945
- }
946
- streamEvents(input, options, streamOptions) {
947
- // eslint-disable-next-line @typescript-eslint/no-this-alias
948
- const outerThis = this;
949
- const generator = async function* () {
950
- yield* outerThis.bound.streamEvents(input, {
951
- ...(await outerThis._mergeConfig((0, config_js_1.ensureConfig)(options), outerThis.kwargs)),
952
- version: options.version,
953
- }, streamOptions);
954
- };
955
- return stream_js_1.IterableReadableStream.fromAsyncGenerator(generator());
956
- }
957
- static isRunnableBinding(
958
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
959
- thing
960
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
961
- ) {
962
- return thing.bound && Runnable.isRunnable(thing.bound);
963
- }
964
- /**
965
- * Bind lifecycle listeners to a Runnable, returning a new Runnable.
966
- * The Run object contains information about the run, including its id,
967
- * type, input, output, error, startTime, endTime, and any tags or metadata
968
- * added to the run.
969
- *
970
- * @param {Object} params - The object containing the callback functions.
971
- * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.
972
- * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.
973
- * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.
974
- */
975
- withListeners({ onStart, onEnd, onError, }) {
976
- return new RunnableBinding({
977
- bound: this.bound,
978
- kwargs: this.kwargs,
979
- config: this.config,
980
- configFactories: [
981
- (config) => ({
982
- callbacks: [
983
- new root_listener_js_1.RootListenersTracer({
984
- config,
985
- onStart,
986
- onEnd,
987
- onError,
988
- }),
989
- ],
990
- }),
991
- ],
992
- });
993
- }
994
- }
995
- exports.RunnableBinding = RunnableBinding;
586
+ * Wraps a runnable and applies partial config upon invocation.
587
+ *
588
+ * @example
589
+ * ```typescript
590
+ * import {
591
+ * type RunnableConfig,
592
+ * RunnableLambda,
593
+ * } from "@langchain/core/runnables";
594
+ *
595
+ * const enhanceProfile = (
596
+ * profile: Record<string, any>,
597
+ * config?: RunnableConfig
598
+ * ) => {
599
+ * if (config?.configurable?.role) {
600
+ * return { ...profile, role: config.configurable.role };
601
+ * }
602
+ * return profile;
603
+ * };
604
+ *
605
+ * const runnable = RunnableLambda.from(enhanceProfile);
606
+ *
607
+ * // Bind configuration to the runnable to set the user's role dynamically
608
+ * const adminRunnable = runnable.bind({ configurable: { role: "Admin" } });
609
+ * const userRunnable = runnable.bind({ configurable: { role: "User" } });
610
+ *
611
+ * const result1 = await adminRunnable.invoke({
612
+ * name: "Alice",
613
+ * email: "alice@example.com"
614
+ * });
615
+ *
616
+ * // { name: "Alice", email: "alice@example.com", role: "Admin" }
617
+ *
618
+ * const result2 = await userRunnable.invoke({
619
+ * name: "Bob",
620
+ * email: "bob@example.com"
621
+ * });
622
+ *
623
+ * // { name: "Bob", email: "bob@example.com", role: "User" }
624
+ * ```
625
+ */
626
+ var RunnableBinding = class RunnableBinding extends Runnable {
627
+ static lc_name() {
628
+ return "RunnableBinding";
629
+ }
630
+ lc_namespace = ["langchain_core", "runnables"];
631
+ lc_serializable = true;
632
+ bound;
633
+ config;
634
+ kwargs;
635
+ configFactories;
636
+ constructor(fields) {
637
+ super(fields);
638
+ this.bound = fields.bound;
639
+ this.kwargs = fields.kwargs;
640
+ this.config = fields.config;
641
+ this.configFactories = fields.configFactories;
642
+ }
643
+ getName(suffix) {
644
+ return this.bound.getName(suffix);
645
+ }
646
+ async _mergeConfig(...options) {
647
+ const config = require_config.mergeConfigs(this.config, ...options);
648
+ return require_config.mergeConfigs(config, ...this.configFactories ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config))) : []);
649
+ }
650
+ /**
651
+ * Binds the runnable with the specified arguments.
652
+ * @param kwargs The arguments to bind the runnable with.
653
+ * @returns A new instance of the `RunnableBinding` class that is bound with the specified arguments.
654
+ *
655
+ * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release.
656
+ */
657
+ bind(kwargs) {
658
+ return new this.constructor({
659
+ bound: this.bound,
660
+ kwargs: {
661
+ ...this.kwargs,
662
+ ...kwargs
663
+ },
664
+ config: this.config
665
+ });
666
+ }
667
+ withConfig(config) {
668
+ return new this.constructor({
669
+ bound: this.bound,
670
+ kwargs: this.kwargs,
671
+ config: {
672
+ ...this.config,
673
+ ...config
674
+ }
675
+ });
676
+ }
677
+ withRetry(fields) {
678
+ return new RunnableRetry({
679
+ bound: this.bound,
680
+ kwargs: this.kwargs,
681
+ config: this.config,
682
+ maxAttemptNumber: fields?.stopAfterAttempt,
683
+ ...fields
684
+ });
685
+ }
686
+ async invoke(input, options) {
687
+ return this.bound.invoke(input, await this._mergeConfig(require_config.ensureConfig(options), this.kwargs));
688
+ }
689
+ async batch(inputs, options, batchOptions) {
690
+ const mergedOptions = Array.isArray(options) ? await Promise.all(options.map(async (individualOption) => this._mergeConfig(require_config.ensureConfig(individualOption), this.kwargs))) : await this._mergeConfig(require_config.ensureConfig(options), this.kwargs);
691
+ return this.bound.batch(inputs, mergedOptions, batchOptions);
692
+ }
693
+ async *_streamIterator(input, options) {
694
+ yield* this.bound._streamIterator(input, await this._mergeConfig(require_config.ensureConfig(options), this.kwargs));
695
+ }
696
+ async stream(input, options) {
697
+ return this.bound.stream(input, await this._mergeConfig(require_config.ensureConfig(options), this.kwargs));
698
+ }
699
+ async *transform(generator, options) {
700
+ yield* this.bound.transform(generator, await this._mergeConfig(require_config.ensureConfig(options), this.kwargs));
701
+ }
702
+ streamEvents(input, options, streamOptions) {
703
+ const outerThis = this;
704
+ const generator = async function* () {
705
+ yield* outerThis.bound.streamEvents(input, {
706
+ ...await outerThis._mergeConfig(require_config.ensureConfig(options), outerThis.kwargs),
707
+ version: options.version
708
+ }, streamOptions);
709
+ };
710
+ return require_utils_stream.IterableReadableStream.fromAsyncGenerator(generator());
711
+ }
712
+ static isRunnableBinding(thing) {
713
+ return thing.bound && Runnable.isRunnable(thing.bound);
714
+ }
715
+ /**
716
+ * Bind lifecycle listeners to a Runnable, returning a new Runnable.
717
+ * The Run object contains information about the run, including its id,
718
+ * type, input, output, error, startTime, endTime, and any tags or metadata
719
+ * added to the run.
720
+ *
721
+ * @param {Object} params - The object containing the callback functions.
722
+ * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.
723
+ * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.
724
+ * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.
725
+ */
726
+ withListeners({ onStart, onEnd, onError }) {
727
+ return new RunnableBinding({
728
+ bound: this.bound,
729
+ kwargs: this.kwargs,
730
+ config: this.config,
731
+ configFactories: [(config) => ({ callbacks: [new require_root_listener.RootListenersTracer({
732
+ config,
733
+ onStart,
734
+ onEnd,
735
+ onError
736
+ })] })]
737
+ });
738
+ }
739
+ };
996
740
  /**
997
- * A runnable that delegates calls to another runnable
998
- * with each element of the input sequence.
999
- * @example
1000
- * ```typescript
1001
- * import { RunnableEach, RunnableLambda } from "@langchain/core/runnables";
1002
- *
1003
- * const toUpperCase = (input: string): string => input.toUpperCase();
1004
- * const addGreeting = (input: string): string => `Hello, ${input}!`;
1005
- *
1006
- * const upperCaseLambda = RunnableLambda.from(toUpperCase);
1007
- * const greetingLambda = RunnableLambda.from(addGreeting);
1008
- *
1009
- * const chain = new RunnableEach({
1010
- * bound: upperCaseLambda.pipe(greetingLambda),
1011
- * });
1012
- *
1013
- * const result = await chain.invoke(["alice", "bob", "carol"])
1014
- *
1015
- * // ["Hello, ALICE!", "Hello, BOB!", "Hello, CAROL!"]
1016
- * ```
1017
- *
1018
- * @deprecated This will be removed in the next breaking release.
1019
- */
1020
- class RunnableEach extends Runnable {
1021
- static lc_name() {
1022
- return "RunnableEach";
1023
- }
1024
- constructor(fields) {
1025
- super(fields);
1026
- Object.defineProperty(this, "lc_serializable", {
1027
- enumerable: true,
1028
- configurable: true,
1029
- writable: true,
1030
- value: true
1031
- });
1032
- Object.defineProperty(this, "lc_namespace", {
1033
- enumerable: true,
1034
- configurable: true,
1035
- writable: true,
1036
- value: ["langchain_core", "runnables"]
1037
- });
1038
- Object.defineProperty(this, "bound", {
1039
- enumerable: true,
1040
- configurable: true,
1041
- writable: true,
1042
- value: void 0
1043
- });
1044
- this.bound = fields.bound;
1045
- }
1046
- /**
1047
- * Binds the runnable with the specified arguments.
1048
- * @param kwargs The arguments to bind the runnable with.
1049
- * @returns A new instance of the `RunnableEach` class that is bound with the specified arguments.
1050
- *
1051
- * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release.
1052
- */
1053
- bind(kwargs) {
1054
- return new RunnableEach({
1055
- bound: this.bound.bind(kwargs),
1056
- });
1057
- }
1058
- /**
1059
- * Invokes the runnable with the specified input and configuration.
1060
- * @param input The input to invoke the runnable with.
1061
- * @param config The configuration to invoke the runnable with.
1062
- * @returns A promise that resolves to the output of the runnable.
1063
- */
1064
- async invoke(inputs, config) {
1065
- return this._callWithConfig(this._invoke.bind(this), inputs, config);
1066
- }
1067
- /**
1068
- * A helper method that is used to invoke the runnable with the specified input and configuration.
1069
- * @param input The input to invoke the runnable with.
1070
- * @param config The configuration to invoke the runnable with.
1071
- * @returns A promise that resolves to the output of the runnable.
1072
- */
1073
- async _invoke(inputs, config, runManager) {
1074
- return this.bound.batch(inputs, (0, config_js_1.patchConfig)(config, { callbacks: runManager?.getChild() }));
1075
- }
1076
- /**
1077
- * Bind lifecycle listeners to a Runnable, returning a new Runnable.
1078
- * The Run object contains information about the run, including its id,
1079
- * type, input, output, error, startTime, endTime, and any tags or metadata
1080
- * added to the run.
1081
- *
1082
- * @param {Object} params - The object containing the callback functions.
1083
- * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.
1084
- * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.
1085
- * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.
1086
- */
1087
- withListeners({ onStart, onEnd, onError, }) {
1088
- return new RunnableEach({
1089
- bound: this.bound.withListeners({ onStart, onEnd, onError }),
1090
- });
1091
- }
1092
- }
1093
- exports.RunnableEach = RunnableEach;
741
+ * A runnable that delegates calls to another runnable
742
+ * with each element of the input sequence.
743
+ * @example
744
+ * ```typescript
745
+ * import { RunnableEach, RunnableLambda } from "@langchain/core/runnables";
746
+ *
747
+ * const toUpperCase = (input: string): string => input.toUpperCase();
748
+ * const addGreeting = (input: string): string => `Hello, ${input}!`;
749
+ *
750
+ * const upperCaseLambda = RunnableLambda.from(toUpperCase);
751
+ * const greetingLambda = RunnableLambda.from(addGreeting);
752
+ *
753
+ * const chain = new RunnableEach({
754
+ * bound: upperCaseLambda.pipe(greetingLambda),
755
+ * });
756
+ *
757
+ * const result = await chain.invoke(["alice", "bob", "carol"])
758
+ *
759
+ * // ["Hello, ALICE!", "Hello, BOB!", "Hello, CAROL!"]
760
+ * ```
761
+ *
762
+ * @deprecated This will be removed in the next breaking release.
763
+ */
764
+ var RunnableEach = class RunnableEach extends Runnable {
765
+ static lc_name() {
766
+ return "RunnableEach";
767
+ }
768
+ lc_serializable = true;
769
+ lc_namespace = ["langchain_core", "runnables"];
770
+ bound;
771
+ constructor(fields) {
772
+ super(fields);
773
+ this.bound = fields.bound;
774
+ }
775
+ /**
776
+ * Binds the runnable with the specified arguments.
777
+ * @param kwargs The arguments to bind the runnable with.
778
+ * @returns A new instance of the `RunnableEach` class that is bound with the specified arguments.
779
+ *
780
+ * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release.
781
+ */
782
+ bind(kwargs) {
783
+ return new RunnableEach({ bound: this.bound.bind(kwargs) });
784
+ }
785
+ /**
786
+ * Invokes the runnable with the specified input and configuration.
787
+ * @param input The input to invoke the runnable with.
788
+ * @param config The configuration to invoke the runnable with.
789
+ * @returns A promise that resolves to the output of the runnable.
790
+ */
791
+ async invoke(inputs, config) {
792
+ return this._callWithConfig(this._invoke.bind(this), inputs, config);
793
+ }
794
+ /**
795
+ * A helper method that is used to invoke the runnable with the specified input and configuration.
796
+ * @param input The input to invoke the runnable with.
797
+ * @param config The configuration to invoke the runnable with.
798
+ * @returns A promise that resolves to the output of the runnable.
799
+ */
800
+ async _invoke(inputs, config, runManager) {
801
+ return this.bound.batch(inputs, require_config.patchConfig(config, { callbacks: runManager?.getChild() }));
802
+ }
803
+ /**
804
+ * Bind lifecycle listeners to a Runnable, returning a new Runnable.
805
+ * The Run object contains information about the run, including its id,
806
+ * type, input, output, error, startTime, endTime, and any tags or metadata
807
+ * added to the run.
808
+ *
809
+ * @param {Object} params - The object containing the callback functions.
810
+ * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.
811
+ * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.
812
+ * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.
813
+ */
814
+ withListeners({ onStart, onEnd, onError }) {
815
+ return new RunnableEach({ bound: this.bound.withListeners({
816
+ onStart,
817
+ onEnd,
818
+ onError
819
+ }) });
820
+ }
821
+ };
1094
822
  /**
1095
- * Base class for runnables that can be retried a
1096
- * specified number of times.
1097
- * @example
1098
- * ```typescript
1099
- * import {
1100
- * RunnableLambda,
1101
- * RunnableRetry,
1102
- * } from "@langchain/core/runnables";
1103
- *
1104
- * // Simulate an API call that fails
1105
- * const simulateApiCall = (input: string): string => {
1106
- * console.log(`Attempting API call with input: ${input}`);
1107
- * throw new Error("API call failed due to network issue");
1108
- * };
1109
- *
1110
- * const apiCallLambda = RunnableLambda.from(simulateApiCall);
1111
- *
1112
- * // Apply retry logic using the .withRetry() method
1113
- * const apiCallWithRetry = apiCallLambda.withRetry({ stopAfterAttempt: 3 });
1114
- *
1115
- * // Alternatively, create a RunnableRetry instance manually
1116
- * const manualRetry = new RunnableRetry({
1117
- * bound: apiCallLambda,
1118
- * maxAttemptNumber: 3,
1119
- * config: {},
1120
- * });
1121
- *
1122
- * // Example invocation using the .withRetry() method
1123
- * const res = await apiCallWithRetry
1124
- * .invoke("Request 1")
1125
- * .catch((error) => {
1126
- * console.error("Failed after multiple retries:", error.message);
1127
- * });
1128
- *
1129
- * // Example invocation using the manual retry instance
1130
- * const res2 = await manualRetry
1131
- * .invoke("Request 2")
1132
- * .catch((error) => {
1133
- * console.error("Failed after multiple retries:", error.message);
1134
- * });
1135
- * ```
1136
- */
1137
- class RunnableRetry extends RunnableBinding {
1138
- static lc_name() {
1139
- return "RunnableRetry";
1140
- }
1141
- constructor(fields) {
1142
- super(fields);
1143
- Object.defineProperty(this, "lc_namespace", {
1144
- enumerable: true,
1145
- configurable: true,
1146
- writable: true,
1147
- value: ["langchain_core", "runnables"]
1148
- });
1149
- Object.defineProperty(this, "maxAttemptNumber", {
1150
- enumerable: true,
1151
- configurable: true,
1152
- writable: true,
1153
- value: 3
1154
- });
1155
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1156
- Object.defineProperty(this, "onFailedAttempt", {
1157
- enumerable: true,
1158
- configurable: true,
1159
- writable: true,
1160
- value: () => { }
1161
- });
1162
- this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber;
1163
- this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt;
1164
- }
1165
- _patchConfigForRetry(attempt, config, runManager) {
1166
- const tag = attempt > 1 ? `retry:attempt:${attempt}` : undefined;
1167
- return (0, config_js_1.patchConfig)(config, { callbacks: runManager?.getChild(tag) });
1168
- }
1169
- async _invoke(input, config, runManager) {
1170
- return (0, p_retry_1.default)((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), {
1171
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1172
- onFailedAttempt: (error) => this.onFailedAttempt(error, input),
1173
- retries: Math.max(this.maxAttemptNumber - 1, 0),
1174
- randomize: true,
1175
- });
1176
- }
1177
- /**
1178
- * Method that invokes the runnable with the specified input, run manager,
1179
- * and config. It handles the retry logic by catching any errors and
1180
- * recursively invoking itself with the updated config for the next retry
1181
- * attempt.
1182
- * @param input The input for the runnable.
1183
- * @param runManager The run manager for the runnable.
1184
- * @param config The config for the runnable.
1185
- * @returns A promise that resolves to the output of the runnable.
1186
- */
1187
- async invoke(input, config) {
1188
- return this._callWithConfig(this._invoke.bind(this), input, config);
1189
- }
1190
- async _batch(inputs, configs, runManagers, batchOptions) {
1191
- const resultsMap = {};
1192
- try {
1193
- await (0, p_retry_1.default)(async (attemptNumber) => {
1194
- const remainingIndexes = inputs
1195
- .map((_, i) => i)
1196
- .filter((i) => resultsMap[i.toString()] === undefined ||
1197
- // eslint-disable-next-line no-instanceof/no-instanceof
1198
- resultsMap[i.toString()] instanceof Error);
1199
- const remainingInputs = remainingIndexes.map((i) => inputs[i]);
1200
- const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i]));
1201
- const results = await super.batch(remainingInputs, patchedConfigs, {
1202
- ...batchOptions,
1203
- returnExceptions: true,
1204
- });
1205
- let firstException;
1206
- for (let i = 0; i < results.length; i += 1) {
1207
- const result = results[i];
1208
- const resultMapIndex = remainingIndexes[i];
1209
- // eslint-disable-next-line no-instanceof/no-instanceof
1210
- if (result instanceof Error) {
1211
- if (firstException === undefined) {
1212
- firstException = result;
1213
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1214
- firstException.input = remainingInputs[i];
1215
- }
1216
- }
1217
- resultsMap[resultMapIndex.toString()] = result;
1218
- }
1219
- if (firstException) {
1220
- throw firstException;
1221
- }
1222
- return results;
1223
- }, {
1224
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1225
- onFailedAttempt: (error) => this.onFailedAttempt(error, error.input),
1226
- retries: Math.max(this.maxAttemptNumber - 1, 0),
1227
- randomize: true,
1228
- });
1229
- }
1230
- catch (e) {
1231
- if (batchOptions?.returnExceptions !== true) {
1232
- throw e;
1233
- }
1234
- }
1235
- return Object.keys(resultsMap)
1236
- .sort((a, b) => parseInt(a, 10) - parseInt(b, 10))
1237
- .map((key) => resultsMap[parseInt(key, 10)]);
1238
- }
1239
- async batch(inputs, options, batchOptions) {
1240
- return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions);
1241
- }
1242
- }
1243
- exports.RunnableRetry = RunnableRetry;
823
+ * Base class for runnables that can be retried a
824
+ * specified number of times.
825
+ * @example
826
+ * ```typescript
827
+ * import {
828
+ * RunnableLambda,
829
+ * RunnableRetry,
830
+ * } from "@langchain/core/runnables";
831
+ *
832
+ * // Simulate an API call that fails
833
+ * const simulateApiCall = (input: string): string => {
834
+ * console.log(`Attempting API call with input: ${input}`);
835
+ * throw new Error("API call failed due to network issue");
836
+ * };
837
+ *
838
+ * const apiCallLambda = RunnableLambda.from(simulateApiCall);
839
+ *
840
+ * // Apply retry logic using the .withRetry() method
841
+ * const apiCallWithRetry = apiCallLambda.withRetry({ stopAfterAttempt: 3 });
842
+ *
843
+ * // Alternatively, create a RunnableRetry instance manually
844
+ * const manualRetry = new RunnableRetry({
845
+ * bound: apiCallLambda,
846
+ * maxAttemptNumber: 3,
847
+ * config: {},
848
+ * });
849
+ *
850
+ * // Example invocation using the .withRetry() method
851
+ * const res = await apiCallWithRetry
852
+ * .invoke("Request 1")
853
+ * .catch((error) => {
854
+ * console.error("Failed after multiple retries:", error.message);
855
+ * });
856
+ *
857
+ * // Example invocation using the manual retry instance
858
+ * const res2 = await manualRetry
859
+ * .invoke("Request 2")
860
+ * .catch((error) => {
861
+ * console.error("Failed after multiple retries:", error.message);
862
+ * });
863
+ * ```
864
+ */
865
+ var RunnableRetry = class extends RunnableBinding {
866
+ static lc_name() {
867
+ return "RunnableRetry";
868
+ }
869
+ lc_namespace = ["langchain_core", "runnables"];
870
+ maxAttemptNumber = 3;
871
+ onFailedAttempt = () => {};
872
+ constructor(fields) {
873
+ super(fields);
874
+ this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber;
875
+ this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt;
876
+ }
877
+ _patchConfigForRetry(attempt, config, runManager) {
878
+ const tag = attempt > 1 ? `retry:attempt:${attempt}` : void 0;
879
+ return require_config.patchConfig(config, { callbacks: runManager?.getChild(tag) });
880
+ }
881
+ async _invoke(input, config, runManager) {
882
+ return (0, p_retry.default)((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), {
883
+ onFailedAttempt: (error) => this.onFailedAttempt(error, input),
884
+ retries: Math.max(this.maxAttemptNumber - 1, 0),
885
+ randomize: true
886
+ });
887
+ }
888
+ /**
889
+ * Method that invokes the runnable with the specified input, run manager,
890
+ * and config. It handles the retry logic by catching any errors and
891
+ * recursively invoking itself with the updated config for the next retry
892
+ * attempt.
893
+ * @param input The input for the runnable.
894
+ * @param runManager The run manager for the runnable.
895
+ * @param config The config for the runnable.
896
+ * @returns A promise that resolves to the output of the runnable.
897
+ */
898
+ async invoke(input, config) {
899
+ return this._callWithConfig(this._invoke.bind(this), input, config);
900
+ }
901
+ async _batch(inputs, configs, runManagers, batchOptions) {
902
+ const resultsMap = {};
903
+ try {
904
+ await (0, p_retry.default)(async (attemptNumber) => {
905
+ const remainingIndexes = inputs.map((_, i) => i).filter((i) => resultsMap[i.toString()] === void 0 || resultsMap[i.toString()] instanceof Error);
906
+ const remainingInputs = remainingIndexes.map((i) => inputs[i]);
907
+ const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i]));
908
+ const results = await super.batch(remainingInputs, patchedConfigs, {
909
+ ...batchOptions,
910
+ returnExceptions: true
911
+ });
912
+ let firstException;
913
+ for (let i = 0; i < results.length; i += 1) {
914
+ const result = results[i];
915
+ const resultMapIndex = remainingIndexes[i];
916
+ if (result instanceof Error) {
917
+ if (firstException === void 0) {
918
+ firstException = result;
919
+ firstException.input = remainingInputs[i];
920
+ }
921
+ }
922
+ resultsMap[resultMapIndex.toString()] = result;
923
+ }
924
+ if (firstException) throw firstException;
925
+ return results;
926
+ }, {
927
+ onFailedAttempt: (error) => this.onFailedAttempt(error, error.input),
928
+ retries: Math.max(this.maxAttemptNumber - 1, 0),
929
+ randomize: true
930
+ });
931
+ } catch (e) {
932
+ if (batchOptions?.returnExceptions !== true) throw e;
933
+ }
934
+ return Object.keys(resultsMap).sort((a, b) => parseInt(a, 10) - parseInt(b, 10)).map((key) => resultsMap[parseInt(key, 10)]);
935
+ }
936
+ async batch(inputs, options, batchOptions) {
937
+ return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions);
938
+ }
939
+ };
1244
940
  /**
1245
- * A sequence of runnables, where the output of each is the input of the next.
1246
- * @example
1247
- * ```typescript
1248
- * const promptTemplate = PromptTemplate.fromTemplate(
1249
- * "Tell me a joke about {topic}",
1250
- * );
1251
- * const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({ model: "gpt-4o-mini" })]);
1252
- * const result = await chain.invoke({ topic: "bears" });
1253
- * ```
1254
- */
1255
- class RunnableSequence extends Runnable {
1256
- static lc_name() {
1257
- return "RunnableSequence";
1258
- }
1259
- constructor(fields) {
1260
- super(fields);
1261
- Object.defineProperty(this, "first", {
1262
- enumerable: true,
1263
- configurable: true,
1264
- writable: true,
1265
- value: void 0
1266
- });
1267
- Object.defineProperty(this, "middle", {
1268
- enumerable: true,
1269
- configurable: true,
1270
- writable: true,
1271
- value: []
1272
- });
1273
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1274
- Object.defineProperty(this, "last", {
1275
- enumerable: true,
1276
- configurable: true,
1277
- writable: true,
1278
- value: void 0
1279
- });
1280
- Object.defineProperty(this, "omitSequenceTags", {
1281
- enumerable: true,
1282
- configurable: true,
1283
- writable: true,
1284
- value: false
1285
- });
1286
- Object.defineProperty(this, "lc_serializable", {
1287
- enumerable: true,
1288
- configurable: true,
1289
- writable: true,
1290
- value: true
1291
- });
1292
- Object.defineProperty(this, "lc_namespace", {
1293
- enumerable: true,
1294
- configurable: true,
1295
- writable: true,
1296
- value: ["langchain_core", "runnables"]
1297
- });
1298
- this.first = fields.first;
1299
- this.middle = fields.middle ?? this.middle;
1300
- this.last = fields.last;
1301
- this.name = fields.name;
1302
- this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags;
1303
- }
1304
- get steps() {
1305
- return [this.first, ...this.middle, this.last];
1306
- }
1307
- async invoke(input, options) {
1308
- const config = (0, config_js_1.ensureConfig)(options);
1309
- const callbackManager_ = await (0, config_js_1.getCallbackManagerForConfig)(config);
1310
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), config.runId, undefined, undefined, undefined, config?.runName);
1311
- delete config.runId;
1312
- let nextStepInput = input;
1313
- let finalOutput;
1314
- try {
1315
- const initialSteps = [this.first, ...this.middle];
1316
- for (let i = 0; i < initialSteps.length; i += 1) {
1317
- const step = initialSteps[i];
1318
- const promise = step.invoke(nextStepInput, (0, config_js_1.patchConfig)(config, {
1319
- callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`),
1320
- }));
1321
- nextStepInput = await (0, signal_js_1.raceWithSignal)(promise, options?.signal);
1322
- }
1323
- // TypeScript can't detect that the last output of the sequence returns RunOutput, so call it out of the loop here
1324
- if (options?.signal?.aborted) {
1325
- throw new Error("Aborted");
1326
- }
1327
- finalOutput = await this.last.invoke(nextStepInput, (0, config_js_1.patchConfig)(config, {
1328
- callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${this.steps.length}`),
1329
- }));
1330
- }
1331
- catch (e) {
1332
- await runManager?.handleChainError(e);
1333
- throw e;
1334
- }
1335
- await runManager?.handleChainEnd(_coerceToDict(finalOutput, "output"));
1336
- return finalOutput;
1337
- }
1338
- async batch(inputs, options, batchOptions) {
1339
- const configList = this._getOptionsList(options ?? {}, inputs.length);
1340
- const callbackManagers = await Promise.all(configList.map(config_js_1.getCallbackManagerForConfig));
1341
- const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => {
1342
- const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName);
1343
- delete configList[i].runId;
1344
- return handleStartRes;
1345
- }));
1346
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1347
- let nextStepInputs = inputs;
1348
- try {
1349
- for (let i = 0; i < this.steps.length; i += 1) {
1350
- const step = this.steps[i];
1351
- const promise = step.batch(nextStepInputs, runManagers.map((runManager, j) => {
1352
- const childRunManager = runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`);
1353
- return (0, config_js_1.patchConfig)(configList[j], { callbacks: childRunManager });
1354
- }), batchOptions);
1355
- nextStepInputs = await (0, signal_js_1.raceWithSignal)(promise, configList[0]?.signal);
1356
- }
1357
- }
1358
- catch (e) {
1359
- await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e)));
1360
- throw e;
1361
- }
1362
- await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict(nextStepInputs, "output"))));
1363
- return nextStepInputs;
1364
- }
1365
- /** @internal */
1366
- _concatOutputChunks(first, second) {
1367
- return this.last._concatOutputChunks(first, second);
1368
- }
1369
- async *_streamIterator(input, options) {
1370
- const callbackManager_ = await (0, config_js_1.getCallbackManagerForConfig)(options);
1371
- const { runId, ...otherOptions } = options ?? {};
1372
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherOptions?.runName);
1373
- const steps = [this.first, ...this.middle, this.last];
1374
- let concatSupported = true;
1375
- let finalOutput;
1376
- async function* inputGenerator() {
1377
- yield input;
1378
- }
1379
- try {
1380
- let finalGenerator = steps[0].transform(inputGenerator(), (0, config_js_1.patchConfig)(otherOptions, {
1381
- callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:1`),
1382
- }));
1383
- for (let i = 1; i < steps.length; i += 1) {
1384
- const step = steps[i];
1385
- finalGenerator = await step.transform(finalGenerator, (0, config_js_1.patchConfig)(otherOptions, {
1386
- callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`),
1387
- }));
1388
- }
1389
- for await (const chunk of finalGenerator) {
1390
- options?.signal?.throwIfAborted();
1391
- yield chunk;
1392
- if (concatSupported) {
1393
- if (finalOutput === undefined) {
1394
- finalOutput = chunk;
1395
- }
1396
- else {
1397
- try {
1398
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1399
- finalOutput = this._concatOutputChunks(finalOutput, chunk);
1400
- }
1401
- catch (e) {
1402
- finalOutput = undefined;
1403
- concatSupported = false;
1404
- }
1405
- }
1406
- }
1407
- }
1408
- }
1409
- catch (e) {
1410
- await runManager?.handleChainError(e);
1411
- throw e;
1412
- }
1413
- await runManager?.handleChainEnd(_coerceToDict(finalOutput, "output"));
1414
- }
1415
- getGraph(config) {
1416
- const graph = new graph_js_1.Graph();
1417
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1418
- let currentLastNode = null;
1419
- this.steps.forEach((step, index) => {
1420
- const stepGraph = step.getGraph(config);
1421
- if (index !== 0) {
1422
- stepGraph.trimFirstNode();
1423
- }
1424
- if (index !== this.steps.length - 1) {
1425
- stepGraph.trimLastNode();
1426
- }
1427
- graph.extend(stepGraph);
1428
- const stepFirstNode = stepGraph.firstNode();
1429
- if (!stepFirstNode) {
1430
- throw new Error(`Runnable ${step} has no first node`);
1431
- }
1432
- if (currentLastNode) {
1433
- graph.addEdge(currentLastNode, stepFirstNode);
1434
- }
1435
- currentLastNode = stepGraph.lastNode();
1436
- });
1437
- return graph;
1438
- }
1439
- pipe(coerceable) {
1440
- if (RunnableSequence.isRunnableSequence(coerceable)) {
1441
- return new RunnableSequence({
1442
- first: this.first,
1443
- middle: this.middle.concat([
1444
- this.last,
1445
- coerceable.first,
1446
- ...coerceable.middle,
1447
- ]),
1448
- last: coerceable.last,
1449
- name: this.name ?? coerceable.name,
1450
- });
1451
- }
1452
- else {
1453
- return new RunnableSequence({
1454
- first: this.first,
1455
- middle: [...this.middle, this.last],
1456
- last: _coerceToRunnable(coerceable),
1457
- name: this.name,
1458
- });
1459
- }
1460
- }
1461
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1462
- static isRunnableSequence(thing) {
1463
- return Array.isArray(thing.middle) && Runnable.isRunnable(thing);
1464
- }
1465
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1466
- static from([first, ...runnables], nameOrFields) {
1467
- let extra = {};
1468
- if (typeof nameOrFields === "string") {
1469
- extra.name = nameOrFields;
1470
- }
1471
- else if (nameOrFields !== undefined) {
1472
- extra = nameOrFields;
1473
- }
1474
- return new RunnableSequence({
1475
- ...extra,
1476
- first: _coerceToRunnable(first),
1477
- middle: runnables.slice(0, -1).map(_coerceToRunnable),
1478
- last: _coerceToRunnable(runnables[runnables.length - 1]),
1479
- });
1480
- }
1481
- }
1482
- exports.RunnableSequence = RunnableSequence;
941
+ * A sequence of runnables, where the output of each is the input of the next.
942
+ * @example
943
+ * ```typescript
944
+ * const promptTemplate = PromptTemplate.fromTemplate(
945
+ * "Tell me a joke about {topic}",
946
+ * );
947
+ * const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({ model: "gpt-4o-mini" })]);
948
+ * const result = await chain.invoke({ topic: "bears" });
949
+ * ```
950
+ */
951
+ var RunnableSequence = class RunnableSequence extends Runnable {
952
+ static lc_name() {
953
+ return "RunnableSequence";
954
+ }
955
+ first;
956
+ middle = [];
957
+ last;
958
+ omitSequenceTags = false;
959
+ lc_serializable = true;
960
+ lc_namespace = ["langchain_core", "runnables"];
961
+ constructor(fields) {
962
+ super(fields);
963
+ this.first = fields.first;
964
+ this.middle = fields.middle ?? this.middle;
965
+ this.last = fields.last;
966
+ this.name = fields.name;
967
+ this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags;
968
+ }
969
+ get steps() {
970
+ return [
971
+ this.first,
972
+ ...this.middle,
973
+ this.last
974
+ ];
975
+ }
976
+ async invoke(input, options) {
977
+ const config = require_config.ensureConfig(options);
978
+ const callbackManager_ = await require_config.getCallbackManagerForConfig(config);
979
+ const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), config.runId, void 0, void 0, void 0, config?.runName);
980
+ delete config.runId;
981
+ let nextStepInput = input;
982
+ let finalOutput;
983
+ try {
984
+ const initialSteps = [this.first, ...this.middle];
985
+ for (let i = 0; i < initialSteps.length; i += 1) {
986
+ const step = initialSteps[i];
987
+ const promise = step.invoke(nextStepInput, require_config.patchConfig(config, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`) }));
988
+ nextStepInput = await require_signal.raceWithSignal(promise, options?.signal);
989
+ }
990
+ if (options?.signal?.aborted) throw require_signal.getAbortSignalError(options.signal);
991
+ finalOutput = await this.last.invoke(nextStepInput, require_config.patchConfig(config, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${this.steps.length}`) }));
992
+ } catch (e) {
993
+ await runManager?.handleChainError(e);
994
+ throw e;
995
+ }
996
+ await runManager?.handleChainEnd(_coerceToDict(finalOutput, "output"));
997
+ return finalOutput;
998
+ }
999
+ async batch(inputs, options, batchOptions) {
1000
+ const configList = this._getOptionsList(options ?? {}, inputs.length);
1001
+ const callbackManagers = await Promise.all(configList.map(require_config.getCallbackManagerForConfig));
1002
+ const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => {
1003
+ const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), configList[i].runId, void 0, void 0, void 0, configList[i].runName);
1004
+ delete configList[i].runId;
1005
+ return handleStartRes;
1006
+ }));
1007
+ let nextStepInputs = inputs;
1008
+ try {
1009
+ for (let i = 0; i < this.steps.length; i += 1) {
1010
+ const step = this.steps[i];
1011
+ const promise = step.batch(nextStepInputs, runManagers.map((runManager, j) => {
1012
+ const childRunManager = runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`);
1013
+ return require_config.patchConfig(configList[j], { callbacks: childRunManager });
1014
+ }), batchOptions);
1015
+ nextStepInputs = await require_signal.raceWithSignal(promise, configList[0]?.signal);
1016
+ }
1017
+ } catch (e) {
1018
+ await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e)));
1019
+ throw e;
1020
+ }
1021
+ await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict(nextStepInputs, "output"))));
1022
+ return nextStepInputs;
1023
+ }
1024
+ async *_streamIterator(input, options) {
1025
+ const callbackManager_ = await require_config.getCallbackManagerForConfig(options);
1026
+ const { runId,...otherOptions } = options ?? {};
1027
+ const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, void 0, void 0, void 0, otherOptions?.runName);
1028
+ const steps = [
1029
+ this.first,
1030
+ ...this.middle,
1031
+ this.last
1032
+ ];
1033
+ let concatSupported = true;
1034
+ let finalOutput;
1035
+ async function* inputGenerator() {
1036
+ yield input;
1037
+ }
1038
+ try {
1039
+ let finalGenerator = steps[0].transform(inputGenerator(), require_config.patchConfig(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:1`) }));
1040
+ for (let i = 1; i < steps.length; i += 1) {
1041
+ const step = steps[i];
1042
+ finalGenerator = await step.transform(finalGenerator, require_config.patchConfig(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`) }));
1043
+ }
1044
+ for await (const chunk of finalGenerator) {
1045
+ options?.signal?.throwIfAborted();
1046
+ yield chunk;
1047
+ if (concatSupported) if (finalOutput === void 0) finalOutput = chunk;
1048
+ else try {
1049
+ finalOutput = require_utils_stream.concat(finalOutput, chunk);
1050
+ } catch (e) {
1051
+ finalOutput = void 0;
1052
+ concatSupported = false;
1053
+ }
1054
+ }
1055
+ } catch (e) {
1056
+ await runManager?.handleChainError(e);
1057
+ throw e;
1058
+ }
1059
+ await runManager?.handleChainEnd(_coerceToDict(finalOutput, "output"));
1060
+ }
1061
+ getGraph(config) {
1062
+ const graph = new require_runnables_graph.Graph();
1063
+ let currentLastNode = null;
1064
+ this.steps.forEach((step, index) => {
1065
+ const stepGraph = step.getGraph(config);
1066
+ if (index !== 0) stepGraph.trimFirstNode();
1067
+ if (index !== this.steps.length - 1) stepGraph.trimLastNode();
1068
+ graph.extend(stepGraph);
1069
+ const stepFirstNode = stepGraph.firstNode();
1070
+ if (!stepFirstNode) throw new Error(`Runnable ${step} has no first node`);
1071
+ if (currentLastNode) graph.addEdge(currentLastNode, stepFirstNode);
1072
+ currentLastNode = stepGraph.lastNode();
1073
+ });
1074
+ return graph;
1075
+ }
1076
+ pipe(coerceable) {
1077
+ if (RunnableSequence.isRunnableSequence(coerceable)) return new RunnableSequence({
1078
+ first: this.first,
1079
+ middle: this.middle.concat([
1080
+ this.last,
1081
+ coerceable.first,
1082
+ ...coerceable.middle
1083
+ ]),
1084
+ last: coerceable.last,
1085
+ name: this.name ?? coerceable.name
1086
+ });
1087
+ else return new RunnableSequence({
1088
+ first: this.first,
1089
+ middle: [...this.middle, this.last],
1090
+ last: _coerceToRunnable(coerceable),
1091
+ name: this.name
1092
+ });
1093
+ }
1094
+ static isRunnableSequence(thing) {
1095
+ return Array.isArray(thing.middle) && Runnable.isRunnable(thing);
1096
+ }
1097
+ static from([first, ...runnables], nameOrFields) {
1098
+ let extra = {};
1099
+ if (typeof nameOrFields === "string") extra.name = nameOrFields;
1100
+ else if (nameOrFields !== void 0) extra = nameOrFields;
1101
+ return new RunnableSequence({
1102
+ ...extra,
1103
+ first: _coerceToRunnable(first),
1104
+ middle: runnables.slice(0, -1).map(_coerceToRunnable),
1105
+ last: _coerceToRunnable(runnables[runnables.length - 1])
1106
+ });
1107
+ }
1108
+ };
1483
1109
  /**
1484
- * A runnable that runs a mapping of runnables in parallel,
1485
- * and returns a mapping of their outputs.
1486
- * @example
1487
- * ```typescript
1488
- * const mapChain = RunnableMap.from({
1489
- * joke: PromptTemplate.fromTemplate("Tell me a joke about {topic}").pipe(
1490
- * new ChatAnthropic({}),
1491
- * ),
1492
- * poem: PromptTemplate.fromTemplate("write a 2-line poem about {topic}").pipe(
1493
- * new ChatAnthropic({}),
1494
- * ),
1495
- * });
1496
- * const result = await mapChain.invoke({ topic: "bear" });
1497
- * ```
1498
- */
1499
- class RunnableMap extends Runnable {
1500
- static lc_name() {
1501
- return "RunnableMap";
1502
- }
1503
- getStepsKeys() {
1504
- return Object.keys(this.steps);
1505
- }
1506
- constructor(fields) {
1507
- super(fields);
1508
- Object.defineProperty(this, "lc_namespace", {
1509
- enumerable: true,
1510
- configurable: true,
1511
- writable: true,
1512
- value: ["langchain_core", "runnables"]
1513
- });
1514
- Object.defineProperty(this, "lc_serializable", {
1515
- enumerable: true,
1516
- configurable: true,
1517
- writable: true,
1518
- value: true
1519
- });
1520
- Object.defineProperty(this, "steps", {
1521
- enumerable: true,
1522
- configurable: true,
1523
- writable: true,
1524
- value: void 0
1525
- });
1526
- this.steps = {};
1527
- for (const [key, value] of Object.entries(fields.steps)) {
1528
- this.steps[key] = _coerceToRunnable(value);
1529
- }
1530
- }
1531
- static from(steps) {
1532
- return new RunnableMap({ steps });
1533
- }
1534
- async invoke(input, options) {
1535
- const config = (0, config_js_1.ensureConfig)(options);
1536
- const callbackManager_ = await (0, config_js_1.getCallbackManagerForConfig)(config);
1537
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), {
1538
- input,
1539
- }, config.runId, undefined, undefined, undefined, config?.runName);
1540
- delete config.runId;
1541
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1542
- const output = {};
1543
- try {
1544
- const promises = Object.entries(this.steps).map(async ([key, runnable]) => {
1545
- output[key] = await runnable.invoke(input, (0, config_js_1.patchConfig)(config, {
1546
- callbacks: runManager?.getChild(`map:key:${key}`),
1547
- }));
1548
- });
1549
- await (0, signal_js_1.raceWithSignal)(Promise.all(promises), options?.signal);
1550
- }
1551
- catch (e) {
1552
- await runManager?.handleChainError(e);
1553
- throw e;
1554
- }
1555
- await runManager?.handleChainEnd(output);
1556
- return output;
1557
- }
1558
- async *_transform(generator, runManager, options) {
1559
- // shallow copy steps to ignore changes while iterating
1560
- const steps = { ...this.steps };
1561
- // each step gets a copy of the input iterator
1562
- const inputCopies = (0, stream_js_1.atee)(generator, Object.keys(steps).length);
1563
- // start the first iteration of each output iterator
1564
- const tasks = new Map(Object.entries(steps).map(([key, runnable], i) => {
1565
- const gen = runnable.transform(inputCopies[i], (0, config_js_1.patchConfig)(options, {
1566
- callbacks: runManager?.getChild(`map:key:${key}`),
1567
- }));
1568
- return [key, gen.next().then((result) => ({ key, gen, result }))];
1569
- }));
1570
- // yield chunks as they become available,
1571
- // starting new iterations as needed,
1572
- // until all iterators are done
1573
- while (tasks.size) {
1574
- const promise = Promise.race(tasks.values());
1575
- const { key, result, gen } = await (0, signal_js_1.raceWithSignal)(promise, options?.signal);
1576
- tasks.delete(key);
1577
- if (!result.done) {
1578
- yield { [key]: result.value };
1579
- tasks.set(key, gen.next().then((result) => ({ key, gen, result })));
1580
- }
1581
- }
1582
- }
1583
- transform(generator, options) {
1584
- return this._transformStreamWithConfig(generator, this._transform.bind(this), options);
1585
- }
1586
- async stream(input, options) {
1587
- async function* generator() {
1588
- yield input;
1589
- }
1590
- const config = (0, config_js_1.ensureConfig)(options);
1591
- const wrappedGenerator = new stream_js_1.AsyncGeneratorWithSetup({
1592
- generator: this.transform(generator(), config),
1593
- config,
1594
- });
1595
- await wrappedGenerator.setup;
1596
- return stream_js_1.IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
1597
- }
1598
- }
1599
- exports.RunnableMap = RunnableMap;
1110
+ * A runnable that runs a mapping of runnables in parallel,
1111
+ * and returns a mapping of their outputs.
1112
+ * @example
1113
+ * ```typescript
1114
+ * const mapChain = RunnableMap.from({
1115
+ * joke: PromptTemplate.fromTemplate("Tell me a joke about {topic}").pipe(
1116
+ * new ChatAnthropic({}),
1117
+ * ),
1118
+ * poem: PromptTemplate.fromTemplate("write a 2-line poem about {topic}").pipe(
1119
+ * new ChatAnthropic({}),
1120
+ * ),
1121
+ * });
1122
+ * const result = await mapChain.invoke({ topic: "bear" });
1123
+ * ```
1124
+ */
1125
+ var RunnableMap = class RunnableMap extends Runnable {
1126
+ static lc_name() {
1127
+ return "RunnableMap";
1128
+ }
1129
+ lc_namespace = ["langchain_core", "runnables"];
1130
+ lc_serializable = true;
1131
+ steps;
1132
+ getStepsKeys() {
1133
+ return Object.keys(this.steps);
1134
+ }
1135
+ constructor(fields) {
1136
+ super(fields);
1137
+ this.steps = {};
1138
+ for (const [key, value] of Object.entries(fields.steps)) this.steps[key] = _coerceToRunnable(value);
1139
+ }
1140
+ static from(steps) {
1141
+ return new RunnableMap({ steps });
1142
+ }
1143
+ async invoke(input, options) {
1144
+ const config = require_config.ensureConfig(options);
1145
+ const callbackManager_ = await require_config.getCallbackManagerForConfig(config);
1146
+ const runManager = await callbackManager_?.handleChainStart(this.toJSON(), { input }, config.runId, void 0, void 0, void 0, config?.runName);
1147
+ delete config.runId;
1148
+ const output = {};
1149
+ try {
1150
+ const promises = Object.entries(this.steps).map(async ([key, runnable]) => {
1151
+ output[key] = await runnable.invoke(input, require_config.patchConfig(config, { callbacks: runManager?.getChild(`map:key:${key}`) }));
1152
+ });
1153
+ await require_signal.raceWithSignal(Promise.all(promises), options?.signal);
1154
+ } catch (e) {
1155
+ await runManager?.handleChainError(e);
1156
+ throw e;
1157
+ }
1158
+ await runManager?.handleChainEnd(output);
1159
+ return output;
1160
+ }
1161
+ async *_transform(generator, runManager, options) {
1162
+ const steps = { ...this.steps };
1163
+ const inputCopies = require_utils_stream.atee(generator, Object.keys(steps).length);
1164
+ const tasks = new Map(Object.entries(steps).map(([key, runnable], i) => {
1165
+ const gen = runnable.transform(inputCopies[i], require_config.patchConfig(options, { callbacks: runManager?.getChild(`map:key:${key}`) }));
1166
+ return [key, gen.next().then((result) => ({
1167
+ key,
1168
+ gen,
1169
+ result
1170
+ }))];
1171
+ }));
1172
+ while (tasks.size) {
1173
+ const promise = Promise.race(tasks.values());
1174
+ const { key, result, gen } = await require_signal.raceWithSignal(promise, options?.signal);
1175
+ tasks.delete(key);
1176
+ if (!result.done) {
1177
+ yield { [key]: result.value };
1178
+ tasks.set(key, gen.next().then((result$1) => ({
1179
+ key,
1180
+ gen,
1181
+ result: result$1
1182
+ })));
1183
+ }
1184
+ }
1185
+ }
1186
+ transform(generator, options) {
1187
+ return this._transformStreamWithConfig(generator, this._transform.bind(this), options);
1188
+ }
1189
+ async stream(input, options) {
1190
+ async function* generator() {
1191
+ yield input;
1192
+ }
1193
+ const config = require_config.ensureConfig(options);
1194
+ const wrappedGenerator = new require_utils_stream.AsyncGeneratorWithSetup({
1195
+ generator: this.transform(generator(), config),
1196
+ config
1197
+ });
1198
+ await wrappedGenerator.setup;
1199
+ return require_utils_stream.IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
1200
+ }
1201
+ };
1600
1202
  /**
1601
- * A runnable that wraps a traced LangSmith function.
1602
- */
1603
- class RunnableTraceable extends Runnable {
1604
- constructor(fields) {
1605
- super(fields);
1606
- Object.defineProperty(this, "lc_serializable", {
1607
- enumerable: true,
1608
- configurable: true,
1609
- writable: true,
1610
- value: false
1611
- });
1612
- Object.defineProperty(this, "lc_namespace", {
1613
- enumerable: true,
1614
- configurable: true,
1615
- writable: true,
1616
- value: ["langchain_core", "runnables"]
1617
- });
1618
- Object.defineProperty(this, "func", {
1619
- enumerable: true,
1620
- configurable: true,
1621
- writable: true,
1622
- value: void 0
1623
- });
1624
- if (!(0, traceable_1.isTraceableFunction)(fields.func)) {
1625
- throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");
1626
- }
1627
- this.func = fields.func;
1628
- }
1629
- async invoke(input, options) {
1630
- const [config] = this._getOptionsList(options ?? {}, 1);
1631
- const callbacks = await (0, config_js_1.getCallbackManagerForConfig)(config);
1632
- const promise = this.func((0, config_js_1.patchConfig)(config, { callbacks }), input);
1633
- return (0, signal_js_1.raceWithSignal)(promise, config?.signal);
1634
- }
1635
- async *_streamIterator(input, options) {
1636
- const [config] = this._getOptionsList(options ?? {}, 1);
1637
- const result = await this.invoke(input, options);
1638
- if ((0, iter_js_1.isAsyncIterable)(result)) {
1639
- for await (const item of result) {
1640
- config?.signal?.throwIfAborted();
1641
- yield item;
1642
- }
1643
- return;
1644
- }
1645
- if ((0, iter_js_1.isIterator)(result)) {
1646
- while (true) {
1647
- config?.signal?.throwIfAborted();
1648
- const state = result.next();
1649
- if (state.done)
1650
- break;
1651
- yield state.value;
1652
- }
1653
- return;
1654
- }
1655
- yield result;
1656
- }
1657
- static from(func) {
1658
- return new RunnableTraceable({ func });
1659
- }
1660
- }
1661
- exports.RunnableTraceable = RunnableTraceable;
1203
+ * A runnable that wraps a traced LangSmith function.
1204
+ */
1205
+ var RunnableTraceable = class RunnableTraceable extends Runnable {
1206
+ lc_serializable = false;
1207
+ lc_namespace = ["langchain_core", "runnables"];
1208
+ func;
1209
+ constructor(fields) {
1210
+ super(fields);
1211
+ if (!(0, langsmith_singletons_traceable.isTraceableFunction)(fields.func)) throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");
1212
+ this.func = fields.func;
1213
+ }
1214
+ async invoke(input, options) {
1215
+ const [config] = this._getOptionsList(options ?? {}, 1);
1216
+ const callbacks = await require_config.getCallbackManagerForConfig(config);
1217
+ const promise = this.func(require_config.patchConfig(config, { callbacks }), input);
1218
+ return require_signal.raceWithSignal(promise, config?.signal);
1219
+ }
1220
+ async *_streamIterator(input, options) {
1221
+ const [config] = this._getOptionsList(options ?? {}, 1);
1222
+ const result = await this.invoke(input, options);
1223
+ if (require_iter.isAsyncIterable(result)) {
1224
+ for await (const item of result) {
1225
+ config?.signal?.throwIfAborted();
1226
+ yield item;
1227
+ }
1228
+ return;
1229
+ }
1230
+ if (require_iter.isIterator(result)) {
1231
+ while (true) {
1232
+ config?.signal?.throwIfAborted();
1233
+ const state = result.next();
1234
+ if (state.done) break;
1235
+ yield state.value;
1236
+ }
1237
+ return;
1238
+ }
1239
+ yield result;
1240
+ }
1241
+ static from(func) {
1242
+ return new RunnableTraceable({ func });
1243
+ }
1244
+ };
1662
1245
  function assertNonTraceableFunction(func) {
1663
- if ((0, traceable_1.isTraceableFunction)(func)) {
1664
- throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.");
1665
- }
1246
+ if ((0, langsmith_singletons_traceable.isTraceableFunction)(func)) throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.");
1666
1247
  }
1667
1248
  /**
1668
- * A runnable that wraps an arbitrary function that takes a single argument.
1669
- * @example
1670
- * ```typescript
1671
- * import { RunnableLambda } from "@langchain/core/runnables";
1672
- *
1673
- * const add = (input: { x: number; y: number }) => input.x + input.y;
1674
- *
1675
- * const multiply = (input: { value: number; multiplier: number }) =>
1676
- * input.value * input.multiplier;
1677
- *
1678
- * // Create runnables for the functions
1679
- * const addLambda = RunnableLambda.from(add);
1680
- * const multiplyLambda = RunnableLambda.from(multiply);
1681
- *
1682
- * // Chain the lambdas for a mathematical operation
1683
- * const chainedLambda = addLambda.pipe((result) =>
1684
- * multiplyLambda.invoke({ value: result, multiplier: 2 })
1685
- * );
1686
- *
1687
- * // Example invocation of the chainedLambda
1688
- * const result = await chainedLambda.invoke({ x: 2, y: 3 });
1689
- *
1690
- * // Will log "10" (since (2 + 3) * 2 = 10)
1691
- * ```
1692
- */
1693
- class RunnableLambda extends Runnable {
1694
- static lc_name() {
1695
- return "RunnableLambda";
1696
- }
1697
- constructor(fields) {
1698
- if ((0, traceable_1.isTraceableFunction)(fields.func)) {
1699
- // eslint-disable-next-line no-constructor-return
1700
- return RunnableTraceable.from(fields.func);
1701
- }
1702
- super(fields);
1703
- Object.defineProperty(this, "lc_namespace", {
1704
- enumerable: true,
1705
- configurable: true,
1706
- writable: true,
1707
- value: ["langchain_core", "runnables"]
1708
- });
1709
- Object.defineProperty(this, "func", {
1710
- enumerable: true,
1711
- configurable: true,
1712
- writable: true,
1713
- value: void 0
1714
- });
1715
- assertNonTraceableFunction(fields.func);
1716
- this.func = fields.func;
1717
- }
1718
- static from(func) {
1719
- return new RunnableLambda({
1720
- func,
1721
- });
1722
- }
1723
- async _invoke(input, config, runManager) {
1724
- return new Promise((resolve, reject) => {
1725
- const childConfig = (0, config_js_1.patchConfig)(config, {
1726
- callbacks: runManager?.getChild(),
1727
- recursionLimit: (config?.recursionLimit ?? config_js_1.DEFAULT_RECURSION_LIMIT) - 1,
1728
- });
1729
- void index_js_1.AsyncLocalStorageProviderSingleton.runWithConfig((0, config_js_1.pickRunnableConfigKeys)(childConfig), async () => {
1730
- try {
1731
- let output = await this.func(input, {
1732
- ...childConfig,
1733
- });
1734
- if (output && Runnable.isRunnable(output)) {
1735
- if (config?.recursionLimit === 0) {
1736
- throw new Error("Recursion limit reached.");
1737
- }
1738
- output = await output.invoke(input, {
1739
- ...childConfig,
1740
- recursionLimit: (childConfig.recursionLimit ?? config_js_1.DEFAULT_RECURSION_LIMIT) - 1,
1741
- });
1742
- }
1743
- else if ((0, iter_js_1.isAsyncIterable)(output)) {
1744
- let finalOutput;
1745
- for await (const chunk of (0, iter_js_1.consumeAsyncIterableInContext)(childConfig, output)) {
1746
- config?.signal?.throwIfAborted();
1747
- if (finalOutput === undefined) {
1748
- finalOutput = chunk;
1749
- }
1750
- else {
1751
- // Make a best effort to gather, for any type that supports concat.
1752
- try {
1753
- finalOutput = this._concatOutputChunks(finalOutput,
1754
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1755
- chunk);
1756
- }
1757
- catch (e) {
1758
- finalOutput = chunk;
1759
- }
1760
- }
1761
- }
1762
- output = finalOutput;
1763
- }
1764
- else if ((0, iter_js_1.isIterableIterator)(output)) {
1765
- let finalOutput;
1766
- for (const chunk of (0, iter_js_1.consumeIteratorInContext)(childConfig, output)) {
1767
- config?.signal?.throwIfAborted();
1768
- if (finalOutput === undefined) {
1769
- finalOutput = chunk;
1770
- }
1771
- else {
1772
- // Make a best effort to gather, for any type that supports concat.
1773
- try {
1774
- finalOutput = this._concatOutputChunks(finalOutput,
1775
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1776
- chunk);
1777
- }
1778
- catch (e) {
1779
- finalOutput = chunk;
1780
- }
1781
- }
1782
- }
1783
- output = finalOutput;
1784
- }
1785
- resolve(output);
1786
- }
1787
- catch (e) {
1788
- reject(e);
1789
- }
1790
- });
1791
- });
1792
- }
1793
- async invoke(input, options) {
1794
- return this._callWithConfig(this._invoke.bind(this), input, options);
1795
- }
1796
- async *_transform(generator, runManager, config) {
1797
- let finalChunk;
1798
- for await (const chunk of generator) {
1799
- if (finalChunk === undefined) {
1800
- finalChunk = chunk;
1801
- }
1802
- else {
1803
- // Make a best effort to gather, for any type that supports concat.
1804
- try {
1805
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1806
- finalChunk = this._concatOutputChunks(finalChunk, chunk);
1807
- }
1808
- catch (e) {
1809
- finalChunk = chunk;
1810
- }
1811
- }
1812
- }
1813
- const childConfig = (0, config_js_1.patchConfig)(config, {
1814
- callbacks: runManager?.getChild(),
1815
- recursionLimit: (config?.recursionLimit ?? config_js_1.DEFAULT_RECURSION_LIMIT) - 1,
1816
- });
1817
- const output = await new Promise((resolve, reject) => {
1818
- void index_js_1.AsyncLocalStorageProviderSingleton.runWithConfig((0, config_js_1.pickRunnableConfigKeys)(childConfig), async () => {
1819
- try {
1820
- const res = await this.func(finalChunk, {
1821
- ...childConfig,
1822
- config: childConfig,
1823
- });
1824
- resolve(res);
1825
- }
1826
- catch (e) {
1827
- reject(e);
1828
- }
1829
- });
1830
- });
1831
- if (output && Runnable.isRunnable(output)) {
1832
- if (config?.recursionLimit === 0) {
1833
- throw new Error("Recursion limit reached.");
1834
- }
1835
- const stream = await output.stream(finalChunk, childConfig);
1836
- for await (const chunk of stream) {
1837
- yield chunk;
1838
- }
1839
- }
1840
- else if ((0, iter_js_1.isAsyncIterable)(output)) {
1841
- for await (const chunk of (0, iter_js_1.consumeAsyncIterableInContext)(childConfig, output)) {
1842
- config?.signal?.throwIfAborted();
1843
- yield chunk;
1844
- }
1845
- }
1846
- else if ((0, iter_js_1.isIterableIterator)(output)) {
1847
- for (const chunk of (0, iter_js_1.consumeIteratorInContext)(childConfig, output)) {
1848
- config?.signal?.throwIfAborted();
1849
- yield chunk;
1850
- }
1851
- }
1852
- else {
1853
- yield output;
1854
- }
1855
- }
1856
- transform(generator, options) {
1857
- return this._transformStreamWithConfig(generator, this._transform.bind(this), options);
1858
- }
1859
- async stream(input, options) {
1860
- async function* generator() {
1861
- yield input;
1862
- }
1863
- const config = (0, config_js_1.ensureConfig)(options);
1864
- const wrappedGenerator = new stream_js_1.AsyncGeneratorWithSetup({
1865
- generator: this.transform(generator(), config),
1866
- config,
1867
- });
1868
- await wrappedGenerator.setup;
1869
- return stream_js_1.IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
1870
- }
1871
- }
1872
- exports.RunnableLambda = RunnableLambda;
1249
+ * A runnable that wraps an arbitrary function that takes a single argument.
1250
+ * @example
1251
+ * ```typescript
1252
+ * import { RunnableLambda } from "@langchain/core/runnables";
1253
+ *
1254
+ * const add = (input: { x: number; y: number }) => input.x + input.y;
1255
+ *
1256
+ * const multiply = (input: { value: number; multiplier: number }) =>
1257
+ * input.value * input.multiplier;
1258
+ *
1259
+ * // Create runnables for the functions
1260
+ * const addLambda = RunnableLambda.from(add);
1261
+ * const multiplyLambda = RunnableLambda.from(multiply);
1262
+ *
1263
+ * // Chain the lambdas for a mathematical operation
1264
+ * const chainedLambda = addLambda.pipe((result) =>
1265
+ * multiplyLambda.invoke({ value: result, multiplier: 2 })
1266
+ * );
1267
+ *
1268
+ * // Example invocation of the chainedLambda
1269
+ * const result = await chainedLambda.invoke({ x: 2, y: 3 });
1270
+ *
1271
+ * // Will log "10" (since (2 + 3) * 2 = 10)
1272
+ * ```
1273
+ */
1274
+ var RunnableLambda = class RunnableLambda extends Runnable {
1275
+ static lc_name() {
1276
+ return "RunnableLambda";
1277
+ }
1278
+ lc_namespace = ["langchain_core", "runnables"];
1279
+ func;
1280
+ constructor(fields) {
1281
+ if ((0, langsmith_singletons_traceable.isTraceableFunction)(fields.func)) return RunnableTraceable.from(fields.func);
1282
+ super(fields);
1283
+ assertNonTraceableFunction(fields.func);
1284
+ this.func = fields.func;
1285
+ }
1286
+ static from(func) {
1287
+ return new RunnableLambda({ func });
1288
+ }
1289
+ async _invoke(input, config, runManager) {
1290
+ return new Promise((resolve, reject) => {
1291
+ const childConfig = require_config.patchConfig(config, {
1292
+ callbacks: runManager?.getChild(),
1293
+ recursionLimit: (config?.recursionLimit ?? require_config.DEFAULT_RECURSION_LIMIT) - 1
1294
+ });
1295
+ require_index.AsyncLocalStorageProviderSingleton.runWithConfig(require_config.pickRunnableConfigKeys(childConfig), async () => {
1296
+ try {
1297
+ let output = await this.func(input, { ...childConfig });
1298
+ if (output && Runnable.isRunnable(output)) {
1299
+ if (config?.recursionLimit === 0) throw new Error("Recursion limit reached.");
1300
+ output = await output.invoke(input, {
1301
+ ...childConfig,
1302
+ recursionLimit: (childConfig.recursionLimit ?? require_config.DEFAULT_RECURSION_LIMIT) - 1
1303
+ });
1304
+ } else if (require_iter.isAsyncIterable(output)) {
1305
+ let finalOutput;
1306
+ for await (const chunk of require_iter.consumeAsyncIterableInContext(childConfig, output)) {
1307
+ config?.signal?.throwIfAborted();
1308
+ if (finalOutput === void 0) finalOutput = chunk;
1309
+ else try {
1310
+ finalOutput = require_utils_stream.concat(finalOutput, chunk);
1311
+ } catch (e) {
1312
+ finalOutput = chunk;
1313
+ }
1314
+ }
1315
+ output = finalOutput;
1316
+ } else if (require_iter.isIterableIterator(output)) {
1317
+ let finalOutput;
1318
+ for (const chunk of require_iter.consumeIteratorInContext(childConfig, output)) {
1319
+ config?.signal?.throwIfAborted();
1320
+ if (finalOutput === void 0) finalOutput = chunk;
1321
+ else try {
1322
+ finalOutput = require_utils_stream.concat(finalOutput, chunk);
1323
+ } catch (e) {
1324
+ finalOutput = chunk;
1325
+ }
1326
+ }
1327
+ output = finalOutput;
1328
+ }
1329
+ resolve(output);
1330
+ } catch (e) {
1331
+ reject(e);
1332
+ }
1333
+ });
1334
+ });
1335
+ }
1336
+ async invoke(input, options) {
1337
+ return this._callWithConfig(this._invoke.bind(this), input, options);
1338
+ }
1339
+ async *_transform(generator, runManager, config) {
1340
+ let finalChunk;
1341
+ for await (const chunk of generator) if (finalChunk === void 0) finalChunk = chunk;
1342
+ else try {
1343
+ finalChunk = require_utils_stream.concat(finalChunk, chunk);
1344
+ } catch (e) {
1345
+ finalChunk = chunk;
1346
+ }
1347
+ const childConfig = require_config.patchConfig(config, {
1348
+ callbacks: runManager?.getChild(),
1349
+ recursionLimit: (config?.recursionLimit ?? require_config.DEFAULT_RECURSION_LIMIT) - 1
1350
+ });
1351
+ const output = await new Promise((resolve, reject) => {
1352
+ require_index.AsyncLocalStorageProviderSingleton.runWithConfig(require_config.pickRunnableConfigKeys(childConfig), async () => {
1353
+ try {
1354
+ const res = await this.func(finalChunk, {
1355
+ ...childConfig,
1356
+ config: childConfig
1357
+ });
1358
+ resolve(res);
1359
+ } catch (e) {
1360
+ reject(e);
1361
+ }
1362
+ });
1363
+ });
1364
+ if (output && Runnable.isRunnable(output)) {
1365
+ if (config?.recursionLimit === 0) throw new Error("Recursion limit reached.");
1366
+ const stream = await output.stream(finalChunk, childConfig);
1367
+ for await (const chunk of stream) yield chunk;
1368
+ } else if (require_iter.isAsyncIterable(output)) for await (const chunk of require_iter.consumeAsyncIterableInContext(childConfig, output)) {
1369
+ config?.signal?.throwIfAborted();
1370
+ yield chunk;
1371
+ }
1372
+ else if (require_iter.isIterableIterator(output)) for (const chunk of require_iter.consumeIteratorInContext(childConfig, output)) {
1373
+ config?.signal?.throwIfAborted();
1374
+ yield chunk;
1375
+ }
1376
+ else yield output;
1377
+ }
1378
+ transform(generator, options) {
1379
+ return this._transformStreamWithConfig(generator, this._transform.bind(this), options);
1380
+ }
1381
+ async stream(input, options) {
1382
+ async function* generator() {
1383
+ yield input;
1384
+ }
1385
+ const config = require_config.ensureConfig(options);
1386
+ const wrappedGenerator = new require_utils_stream.AsyncGeneratorWithSetup({
1387
+ generator: this.transform(generator(), config),
1388
+ config
1389
+ });
1390
+ await wrappedGenerator.setup;
1391
+ return require_utils_stream.IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
1392
+ }
1393
+ };
1873
1394
  /**
1874
- * A runnable that runs a mapping of runnables in parallel,
1875
- * and returns a mapping of their outputs.
1876
- * @example
1877
- * ```typescript
1878
- * import {
1879
- * RunnableLambda,
1880
- * RunnableParallel,
1881
- * } from "@langchain/core/runnables";
1882
- *
1883
- * const addYears = (age: number): number => age + 5;
1884
- * const yearsToFifty = (age: number): number => 50 - age;
1885
- * const yearsToHundred = (age: number): number => 100 - age;
1886
- *
1887
- * const addYearsLambda = RunnableLambda.from(addYears);
1888
- * const milestoneFiftyLambda = RunnableLambda.from(yearsToFifty);
1889
- * const milestoneHundredLambda = RunnableLambda.from(yearsToHundred);
1890
- *
1891
- * // Pipe will coerce objects into RunnableParallel by default, but we
1892
- * // explicitly instantiate one here to demonstrate
1893
- * const sequence = addYearsLambda.pipe(
1894
- * RunnableParallel.from({
1895
- * years_to_fifty: milestoneFiftyLambda,
1896
- * years_to_hundred: milestoneHundredLambda,
1897
- * })
1898
- * );
1899
- *
1900
- * // Invoke the sequence with a single age input
1901
- * const res = await sequence.invoke(25);
1902
- *
1903
- * // { years_to_fifty: 20, years_to_hundred: 70 }
1904
- * ```
1905
- */
1906
- class RunnableParallel extends RunnableMap {
1907
- }
1908
- exports.RunnableParallel = RunnableParallel;
1395
+ * A runnable that runs a mapping of runnables in parallel,
1396
+ * and returns a mapping of their outputs.
1397
+ * @example
1398
+ * ```typescript
1399
+ * import {
1400
+ * RunnableLambda,
1401
+ * RunnableParallel,
1402
+ * } from "@langchain/core/runnables";
1403
+ *
1404
+ * const addYears = (age: number): number => age + 5;
1405
+ * const yearsToFifty = (age: number): number => 50 - age;
1406
+ * const yearsToHundred = (age: number): number => 100 - age;
1407
+ *
1408
+ * const addYearsLambda = RunnableLambda.from(addYears);
1409
+ * const milestoneFiftyLambda = RunnableLambda.from(yearsToFifty);
1410
+ * const milestoneHundredLambda = RunnableLambda.from(yearsToHundred);
1411
+ *
1412
+ * // Pipe will coerce objects into RunnableParallel by default, but we
1413
+ * // explicitly instantiate one here to demonstrate
1414
+ * const sequence = addYearsLambda.pipe(
1415
+ * RunnableParallel.from({
1416
+ * years_to_fifty: milestoneFiftyLambda,
1417
+ * years_to_hundred: milestoneHundredLambda,
1418
+ * })
1419
+ * );
1420
+ *
1421
+ * // Invoke the sequence with a single age input
1422
+ * const res = await sequence.invoke(25);
1423
+ *
1424
+ * // { years_to_fifty: 20, years_to_hundred: 70 }
1425
+ * ```
1426
+ */
1427
+ var RunnableParallel = class extends RunnableMap {};
1909
1428
  /**
1910
- * A Runnable that can fallback to other Runnables if it fails.
1911
- * External APIs (e.g., APIs for a language model) may at times experience
1912
- * degraded performance or even downtime.
1913
- *
1914
- * In these cases, it can be useful to have a fallback Runnable that can be
1915
- * used in place of the original Runnable (e.g., fallback to another LLM provider).
1916
- *
1917
- * Fallbacks can be defined at the level of a single Runnable, or at the level
1918
- * of a chain of Runnables. Fallbacks are tried in order until one succeeds or
1919
- * all fail.
1920
- *
1921
- * While you can instantiate a `RunnableWithFallbacks` directly, it is usually
1922
- * more convenient to use the `withFallbacks` method on an existing Runnable.
1923
- *
1924
- * When streaming, fallbacks will only be called on failures during the initial
1925
- * stream creation. Errors that occur after a stream starts will not fallback
1926
- * to the next Runnable.
1927
- *
1928
- * @example
1929
- * ```typescript
1930
- * import {
1931
- * RunnableLambda,
1932
- * RunnableWithFallbacks,
1933
- * } from "@langchain/core/runnables";
1934
- *
1935
- * const primaryOperation = (input: string): string => {
1936
- * if (input !== "safe") {
1937
- * throw new Error("Primary operation failed due to unsafe input");
1938
- * }
1939
- * return `Processed: ${input}`;
1940
- * };
1941
- *
1942
- * // Define a fallback operation that processes the input differently
1943
- * const fallbackOperation = (input: string): string =>
1944
- * `Fallback processed: ${input}`;
1945
- *
1946
- * const primaryRunnable = RunnableLambda.from(primaryOperation);
1947
- * const fallbackRunnable = RunnableLambda.from(fallbackOperation);
1948
- *
1949
- * // Apply the fallback logic using the .withFallbacks() method
1950
- * const runnableWithFallback = primaryRunnable.withFallbacks([fallbackRunnable]);
1951
- *
1952
- * // Alternatively, create a RunnableWithFallbacks instance manually
1953
- * const manualFallbackChain = new RunnableWithFallbacks({
1954
- * runnable: primaryRunnable,
1955
- * fallbacks: [fallbackRunnable],
1956
- * });
1957
- *
1958
- * // Example invocation using .withFallbacks()
1959
- * const res = await runnableWithFallback
1960
- * .invoke("unsafe input")
1961
- * .catch((error) => {
1962
- * console.error("Failed after all attempts:", error.message);
1963
- * });
1964
- *
1965
- * // "Fallback processed: unsafe input"
1966
- *
1967
- * // Example invocation using manual instantiation
1968
- * const res = await manualFallbackChain
1969
- * .invoke("safe")
1970
- * .catch((error) => {
1971
- * console.error("Failed after all attempts:", error.message);
1972
- * });
1973
- *
1974
- * // "Processed: safe"
1975
- * ```
1976
- */
1977
- class RunnableWithFallbacks extends Runnable {
1978
- static lc_name() {
1979
- return "RunnableWithFallbacks";
1980
- }
1981
- constructor(fields) {
1982
- super(fields);
1983
- Object.defineProperty(this, "lc_namespace", {
1984
- enumerable: true,
1985
- configurable: true,
1986
- writable: true,
1987
- value: ["langchain_core", "runnables"]
1988
- });
1989
- Object.defineProperty(this, "lc_serializable", {
1990
- enumerable: true,
1991
- configurable: true,
1992
- writable: true,
1993
- value: true
1994
- });
1995
- Object.defineProperty(this, "runnable", {
1996
- enumerable: true,
1997
- configurable: true,
1998
- writable: true,
1999
- value: void 0
2000
- });
2001
- Object.defineProperty(this, "fallbacks", {
2002
- enumerable: true,
2003
- configurable: true,
2004
- writable: true,
2005
- value: void 0
2006
- });
2007
- this.runnable = fields.runnable;
2008
- this.fallbacks = fields.fallbacks;
2009
- }
2010
- *runnables() {
2011
- yield this.runnable;
2012
- for (const fallback of this.fallbacks) {
2013
- yield fallback;
2014
- }
2015
- }
2016
- async invoke(input, options) {
2017
- const config = (0, config_js_1.ensureConfig)(options);
2018
- const callbackManager_ = await (0, config_js_1.getCallbackManagerForConfig)(config);
2019
- const { runId, ...otherConfigFields } = config;
2020
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName);
2021
- const childConfig = (0, config_js_1.patchConfig)(otherConfigFields, {
2022
- callbacks: runManager?.getChild(),
2023
- });
2024
- const res = await index_js_1.AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => {
2025
- let firstError;
2026
- for (const runnable of this.runnables()) {
2027
- config?.signal?.throwIfAborted();
2028
- try {
2029
- const output = await runnable.invoke(input, childConfig);
2030
- await runManager?.handleChainEnd(_coerceToDict(output, "output"));
2031
- return output;
2032
- }
2033
- catch (e) {
2034
- if (firstError === undefined) {
2035
- firstError = e;
2036
- }
2037
- }
2038
- }
2039
- if (firstError === undefined) {
2040
- throw new Error("No error stored at end of fallback.");
2041
- }
2042
- await runManager?.handleChainError(firstError);
2043
- throw firstError;
2044
- });
2045
- return res;
2046
- }
2047
- async *_streamIterator(input, options) {
2048
- const config = (0, config_js_1.ensureConfig)(options);
2049
- const callbackManager_ = await (0, config_js_1.getCallbackManagerForConfig)(config);
2050
- const { runId, ...otherConfigFields } = config;
2051
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName);
2052
- let firstError;
2053
- let stream;
2054
- for (const runnable of this.runnables()) {
2055
- config?.signal?.throwIfAborted();
2056
- const childConfig = (0, config_js_1.patchConfig)(otherConfigFields, {
2057
- callbacks: runManager?.getChild(),
2058
- });
2059
- try {
2060
- const originalStream = await runnable.stream(input, childConfig);
2061
- stream = (0, iter_js_1.consumeAsyncIterableInContext)(childConfig, originalStream);
2062
- break;
2063
- }
2064
- catch (e) {
2065
- if (firstError === undefined) {
2066
- firstError = e;
2067
- }
2068
- }
2069
- }
2070
- if (stream === undefined) {
2071
- const error = firstError ?? new Error("No error stored at end of fallback.");
2072
- await runManager?.handleChainError(error);
2073
- throw error;
2074
- }
2075
- let output;
2076
- try {
2077
- for await (const chunk of stream) {
2078
- yield chunk;
2079
- try {
2080
- output =
2081
- output === undefined
2082
- ? output
2083
- : this._concatOutputChunks(output, chunk);
2084
- }
2085
- catch (e) {
2086
- output = undefined;
2087
- }
2088
- }
2089
- }
2090
- catch (e) {
2091
- await runManager?.handleChainError(e);
2092
- throw e;
2093
- }
2094
- await runManager?.handleChainEnd(_coerceToDict(output, "output"));
2095
- }
2096
- async batch(inputs, options, batchOptions) {
2097
- if (batchOptions?.returnExceptions) {
2098
- throw new Error("Not implemented.");
2099
- }
2100
- const configList = this._getOptionsList(options ?? {}, inputs.length);
2101
- const callbackManagers = await Promise.all(configList.map((config) => (0, config_js_1.getCallbackManagerForConfig)(config)));
2102
- const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => {
2103
- const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName);
2104
- delete configList[i].runId;
2105
- return handleStartRes;
2106
- }));
2107
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2108
- let firstError;
2109
- for (const runnable of this.runnables()) {
2110
- configList[0].signal?.throwIfAborted();
2111
- try {
2112
- const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => (0, config_js_1.patchConfig)(configList[j], {
2113
- callbacks: runManager?.getChild(),
2114
- })), batchOptions);
2115
- await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(_coerceToDict(outputs[i], "output"))));
2116
- return outputs;
2117
- }
2118
- catch (e) {
2119
- if (firstError === undefined) {
2120
- firstError = e;
2121
- }
2122
- }
2123
- }
2124
- if (!firstError) {
2125
- throw new Error("No error stored at end of fallbacks.");
2126
- }
2127
- await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError)));
2128
- throw firstError;
2129
- }
2130
- }
2131
- exports.RunnableWithFallbacks = RunnableWithFallbacks;
2132
- // TODO: Figure out why the compiler needs help eliminating Error as a RunOutput type
1429
+ * A Runnable that can fallback to other Runnables if it fails.
1430
+ * External APIs (e.g., APIs for a language model) may at times experience
1431
+ * degraded performance or even downtime.
1432
+ *
1433
+ * In these cases, it can be useful to have a fallback Runnable that can be
1434
+ * used in place of the original Runnable (e.g., fallback to another LLM provider).
1435
+ *
1436
+ * Fallbacks can be defined at the level of a single Runnable, or at the level
1437
+ * of a chain of Runnables. Fallbacks are tried in order until one succeeds or
1438
+ * all fail.
1439
+ *
1440
+ * While you can instantiate a `RunnableWithFallbacks` directly, it is usually
1441
+ * more convenient to use the `withFallbacks` method on an existing Runnable.
1442
+ *
1443
+ * When streaming, fallbacks will only be called on failures during the initial
1444
+ * stream creation. Errors that occur after a stream starts will not fallback
1445
+ * to the next Runnable.
1446
+ *
1447
+ * @example
1448
+ * ```typescript
1449
+ * import {
1450
+ * RunnableLambda,
1451
+ * RunnableWithFallbacks,
1452
+ * } from "@langchain/core/runnables";
1453
+ *
1454
+ * const primaryOperation = (input: string): string => {
1455
+ * if (input !== "safe") {
1456
+ * throw new Error("Primary operation failed due to unsafe input");
1457
+ * }
1458
+ * return `Processed: ${input}`;
1459
+ * };
1460
+ *
1461
+ * // Define a fallback operation that processes the input differently
1462
+ * const fallbackOperation = (input: string): string =>
1463
+ * `Fallback processed: ${input}`;
1464
+ *
1465
+ * const primaryRunnable = RunnableLambda.from(primaryOperation);
1466
+ * const fallbackRunnable = RunnableLambda.from(fallbackOperation);
1467
+ *
1468
+ * // Apply the fallback logic using the .withFallbacks() method
1469
+ * const runnableWithFallback = primaryRunnable.withFallbacks([fallbackRunnable]);
1470
+ *
1471
+ * // Alternatively, create a RunnableWithFallbacks instance manually
1472
+ * const manualFallbackChain = new RunnableWithFallbacks({
1473
+ * runnable: primaryRunnable,
1474
+ * fallbacks: [fallbackRunnable],
1475
+ * });
1476
+ *
1477
+ * // Example invocation using .withFallbacks()
1478
+ * const res = await runnableWithFallback
1479
+ * .invoke("unsafe input")
1480
+ * .catch((error) => {
1481
+ * console.error("Failed after all attempts:", error.message);
1482
+ * });
1483
+ *
1484
+ * // "Fallback processed: unsafe input"
1485
+ *
1486
+ * // Example invocation using manual instantiation
1487
+ * const res = await manualFallbackChain
1488
+ * .invoke("safe")
1489
+ * .catch((error) => {
1490
+ * console.error("Failed after all attempts:", error.message);
1491
+ * });
1492
+ *
1493
+ * // "Processed: safe"
1494
+ * ```
1495
+ */
1496
+ var RunnableWithFallbacks = class extends Runnable {
1497
+ static lc_name() {
1498
+ return "RunnableWithFallbacks";
1499
+ }
1500
+ lc_namespace = ["langchain_core", "runnables"];
1501
+ lc_serializable = true;
1502
+ runnable;
1503
+ fallbacks;
1504
+ constructor(fields) {
1505
+ super(fields);
1506
+ this.runnable = fields.runnable;
1507
+ this.fallbacks = fields.fallbacks;
1508
+ }
1509
+ *runnables() {
1510
+ yield this.runnable;
1511
+ for (const fallback of this.fallbacks) yield fallback;
1512
+ }
1513
+ async invoke(input, options) {
1514
+ const config = require_config.ensureConfig(options);
1515
+ const callbackManager_ = await require_config.getCallbackManagerForConfig(config);
1516
+ const { runId,...otherConfigFields } = config;
1517
+ const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName);
1518
+ const childConfig = require_config.patchConfig(otherConfigFields, { callbacks: runManager?.getChild() });
1519
+ const res = await require_index.AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => {
1520
+ let firstError;
1521
+ for (const runnable of this.runnables()) {
1522
+ config?.signal?.throwIfAborted();
1523
+ try {
1524
+ const output = await runnable.invoke(input, childConfig);
1525
+ await runManager?.handleChainEnd(_coerceToDict(output, "output"));
1526
+ return output;
1527
+ } catch (e) {
1528
+ if (firstError === void 0) firstError = e;
1529
+ }
1530
+ }
1531
+ if (firstError === void 0) throw new Error("No error stored at end of fallback.");
1532
+ await runManager?.handleChainError(firstError);
1533
+ throw firstError;
1534
+ });
1535
+ return res;
1536
+ }
1537
+ async *_streamIterator(input, options) {
1538
+ const config = require_config.ensureConfig(options);
1539
+ const callbackManager_ = await require_config.getCallbackManagerForConfig(config);
1540
+ const { runId,...otherConfigFields } = config;
1541
+ const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName);
1542
+ let firstError;
1543
+ let stream;
1544
+ for (const runnable of this.runnables()) {
1545
+ config?.signal?.throwIfAborted();
1546
+ const childConfig = require_config.patchConfig(otherConfigFields, { callbacks: runManager?.getChild() });
1547
+ try {
1548
+ const originalStream = await runnable.stream(input, childConfig);
1549
+ stream = require_iter.consumeAsyncIterableInContext(childConfig, originalStream);
1550
+ break;
1551
+ } catch (e) {
1552
+ if (firstError === void 0) firstError = e;
1553
+ }
1554
+ }
1555
+ if (stream === void 0) {
1556
+ const error = firstError ?? /* @__PURE__ */ new Error("No error stored at end of fallback.");
1557
+ await runManager?.handleChainError(error);
1558
+ throw error;
1559
+ }
1560
+ let output;
1561
+ try {
1562
+ for await (const chunk of stream) {
1563
+ yield chunk;
1564
+ try {
1565
+ output = output === void 0 ? output : require_utils_stream.concat(output, chunk);
1566
+ } catch (e) {
1567
+ output = void 0;
1568
+ }
1569
+ }
1570
+ } catch (e) {
1571
+ await runManager?.handleChainError(e);
1572
+ throw e;
1573
+ }
1574
+ await runManager?.handleChainEnd(_coerceToDict(output, "output"));
1575
+ }
1576
+ async batch(inputs, options, batchOptions) {
1577
+ if (batchOptions?.returnExceptions) throw new Error("Not implemented.");
1578
+ const configList = this._getOptionsList(options ?? {}, inputs.length);
1579
+ const callbackManagers = await Promise.all(configList.map((config) => require_config.getCallbackManagerForConfig(config)));
1580
+ const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => {
1581
+ const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), configList[i].runId, void 0, void 0, void 0, configList[i].runName);
1582
+ delete configList[i].runId;
1583
+ return handleStartRes;
1584
+ }));
1585
+ let firstError;
1586
+ for (const runnable of this.runnables()) {
1587
+ configList[0].signal?.throwIfAborted();
1588
+ try {
1589
+ const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => require_config.patchConfig(configList[j], { callbacks: runManager?.getChild() })), batchOptions);
1590
+ await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(_coerceToDict(outputs[i], "output"))));
1591
+ return outputs;
1592
+ } catch (e) {
1593
+ if (firstError === void 0) firstError = e;
1594
+ }
1595
+ }
1596
+ if (!firstError) throw new Error("No error stored at end of fallbacks.");
1597
+ await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError)));
1598
+ throw firstError;
1599
+ }
1600
+ };
2133
1601
  function _coerceToRunnable(coerceable) {
2134
- if (typeof coerceable === "function") {
2135
- return new RunnableLambda({ func: coerceable });
2136
- }
2137
- else if (Runnable.isRunnable(coerceable)) {
2138
- return coerceable;
2139
- }
2140
- else if (!Array.isArray(coerceable) && typeof coerceable === "object") {
2141
- const runnables = {};
2142
- for (const [key, value] of Object.entries(coerceable)) {
2143
- runnables[key] = _coerceToRunnable(value);
2144
- }
2145
- return new RunnableMap({
2146
- steps: runnables,
2147
- });
2148
- }
2149
- else {
2150
- throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`);
2151
- }
1602
+ if (typeof coerceable === "function") return new RunnableLambda({ func: coerceable });
1603
+ else if (Runnable.isRunnable(coerceable)) return coerceable;
1604
+ else if (!Array.isArray(coerceable) && typeof coerceable === "object") {
1605
+ const runnables = {};
1606
+ for (const [key, value] of Object.entries(coerceable)) runnables[key] = _coerceToRunnable(value);
1607
+ return new RunnableMap({ steps: runnables });
1608
+ } else throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`);
2152
1609
  }
2153
1610
  /**
2154
- * A runnable that assigns key-value pairs to inputs of type `Record<string, unknown>`.
2155
- * @example
2156
- * ```typescript
2157
- * import {
2158
- * RunnableAssign,
2159
- * RunnableLambda,
2160
- * RunnableParallel,
2161
- * } from "@langchain/core/runnables";
2162
- *
2163
- * const calculateAge = (x: { birthYear: number }): { age: number } => {
2164
- * const currentYear = new Date().getFullYear();
2165
- * return { age: currentYear - x.birthYear };
2166
- * };
2167
- *
2168
- * const createGreeting = (x: { name: string }): { greeting: string } => {
2169
- * return { greeting: `Hello, ${x.name}!` };
2170
- * };
2171
- *
2172
- * const mapper = RunnableParallel.from({
2173
- * age_step: RunnableLambda.from(calculateAge),
2174
- * greeting_step: RunnableLambda.from(createGreeting),
2175
- * });
2176
- *
2177
- * const runnableAssign = new RunnableAssign({ mapper });
2178
- *
2179
- * const res = await runnableAssign.invoke({ name: "Alice", birthYear: 1990 });
2180
- *
2181
- * // { name: "Alice", birthYear: 1990, age_step: { age: 34 }, greeting_step: { greeting: "Hello, Alice!" } }
2182
- * ```
2183
- */
2184
- class RunnableAssign extends Runnable {
2185
- static lc_name() {
2186
- return "RunnableAssign";
2187
- }
2188
- constructor(fields) {
2189
- // eslint-disable-next-line no-instanceof/no-instanceof
2190
- if (fields instanceof RunnableMap) {
2191
- // eslint-disable-next-line no-param-reassign
2192
- fields = { mapper: fields };
2193
- }
2194
- super(fields);
2195
- Object.defineProperty(this, "lc_namespace", {
2196
- enumerable: true,
2197
- configurable: true,
2198
- writable: true,
2199
- value: ["langchain_core", "runnables"]
2200
- });
2201
- Object.defineProperty(this, "lc_serializable", {
2202
- enumerable: true,
2203
- configurable: true,
2204
- writable: true,
2205
- value: true
2206
- });
2207
- Object.defineProperty(this, "mapper", {
2208
- enumerable: true,
2209
- configurable: true,
2210
- writable: true,
2211
- value: void 0
2212
- });
2213
- this.mapper = fields.mapper;
2214
- }
2215
- async invoke(input, options) {
2216
- const mapperResult = await this.mapper.invoke(input, options);
2217
- return {
2218
- ...input,
2219
- ...mapperResult,
2220
- };
2221
- }
2222
- async *_transform(generator, runManager, options) {
2223
- // collect mapper keys
2224
- const mapperKeys = this.mapper.getStepsKeys();
2225
- // create two input gens, one for the mapper, one for the input
2226
- const [forPassthrough, forMapper] = (0, stream_js_1.atee)(generator);
2227
- // create mapper output gen
2228
- const mapperOutput = this.mapper.transform(forMapper, (0, config_js_1.patchConfig)(options, { callbacks: runManager?.getChild() }));
2229
- // start the mapper
2230
- const firstMapperChunkPromise = mapperOutput.next();
2231
- // yield the passthrough
2232
- for await (const chunk of forPassthrough) {
2233
- if (typeof chunk !== "object" || Array.isArray(chunk)) {
2234
- throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`);
2235
- }
2236
- const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key)));
2237
- if (Object.keys(filtered).length > 0) {
2238
- yield filtered;
2239
- }
2240
- }
2241
- // yield the mapper output
2242
- yield (await firstMapperChunkPromise).value;
2243
- for await (const chunk of mapperOutput) {
2244
- yield chunk;
2245
- }
2246
- }
2247
- transform(generator, options) {
2248
- return this._transformStreamWithConfig(generator, this._transform.bind(this), options);
2249
- }
2250
- async stream(input, options) {
2251
- async function* generator() {
2252
- yield input;
2253
- }
2254
- const config = (0, config_js_1.ensureConfig)(options);
2255
- const wrappedGenerator = new stream_js_1.AsyncGeneratorWithSetup({
2256
- generator: this.transform(generator(), config),
2257
- config,
2258
- });
2259
- await wrappedGenerator.setup;
2260
- return stream_js_1.IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
2261
- }
2262
- }
2263
- exports.RunnableAssign = RunnableAssign;
1611
+ * A runnable that assigns key-value pairs to inputs of type `Record<string, unknown>`.
1612
+ * @example
1613
+ * ```typescript
1614
+ * import {
1615
+ * RunnableAssign,
1616
+ * RunnableLambda,
1617
+ * RunnableParallel,
1618
+ * } from "@langchain/core/runnables";
1619
+ *
1620
+ * const calculateAge = (x: { birthYear: number }): { age: number } => {
1621
+ * const currentYear = new Date().getFullYear();
1622
+ * return { age: currentYear - x.birthYear };
1623
+ * };
1624
+ *
1625
+ * const createGreeting = (x: { name: string }): { greeting: string } => {
1626
+ * return { greeting: `Hello, ${x.name}!` };
1627
+ * };
1628
+ *
1629
+ * const mapper = RunnableParallel.from({
1630
+ * age_step: RunnableLambda.from(calculateAge),
1631
+ * greeting_step: RunnableLambda.from(createGreeting),
1632
+ * });
1633
+ *
1634
+ * const runnableAssign = new RunnableAssign({ mapper });
1635
+ *
1636
+ * const res = await runnableAssign.invoke({ name: "Alice", birthYear: 1990 });
1637
+ *
1638
+ * // { name: "Alice", birthYear: 1990, age_step: { age: 34 }, greeting_step: { greeting: "Hello, Alice!" } }
1639
+ * ```
1640
+ */
1641
+ var RunnableAssign = class extends Runnable {
1642
+ static lc_name() {
1643
+ return "RunnableAssign";
1644
+ }
1645
+ lc_namespace = ["langchain_core", "runnables"];
1646
+ lc_serializable = true;
1647
+ mapper;
1648
+ constructor(fields) {
1649
+ if (fields instanceof RunnableMap) fields = { mapper: fields };
1650
+ super(fields);
1651
+ this.mapper = fields.mapper;
1652
+ }
1653
+ async invoke(input, options) {
1654
+ const mapperResult = await this.mapper.invoke(input, options);
1655
+ return {
1656
+ ...input,
1657
+ ...mapperResult
1658
+ };
1659
+ }
1660
+ async *_transform(generator, runManager, options) {
1661
+ const mapperKeys = this.mapper.getStepsKeys();
1662
+ const [forPassthrough, forMapper] = require_utils_stream.atee(generator);
1663
+ const mapperOutput = this.mapper.transform(forMapper, require_config.patchConfig(options, { callbacks: runManager?.getChild() }));
1664
+ const firstMapperChunkPromise = mapperOutput.next();
1665
+ for await (const chunk of forPassthrough) {
1666
+ if (typeof chunk !== "object" || Array.isArray(chunk)) throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`);
1667
+ const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key)));
1668
+ if (Object.keys(filtered).length > 0) yield filtered;
1669
+ }
1670
+ yield (await firstMapperChunkPromise).value;
1671
+ for await (const chunk of mapperOutput) yield chunk;
1672
+ }
1673
+ transform(generator, options) {
1674
+ return this._transformStreamWithConfig(generator, this._transform.bind(this), options);
1675
+ }
1676
+ async stream(input, options) {
1677
+ async function* generator() {
1678
+ yield input;
1679
+ }
1680
+ const config = require_config.ensureConfig(options);
1681
+ const wrappedGenerator = new require_utils_stream.AsyncGeneratorWithSetup({
1682
+ generator: this.transform(generator(), config),
1683
+ config
1684
+ });
1685
+ await wrappedGenerator.setup;
1686
+ return require_utils_stream.IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
1687
+ }
1688
+ };
2264
1689
  /**
2265
- * A runnable that assigns key-value pairs to inputs of type `Record<string, unknown>`.
2266
- * Useful for streaming, can be automatically created and chained by calling `runnable.pick();`.
2267
- * @example
2268
- * ```typescript
2269
- * import { RunnablePick } from "@langchain/core/runnables";
2270
- *
2271
- * const inputData = {
2272
- * name: "John",
2273
- * age: 30,
2274
- * city: "New York",
2275
- * country: "USA",
2276
- * email: "john.doe@example.com",
2277
- * phone: "+1234567890",
2278
- * };
2279
- *
2280
- * const basicInfoRunnable = new RunnablePick(["name", "city"]);
2281
- *
2282
- * // Example invocation
2283
- * const res = await basicInfoRunnable.invoke(inputData);
2284
- *
2285
- * // { name: 'John', city: 'New York' }
2286
- * ```
2287
- */
2288
- class RunnablePick extends Runnable {
2289
- static lc_name() {
2290
- return "RunnablePick";
2291
- }
2292
- constructor(fields) {
2293
- if (typeof fields === "string" || Array.isArray(fields)) {
2294
- // eslint-disable-next-line no-param-reassign
2295
- fields = { keys: fields };
2296
- }
2297
- super(fields);
2298
- Object.defineProperty(this, "lc_namespace", {
2299
- enumerable: true,
2300
- configurable: true,
2301
- writable: true,
2302
- value: ["langchain_core", "runnables"]
2303
- });
2304
- Object.defineProperty(this, "lc_serializable", {
2305
- enumerable: true,
2306
- configurable: true,
2307
- writable: true,
2308
- value: true
2309
- });
2310
- Object.defineProperty(this, "keys", {
2311
- enumerable: true,
2312
- configurable: true,
2313
- writable: true,
2314
- value: void 0
2315
- });
2316
- this.keys = fields.keys;
2317
- }
2318
- async _pick(input) {
2319
- if (typeof this.keys === "string") {
2320
- return input[this.keys];
2321
- }
2322
- else {
2323
- const picked = this.keys
2324
- .map((key) => [key, input[key]])
2325
- .filter((v) => v[1] !== undefined);
2326
- return picked.length === 0
2327
- ? undefined
2328
- : Object.fromEntries(picked);
2329
- }
2330
- }
2331
- async invoke(input, options) {
2332
- return this._callWithConfig(this._pick.bind(this), input, options);
2333
- }
2334
- async *_transform(generator) {
2335
- for await (const chunk of generator) {
2336
- const picked = await this._pick(chunk);
2337
- if (picked !== undefined) {
2338
- yield picked;
2339
- }
2340
- }
2341
- }
2342
- transform(generator, options) {
2343
- return this._transformStreamWithConfig(generator, this._transform.bind(this), options);
2344
- }
2345
- async stream(input, options) {
2346
- async function* generator() {
2347
- yield input;
2348
- }
2349
- const config = (0, config_js_1.ensureConfig)(options);
2350
- const wrappedGenerator = new stream_js_1.AsyncGeneratorWithSetup({
2351
- generator: this.transform(generator(), config),
2352
- config,
2353
- });
2354
- await wrappedGenerator.setup;
2355
- return stream_js_1.IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
2356
- }
2357
- }
2358
- exports.RunnablePick = RunnablePick;
2359
- class RunnableToolLike extends RunnableBinding {
2360
- constructor(fields) {
2361
- const sequence = RunnableSequence.from([
2362
- RunnableLambda.from(async (input) => {
2363
- let toolInput;
2364
- if ((0, utils_js_2._isToolCall)(input)) {
2365
- try {
2366
- toolInput = await (0, zod_js_1.interopParseAsync)(this.schema, input.args);
2367
- }
2368
- catch (e) {
2369
- throw new utils_js_2.ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args));
2370
- }
2371
- }
2372
- else {
2373
- toolInput = input;
2374
- }
2375
- return toolInput;
2376
- }).withConfig({ runName: `${fields.name}:parse_input` }),
2377
- fields.bound,
2378
- ]).withConfig({ runName: fields.name });
2379
- super({
2380
- bound: sequence,
2381
- config: fields.config ?? {},
2382
- });
2383
- Object.defineProperty(this, "name", {
2384
- enumerable: true,
2385
- configurable: true,
2386
- writable: true,
2387
- value: void 0
2388
- });
2389
- Object.defineProperty(this, "description", {
2390
- enumerable: true,
2391
- configurable: true,
2392
- writable: true,
2393
- value: void 0
2394
- });
2395
- Object.defineProperty(this, "schema", {
2396
- enumerable: true,
2397
- configurable: true,
2398
- writable: true,
2399
- value: void 0
2400
- });
2401
- this.name = fields.name;
2402
- this.description = fields.description;
2403
- this.schema = fields.schema;
2404
- }
2405
- static lc_name() {
2406
- return "RunnableToolLike";
2407
- }
2408
- }
2409
- exports.RunnableToolLike = RunnableToolLike;
1690
+ * A runnable that assigns key-value pairs to inputs of type `Record<string, unknown>`.
1691
+ * Useful for streaming, can be automatically created and chained by calling `runnable.pick();`.
1692
+ * @example
1693
+ * ```typescript
1694
+ * import { RunnablePick } from "@langchain/core/runnables";
1695
+ *
1696
+ * const inputData = {
1697
+ * name: "John",
1698
+ * age: 30,
1699
+ * city: "New York",
1700
+ * country: "USA",
1701
+ * email: "john.doe@example.com",
1702
+ * phone: "+1234567890",
1703
+ * };
1704
+ *
1705
+ * const basicInfoRunnable = new RunnablePick(["name", "city"]);
1706
+ *
1707
+ * // Example invocation
1708
+ * const res = await basicInfoRunnable.invoke(inputData);
1709
+ *
1710
+ * // { name: 'John', city: 'New York' }
1711
+ * ```
1712
+ */
1713
+ var RunnablePick = class extends Runnable {
1714
+ static lc_name() {
1715
+ return "RunnablePick";
1716
+ }
1717
+ lc_namespace = ["langchain_core", "runnables"];
1718
+ lc_serializable = true;
1719
+ keys;
1720
+ constructor(fields) {
1721
+ if (typeof fields === "string" || Array.isArray(fields)) fields = { keys: fields };
1722
+ super(fields);
1723
+ this.keys = fields.keys;
1724
+ }
1725
+ async _pick(input) {
1726
+ if (typeof this.keys === "string") return input[this.keys];
1727
+ else {
1728
+ const picked = this.keys.map((key) => [key, input[key]]).filter((v) => v[1] !== void 0);
1729
+ return picked.length === 0 ? void 0 : Object.fromEntries(picked);
1730
+ }
1731
+ }
1732
+ async invoke(input, options) {
1733
+ return this._callWithConfig(this._pick.bind(this), input, options);
1734
+ }
1735
+ async *_transform(generator) {
1736
+ for await (const chunk of generator) {
1737
+ const picked = await this._pick(chunk);
1738
+ if (picked !== void 0) yield picked;
1739
+ }
1740
+ }
1741
+ transform(generator, options) {
1742
+ return this._transformStreamWithConfig(generator, this._transform.bind(this), options);
1743
+ }
1744
+ async stream(input, options) {
1745
+ async function* generator() {
1746
+ yield input;
1747
+ }
1748
+ const config = require_config.ensureConfig(options);
1749
+ const wrappedGenerator = new require_utils_stream.AsyncGeneratorWithSetup({
1750
+ generator: this.transform(generator(), config),
1751
+ config
1752
+ });
1753
+ await wrappedGenerator.setup;
1754
+ return require_utils_stream.IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
1755
+ }
1756
+ };
1757
+ var RunnableToolLike = class extends RunnableBinding {
1758
+ name;
1759
+ description;
1760
+ schema;
1761
+ constructor(fields) {
1762
+ const sequence = RunnableSequence.from([RunnableLambda.from(async (input) => {
1763
+ let toolInput;
1764
+ if (require_utils._isToolCall(input)) try {
1765
+ toolInput = await require_zod.interopParseAsync(this.schema, input.args);
1766
+ } catch (e) {
1767
+ throw new require_utils.ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args));
1768
+ }
1769
+ else toolInput = input;
1770
+ return toolInput;
1771
+ }).withConfig({ runName: `${fields.name}:parse_input` }), fields.bound]).withConfig({ runName: fields.name });
1772
+ super({
1773
+ bound: sequence,
1774
+ config: fields.config ?? {}
1775
+ });
1776
+ this.name = fields.name;
1777
+ this.description = fields.description;
1778
+ this.schema = fields.schema;
1779
+ }
1780
+ static lc_name() {
1781
+ return "RunnableToolLike";
1782
+ }
1783
+ };
2410
1784
  /**
2411
- * Given a runnable and a Zod schema, convert the runnable to a tool.
2412
- *
2413
- * @template RunInput The input type for the runnable.
2414
- * @template RunOutput The output type for the runnable.
2415
- *
2416
- * @param {Runnable<RunInput, RunOutput>} runnable The runnable to convert to a tool.
2417
- * @param fields
2418
- * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.
2419
- * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided.
2420
- * @param {InteropZodType<RunInput>} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.
2421
- * @returns {RunnableToolLike<InteropZodType<RunInput>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.
2422
- */
1785
+ * Given a runnable and a Zod schema, convert the runnable to a tool.
1786
+ *
1787
+ * @template RunInput The input type for the runnable.
1788
+ * @template RunOutput The output type for the runnable.
1789
+ *
1790
+ * @param {Runnable<RunInput, RunOutput>} runnable The runnable to convert to a tool.
1791
+ * @param fields
1792
+ * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.
1793
+ * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided.
1794
+ * @param {InteropZodType<RunInput>} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.
1795
+ * @returns {RunnableToolLike<InteropZodType<RunInput>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.
1796
+ */
2423
1797
  function convertRunnableToTool(runnable, fields) {
2424
- const name = fields.name ?? runnable.getName();
2425
- const description = fields.description ?? (0, zod_js_1.getSchemaDescription)(fields.schema);
2426
- if ((0, zod_js_1.isSimpleStringZodSchema)(fields.schema)) {
2427
- return new RunnableToolLike({
2428
- name,
2429
- description,
2430
- schema: v3_1.z
2431
- .object({ input: v3_1.z.string() })
2432
- .transform((input) => input.input),
2433
- bound: runnable,
2434
- });
2435
- }
2436
- return new RunnableToolLike({
2437
- name,
2438
- description,
2439
- schema: fields.schema,
2440
- bound: runnable,
2441
- });
1798
+ const name = fields.name ?? runnable.getName();
1799
+ const description = fields.description ?? require_zod.getSchemaDescription(fields.schema);
1800
+ if (require_zod.isSimpleStringZodSchema(fields.schema)) return new RunnableToolLike({
1801
+ name,
1802
+ description,
1803
+ schema: zod_v3.z.object({ input: zod_v3.z.string() }).transform((input) => input.input),
1804
+ bound: runnable
1805
+ });
1806
+ return new RunnableToolLike({
1807
+ name,
1808
+ description,
1809
+ schema: fields.schema,
1810
+ bound: runnable
1811
+ });
2442
1812
  }
1813
+
1814
+ //#endregion
1815
+ exports.Runnable = Runnable;
1816
+ exports.RunnableAssign = RunnableAssign;
1817
+ exports.RunnableBinding = RunnableBinding;
1818
+ exports.RunnableEach = RunnableEach;
1819
+ exports.RunnableLambda = RunnableLambda;
1820
+ exports.RunnableMap = RunnableMap;
1821
+ exports.RunnableParallel = RunnableParallel;
1822
+ exports.RunnablePick = RunnablePick;
1823
+ exports.RunnableRetry = RunnableRetry;
1824
+ exports.RunnableSequence = RunnableSequence;
1825
+ exports.RunnableToolLike = RunnableToolLike;
1826
+ exports.RunnableWithFallbacks = RunnableWithFallbacks;
1827
+ exports._coerceToDict = _coerceToDict;
1828
+ exports._coerceToRunnable = _coerceToRunnable;
1829
+ //# sourceMappingURL=base.cjs.map