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