@langchain/langgraph 1.0.6 → 1.0.12

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 (383) hide show
  1. package/package.json +7 -7
  2. package/CHANGELOG.md +0 -280
  3. package/dist/_virtual/rolldown_runtime.cjs +0 -25
  4. package/dist/channels/any_value.cjs +0 -46
  5. package/dist/channels/any_value.cjs.map +0 -1
  6. package/dist/channels/any_value.d.cts +0 -24
  7. package/dist/channels/any_value.d.cts.map +0 -1
  8. package/dist/channels/any_value.d.ts +0 -24
  9. package/dist/channels/any_value.d.ts.map +0 -1
  10. package/dist/channels/any_value.js +0 -46
  11. package/dist/channels/any_value.js.map +0 -1
  12. package/dist/channels/base.cjs +0 -102
  13. package/dist/channels/base.cjs.map +0 -1
  14. package/dist/channels/base.d.cts +0 -79
  15. package/dist/channels/base.d.cts.map +0 -1
  16. package/dist/channels/base.d.ts +0 -79
  17. package/dist/channels/base.d.ts.map +0 -1
  18. package/dist/channels/base.js +0 -97
  19. package/dist/channels/base.js.map +0 -1
  20. package/dist/channels/binop.cjs +0 -49
  21. package/dist/channels/binop.cjs.map +0 -1
  22. package/dist/channels/binop.d.cts +0 -22
  23. package/dist/channels/binop.d.cts.map +0 -1
  24. package/dist/channels/binop.d.ts +0 -22
  25. package/dist/channels/binop.d.ts.map +0 -1
  26. package/dist/channels/binop.js +0 -49
  27. package/dist/channels/binop.js.map +0 -1
  28. package/dist/channels/dynamic_barrier_value.cjs +0 -76
  29. package/dist/channels/dynamic_barrier_value.cjs.map +0 -1
  30. package/dist/channels/dynamic_barrier_value.d.cts +0 -42
  31. package/dist/channels/dynamic_barrier_value.d.cts.map +0 -1
  32. package/dist/channels/dynamic_barrier_value.d.ts +0 -42
  33. package/dist/channels/dynamic_barrier_value.d.ts.map +0 -1
  34. package/dist/channels/dynamic_barrier_value.js +0 -76
  35. package/dist/channels/dynamic_barrier_value.js.map +0 -1
  36. package/dist/channels/ephemeral_value.cjs +0 -46
  37. package/dist/channels/ephemeral_value.cjs.map +0 -1
  38. package/dist/channels/ephemeral_value.d.cts +0 -22
  39. package/dist/channels/ephemeral_value.d.cts.map +0 -1
  40. package/dist/channels/ephemeral_value.d.ts +0 -22
  41. package/dist/channels/ephemeral_value.d.ts.map +0 -1
  42. package/dist/channels/ephemeral_value.js +0 -46
  43. package/dist/channels/ephemeral_value.js.map +0 -1
  44. package/dist/channels/index.cjs +0 -21
  45. package/dist/channels/index.d.cts +0 -9
  46. package/dist/channels/index.d.ts +0 -9
  47. package/dist/channels/index.js +0 -10
  48. package/dist/channels/last_value.cjs +0 -98
  49. package/dist/channels/last_value.cjs.map +0 -1
  50. package/dist/channels/last_value.d.cts +0 -44
  51. package/dist/channels/last_value.d.cts.map +0 -1
  52. package/dist/channels/last_value.d.ts +0 -44
  53. package/dist/channels/last_value.d.ts.map +0 -1
  54. package/dist/channels/last_value.js +0 -97
  55. package/dist/channels/last_value.js.map +0 -1
  56. package/dist/channels/named_barrier_value.cjs +0 -118
  57. package/dist/channels/named_barrier_value.cjs.map +0 -1
  58. package/dist/channels/named_barrier_value.d.cts +0 -46
  59. package/dist/channels/named_barrier_value.d.cts.map +0 -1
  60. package/dist/channels/named_barrier_value.d.ts +0 -46
  61. package/dist/channels/named_barrier_value.d.ts.map +0 -1
  62. package/dist/channels/named_barrier_value.js +0 -116
  63. package/dist/channels/named_barrier_value.js.map +0 -1
  64. package/dist/channels/topic.cjs +0 -65
  65. package/dist/channels/topic.cjs.map +0 -1
  66. package/dist/channels/topic.d.cts +0 -32
  67. package/dist/channels/topic.d.cts.map +0 -1
  68. package/dist/channels/topic.d.ts +0 -32
  69. package/dist/channels/topic.d.ts.map +0 -1
  70. package/dist/channels/topic.js +0 -65
  71. package/dist/channels/topic.js.map +0 -1
  72. package/dist/constants.cjs +0 -406
  73. package/dist/constants.cjs.map +0 -1
  74. package/dist/constants.d.cts +0 -285
  75. package/dist/constants.d.cts.map +0 -1
  76. package/dist/constants.d.ts +0 -285
  77. package/dist/constants.d.ts.map +0 -1
  78. package/dist/constants.js +0 -362
  79. package/dist/constants.js.map +0 -1
  80. package/dist/errors.cjs +0 -163
  81. package/dist/errors.cjs.map +0 -1
  82. package/dist/errors.d.cts +0 -81
  83. package/dist/errors.d.cts.map +0 -1
  84. package/dist/errors.d.ts +0 -81
  85. package/dist/errors.d.ts.map +0 -1
  86. package/dist/errors.js +0 -146
  87. package/dist/errors.js.map +0 -1
  88. package/dist/func/index.cjs +0 -301
  89. package/dist/func/index.cjs.map +0 -1
  90. package/dist/func/index.d.cts +0 -293
  91. package/dist/func/index.d.cts.map +0 -1
  92. package/dist/func/index.d.ts +0 -293
  93. package/dist/func/index.d.ts.map +0 -1
  94. package/dist/func/index.js +0 -298
  95. package/dist/func/index.js.map +0 -1
  96. package/dist/func/types.d.cts +0 -64
  97. package/dist/func/types.d.cts.map +0 -1
  98. package/dist/func/types.d.ts +0 -64
  99. package/dist/func/types.d.ts.map +0 -1
  100. package/dist/graph/annotation.cjs +0 -101
  101. package/dist/graph/annotation.cjs.map +0 -1
  102. package/dist/graph/annotation.d.cts +0 -116
  103. package/dist/graph/annotation.d.cts.map +0 -1
  104. package/dist/graph/annotation.d.ts +0 -116
  105. package/dist/graph/annotation.d.ts.map +0 -1
  106. package/dist/graph/annotation.js +0 -99
  107. package/dist/graph/annotation.js.map +0 -1
  108. package/dist/graph/graph.cjs +0 -423
  109. package/dist/graph/graph.cjs.map +0 -1
  110. package/dist/graph/graph.d.cts +0 -132
  111. package/dist/graph/graph.d.cts.map +0 -1
  112. package/dist/graph/graph.d.ts +0 -132
  113. package/dist/graph/graph.d.ts.map +0 -1
  114. package/dist/graph/graph.js +0 -420
  115. package/dist/graph/graph.js.map +0 -1
  116. package/dist/graph/index.cjs +0 -5
  117. package/dist/graph/index.js +0 -7
  118. package/dist/graph/message.cjs +0 -99
  119. package/dist/graph/message.cjs.map +0 -1
  120. package/dist/graph/message.d.cts +0 -40
  121. package/dist/graph/message.d.cts.map +0 -1
  122. package/dist/graph/message.d.ts +0 -40
  123. package/dist/graph/message.d.ts.map +0 -1
  124. package/dist/graph/message.js +0 -95
  125. package/dist/graph/message.js.map +0 -1
  126. package/dist/graph/messages_annotation.cjs +0 -110
  127. package/dist/graph/messages_annotation.cjs.map +0 -1
  128. package/dist/graph/messages_annotation.d.cts +0 -112
  129. package/dist/graph/messages_annotation.d.cts.map +0 -1
  130. package/dist/graph/messages_annotation.d.ts +0 -112
  131. package/dist/graph/messages_annotation.d.ts.map +0 -1
  132. package/dist/graph/messages_annotation.js +0 -107
  133. package/dist/graph/messages_annotation.js.map +0 -1
  134. package/dist/graph/state.cjs +0 -501
  135. package/dist/graph/state.cjs.map +0 -1
  136. package/dist/graph/state.d.cts +0 -236
  137. package/dist/graph/state.d.cts.map +0 -1
  138. package/dist/graph/state.d.ts +0 -236
  139. package/dist/graph/state.d.ts.map +0 -1
  140. package/dist/graph/state.js +0 -499
  141. package/dist/graph/state.js.map +0 -1
  142. package/dist/graph/zod/index.cjs +0 -10
  143. package/dist/graph/zod/index.d.cts +0 -3
  144. package/dist/graph/zod/index.d.ts +0 -3
  145. package/dist/graph/zod/index.js +0 -5
  146. package/dist/graph/zod/meta.cjs +0 -145
  147. package/dist/graph/zod/meta.cjs.map +0 -1
  148. package/dist/graph/zod/meta.d.cts +0 -116
  149. package/dist/graph/zod/meta.d.cts.map +0 -1
  150. package/dist/graph/zod/meta.d.ts +0 -116
  151. package/dist/graph/zod/meta.d.ts.map +0 -1
  152. package/dist/graph/zod/meta.js +0 -141
  153. package/dist/graph/zod/meta.js.map +0 -1
  154. package/dist/graph/zod/plugin.cjs +0 -41
  155. package/dist/graph/zod/plugin.cjs.map +0 -1
  156. package/dist/graph/zod/plugin.js +0 -41
  157. package/dist/graph/zod/plugin.js.map +0 -1
  158. package/dist/graph/zod/schema.cjs +0 -99
  159. package/dist/graph/zod/schema.cjs.map +0 -1
  160. package/dist/graph/zod/schema.d.cts +0 -38
  161. package/dist/graph/zod/schema.d.cts.map +0 -1
  162. package/dist/graph/zod/schema.d.ts +0 -38
  163. package/dist/graph/zod/schema.d.ts.map +0 -1
  164. package/dist/graph/zod/schema.js +0 -94
  165. package/dist/graph/zod/schema.js.map +0 -1
  166. package/dist/graph/zod/zod-registry.cjs +0 -43
  167. package/dist/graph/zod/zod-registry.cjs.map +0 -1
  168. package/dist/graph/zod/zod-registry.d.cts +0 -51
  169. package/dist/graph/zod/zod-registry.d.cts.map +0 -1
  170. package/dist/graph/zod/zod-registry.d.ts +0 -51
  171. package/dist/graph/zod/zod-registry.d.ts.map +0 -1
  172. package/dist/graph/zod/zod-registry.js +0 -41
  173. package/dist/graph/zod/zod-registry.js.map +0 -1
  174. package/dist/hash.cjs +0 -271
  175. package/dist/hash.cjs.map +0 -1
  176. package/dist/hash.js +0 -269
  177. package/dist/hash.js.map +0 -1
  178. package/dist/index.cjs +0 -112
  179. package/dist/index.cjs.map +0 -1
  180. package/dist/index.d.cts +0 -26
  181. package/dist/index.d.ts +0 -26
  182. package/dist/index.js +0 -22
  183. package/dist/index.js.map +0 -1
  184. package/dist/interrupt.cjs +0 -82
  185. package/dist/interrupt.cjs.map +0 -1
  186. package/dist/interrupt.d.cts +0 -58
  187. package/dist/interrupt.d.cts.map +0 -1
  188. package/dist/interrupt.d.ts +0 -58
  189. package/dist/interrupt.d.ts.map +0 -1
  190. package/dist/interrupt.js +0 -81
  191. package/dist/interrupt.js.map +0 -1
  192. package/dist/prebuilt/agentName.cjs +0 -153
  193. package/dist/prebuilt/agentName.cjs.map +0 -1
  194. package/dist/prebuilt/agentName.d.cts +0 -42
  195. package/dist/prebuilt/agentName.d.cts.map +0 -1
  196. package/dist/prebuilt/agentName.d.ts +0 -42
  197. package/dist/prebuilt/agentName.d.ts.map +0 -1
  198. package/dist/prebuilt/agentName.js +0 -152
  199. package/dist/prebuilt/agentName.js.map +0 -1
  200. package/dist/prebuilt/agent_executor.cjs +0 -44
  201. package/dist/prebuilt/agent_executor.cjs.map +0 -1
  202. package/dist/prebuilt/agent_executor.d.cts +0 -58
  203. package/dist/prebuilt/agent_executor.d.cts.map +0 -1
  204. package/dist/prebuilt/agent_executor.d.ts +0 -58
  205. package/dist/prebuilt/agent_executor.d.ts.map +0 -1
  206. package/dist/prebuilt/agent_executor.js +0 -44
  207. package/dist/prebuilt/agent_executor.js.map +0 -1
  208. package/dist/prebuilt/chat_agent_executor.cjs +0 -68
  209. package/dist/prebuilt/chat_agent_executor.cjs.map +0 -1
  210. package/dist/prebuilt/chat_agent_executor.d.cts +0 -23
  211. package/dist/prebuilt/chat_agent_executor.d.cts.map +0 -1
  212. package/dist/prebuilt/chat_agent_executor.d.ts +0 -23
  213. package/dist/prebuilt/chat_agent_executor.d.ts.map +0 -1
  214. package/dist/prebuilt/chat_agent_executor.js +0 -67
  215. package/dist/prebuilt/chat_agent_executor.js.map +0 -1
  216. package/dist/prebuilt/index.cjs +0 -15
  217. package/dist/prebuilt/index.d.cts +0 -8
  218. package/dist/prebuilt/index.d.ts +0 -8
  219. package/dist/prebuilt/index.js +0 -8
  220. package/dist/prebuilt/interrupt.d.cts +0 -61
  221. package/dist/prebuilt/interrupt.d.cts.map +0 -1
  222. package/dist/prebuilt/interrupt.d.ts +0 -61
  223. package/dist/prebuilt/interrupt.d.ts.map +0 -1
  224. package/dist/prebuilt/react_agent_executor.cjs +0 -344
  225. package/dist/prebuilt/react_agent_executor.cjs.map +0 -1
  226. package/dist/prebuilt/react_agent_executor.d.cts +0 -230
  227. package/dist/prebuilt/react_agent_executor.d.cts.map +0 -1
  228. package/dist/prebuilt/react_agent_executor.d.ts +0 -230
  229. package/dist/prebuilt/react_agent_executor.d.ts.map +0 -1
  230. package/dist/prebuilt/react_agent_executor.js +0 -342
  231. package/dist/prebuilt/react_agent_executor.js.map +0 -1
  232. package/dist/prebuilt/tool_executor.cjs +0 -48
  233. package/dist/prebuilt/tool_executor.cjs.map +0 -1
  234. package/dist/prebuilt/tool_executor.d.cts +0 -42
  235. package/dist/prebuilt/tool_executor.d.cts.map +0 -1
  236. package/dist/prebuilt/tool_executor.d.ts +0 -42
  237. package/dist/prebuilt/tool_executor.d.ts.map +0 -1
  238. package/dist/prebuilt/tool_executor.js +0 -47
  239. package/dist/prebuilt/tool_executor.js.map +0 -1
  240. package/dist/prebuilt/tool_node.cjs +0 -248
  241. package/dist/prebuilt/tool_node.cjs.map +0 -1
  242. package/dist/prebuilt/tool_node.d.cts +0 -182
  243. package/dist/prebuilt/tool_node.d.cts.map +0 -1
  244. package/dist/prebuilt/tool_node.d.ts +0 -182
  245. package/dist/prebuilt/tool_node.d.ts.map +0 -1
  246. package/dist/prebuilt/tool_node.js +0 -246
  247. package/dist/prebuilt/tool_node.js.map +0 -1
  248. package/dist/pregel/algo.cjs +0 -573
  249. package/dist/pregel/algo.cjs.map +0 -1
  250. package/dist/pregel/algo.d.cts +0 -13
  251. package/dist/pregel/algo.d.cts.map +0 -1
  252. package/dist/pregel/algo.d.ts +0 -13
  253. package/dist/pregel/algo.d.ts.map +0 -1
  254. package/dist/pregel/algo.js +0 -567
  255. package/dist/pregel/algo.js.map +0 -1
  256. package/dist/pregel/call.cjs +0 -53
  257. package/dist/pregel/call.cjs.map +0 -1
  258. package/dist/pregel/call.js +0 -50
  259. package/dist/pregel/call.js.map +0 -1
  260. package/dist/pregel/debug.cjs +0 -175
  261. package/dist/pregel/debug.cjs.map +0 -1
  262. package/dist/pregel/debug.js +0 -169
  263. package/dist/pregel/debug.js.map +0 -1
  264. package/dist/pregel/index.cjs +0 -1170
  265. package/dist/pregel/index.cjs.map +0 -1
  266. package/dist/pregel/index.d.cts +0 -546
  267. package/dist/pregel/index.d.cts.map +0 -1
  268. package/dist/pregel/index.d.ts +0 -546
  269. package/dist/pregel/index.d.ts.map +0 -1
  270. package/dist/pregel/index.js +0 -1168
  271. package/dist/pregel/index.js.map +0 -1
  272. package/dist/pregel/io.cjs +0 -140
  273. package/dist/pregel/io.cjs.map +0 -1
  274. package/dist/pregel/io.js +0 -135
  275. package/dist/pregel/io.js.map +0 -1
  276. package/dist/pregel/loop.cjs +0 -548
  277. package/dist/pregel/loop.cjs.map +0 -1
  278. package/dist/pregel/loop.js +0 -547
  279. package/dist/pregel/loop.js.map +0 -1
  280. package/dist/pregel/messages.cjs +0 -108
  281. package/dist/pregel/messages.cjs.map +0 -1
  282. package/dist/pregel/messages.js +0 -107
  283. package/dist/pregel/messages.js.map +0 -1
  284. package/dist/pregel/read.cjs +0 -152
  285. package/dist/pregel/read.cjs.map +0 -1
  286. package/dist/pregel/read.d.cts +0 -51
  287. package/dist/pregel/read.d.cts.map +0 -1
  288. package/dist/pregel/read.d.ts +0 -51
  289. package/dist/pregel/read.d.ts.map +0 -1
  290. package/dist/pregel/read.js +0 -150
  291. package/dist/pregel/read.js.map +0 -1
  292. package/dist/pregel/remote.cjs +0 -346
  293. package/dist/pregel/remote.cjs.map +0 -1
  294. package/dist/pregel/remote.d.cts +0 -121
  295. package/dist/pregel/remote.d.cts.map +0 -1
  296. package/dist/pregel/remote.d.ts +0 -121
  297. package/dist/pregel/remote.d.ts.map +0 -1
  298. package/dist/pregel/remote.js +0 -345
  299. package/dist/pregel/remote.js.map +0 -1
  300. package/dist/pregel/retry.cjs +0 -92
  301. package/dist/pregel/retry.cjs.map +0 -1
  302. package/dist/pregel/retry.js +0 -92
  303. package/dist/pregel/retry.js.map +0 -1
  304. package/dist/pregel/runnable_types.d.cts +0 -49
  305. package/dist/pregel/runnable_types.d.cts.map +0 -1
  306. package/dist/pregel/runnable_types.d.ts +0 -49
  307. package/dist/pregel/runnable_types.d.ts.map +0 -1
  308. package/dist/pregel/runner.cjs +0 -228
  309. package/dist/pregel/runner.cjs.map +0 -1
  310. package/dist/pregel/runner.js +0 -228
  311. package/dist/pregel/runner.js.map +0 -1
  312. package/dist/pregel/stream.cjs +0 -199
  313. package/dist/pregel/stream.cjs.map +0 -1
  314. package/dist/pregel/stream.js +0 -196
  315. package/dist/pregel/stream.js.map +0 -1
  316. package/dist/pregel/types.cjs +0 -27
  317. package/dist/pregel/types.cjs.map +0 -1
  318. package/dist/pregel/types.d.cts +0 -453
  319. package/dist/pregel/types.d.cts.map +0 -1
  320. package/dist/pregel/types.d.ts +0 -453
  321. package/dist/pregel/types.d.ts.map +0 -1
  322. package/dist/pregel/types.js +0 -25
  323. package/dist/pregel/types.js.map +0 -1
  324. package/dist/pregel/utils/config.cjs +0 -122
  325. package/dist/pregel/utils/config.cjs.map +0 -1
  326. package/dist/pregel/utils/config.d.cts +0 -36
  327. package/dist/pregel/utils/config.d.cts.map +0 -1
  328. package/dist/pregel/utils/config.d.ts +0 -36
  329. package/dist/pregel/utils/config.d.ts.map +0 -1
  330. package/dist/pregel/utils/config.js +0 -115
  331. package/dist/pregel/utils/config.js.map +0 -1
  332. package/dist/pregel/utils/index.cjs +0 -103
  333. package/dist/pregel/utils/index.cjs.map +0 -1
  334. package/dist/pregel/utils/index.d.cts +0 -51
  335. package/dist/pregel/utils/index.d.cts.map +0 -1
  336. package/dist/pregel/utils/index.d.ts +0 -51
  337. package/dist/pregel/utils/index.d.ts.map +0 -1
  338. package/dist/pregel/utils/index.js +0 -97
  339. package/dist/pregel/utils/index.js.map +0 -1
  340. package/dist/pregel/utils/subgraph.cjs +0 -19
  341. package/dist/pregel/utils/subgraph.cjs.map +0 -1
  342. package/dist/pregel/utils/subgraph.js +0 -17
  343. package/dist/pregel/utils/subgraph.js.map +0 -1
  344. package/dist/pregel/validate.cjs +0 -45
  345. package/dist/pregel/validate.cjs.map +0 -1
  346. package/dist/pregel/validate.js +0 -44
  347. package/dist/pregel/validate.js.map +0 -1
  348. package/dist/pregel/write.cjs +0 -97
  349. package/dist/pregel/write.cjs.map +0 -1
  350. package/dist/pregel/write.d.cts +0 -35
  351. package/dist/pregel/write.d.cts.map +0 -1
  352. package/dist/pregel/write.d.ts +0 -35
  353. package/dist/pregel/write.d.ts.map +0 -1
  354. package/dist/pregel/write.js +0 -95
  355. package/dist/pregel/write.js.map +0 -1
  356. package/dist/remote.cjs +0 -3
  357. package/dist/remote.d.cts +0 -2
  358. package/dist/remote.d.ts +0 -2
  359. package/dist/remote.js +0 -3
  360. package/dist/setup/async_local_storage.cjs +0 -12
  361. package/dist/setup/async_local_storage.cjs.map +0 -1
  362. package/dist/setup/async_local_storage.js +0 -11
  363. package/dist/setup/async_local_storage.js.map +0 -1
  364. package/dist/utils.cjs +0 -88
  365. package/dist/utils.cjs.map +0 -1
  366. package/dist/utils.d.cts +0 -32
  367. package/dist/utils.d.cts.map +0 -1
  368. package/dist/utils.d.ts +0 -32
  369. package/dist/utils.d.ts.map +0 -1
  370. package/dist/utils.js +0 -81
  371. package/dist/utils.js.map +0 -1
  372. package/dist/web.cjs +0 -96
  373. package/dist/web.d.cts +0 -23
  374. package/dist/web.d.ts +0 -23
  375. package/dist/web.js +0 -15
  376. package/dist/writer.cjs +0 -15
  377. package/dist/writer.cjs.map +0 -1
  378. package/dist/writer.d.cts +0 -7
  379. package/dist/writer.d.cts.map +0 -1
  380. package/dist/writer.d.ts +0 -7
  381. package/dist/writer.d.ts.map +0 -1
  382. package/dist/writer.js +0 -14
  383. package/dist/writer.js.map +0 -1
@@ -1,1168 +0,0 @@
1
- import { GraphRecursionError, GraphValueError, InvalidUpdateError } from "../errors.js";
2
- import { createCheckpoint, emptyChannels, getOnlyChannels } from "../channels/base.js";
3
- import { CHECKPOINT_NAMESPACE_END, CHECKPOINT_NAMESPACE_SEPARATOR, CONFIG_KEY_CHECKPOINTER, CONFIG_KEY_CHECKPOINT_NS, CONFIG_KEY_DURABILITY, CONFIG_KEY_NODE_FINISHED, CONFIG_KEY_READ, CONFIG_KEY_SEND, CONFIG_KEY_STREAM, CONFIG_KEY_TASK_ID, COPY, END, ERROR, INPUT, INTERRUPT, NULL_TASK_ID, PUSH, TASKS, isInterrupted } from "../constants.js";
4
- import { ensureLangGraphConfig, getConfig, recastCheckpointNamespace } from "./utils/config.js";
5
- import { gatherIterator, patchConfigurable } from "../utils.js";
6
- import { ChannelWrite, PASSTHROUGH } from "./write.js";
7
- import { PregelNode } from "./read.js";
8
- import { mapInput, readChannels } from "./io.js";
9
- import { _coerceToDict, combineAbortSignals, combineCallbacks, getNewChannelVersions, patchCheckpointMap } from "./utils/index.js";
10
- import { _applyWrites, _localRead, _prepareNextTasks } from "./algo.js";
11
- import { findSubgraphPregel } from "./utils/subgraph.js";
12
- import { printStepCheckpoint, printStepTasks, printStepWrites, tasksWithWrites } from "./debug.js";
13
- import { IterableReadableStreamWithAbortSignal, IterableReadableWritableStream, toEventStream } from "./stream.js";
14
- import { PregelLoop } from "./loop.js";
15
- import { StreamMessagesHandler } from "./messages.js";
16
- import { PregelRunner } from "./runner.js";
17
- import { validateGraph, validateKeys } from "./validate.js";
18
- import { Topic } from "../channels/topic.js";
19
- import { interrupt } from "../interrupt.js";
20
- import { SCHEDULED, compareChannelVersions, copyCheckpoint, emptyCheckpoint, uuid5 } from "@langchain/langgraph-checkpoint";
21
- import { Runnable, RunnableSequence, _coerceToRunnable, getCallbackManagerForConfig, mergeConfigs, patchConfig } from "@langchain/core/runnables";
22
-
23
- //#region src/pregel/index.ts
24
- /**
25
- * Utility class for working with channels in the Pregel system.
26
- * Provides static methods for subscribing to channels and writing to them.
27
- *
28
- * Channels are the communication pathways between nodes in a Pregel graph.
29
- * They enable message passing and state updates between different parts of the graph.
30
- */
31
- var Channel = class {
32
- static subscribeTo(channels, options) {
33
- const { key, tags } = {
34
- key: void 0,
35
- tags: void 0,
36
- ...options ?? {}
37
- };
38
- if (Array.isArray(channels) && key !== void 0) throw new Error("Can't specify a key when subscribing to multiple channels");
39
- let channelMappingOrArray;
40
- if (typeof channels === "string") if (key) channelMappingOrArray = { [key]: channels };
41
- else channelMappingOrArray = [channels];
42
- else channelMappingOrArray = Object.fromEntries(channels.map((chan) => [chan, chan]));
43
- const triggers = Array.isArray(channels) ? channels : [channels];
44
- return new PregelNode({
45
- channels: channelMappingOrArray,
46
- triggers,
47
- tags
48
- });
49
- }
50
- /**
51
- * Creates a ChannelWrite that specifies how to write values to channels.
52
- * This is used to define how nodes send output to channels.
53
- *
54
- * @example
55
- * ```typescript
56
- * // Write to multiple channels
57
- * const write = Channel.writeTo(["output", "state"]);
58
- *
59
- * // Write with specific values
60
- * const write = Channel.writeTo(["output"], {
61
- * state: "completed",
62
- * result: calculateResult()
63
- * });
64
- *
65
- * // Write with a transformation function
66
- * const write = Channel.writeTo(["output"], {
67
- * result: (x) => processResult(x)
68
- * });
69
- * ```
70
- *
71
- * @param channels - Array of channel names to write to
72
- * @param writes - Optional map of channel names to values or transformations
73
- * @returns A ChannelWrite object that can be used to write to the specified channels
74
- */
75
- static writeTo(channels, writes) {
76
- const channelWriteEntries = [];
77
- for (const channel of channels) channelWriteEntries.push({
78
- channel,
79
- value: PASSTHROUGH,
80
- skipNone: false
81
- });
82
- for (const [key, value] of Object.entries(writes ?? {})) if (Runnable.isRunnable(value) || typeof value === "function") channelWriteEntries.push({
83
- channel: key,
84
- value: PASSTHROUGH,
85
- skipNone: true,
86
- mapper: _coerceToRunnable(value)
87
- });
88
- else channelWriteEntries.push({
89
- channel: key,
90
- value,
91
- skipNone: false
92
- });
93
- return new ChannelWrite(channelWriteEntries);
94
- }
95
- };
96
- var PartialRunnable = class extends Runnable {
97
- lc_namespace = ["langgraph", "pregel"];
98
- invoke(_input, _options) {
99
- throw new Error("Not implemented");
100
- }
101
- withConfig(_config) {
102
- return super.withConfig(_config);
103
- }
104
- stream(input, options) {
105
- return super.stream(input, options);
106
- }
107
- };
108
- /**
109
- * The Pregel class is the core runtime engine of LangGraph, implementing a message-passing graph computation model
110
- * inspired by [Google's Pregel system](https://research.google/pubs/pregel-a-system-for-large-scale-graph-processing/).
111
- * It provides the foundation for building reliable, controllable agent workflows that can evolve state over time.
112
- *
113
- * Key features:
114
- * - Message passing between nodes in discrete "supersteps"
115
- * - Built-in persistence layer through checkpointers
116
- * - First-class streaming support for values, updates, and events
117
- * - Human-in-the-loop capabilities via interrupts
118
- * - Support for parallel node execution within supersteps
119
- *
120
- * The Pregel class is not intended to be instantiated directly by consumers. Instead, use the following higher-level APIs:
121
- * - {@link StateGraph}: The main graph class for building agent workflows
122
- * - Compiling a {@link StateGraph} will return a {@link CompiledGraph} instance, which extends `Pregel`
123
- * - Functional API: A declarative approach using tasks and entrypoints
124
- * - A `Pregel` instance is returned by the {@link entrypoint} function
125
- *
126
- * @example
127
- * ```typescript
128
- * // Using StateGraph API
129
- * const graph = new StateGraph(annotation)
130
- * .addNode("nodeA", myNodeFunction)
131
- * .addEdge("nodeA", "nodeB")
132
- * .compile();
133
- *
134
- * // The compiled graph is a Pregel instance
135
- * const result = await graph.invoke(input);
136
- * ```
137
- *
138
- * @example
139
- * ```typescript
140
- * // Using Functional API
141
- * import { task, entrypoint } from "@langchain/langgraph";
142
- * import { MemorySaver } from "@langchain/langgraph-checkpoint";
143
- *
144
- * // Define tasks that can be composed
145
- * const addOne = task("add", async (x: number) => x + 1);
146
- *
147
- * // Create a workflow using the entrypoint function
148
- * const workflow = entrypoint({
149
- * name: "workflow",
150
- * checkpointer: new MemorySaver()
151
- * }, async (numbers: number[]) => {
152
- * // Tasks can be run in parallel
153
- * const results = await Promise.all(numbers.map(n => addOne(n)));
154
- * return results;
155
- * });
156
- *
157
- * // The workflow is a Pregel instance
158
- * const result = await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4]
159
- * ```
160
- *
161
- * @typeParam Nodes - Mapping of node names to their {@link PregelNode} implementations
162
- * @typeParam Channels - Mapping of channel names to their {@link BaseChannel} or {@link ManagedValueSpec} implementations
163
- * @typeParam ContextType - Type of context that can be passed to the graph
164
- * @typeParam InputType - Type of input values accepted by the graph
165
- * @typeParam OutputType - Type of output values produced by the graph
166
- */
167
- var Pregel = class extends PartialRunnable {
168
- /**
169
- * Name of the class when serialized
170
- * @internal
171
- */
172
- static lc_name() {
173
- return "LangGraph";
174
- }
175
- /** @internal LangChain namespace for serialization necessary because Pregel extends Runnable */
176
- lc_namespace = ["langgraph", "pregel"];
177
- /** @internal Flag indicating this is a Pregel instance - necessary for serialization */
178
- lg_is_pregel = true;
179
- /** The nodes in the graph, mapping node names to their PregelNode instances */
180
- nodes;
181
- /** The channels in the graph, mapping channel names to their BaseChannel or ManagedValueSpec instances */
182
- channels;
183
- /**
184
- * The input channels for the graph. These channels receive the initial input when the graph is invoked.
185
- * Can be a single channel key or an array of channel keys.
186
- */
187
- inputChannels;
188
- /**
189
- * The output channels for the graph. These channels contain the final output when the graph completes.
190
- * Can be a single channel key or an array of channel keys.
191
- */
192
- outputChannels;
193
- /** Whether to automatically validate the graph structure when it is compiled. Defaults to true. */
194
- autoValidate = true;
195
- /**
196
- * The streaming modes enabled for this graph. Defaults to ["values"].
197
- * Supported modes:
198
- * - "values": Streams the full state after each step
199
- * - "updates": Streams state updates after each step
200
- * - "messages": Streams messages from within nodes
201
- * - "custom": Streams custom events from within nodes
202
- * - "debug": Streams events related to the execution of the graph - useful for tracing & debugging graph execution
203
- */
204
- streamMode = ["values"];
205
- /**
206
- * Optional channels to stream. If not specified, all channels will be streamed.
207
- * Can be a single channel key or an array of channel keys.
208
- */
209
- streamChannels;
210
- /**
211
- * Optional array of node names or "all" to interrupt after executing these nodes.
212
- * Used for implementing human-in-the-loop workflows.
213
- */
214
- interruptAfter;
215
- /**
216
- * Optional array of node names or "all" to interrupt before executing these nodes.
217
- * Used for implementing human-in-the-loop workflows.
218
- */
219
- interruptBefore;
220
- /** Optional timeout in milliseconds for the execution of each superstep */
221
- stepTimeout;
222
- /** Whether to enable debug logging. Defaults to false. */
223
- debug = false;
224
- /**
225
- * Optional checkpointer for persisting graph state.
226
- * When provided, saves a checkpoint of the graph state at every superstep.
227
- * When false or undefined, checkpointing is disabled, and the graph will not be able to save or restore state.
228
- */
229
- checkpointer;
230
- /** Optional retry policy for handling failures in node execution */
231
- retryPolicy;
232
- /** The default configuration for graph execution, can be overridden on a per-invocation basis */
233
- config;
234
- /**
235
- * Optional long-term memory store for the graph, allows for persistence & retrieval of data across threads
236
- */
237
- store;
238
- /**
239
- * Optional cache for the graph, useful for caching tasks.
240
- */
241
- cache;
242
- /**
243
- * Optional interrupt helper function.
244
- * @internal
245
- */
246
- userInterrupt;
247
- /**
248
- * The trigger to node mapping for the graph run.
249
- * @internal
250
- */
251
- triggerToNodes = {};
252
- /**
253
- * Constructor for Pregel - meant for internal use only.
254
- *
255
- * @internal
256
- */
257
- constructor(fields) {
258
- super(fields);
259
- let { streamMode } = fields;
260
- if (streamMode != null && !Array.isArray(streamMode)) streamMode = [streamMode];
261
- this.nodes = fields.nodes;
262
- this.channels = fields.channels;
263
- if (TASKS in this.channels && "lc_graph_name" in this.channels[TASKS] && this.channels[TASKS].lc_graph_name !== "Topic") throw new Error(`Channel '${TASKS}' is reserved and cannot be used in the graph.`);
264
- else this.channels[TASKS] = new Topic({ accumulate: false });
265
- this.autoValidate = fields.autoValidate ?? this.autoValidate;
266
- this.streamMode = streamMode ?? this.streamMode;
267
- this.inputChannels = fields.inputChannels;
268
- this.outputChannels = fields.outputChannels;
269
- this.streamChannels = fields.streamChannels ?? this.streamChannels;
270
- this.interruptAfter = fields.interruptAfter;
271
- this.interruptBefore = fields.interruptBefore;
272
- this.stepTimeout = fields.stepTimeout ?? this.stepTimeout;
273
- this.debug = fields.debug ?? this.debug;
274
- this.checkpointer = fields.checkpointer;
275
- this.retryPolicy = fields.retryPolicy;
276
- this.config = fields.config;
277
- this.store = fields.store;
278
- this.cache = fields.cache;
279
- this.name = fields.name;
280
- this.triggerToNodes = fields.triggerToNodes ?? this.triggerToNodes;
281
- this.userInterrupt = fields.userInterrupt;
282
- if (this.autoValidate) this.validate();
283
- }
284
- /**
285
- * Creates a new instance of the Pregel graph with updated configuration.
286
- * This method follows the immutable pattern - instead of modifying the current instance,
287
- * it returns a new instance with the merged configuration.
288
- *
289
- * @example
290
- * ```typescript
291
- * // Create a new instance with debug enabled
292
- * const debugGraph = graph.withConfig({ debug: true });
293
- *
294
- * // Create a new instance with a specific thread ID
295
- * const threadGraph = graph.withConfig({
296
- * configurable: { thread_id: "123" }
297
- * });
298
- * ```
299
- *
300
- * @param config - The configuration to merge with the current configuration
301
- * @returns A new Pregel instance with the merged configuration
302
- */
303
- withConfig(config) {
304
- const mergedConfig = mergeConfigs(this.config, config);
305
- return new this.constructor({
306
- ...this,
307
- config: mergedConfig
308
- });
309
- }
310
- /**
311
- * Validates the graph structure to ensure it is well-formed.
312
- * Checks for:
313
- * - No orphaned nodes
314
- * - Valid input/output channel configurations
315
- * - Valid interrupt configurations
316
- *
317
- * @returns this - The Pregel instance for method chaining
318
- * @throws {GraphValidationError} If the graph structure is invalid
319
- */
320
- validate() {
321
- validateGraph({
322
- nodes: this.nodes,
323
- channels: this.channels,
324
- outputChannels: this.outputChannels,
325
- inputChannels: this.inputChannels,
326
- streamChannels: this.streamChannels,
327
- interruptAfterNodes: this.interruptAfter,
328
- interruptBeforeNodes: this.interruptBefore
329
- });
330
- for (const [name, node] of Object.entries(this.nodes)) for (const trigger of node.triggers) {
331
- this.triggerToNodes[trigger] ??= [];
332
- this.triggerToNodes[trigger].push(name);
333
- }
334
- return this;
335
- }
336
- /**
337
- * Gets a list of all channels that should be streamed.
338
- * If streamChannels is specified, returns those channels.
339
- * Otherwise, returns all channels in the graph.
340
- *
341
- * @returns Array of channel keys to stream
342
- */
343
- get streamChannelsList() {
344
- if (Array.isArray(this.streamChannels)) return this.streamChannels;
345
- else if (this.streamChannels) return [this.streamChannels];
346
- else return Object.keys(this.channels);
347
- }
348
- /**
349
- * Gets the channels to stream in their original format.
350
- * If streamChannels is specified, returns it as-is (either single key or array).
351
- * Otherwise, returns all channels in the graph as an array.
352
- *
353
- * @returns Channel keys to stream, either as a single key or array
354
- */
355
- get streamChannelsAsIs() {
356
- if (this.streamChannels) return this.streamChannels;
357
- else return Object.keys(this.channels);
358
- }
359
- /**
360
- * Gets a drawable representation of the graph structure.
361
- * This is an async version of getGraph() and is the preferred method to use.
362
- *
363
- * @param config - Configuration for generating the graph visualization
364
- * @returns A representation of the graph that can be visualized
365
- */
366
- async getGraphAsync(config) {
367
- return this.getGraph(config);
368
- }
369
- /**
370
- * Gets all subgraphs within this graph.
371
- * A subgraph is a Pregel instance that is nested within a node of this graph.
372
- *
373
- * @deprecated Use getSubgraphsAsync instead. The async method will become the default in the next minor release.
374
- * @param namespace - Optional namespace to filter subgraphs
375
- * @param recurse - Whether to recursively get subgraphs of subgraphs
376
- * @returns Generator yielding tuples of [name, subgraph]
377
- */
378
- *getSubgraphs(namespace, recurse) {
379
- for (const [name, node] of Object.entries(this.nodes)) {
380
- if (namespace !== void 0) {
381
- if (!namespace.startsWith(name)) continue;
382
- }
383
- const candidates = node.subgraphs?.length ? node.subgraphs : [node.bound];
384
- for (const candidate of candidates) {
385
- const graph = findSubgraphPregel(candidate);
386
- if (graph !== void 0) {
387
- if (name === namespace) {
388
- yield [name, graph];
389
- return;
390
- }
391
- if (namespace === void 0) yield [name, graph];
392
- if (recurse) {
393
- let newNamespace = namespace;
394
- if (namespace !== void 0) newNamespace = namespace.slice(name.length + 1);
395
- for (const [subgraphName, subgraph] of graph.getSubgraphs(newNamespace, recurse)) yield [`${name}${CHECKPOINT_NAMESPACE_SEPARATOR}${subgraphName}`, subgraph];
396
- }
397
- }
398
- }
399
- }
400
- }
401
- /**
402
- * Gets all subgraphs within this graph asynchronously.
403
- * A subgraph is a Pregel instance that is nested within a node of this graph.
404
- *
405
- * @param namespace - Optional namespace to filter subgraphs
406
- * @param recurse - Whether to recursively get subgraphs of subgraphs
407
- * @returns AsyncGenerator yielding tuples of [name, subgraph]
408
- */
409
- async *getSubgraphsAsync(namespace, recurse) {
410
- yield* this.getSubgraphs(namespace, recurse);
411
- }
412
- /**
413
- * Prepares a state snapshot from saved checkpoint data.
414
- * This is an internal method used by getState and getStateHistory.
415
- *
416
- * @param config - Configuration for preparing the snapshot
417
- * @param saved - Optional saved checkpoint data
418
- * @param subgraphCheckpointer - Optional checkpointer for subgraphs
419
- * @param applyPendingWrites - Whether to apply pending writes to tasks and then to channels
420
- * @returns A snapshot of the graph state
421
- * @internal
422
- */
423
- async _prepareStateSnapshot({ config, saved, subgraphCheckpointer, applyPendingWrites = false }) {
424
- if (saved === void 0) return {
425
- values: {},
426
- next: [],
427
- config,
428
- tasks: []
429
- };
430
- const channels = emptyChannels(this.channels, saved.checkpoint);
431
- if (saved.pendingWrites?.length) {
432
- const nullWrites = saved.pendingWrites.filter(([taskId, _]) => taskId === NULL_TASK_ID).map(([_, channel, value]) => [String(channel), value]);
433
- if (nullWrites.length > 0) _applyWrites(saved.checkpoint, channels, [{
434
- name: INPUT,
435
- writes: nullWrites,
436
- triggers: []
437
- }], void 0, this.triggerToNodes);
438
- }
439
- const nextTasks = Object.values(_prepareNextTasks(saved.checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, {
440
- step: (saved.metadata?.step ?? -1) + 1,
441
- store: this.store
442
- }));
443
- const subgraphs = await gatherIterator(this.getSubgraphsAsync());
444
- const parentNamespace = saved.config.configurable?.checkpoint_ns ?? "";
445
- const taskStates = {};
446
- for (const task of nextTasks) {
447
- const matchingSubgraph = subgraphs.find(([name]) => name === task.name);
448
- if (!matchingSubgraph) continue;
449
- let taskNs = `${String(task.name)}${CHECKPOINT_NAMESPACE_END}${task.id}`;
450
- if (parentNamespace) taskNs = `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${taskNs}`;
451
- if (subgraphCheckpointer === void 0) {
452
- const config$1 = { configurable: {
453
- thread_id: saved.config.configurable?.thread_id,
454
- checkpoint_ns: taskNs
455
- } };
456
- taskStates[task.id] = config$1;
457
- } else {
458
- const subgraphConfig = { configurable: {
459
- [CONFIG_KEY_CHECKPOINTER]: subgraphCheckpointer,
460
- thread_id: saved.config.configurable?.thread_id,
461
- checkpoint_ns: taskNs
462
- } };
463
- const pregel = matchingSubgraph[1];
464
- taskStates[task.id] = await pregel.getState(subgraphConfig, { subgraphs: true });
465
- }
466
- }
467
- if (applyPendingWrites && saved.pendingWrites?.length) {
468
- const nextTaskById = Object.fromEntries(nextTasks.map((task) => [task.id, task]));
469
- for (const [taskId, channel, value] of saved.pendingWrites) {
470
- if ([
471
- ERROR,
472
- INTERRUPT,
473
- SCHEDULED
474
- ].includes(channel)) continue;
475
- if (!(taskId in nextTaskById)) continue;
476
- nextTaskById[taskId].writes.push([String(channel), value]);
477
- }
478
- const tasksWithWrites$1 = nextTasks.filter((task) => task.writes.length > 0);
479
- if (tasksWithWrites$1.length > 0) _applyWrites(saved.checkpoint, channels, tasksWithWrites$1, void 0, this.triggerToNodes);
480
- }
481
- let metadata = saved?.metadata;
482
- if (metadata && saved?.config?.configurable?.thread_id) metadata = {
483
- ...metadata,
484
- thread_id: saved.config.configurable.thread_id
485
- };
486
- const nextList = nextTasks.filter((task) => task.writes.length === 0).map((task) => task.name);
487
- return {
488
- values: readChannels(channels, this.streamChannelsAsIs),
489
- next: nextList,
490
- tasks: tasksWithWrites(nextTasks, saved?.pendingWrites ?? [], taskStates, this.streamChannelsAsIs),
491
- metadata,
492
- config: patchCheckpointMap(saved.config, saved.metadata),
493
- createdAt: saved.checkpoint.ts,
494
- parentConfig: saved.parentConfig
495
- };
496
- }
497
- /**
498
- * Gets the current state of the graph.
499
- * Requires a checkpointer to be configured.
500
- *
501
- * @param config - Configuration for retrieving the state
502
- * @param options - Additional options
503
- * @returns A snapshot of the current graph state
504
- * @throws {GraphValueError} If no checkpointer is configured
505
- */
506
- async getState(config, options) {
507
- const checkpointer = config.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;
508
- if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" });
509
- const checkpointNamespace = config.configurable?.checkpoint_ns ?? "";
510
- if (checkpointNamespace !== "" && config.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) {
511
- const recastNamespace = recastCheckpointNamespace(checkpointNamespace);
512
- for await (const [name, subgraph] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) return await subgraph.getState(patchConfigurable(config, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), { subgraphs: options?.subgraphs });
513
- throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`);
514
- }
515
- const mergedConfig = mergeConfigs(this.config, config);
516
- const saved = await checkpointer.getTuple(config);
517
- const snapshot = await this._prepareStateSnapshot({
518
- config: mergedConfig,
519
- saved,
520
- subgraphCheckpointer: options?.subgraphs ? checkpointer : void 0,
521
- applyPendingWrites: !config.configurable?.checkpoint_id
522
- });
523
- return snapshot;
524
- }
525
- /**
526
- * Gets the history of graph states.
527
- * Requires a checkpointer to be configured.
528
- * Useful for:
529
- * - Debugging execution history
530
- * - Implementing time travel
531
- * - Analyzing graph behavior
532
- *
533
- * @param config - Configuration for retrieving the history
534
- * @param options - Options for filtering the history
535
- * @returns An async iterator of state snapshots
536
- * @throws {Error} If no checkpointer is configured
537
- */
538
- async *getStateHistory(config, options) {
539
- const checkpointer = config.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;
540
- if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" });
541
- const checkpointNamespace = config.configurable?.checkpoint_ns ?? "";
542
- if (checkpointNamespace !== "" && config.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) {
543
- const recastNamespace = recastCheckpointNamespace(checkpointNamespace);
544
- for await (const [name, pregel] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) {
545
- yield* pregel.getStateHistory(patchConfigurable(config, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), options);
546
- return;
547
- }
548
- throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`);
549
- }
550
- const mergedConfig = mergeConfigs(this.config, config, { configurable: { checkpoint_ns: checkpointNamespace } });
551
- for await (const checkpointTuple of checkpointer.list(mergedConfig, options)) yield this._prepareStateSnapshot({
552
- config: checkpointTuple.config,
553
- saved: checkpointTuple
554
- });
555
- }
556
- /**
557
- * Apply updates to the graph state in bulk.
558
- * Requires a checkpointer to be configured.
559
- *
560
- * This method is useful for recreating a thread
561
- * from a list of updates, especially if a checkpoint
562
- * is created as a result of multiple tasks.
563
- *
564
- * @internal The API might change in the future.
565
- *
566
- * @param startConfig - Configuration for the update
567
- * @param updates - The list of updates to apply to graph state
568
- * @returns Updated configuration
569
- * @throws {GraphValueError} If no checkpointer is configured
570
- * @throws {InvalidUpdateError} If the update cannot be attributed to a node or an update can be only applied in sequence.
571
- */
572
- async bulkUpdateState(startConfig, supersteps) {
573
- const checkpointer = startConfig.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;
574
- if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" });
575
- if (supersteps.length === 0) throw new Error("No supersteps provided");
576
- if (supersteps.some((s) => s.updates.length === 0)) throw new Error("No updates provided");
577
- const checkpointNamespace = startConfig.configurable?.checkpoint_ns ?? "";
578
- if (checkpointNamespace !== "" && startConfig.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) {
579
- const recastNamespace = recastCheckpointNamespace(checkpointNamespace);
580
- for await (const [, pregel] of this.getSubgraphsAsync(recastNamespace, true)) return await pregel.bulkUpdateState(patchConfigurable(startConfig, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), supersteps);
581
- throw new Error(`Subgraph "${recastNamespace}" not found`);
582
- }
583
- const updateSuperStep = async (inputConfig, updates) => {
584
- const config = this.config ? mergeConfigs(this.config, inputConfig) : inputConfig;
585
- const saved = await checkpointer.getTuple(config);
586
- const checkpoint = saved !== void 0 ? copyCheckpoint(saved.checkpoint) : emptyCheckpoint();
587
- const checkpointPreviousVersions = { ...saved?.checkpoint.channel_versions };
588
- const step = saved?.metadata?.step ?? -1;
589
- let checkpointConfig = patchConfigurable(config, { checkpoint_ns: config.configurable?.checkpoint_ns ?? "" });
590
- let checkpointMetadata = config.metadata ?? {};
591
- if (saved?.config.configurable) {
592
- checkpointConfig = patchConfigurable(config, saved.config.configurable);
593
- checkpointMetadata = {
594
- ...saved.metadata,
595
- ...checkpointMetadata
596
- };
597
- }
598
- const { values, asNode } = updates[0];
599
- if (values == null && asNode === void 0) {
600
- if (updates.length > 1) throw new InvalidUpdateError(`Cannot create empty checkpoint with multiple updates`);
601
- const nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, void 0, step), {
602
- source: "update",
603
- step: step + 1,
604
- parents: saved?.metadata?.parents ?? {}
605
- }, {});
606
- return patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0);
607
- }
608
- const channels = emptyChannels(this.channels, checkpoint);
609
- if (values === null && asNode === END) {
610
- if (updates.length > 1) throw new InvalidUpdateError(`Cannot apply multiple updates when clearing state`);
611
- if (saved) {
612
- const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites || [], this.nodes, channels, saved.config, true, {
613
- step: (saved.metadata?.step ?? -1) + 1,
614
- checkpointer,
615
- store: this.store
616
- });
617
- const nullWrites = (saved.pendingWrites || []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1));
618
- if (nullWrites.length > 0) _applyWrites(checkpoint, channels, [{
619
- name: INPUT,
620
- writes: nullWrites,
621
- triggers: []
622
- }], checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes);
623
- for (const [taskId, k, v] of saved.pendingWrites || []) {
624
- if ([
625
- ERROR,
626
- INTERRUPT,
627
- SCHEDULED
628
- ].includes(k)) continue;
629
- if (!(taskId in nextTasks)) continue;
630
- nextTasks[taskId].writes.push([k, v]);
631
- }
632
- _applyWrites(checkpoint, channels, Object.values(nextTasks), checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes);
633
- }
634
- const nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step), {
635
- ...checkpointMetadata,
636
- source: "update",
637
- step: step + 1,
638
- parents: saved?.metadata?.parents ?? {}
639
- }, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions));
640
- return patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0);
641
- }
642
- if (asNode === COPY) {
643
- if (updates.length > 1) throw new InvalidUpdateError(`Cannot copy checkpoint with multiple updates`);
644
- if (saved == null) throw new InvalidUpdateError(`Cannot copy a non-existent checkpoint`);
645
- const isCopyWithUpdates = (values$1) => {
646
- if (!Array.isArray(values$1)) return false;
647
- if (values$1.length === 0) return false;
648
- return values$1.every((v) => Array.isArray(v) && v.length === 2);
649
- };
650
- const nextCheckpoint = createCheckpoint(checkpoint, void 0, step);
651
- const nextConfig$1 = await checkpointer.put(saved.parentConfig ?? patchConfigurable(saved.config, { checkpoint_id: void 0 }), nextCheckpoint, {
652
- source: "fork",
653
- step: step + 1,
654
- parents: saved.metadata?.parents ?? {}
655
- }, {});
656
- if (isCopyWithUpdates(values)) {
657
- const nextTasks = _prepareNextTasks(nextCheckpoint, saved.pendingWrites, this.nodes, channels, nextConfig$1, false, { step: step + 2 });
658
- const tasksGroupBy = Object.values(nextTasks).reduce((acc, { name, id }) => {
659
- acc[name] ??= [];
660
- acc[name].push({ id });
661
- return acc;
662
- }, {});
663
- const userGroupBy = values.reduce((acc, item) => {
664
- const [values$1, asNode$1] = item;
665
- acc[asNode$1] ??= [];
666
- const targetIdx = acc[asNode$1].length;
667
- const taskId = tasksGroupBy[asNode$1]?.[targetIdx]?.id;
668
- acc[asNode$1].push({
669
- values: values$1,
670
- asNode: asNode$1,
671
- taskId
672
- });
673
- return acc;
674
- }, {});
675
- return updateSuperStep(patchCheckpointMap(nextConfig$1, saved.metadata), Object.values(userGroupBy).flat());
676
- }
677
- return patchCheckpointMap(nextConfig$1, saved.metadata);
678
- }
679
- if (asNode === INPUT) {
680
- if (updates.length > 1) throw new InvalidUpdateError(`Cannot apply multiple updates when updating as input`);
681
- const inputWrites = await gatherIterator(mapInput(this.inputChannels, values));
682
- if (inputWrites.length === 0) throw new InvalidUpdateError(`Received no input writes for ${JSON.stringify(this.inputChannels, null, 2)}`);
683
- _applyWrites(checkpoint, channels, [{
684
- name: INPUT,
685
- writes: inputWrites,
686
- triggers: []
687
- }], checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes);
688
- const nextStep = saved?.metadata?.step != null ? saved.metadata.step + 1 : -1;
689
- const nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, nextStep), {
690
- source: "input",
691
- step: nextStep,
692
- parents: saved?.metadata?.parents ?? {}
693
- }, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions));
694
- await checkpointer.putWrites(nextConfig$1, inputWrites, uuid5(INPUT, checkpoint.id));
695
- return patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0);
696
- }
697
- if (config.configurable?.checkpoint_id === void 0 && saved?.pendingWrites !== void 0 && saved.pendingWrites.length > 0) {
698
- const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, {
699
- store: this.store,
700
- checkpointer: this.checkpointer,
701
- step: (saved.metadata?.step ?? -1) + 1
702
- });
703
- const nullWrites = (saved.pendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1));
704
- if (nullWrites.length > 0) _applyWrites(saved.checkpoint, channels, [{
705
- name: INPUT,
706
- writes: nullWrites,
707
- triggers: []
708
- }], void 0, this.triggerToNodes);
709
- for (const [tid, k, v] of saved.pendingWrites) {
710
- if ([
711
- ERROR,
712
- INTERRUPT,
713
- SCHEDULED
714
- ].includes(k) || nextTasks[tid] === void 0) continue;
715
- nextTasks[tid].writes.push([k, v]);
716
- }
717
- const tasks$1 = Object.values(nextTasks).filter((task) => {
718
- return task.writes.length > 0;
719
- });
720
- if (tasks$1.length > 0) _applyWrites(checkpoint, channels, tasks$1, void 0, this.triggerToNodes);
721
- }
722
- const nonNullVersion = Object.values(checkpoint.versions_seen).map((seenVersions) => {
723
- return Object.values(seenVersions);
724
- }).flat().find((v) => !!v);
725
- const validUpdates = [];
726
- if (updates.length === 1) {
727
- let { values: values$1, asNode: asNode$1, taskId } = updates[0];
728
- if (asNode$1 === void 0 && Object.keys(this.nodes).length === 1) [asNode$1] = Object.keys(this.nodes);
729
- else if (asNode$1 === void 0 && nonNullVersion === void 0) {
730
- if (typeof this.inputChannels === "string" && this.nodes[this.inputChannels] !== void 0) asNode$1 = this.inputChannels;
731
- } else if (asNode$1 === void 0) {
732
- const lastSeenByNode = Object.entries(checkpoint.versions_seen).map(([n, seen]) => {
733
- return Object.values(seen).map((v) => {
734
- return [v, n];
735
- });
736
- }).flat().filter(([_, v]) => v !== INTERRUPT).sort(([aNumber], [bNumber]) => compareChannelVersions(aNumber, bNumber));
737
- if (lastSeenByNode) {
738
- if (lastSeenByNode.length === 1) asNode$1 = lastSeenByNode[0][1];
739
- else if (lastSeenByNode[lastSeenByNode.length - 1][0] !== lastSeenByNode[lastSeenByNode.length - 2][0]) asNode$1 = lastSeenByNode[lastSeenByNode.length - 1][1];
740
- }
741
- }
742
- if (asNode$1 === void 0) throw new InvalidUpdateError(`Ambiguous update, specify "asNode"`);
743
- validUpdates.push({
744
- values: values$1,
745
- asNode: asNode$1,
746
- taskId
747
- });
748
- } else for (const { asNode: asNode$1, values: values$1, taskId } of updates) {
749
- if (asNode$1 == null) throw new InvalidUpdateError(`"asNode" is required when applying multiple updates`);
750
- validUpdates.push({
751
- values: values$1,
752
- asNode: asNode$1,
753
- taskId
754
- });
755
- }
756
- const tasks = [];
757
- for (const { asNode: asNode$1, values: values$1, taskId } of validUpdates) {
758
- if (this.nodes[asNode$1] === void 0) throw new InvalidUpdateError(`Node "${asNode$1.toString()}" does not exist`);
759
- const writers = this.nodes[asNode$1].getWriters();
760
- if (!writers.length) throw new InvalidUpdateError(`No writers found for node "${asNode$1.toString()}"`);
761
- tasks.push({
762
- name: asNode$1,
763
- input: values$1,
764
- proc: writers.length > 1 ? RunnableSequence.from(writers, { omitSequenceTags: true }) : writers[0],
765
- writes: [],
766
- triggers: [INTERRUPT],
767
- id: taskId ?? uuid5(INTERRUPT, checkpoint.id),
768
- writers: []
769
- });
770
- }
771
- for (const task of tasks) await task.proc.invoke(task.input, patchConfig({
772
- ...config,
773
- store: config?.store ?? this.store
774
- }, {
775
- runName: config.runName ?? `${this.getName()}UpdateState`,
776
- configurable: {
777
- [CONFIG_KEY_SEND]: (items) => task.writes.push(...items),
778
- [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, task, select_, fresh_)
779
- }
780
- }));
781
- for (const task of tasks) {
782
- const channelWrites = task.writes.filter((w) => w[0] !== PUSH);
783
- if (saved !== void 0 && channelWrites.length > 0) await checkpointer.putWrites(checkpointConfig, channelWrites, task.id);
784
- }
785
- _applyWrites(checkpoint, channels, tasks, checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes);
786
- const newVersions = getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions);
787
- const nextConfig = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step + 1), {
788
- source: "update",
789
- step: step + 1,
790
- parents: saved?.metadata?.parents ?? {}
791
- }, newVersions);
792
- for (const task of tasks) {
793
- const pushWrites = task.writes.filter((w) => w[0] === PUSH);
794
- if (pushWrites.length > 0) await checkpointer.putWrites(nextConfig, pushWrites, task.id);
795
- }
796
- return patchCheckpointMap(nextConfig, saved ? saved.metadata : void 0);
797
- };
798
- let currentConfig = startConfig;
799
- for (const { updates } of supersteps) currentConfig = await updateSuperStep(currentConfig, updates);
800
- return currentConfig;
801
- }
802
- /**
803
- * Updates the state of the graph with new values.
804
- * Requires a checkpointer to be configured.
805
- *
806
- * This method can be used for:
807
- * - Implementing human-in-the-loop workflows
808
- * - Modifying graph state during breakpoints
809
- * - Integrating external inputs into the graph
810
- *
811
- * @param inputConfig - Configuration for the update
812
- * @param values - The values to update the state with
813
- * @param asNode - Optional node name to attribute the update to
814
- * @returns Updated configuration
815
- * @throws {GraphValueError} If no checkpointer is configured
816
- * @throws {InvalidUpdateError} If the update cannot be attributed to a node
817
- */
818
- async updateState(inputConfig, values, asNode) {
819
- return this.bulkUpdateState(inputConfig, [{ updates: [{
820
- values,
821
- asNode
822
- }] }]);
823
- }
824
- /**
825
- * Gets the default values for various graph configuration options.
826
- * This is an internal method used to process and normalize configuration options.
827
- *
828
- * @param config - The input configuration options
829
- * @returns A tuple containing normalized values for:
830
- * - debug mode
831
- * - stream modes
832
- * - input keys
833
- * - output keys
834
- * - remaining config
835
- * - interrupt before nodes
836
- * - interrupt after nodes
837
- * - checkpointer
838
- * - store
839
- * - whether stream mode is single
840
- * - node cache
841
- * - whether checkpoint during is enabled
842
- * @internal
843
- */
844
- _defaults(config) {
845
- const { debug, streamMode, inputKeys, outputKeys, interruptAfter, interruptBefore,...rest } = config;
846
- let streamModeSingle = true;
847
- const defaultDebug = debug !== void 0 ? debug : this.debug;
848
- let defaultOutputKeys = outputKeys;
849
- if (defaultOutputKeys === void 0) defaultOutputKeys = this.streamChannelsAsIs;
850
- else validateKeys(defaultOutputKeys, this.channels);
851
- let defaultInputKeys = inputKeys;
852
- if (defaultInputKeys === void 0) defaultInputKeys = this.inputChannels;
853
- else validateKeys(defaultInputKeys, this.channels);
854
- const defaultInterruptBefore = interruptBefore ?? this.interruptBefore ?? [];
855
- const defaultInterruptAfter = interruptAfter ?? this.interruptAfter ?? [];
856
- let defaultStreamMode;
857
- if (streamMode !== void 0) {
858
- defaultStreamMode = Array.isArray(streamMode) ? streamMode : [streamMode];
859
- streamModeSingle = typeof streamMode === "string";
860
- } else {
861
- if (config.configurable?.[CONFIG_KEY_TASK_ID] !== void 0) defaultStreamMode = ["values"];
862
- else defaultStreamMode = this.streamMode;
863
- streamModeSingle = true;
864
- }
865
- let defaultCheckpointer;
866
- if (this.checkpointer === false) defaultCheckpointer = void 0;
867
- else if (config !== void 0 && config.configurable?.[CONFIG_KEY_CHECKPOINTER] !== void 0) defaultCheckpointer = config.configurable[CONFIG_KEY_CHECKPOINTER];
868
- else if (this.checkpointer === true) throw new Error("checkpointer: true cannot be used for root graphs.");
869
- else defaultCheckpointer = this.checkpointer;
870
- const defaultStore = config.store ?? this.store;
871
- const defaultCache = config.cache ?? this.cache;
872
- if (config.durability != null && config.checkpointDuring != null) throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");
873
- const checkpointDuringDurability = (() => {
874
- if (config.checkpointDuring == null) return void 0;
875
- if (config.checkpointDuring === false) return "exit";
876
- return "async";
877
- })();
878
- const defaultDurability = config.durability ?? checkpointDuringDurability ?? config?.configurable?.[CONFIG_KEY_DURABILITY] ?? "async";
879
- return [
880
- defaultDebug,
881
- defaultStreamMode,
882
- defaultInputKeys,
883
- defaultOutputKeys,
884
- rest,
885
- defaultInterruptBefore,
886
- defaultInterruptAfter,
887
- defaultCheckpointer,
888
- defaultStore,
889
- streamModeSingle,
890
- defaultCache,
891
- defaultDurability
892
- ];
893
- }
894
- /**
895
- * Streams the execution of the graph, emitting state updates as they occur.
896
- * This is the primary method for observing graph execution in real-time.
897
- *
898
- * Stream modes:
899
- * - "values": Emits complete state after each step
900
- * - "updates": Emits only state changes after each step
901
- * - "debug": Emits detailed debug information
902
- * - "messages": Emits messages from within nodes
903
- * - "custom": Emits custom events from within nodes
904
- * - "checkpoints": Emits checkpoints from within nodes
905
- * - "tasks": Emits tasks from within nodes
906
- *
907
- * @param input - The input to start graph execution with
908
- * @param options - Configuration options for streaming
909
- * @returns An async iterable stream of graph state updates
910
- */
911
- async stream(input, options) {
912
- const abortController = new AbortController();
913
- const config = {
914
- recursionLimit: this.config?.recursionLimit,
915
- ...options,
916
- signal: combineAbortSignals(options?.signal, abortController.signal).signal
917
- };
918
- const stream = await super.stream(input, config);
919
- return new IterableReadableStreamWithAbortSignal(options?.encoding === "text/event-stream" ? toEventStream(stream) : stream, abortController);
920
- }
921
- streamEvents(input, options, streamOptions) {
922
- const abortController = new AbortController();
923
- const config = {
924
- recursionLimit: this.config?.recursionLimit,
925
- ...options,
926
- callbacks: combineCallbacks(this.config?.callbacks, options?.callbacks),
927
- signal: combineAbortSignals(options?.signal, abortController.signal).signal
928
- };
929
- return new IterableReadableStreamWithAbortSignal(super.streamEvents(input, config, streamOptions), abortController);
930
- }
931
- /**
932
- * Validates the input for the graph.
933
- * @param input - The input to validate
934
- * @returns The validated input
935
- * @internal
936
- */
937
- async _validateInput(input) {
938
- return input;
939
- }
940
- /**
941
- * Validates the context options for the graph.
942
- * @param context - The context options to validate
943
- * @returns The validated context options
944
- * @internal
945
- */
946
- async _validateContext(context) {
947
- return context;
948
- }
949
- /**
950
- * Internal iterator used by stream() to generate state updates.
951
- * This method handles the core logic of graph execution and streaming.
952
- *
953
- * @param input - The input to start graph execution with
954
- * @param options - Configuration options for streaming
955
- * @returns AsyncGenerator yielding state updates
956
- * @internal
957
- */
958
- async *_streamIterator(input, options) {
959
- const streamEncoding = "version" in (options ?? {}) ? void 0 : options?.encoding ?? void 0;
960
- const streamSubgraphs = options?.subgraphs;
961
- const inputConfig = ensureLangGraphConfig(this.config, options);
962
- if (inputConfig.recursionLimit === void 0 || inputConfig.recursionLimit < 1) throw new Error(`Passed "recursionLimit" must be at least 1.`);
963
- if (this.checkpointer !== void 0 && this.checkpointer !== false && inputConfig.configurable === void 0) throw new Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`);
964
- const validInput = await this._validateInput(input);
965
- const { runId,...restConfig } = inputConfig;
966
- const [debug, streamMode, , outputKeys, config, interruptBefore, interruptAfter, checkpointer, store, streamModeSingle, cache, durability] = this._defaults(restConfig);
967
- if (typeof config.context !== "undefined") config.context = await this._validateContext(config.context);
968
- else config.configurable = await this._validateContext(config.configurable);
969
- const stream = new IterableReadableWritableStream({ modes: new Set(streamMode) });
970
- if (this.checkpointer === true) {
971
- config.configurable ??= {};
972
- const ns = config.configurable[CONFIG_KEY_CHECKPOINT_NS] ?? "";
973
- config.configurable[CONFIG_KEY_CHECKPOINT_NS] = ns.split(CHECKPOINT_NAMESPACE_SEPARATOR).map((part) => part.split(CHECKPOINT_NAMESPACE_END)[0]).join(CHECKPOINT_NAMESPACE_SEPARATOR);
974
- }
975
- if (streamMode.includes("messages")) {
976
- const messageStreamer = new StreamMessagesHandler((chunk) => stream.push(chunk));
977
- const { callbacks } = config;
978
- if (callbacks === void 0) config.callbacks = [messageStreamer];
979
- else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(messageStreamer);
980
- else {
981
- const copiedCallbacks = callbacks.copy();
982
- copiedCallbacks.addHandler(messageStreamer, true);
983
- config.callbacks = copiedCallbacks;
984
- }
985
- }
986
- config.writer ??= (chunk) => {
987
- if (!streamMode.includes("custom")) return;
988
- const ns = (getConfig()?.configurable?.[CONFIG_KEY_CHECKPOINT_NS])?.split(CHECKPOINT_NAMESPACE_SEPARATOR).slice(0, -1);
989
- stream.push([
990
- ns ?? [],
991
- "custom",
992
- chunk
993
- ]);
994
- };
995
- config.interrupt ??= this.userInterrupt ?? interrupt;
996
- const callbackManager = await getCallbackManagerForConfig(config);
997
- const runManager = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, void 0, void 0, void 0, config?.runName ?? this.getName());
998
- const channelSpecs = getOnlyChannels(this.channels);
999
- let loop;
1000
- let loopError;
1001
- /**
1002
- * The PregelLoop will yield events from concurrent tasks as soon as they are
1003
- * generated. Each task can push multiple events onto the stream in any order.
1004
- *
1005
- * We use a separate background method and stream here in order to yield events
1006
- * from the loop to the main stream and therefore back to the user as soon as
1007
- * they are available.
1008
- */
1009
- const createAndRunLoop = async () => {
1010
- try {
1011
- loop = await PregelLoop.initialize({
1012
- input: validInput,
1013
- config,
1014
- checkpointer,
1015
- nodes: this.nodes,
1016
- channelSpecs,
1017
- outputKeys,
1018
- streamKeys: this.streamChannelsAsIs,
1019
- store,
1020
- cache,
1021
- stream,
1022
- interruptAfter,
1023
- interruptBefore,
1024
- manager: runManager,
1025
- debug: this.debug,
1026
- triggerToNodes: this.triggerToNodes,
1027
- durability
1028
- });
1029
- const runner = new PregelRunner({
1030
- loop,
1031
- nodeFinished: config.configurable?.[CONFIG_KEY_NODE_FINISHED]
1032
- });
1033
- if (options?.subgraphs) loop.config.configurable = {
1034
- ...loop.config.configurable,
1035
- [CONFIG_KEY_STREAM]: loop.stream
1036
- };
1037
- await this._runLoop({
1038
- loop,
1039
- runner,
1040
- debug,
1041
- config
1042
- });
1043
- if (durability === "sync") await Promise.all(loop?.checkpointerPromises ?? []);
1044
- } catch (e) {
1045
- loopError = e;
1046
- } finally {
1047
- try {
1048
- if (loop) {
1049
- await loop.store?.stop();
1050
- await loop.cache?.stop();
1051
- }
1052
- await Promise.all(loop?.checkpointerPromises ?? []);
1053
- } catch (e) {
1054
- loopError = loopError ?? e;
1055
- }
1056
- if (loopError) stream.error(loopError);
1057
- else stream.close();
1058
- }
1059
- };
1060
- const runLoopPromise = createAndRunLoop();
1061
- try {
1062
- for await (const chunk of stream) {
1063
- if (chunk === void 0) throw new Error("Data structure error.");
1064
- const [namespace, mode, payload] = chunk;
1065
- if (streamMode.includes(mode)) {
1066
- if (streamEncoding === "text/event-stream") {
1067
- if (streamSubgraphs) yield [
1068
- namespace,
1069
- mode,
1070
- payload
1071
- ];
1072
- else yield [
1073
- null,
1074
- mode,
1075
- payload
1076
- ];
1077
- continue;
1078
- }
1079
- if (streamSubgraphs && !streamModeSingle) yield [
1080
- namespace,
1081
- mode,
1082
- payload
1083
- ];
1084
- else if (!streamModeSingle) yield [mode, payload];
1085
- else if (streamSubgraphs) yield [namespace, payload];
1086
- else yield payload;
1087
- }
1088
- }
1089
- } catch (e) {
1090
- await runManager?.handleChainError(loopError);
1091
- throw e;
1092
- } finally {
1093
- await runLoopPromise;
1094
- }
1095
- await runManager?.handleChainEnd(loop?.output ?? {}, runId, void 0, void 0, void 0);
1096
- }
1097
- /**
1098
- * Run the graph with a single input and config.
1099
- * @param input The input to the graph.
1100
- * @param options The configuration to use for the run.
1101
- */
1102
- async invoke(input, options) {
1103
- const streamMode = options?.streamMode ?? "values";
1104
- const config = {
1105
- ...options,
1106
- outputKeys: options?.outputKeys ?? this.outputChannels,
1107
- streamMode,
1108
- encoding: void 0
1109
- };
1110
- const chunks = [];
1111
- const stream = await this.stream(input, config);
1112
- const interruptChunks = [];
1113
- let latest;
1114
- for await (const chunk of stream) if (streamMode === "values") if (isInterrupted(chunk)) interruptChunks.push(chunk[INTERRUPT]);
1115
- else latest = chunk;
1116
- else chunks.push(chunk);
1117
- if (streamMode === "values") {
1118
- if (interruptChunks.length > 0) {
1119
- const interrupts = interruptChunks.flat(1);
1120
- if (latest == null) return { [INTERRUPT]: interrupts };
1121
- if (typeof latest === "object") return {
1122
- ...latest,
1123
- [INTERRUPT]: interrupts
1124
- };
1125
- }
1126
- return latest;
1127
- }
1128
- return chunks;
1129
- }
1130
- async _runLoop(params) {
1131
- const { loop, runner, debug, config } = params;
1132
- let tickError;
1133
- try {
1134
- while (await loop.tick({ inputKeys: this.inputChannels })) {
1135
- for (const { task } of await loop._matchCachedWrites()) loop._outputWrites(task.id, task.writes, true);
1136
- if (debug) printStepCheckpoint(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList);
1137
- if (debug) printStepTasks(loop.step, Object.values(loop.tasks));
1138
- await runner.tick({
1139
- timeout: this.stepTimeout,
1140
- retryPolicy: this.retryPolicy,
1141
- onStepWrite: (step, writes) => {
1142
- if (debug) printStepWrites(step, writes, this.streamChannelsList);
1143
- },
1144
- maxConcurrency: config.maxConcurrency,
1145
- signal: config.signal
1146
- });
1147
- }
1148
- if (loop.status === "out_of_steps") throw new GraphRecursionError([
1149
- `Recursion limit of ${config.recursionLimit} reached`,
1150
- "without hitting a stop condition. You can increase the",
1151
- `limit by setting the "recursionLimit" config key.`
1152
- ].join(" "), { lc_error_code: "GRAPH_RECURSION_LIMIT" });
1153
- } catch (e) {
1154
- tickError = e;
1155
- const suppress = await loop.finishAndHandleError(tickError);
1156
- if (!suppress) throw e;
1157
- } finally {
1158
- if (tickError === void 0) await loop.finishAndHandleError();
1159
- }
1160
- }
1161
- async clearCache() {
1162
- await this.cache?.clear([]);
1163
- }
1164
- };
1165
-
1166
- //#endregion
1167
- export { Channel, Pregel };
1168
- //# sourceMappingURL=index.js.map