@langchain/langgraph 1.0.12 → 1.0.13

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 (381) hide show
  1. package/dist/channels/any_value.cjs +46 -0
  2. package/dist/channels/any_value.cjs.map +1 -0
  3. package/dist/channels/any_value.d.cts +23 -0
  4. package/dist/channels/any_value.d.cts.map +1 -0
  5. package/dist/channels/any_value.d.ts +23 -0
  6. package/dist/channels/any_value.d.ts.map +1 -0
  7. package/dist/channels/any_value.js +46 -0
  8. package/dist/channels/any_value.js.map +1 -0
  9. package/dist/channels/base.cjs +101 -0
  10. package/dist/channels/base.cjs.map +1 -0
  11. package/dist/channels/base.d.cts +79 -0
  12. package/dist/channels/base.d.cts.map +1 -0
  13. package/dist/channels/base.d.ts +79 -0
  14. package/dist/channels/base.d.ts.map +1 -0
  15. package/dist/channels/base.js +97 -0
  16. package/dist/channels/base.js.map +1 -0
  17. package/dist/channels/binop.cjs +49 -0
  18. package/dist/channels/binop.cjs.map +1 -0
  19. package/dist/channels/binop.d.cts +22 -0
  20. package/dist/channels/binop.d.cts.map +1 -0
  21. package/dist/channels/binop.d.ts +22 -0
  22. package/dist/channels/binop.d.ts.map +1 -0
  23. package/dist/channels/binop.js +49 -0
  24. package/dist/channels/binop.js.map +1 -0
  25. package/dist/channels/dynamic_barrier_value.cjs +75 -0
  26. package/dist/channels/dynamic_barrier_value.cjs.map +1 -0
  27. package/dist/channels/dynamic_barrier_value.d.cts +40 -0
  28. package/dist/channels/dynamic_barrier_value.d.cts.map +1 -0
  29. package/dist/channels/dynamic_barrier_value.d.ts +40 -0
  30. package/dist/channels/dynamic_barrier_value.d.ts.map +1 -0
  31. package/dist/channels/dynamic_barrier_value.js +75 -0
  32. package/dist/channels/dynamic_barrier_value.js.map +1 -0
  33. package/dist/channels/ephemeral_value.cjs +46 -0
  34. package/dist/channels/ephemeral_value.cjs.map +1 -0
  35. package/dist/channels/ephemeral_value.d.cts +21 -0
  36. package/dist/channels/ephemeral_value.d.cts.map +1 -0
  37. package/dist/channels/ephemeral_value.d.ts +21 -0
  38. package/dist/channels/ephemeral_value.d.ts.map +1 -0
  39. package/dist/channels/ephemeral_value.js +46 -0
  40. package/dist/channels/ephemeral_value.js.map +1 -0
  41. package/dist/channels/index.cjs +21 -0
  42. package/dist/channels/index.d.cts +9 -0
  43. package/dist/channels/index.d.ts +9 -0
  44. package/dist/channels/index.js +10 -0
  45. package/dist/channels/last_value.cjs +98 -0
  46. package/dist/channels/last_value.cjs.map +1 -0
  47. package/dist/channels/last_value.d.cts +42 -0
  48. package/dist/channels/last_value.d.cts.map +1 -0
  49. package/dist/channels/last_value.d.ts +42 -0
  50. package/dist/channels/last_value.d.ts.map +1 -0
  51. package/dist/channels/last_value.js +97 -0
  52. package/dist/channels/last_value.js.map +1 -0
  53. package/dist/channels/named_barrier_value.cjs +116 -0
  54. package/dist/channels/named_barrier_value.cjs.map +1 -0
  55. package/dist/channels/named_barrier_value.d.cts +44 -0
  56. package/dist/channels/named_barrier_value.d.cts.map +1 -0
  57. package/dist/channels/named_barrier_value.d.ts +44 -0
  58. package/dist/channels/named_barrier_value.d.ts.map +1 -0
  59. package/dist/channels/named_barrier_value.js +114 -0
  60. package/dist/channels/named_barrier_value.js.map +1 -0
  61. package/dist/channels/topic.cjs +65 -0
  62. package/dist/channels/topic.cjs.map +1 -0
  63. package/dist/channels/topic.d.cts +32 -0
  64. package/dist/channels/topic.d.cts.map +1 -0
  65. package/dist/channels/topic.d.ts +32 -0
  66. package/dist/channels/topic.d.ts.map +1 -0
  67. package/dist/channels/topic.js +65 -0
  68. package/dist/channels/topic.js.map +1 -0
  69. package/dist/constants.cjs +406 -0
  70. package/dist/constants.cjs.map +1 -0
  71. package/dist/constants.d.cts +281 -0
  72. package/dist/constants.d.cts.map +1 -0
  73. package/dist/constants.d.ts +281 -0
  74. package/dist/constants.d.ts.map +1 -0
  75. package/dist/constants.js +362 -0
  76. package/dist/constants.js.map +1 -0
  77. package/dist/errors.cjs +163 -0
  78. package/dist/errors.cjs.map +1 -0
  79. package/dist/errors.d.cts +77 -0
  80. package/dist/errors.d.cts.map +1 -0
  81. package/dist/errors.d.ts +77 -0
  82. package/dist/errors.d.ts.map +1 -0
  83. package/dist/errors.js +146 -0
  84. package/dist/errors.js.map +1 -0
  85. package/dist/func/index.cjs +299 -0
  86. package/dist/func/index.cjs.map +1 -0
  87. package/dist/func/index.d.cts +288 -0
  88. package/dist/func/index.d.cts.map +1 -0
  89. package/dist/func/index.d.ts +288 -0
  90. package/dist/func/index.d.ts.map +1 -0
  91. package/dist/func/index.js +297 -0
  92. package/dist/func/index.js.map +1 -0
  93. package/dist/func/types.d.cts +62 -0
  94. package/dist/func/types.d.cts.map +1 -0
  95. package/dist/func/types.d.ts +62 -0
  96. package/dist/func/types.d.ts.map +1 -0
  97. package/dist/graph/annotation.cjs +101 -0
  98. package/dist/graph/annotation.cjs.map +1 -0
  99. package/dist/graph/annotation.d.cts +116 -0
  100. package/dist/graph/annotation.d.cts.map +1 -0
  101. package/dist/graph/annotation.d.ts +116 -0
  102. package/dist/graph/annotation.d.ts.map +1 -0
  103. package/dist/graph/annotation.js +99 -0
  104. package/dist/graph/annotation.js.map +1 -0
  105. package/dist/graph/graph.cjs +420 -0
  106. package/dist/graph/graph.cjs.map +1 -0
  107. package/dist/graph/graph.d.cts +108 -0
  108. package/dist/graph/graph.d.cts.map +1 -0
  109. package/dist/graph/graph.d.ts +108 -0
  110. package/dist/graph/graph.d.ts.map +1 -0
  111. package/dist/graph/graph.js +418 -0
  112. package/dist/graph/graph.js.map +1 -0
  113. package/dist/graph/index.cjs +5 -0
  114. package/dist/graph/index.js +7 -0
  115. package/dist/graph/message.cjs +97 -0
  116. package/dist/graph/message.cjs.map +1 -0
  117. package/dist/graph/message.d.cts +40 -0
  118. package/dist/graph/message.d.cts.map +1 -0
  119. package/dist/graph/message.d.ts +40 -0
  120. package/dist/graph/message.d.ts.map +1 -0
  121. package/dist/graph/message.js +94 -0
  122. package/dist/graph/message.js.map +1 -0
  123. package/dist/graph/messages_annotation.cjs +109 -0
  124. package/dist/graph/messages_annotation.cjs.map +1 -0
  125. package/dist/graph/messages_annotation.d.cts +112 -0
  126. package/dist/graph/messages_annotation.d.cts.map +1 -0
  127. package/dist/graph/messages_annotation.d.ts +112 -0
  128. package/dist/graph/messages_annotation.d.ts.map +1 -0
  129. package/dist/graph/messages_annotation.js +107 -0
  130. package/dist/graph/messages_annotation.js.map +1 -0
  131. package/dist/graph/state.cjs +494 -0
  132. package/dist/graph/state.cjs.map +1 -0
  133. package/dist/graph/state.d.cts +229 -0
  134. package/dist/graph/state.d.cts.map +1 -0
  135. package/dist/graph/state.d.ts +229 -0
  136. package/dist/graph/state.d.ts.map +1 -0
  137. package/dist/graph/state.js +493 -0
  138. package/dist/graph/state.js.map +1 -0
  139. package/dist/graph/zod/index.cjs +10 -0
  140. package/dist/graph/zod/index.d.cts +3 -0
  141. package/dist/graph/zod/index.d.ts +3 -0
  142. package/dist/graph/zod/index.js +5 -0
  143. package/dist/graph/zod/meta.cjs +144 -0
  144. package/dist/graph/zod/meta.cjs.map +1 -0
  145. package/dist/graph/zod/meta.d.cts +115 -0
  146. package/dist/graph/zod/meta.d.cts.map +1 -0
  147. package/dist/graph/zod/meta.d.ts +115 -0
  148. package/dist/graph/zod/meta.d.ts.map +1 -0
  149. package/dist/graph/zod/meta.js +141 -0
  150. package/dist/graph/zod/meta.js.map +1 -0
  151. package/dist/graph/zod/plugin.cjs +39 -0
  152. package/dist/graph/zod/plugin.cjs.map +1 -0
  153. package/dist/graph/zod/plugin.js +40 -0
  154. package/dist/graph/zod/plugin.js.map +1 -0
  155. package/dist/graph/zod/schema.cjs +98 -0
  156. package/dist/graph/zod/schema.cjs.map +1 -0
  157. package/dist/graph/zod/schema.d.cts +38 -0
  158. package/dist/graph/zod/schema.d.cts.map +1 -0
  159. package/dist/graph/zod/schema.d.ts +38 -0
  160. package/dist/graph/zod/schema.d.ts.map +1 -0
  161. package/dist/graph/zod/schema.js +94 -0
  162. package/dist/graph/zod/schema.js.map +1 -0
  163. package/dist/graph/zod/zod-registry.cjs +42 -0
  164. package/dist/graph/zod/zod-registry.cjs.map +1 -0
  165. package/dist/graph/zod/zod-registry.d.cts +49 -0
  166. package/dist/graph/zod/zod-registry.d.cts.map +1 -0
  167. package/dist/graph/zod/zod-registry.d.ts +49 -0
  168. package/dist/graph/zod/zod-registry.d.ts.map +1 -0
  169. package/dist/graph/zod/zod-registry.js +41 -0
  170. package/dist/graph/zod/zod-registry.js.map +1 -0
  171. package/dist/hash.cjs +265 -0
  172. package/dist/hash.cjs.map +1 -0
  173. package/dist/hash.js +263 -0
  174. package/dist/hash.js.map +1 -0
  175. package/dist/index.cjs +111 -0
  176. package/dist/index.cjs.map +1 -0
  177. package/dist/index.d.cts +26 -0
  178. package/dist/index.d.ts +26 -0
  179. package/dist/index.js +22 -0
  180. package/dist/index.js.map +1 -0
  181. package/dist/interrupt.cjs +79 -0
  182. package/dist/interrupt.cjs.map +1 -0
  183. package/dist/interrupt.d.cts +55 -0
  184. package/dist/interrupt.d.cts.map +1 -0
  185. package/dist/interrupt.d.ts +55 -0
  186. package/dist/interrupt.d.ts.map +1 -0
  187. package/dist/interrupt.js +79 -0
  188. package/dist/interrupt.js.map +1 -0
  189. package/dist/prebuilt/agentName.cjs +148 -0
  190. package/dist/prebuilt/agentName.cjs.map +1 -0
  191. package/dist/prebuilt/agentName.d.cts +42 -0
  192. package/dist/prebuilt/agentName.d.cts.map +1 -0
  193. package/dist/prebuilt/agentName.d.ts +42 -0
  194. package/dist/prebuilt/agentName.d.ts.map +1 -0
  195. package/dist/prebuilt/agentName.js +148 -0
  196. package/dist/prebuilt/agentName.js.map +1 -0
  197. package/dist/prebuilt/agent_executor.cjs +41 -0
  198. package/dist/prebuilt/agent_executor.cjs.map +1 -0
  199. package/dist/prebuilt/agent_executor.d.cts +58 -0
  200. package/dist/prebuilt/agent_executor.d.cts.map +1 -0
  201. package/dist/prebuilt/agent_executor.d.ts +58 -0
  202. package/dist/prebuilt/agent_executor.d.ts.map +1 -0
  203. package/dist/prebuilt/agent_executor.js +41 -0
  204. package/dist/prebuilt/agent_executor.js.map +1 -0
  205. package/dist/prebuilt/chat_agent_executor.cjs +62 -0
  206. package/dist/prebuilt/chat_agent_executor.cjs.map +1 -0
  207. package/dist/prebuilt/chat_agent_executor.d.cts +23 -0
  208. package/dist/prebuilt/chat_agent_executor.d.cts.map +1 -0
  209. package/dist/prebuilt/chat_agent_executor.d.ts +23 -0
  210. package/dist/prebuilt/chat_agent_executor.d.ts.map +1 -0
  211. package/dist/prebuilt/chat_agent_executor.js +62 -0
  212. package/dist/prebuilt/chat_agent_executor.js.map +1 -0
  213. package/dist/prebuilt/index.cjs +15 -0
  214. package/dist/prebuilt/index.d.cts +8 -0
  215. package/dist/prebuilt/index.d.ts +8 -0
  216. package/dist/prebuilt/index.js +8 -0
  217. package/dist/prebuilt/interrupt.d.cts +60 -0
  218. package/dist/prebuilt/interrupt.d.cts.map +1 -0
  219. package/dist/prebuilt/interrupt.d.ts +60 -0
  220. package/dist/prebuilt/interrupt.d.ts.map +1 -0
  221. package/dist/prebuilt/react_agent_executor.cjs +339 -0
  222. package/dist/prebuilt/react_agent_executor.cjs.map +1 -0
  223. package/dist/prebuilt/react_agent_executor.d.cts +211 -0
  224. package/dist/prebuilt/react_agent_executor.d.cts.map +1 -0
  225. package/dist/prebuilt/react_agent_executor.d.ts +211 -0
  226. package/dist/prebuilt/react_agent_executor.d.ts.map +1 -0
  227. package/dist/prebuilt/react_agent_executor.js +338 -0
  228. package/dist/prebuilt/react_agent_executor.js.map +1 -0
  229. package/dist/prebuilt/tool_executor.cjs +43 -0
  230. package/dist/prebuilt/tool_executor.cjs.map +1 -0
  231. package/dist/prebuilt/tool_executor.d.cts +40 -0
  232. package/dist/prebuilt/tool_executor.d.cts.map +1 -0
  233. package/dist/prebuilt/tool_executor.d.ts +40 -0
  234. package/dist/prebuilt/tool_executor.d.ts.map +1 -0
  235. package/dist/prebuilt/tool_executor.js +43 -0
  236. package/dist/prebuilt/tool_executor.js.map +1 -0
  237. package/dist/prebuilt/tool_node.cjs +247 -0
  238. package/dist/prebuilt/tool_node.cjs.map +1 -0
  239. package/dist/prebuilt/tool_node.d.cts +180 -0
  240. package/dist/prebuilt/tool_node.d.cts.map +1 -0
  241. package/dist/prebuilt/tool_node.d.ts +180 -0
  242. package/dist/prebuilt/tool_node.d.ts.map +1 -0
  243. package/dist/prebuilt/tool_node.js +246 -0
  244. package/dist/prebuilt/tool_node.js.map +1 -0
  245. package/dist/pregel/algo.cjs +565 -0
  246. package/dist/pregel/algo.cjs.map +1 -0
  247. package/dist/pregel/algo.d.cts +13 -0
  248. package/dist/pregel/algo.d.cts.map +1 -0
  249. package/dist/pregel/algo.d.ts +13 -0
  250. package/dist/pregel/algo.d.ts.map +1 -0
  251. package/dist/pregel/algo.js +560 -0
  252. package/dist/pregel/algo.js.map +1 -0
  253. package/dist/pregel/call.cjs +50 -0
  254. package/dist/pregel/call.cjs.map +1 -0
  255. package/dist/pregel/call.js +48 -0
  256. package/dist/pregel/call.js.map +1 -0
  257. package/dist/pregel/debug.cjs +172 -0
  258. package/dist/pregel/debug.cjs.map +1 -0
  259. package/dist/pregel/debug.js +166 -0
  260. package/dist/pregel/debug.js.map +1 -0
  261. package/dist/pregel/index.cjs +1163 -0
  262. package/dist/pregel/index.cjs.map +1 -0
  263. package/dist/pregel/index.d.cts +498 -0
  264. package/dist/pregel/index.d.cts.map +1 -0
  265. package/dist/pregel/index.d.ts +498 -0
  266. package/dist/pregel/index.d.ts.map +1 -0
  267. package/dist/pregel/index.js +1162 -0
  268. package/dist/pregel/index.js.map +1 -0
  269. package/dist/pregel/io.cjs +140 -0
  270. package/dist/pregel/io.cjs.map +1 -0
  271. package/dist/pregel/io.js +135 -0
  272. package/dist/pregel/io.js.map +1 -0
  273. package/dist/pregel/loop.cjs +545 -0
  274. package/dist/pregel/loop.cjs.map +1 -0
  275. package/dist/pregel/loop.js +545 -0
  276. package/dist/pregel/loop.js.map +1 -0
  277. package/dist/pregel/messages.cjs +107 -0
  278. package/dist/pregel/messages.cjs.map +1 -0
  279. package/dist/pregel/messages.js +107 -0
  280. package/dist/pregel/messages.js.map +1 -0
  281. package/dist/pregel/read.cjs +151 -0
  282. package/dist/pregel/read.cjs.map +1 -0
  283. package/dist/pregel/read.d.cts +45 -0
  284. package/dist/pregel/read.d.cts.map +1 -0
  285. package/dist/pregel/read.d.ts +45 -0
  286. package/dist/pregel/read.d.ts.map +1 -0
  287. package/dist/pregel/read.js +150 -0
  288. package/dist/pregel/read.js.map +1 -0
  289. package/dist/pregel/remote.cjs +341 -0
  290. package/dist/pregel/remote.cjs.map +1 -0
  291. package/dist/pregel/remote.d.cts +118 -0
  292. package/dist/pregel/remote.d.cts.map +1 -0
  293. package/dist/pregel/remote.d.ts +118 -0
  294. package/dist/pregel/remote.d.ts.map +1 -0
  295. package/dist/pregel/remote.js +341 -0
  296. package/dist/pregel/remote.js.map +1 -0
  297. package/dist/pregel/retry.cjs +91 -0
  298. package/dist/pregel/retry.cjs.map +1 -0
  299. package/dist/pregel/retry.js +91 -0
  300. package/dist/pregel/retry.js.map +1 -0
  301. package/dist/pregel/runnable_types.d.cts +43 -0
  302. package/dist/pregel/runnable_types.d.cts.map +1 -0
  303. package/dist/pregel/runnable_types.d.ts +43 -0
  304. package/dist/pregel/runnable_types.d.ts.map +1 -0
  305. package/dist/pregel/runner.cjs +228 -0
  306. package/dist/pregel/runner.cjs.map +1 -0
  307. package/dist/pregel/runner.js +228 -0
  308. package/dist/pregel/runner.js.map +1 -0
  309. package/dist/pregel/stream.cjs +197 -0
  310. package/dist/pregel/stream.cjs.map +1 -0
  311. package/dist/pregel/stream.js +195 -0
  312. package/dist/pregel/stream.js.map +1 -0
  313. package/dist/pregel/types.cjs +27 -0
  314. package/dist/pregel/types.cjs.map +1 -0
  315. package/dist/pregel/types.d.cts +440 -0
  316. package/dist/pregel/types.d.cts.map +1 -0
  317. package/dist/pregel/types.d.ts +440 -0
  318. package/dist/pregel/types.d.ts.map +1 -0
  319. package/dist/pregel/types.js +25 -0
  320. package/dist/pregel/types.js.map +1 -0
  321. package/dist/pregel/utils/config.cjs +121 -0
  322. package/dist/pregel/utils/config.cjs.map +1 -0
  323. package/dist/pregel/utils/config.d.cts +36 -0
  324. package/dist/pregel/utils/config.d.cts.map +1 -0
  325. package/dist/pregel/utils/config.d.ts +36 -0
  326. package/dist/pregel/utils/config.d.ts.map +1 -0
  327. package/dist/pregel/utils/config.js +115 -0
  328. package/dist/pregel/utils/config.js.map +1 -0
  329. package/dist/pregel/utils/index.cjs +102 -0
  330. package/dist/pregel/utils/index.cjs.map +1 -0
  331. package/dist/pregel/utils/index.d.cts +51 -0
  332. package/dist/pregel/utils/index.d.cts.map +1 -0
  333. package/dist/pregel/utils/index.d.ts +51 -0
  334. package/dist/pregel/utils/index.d.ts.map +1 -0
  335. package/dist/pregel/utils/index.js +96 -0
  336. package/dist/pregel/utils/index.js.map +1 -0
  337. package/dist/pregel/utils/subgraph.cjs +18 -0
  338. package/dist/pregel/utils/subgraph.cjs.map +1 -0
  339. package/dist/pregel/utils/subgraph.js +16 -0
  340. package/dist/pregel/utils/subgraph.js.map +1 -0
  341. package/dist/pregel/validate.cjs +45 -0
  342. package/dist/pregel/validate.cjs.map +1 -0
  343. package/dist/pregel/validate.js +44 -0
  344. package/dist/pregel/validate.js.map +1 -0
  345. package/dist/pregel/write.cjs +96 -0
  346. package/dist/pregel/write.cjs.map +1 -0
  347. package/dist/pregel/write.d.cts +31 -0
  348. package/dist/pregel/write.d.cts.map +1 -0
  349. package/dist/pregel/write.d.ts +31 -0
  350. package/dist/pregel/write.d.ts.map +1 -0
  351. package/dist/pregel/write.js +95 -0
  352. package/dist/pregel/write.js.map +1 -0
  353. package/dist/remote.cjs +3 -0
  354. package/dist/remote.d.cts +2 -0
  355. package/dist/remote.d.ts +2 -0
  356. package/dist/remote.js +3 -0
  357. package/dist/setup/async_local_storage.cjs +11 -0
  358. package/dist/setup/async_local_storage.cjs.map +1 -0
  359. package/dist/setup/async_local_storage.js +11 -0
  360. package/dist/setup/async_local_storage.js.map +1 -0
  361. package/dist/utils.cjs +86 -0
  362. package/dist/utils.cjs.map +1 -0
  363. package/dist/utils.d.cts +25 -0
  364. package/dist/utils.d.cts.map +1 -0
  365. package/dist/utils.d.ts +25 -0
  366. package/dist/utils.d.ts.map +1 -0
  367. package/dist/utils.js +80 -0
  368. package/dist/utils.js.map +1 -0
  369. package/dist/web.cjs +95 -0
  370. package/dist/web.d.cts +23 -0
  371. package/dist/web.d.ts +23 -0
  372. package/dist/web.js +15 -0
  373. package/dist/writer.cjs +14 -0
  374. package/dist/writer.cjs.map +1 -0
  375. package/dist/writer.d.cts +6 -0
  376. package/dist/writer.d.cts.map +1 -0
  377. package/dist/writer.d.ts +6 -0
  378. package/dist/writer.d.ts.map +1 -0
  379. package/dist/writer.js +14 -0
  380. package/dist/writer.js.map +1 -0
  381. package/package.json +2 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"react_agent_executor.js","names":["model","llm","prompt"],"sources":["../../src/prebuilt/react_agent_executor.ts"],"sourcesContent":["import {\n BaseChatModel,\n BindToolsInput,\n} from \"@langchain/core/language_models/chat_models\";\nimport { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport {\n BaseMessage,\n BaseMessageLike,\n isAIMessage,\n isBaseMessage,\n isToolMessage,\n SystemMessage,\n type AIMessage,\n} from \"@langchain/core/messages\";\nimport {\n Runnable,\n RunnableLambda,\n RunnableToolLike,\n RunnableSequence,\n RunnableBinding,\n type RunnableLike,\n} from \"@langchain/core/runnables\";\nimport { DynamicTool, StructuredToolInterface } from \"@langchain/core/tools\";\nimport type {\n InteropZodObject,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\nimport {\n All,\n BaseCheckpointSaver,\n BaseStore,\n} from \"@langchain/langgraph-checkpoint\";\n\nimport {\n StateGraph,\n type CompiledStateGraph,\n AnnotationRoot,\n} from \"../graph/index.js\";\nimport { MessagesAnnotation } from \"../graph/messages_annotation.js\";\nimport { ToolNode } from \"./tool_node.js\";\nimport { LangGraphRunnableConfig, Runtime } from \"../pregel/runnable_types.js\";\nimport { Annotation } from \"../graph/annotation.js\";\nimport { Messages, messagesStateReducer } from \"../graph/message.js\";\nimport { END, Send, START } from \"../constants.js\";\nimport { withAgentName } from \"./agentName.js\";\nimport type { InteropZodToStateDefinition } from \"../graph/zod/meta.js\";\n\n/**\n * @deprecated `AgentState` has been moved to {@link https://www.npmjs.com/package/langchain langchain} package.\n * Update your import to `import { AgentState } from \"langchain\";`\n */\nexport interface AgentState<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n StructuredResponseType extends Record<string, any> = Record<string, any>\n> {\n messages: BaseMessage[];\n // TODO: This won't be set until we\n // implement managed values in LangGraphJS\n // Will be useful for inserting a message on\n // graph recursion end\n // is_last_step: boolean;\n structuredResponse: StructuredResponseType;\n}\n\nexport type N = typeof START | \"agent\" | \"tools\";\n\ntype StructuredResponseSchemaOptions<StructuredResponseType> = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schema: InteropZodType<StructuredResponseType> | Record<string, any>;\n prompt?: string;\n\n strict?: boolean;\n [key: string]: unknown;\n};\n\nfunction _convertMessageModifierToPrompt(\n messageModifier: MessageModifier\n): Prompt {\n // Handle string or SystemMessage\n if (\n typeof messageModifier === \"string\" ||\n (isBaseMessage(messageModifier) && messageModifier._getType() === \"system\")\n ) {\n return messageModifier;\n }\n\n // Handle callable function\n if (typeof messageModifier === \"function\") {\n return async (state: typeof MessagesAnnotation.State) =>\n messageModifier(state.messages);\n }\n\n // Handle Runnable\n if (Runnable.isRunnable(messageModifier)) {\n return RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => state.messages\n ).pipe(messageModifier);\n }\n\n throw new Error(\n `Unexpected type for messageModifier: ${typeof messageModifier}`\n );\n}\n\nconst PROMPT_RUNNABLE_NAME = \"prompt\";\n\nfunction _getPromptRunnable(prompt?: Prompt): Runnable {\n let promptRunnable: Runnable;\n\n if (prompt == null) {\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => state.messages\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else if (typeof prompt === \"string\") {\n const systemMessage = new SystemMessage(prompt);\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => {\n return [systemMessage, ...(state.messages ?? [])];\n }\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else if (isBaseMessage(prompt) && prompt._getType() === \"system\") {\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => [prompt, ...state.messages]\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else if (typeof prompt === \"function\") {\n promptRunnable = RunnableLambda.from(prompt).withConfig({\n runName: PROMPT_RUNNABLE_NAME,\n });\n } else if (Runnable.isRunnable(prompt)) {\n promptRunnable = prompt;\n } else {\n throw new Error(`Got unexpected type for 'prompt': ${typeof prompt}`);\n }\n\n return promptRunnable;\n}\n\ntype ServerTool = Record<string, unknown>;\ntype ClientTool = StructuredToolInterface | DynamicTool | RunnableToolLike;\n\nfunction isClientTool(tool: ClientTool | ServerTool): tool is ClientTool {\n return Runnable.isRunnable(tool);\n}\n\nfunction _getPrompt(\n prompt?: Prompt,\n stateModifier?: CreateReactAgentParams[\"stateModifier\"],\n messageModifier?: CreateReactAgentParams[\"messageModifier\"]\n): Runnable {\n // Check if multiple modifiers exist\n const definedCount = [prompt, stateModifier, messageModifier].filter(\n (x) => x != null\n ).length;\n if (definedCount > 1) {\n throw new Error(\n \"Expected only one of prompt, stateModifier, or messageModifier, got multiple values\"\n );\n }\n\n let finalPrompt = prompt;\n if (stateModifier != null) {\n finalPrompt = stateModifier;\n } else if (messageModifier != null) {\n finalPrompt = _convertMessageModifierToPrompt(messageModifier);\n }\n\n return _getPromptRunnable(finalPrompt);\n}\n\nfunction _isBaseChatModel(model: LanguageModelLike): model is BaseChatModel {\n return (\n \"invoke\" in model &&\n typeof model.invoke === \"function\" &&\n \"_modelType\" in model\n );\n}\n\ninterface ConfigurableModelInterface {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _queuedMethodOperations: Record<string, any>;\n _model: () => Promise<BaseChatModel>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _isConfigurableModel(model: any): model is ConfigurableModelInterface {\n return (\n \"_queuedMethodOperations\" in model &&\n \"_model\" in model &&\n typeof model._model === \"function\"\n );\n}\n\nfunction _isChatModelWithBindTools(\n llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n if (!_isBaseChatModel(llm)) return false;\n return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\nexport async function _shouldBindTools(\n llm: LanguageModelLike,\n tools: (ClientTool | ServerTool)[]\n): Promise<boolean> {\n // If model is a RunnableSequence, find a RunnableBinding or BaseChatModel in its steps\n let model = llm;\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n _isBaseChatModel(step) ||\n _isConfigurableModel(step)\n ) || model;\n }\n\n if (_isConfigurableModel(model)) {\n model = await model._model();\n }\n\n // If not a RunnableBinding, we should bind tools\n if (!RunnableBinding.isRunnableBinding(model)) {\n return true;\n }\n\n let boundTools = (() => {\n // check if model.kwargs contain the tools key\n if (\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools)\n ) {\n return (model.kwargs.tools ?? null) as BindToolsInput[] | null;\n }\n\n // Some models can bind the tools via `withConfig()` instead of `bind()`\n if (\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools)\n ) {\n return (model.config.tools ?? null) as BindToolsInput[] | null;\n }\n\n return null;\n })();\n\n // google-style\n if (\n boundTools != null &&\n boundTools.length === 1 &&\n \"functionDeclarations\" in boundTools[0]\n ) {\n boundTools = boundTools[0].functionDeclarations;\n }\n\n // If no tools in kwargs, we should bind tools\n if (boundTools == null) return true;\n\n // Check if tools count matches\n if (tools.length !== boundTools.length) {\n throw new Error(\n \"Number of tools in the model.bindTools() and tools passed to createReactAgent must match\"\n );\n }\n\n const toolNames = new Set<string>(\n tools.flatMap((tool) => (isClientTool(tool) ? tool.name : []))\n );\n\n const boundToolNames = new Set<string>();\n\n for (const boundTool of boundTools) {\n let boundToolName: string | undefined;\n\n // OpenAI-style tool\n if (\"type\" in boundTool && boundTool.type === \"function\") {\n boundToolName = boundTool.function.name;\n }\n // Anthropic or Google-style tool\n else if (\"name\" in boundTool) {\n boundToolName = boundTool.name;\n }\n // Bedrock-style tool\n else if (\"toolSpec\" in boundTool && \"name\" in boundTool.toolSpec) {\n boundToolName = boundTool.toolSpec.name;\n }\n // unknown tool type so we'll ignore it\n else {\n continue;\n }\n\n if (boundToolName) {\n boundToolNames.add(boundToolName);\n }\n }\n\n const missingTools = [...toolNames].filter((x) => !boundToolNames.has(x));\n if (missingTools.length > 0) {\n throw new Error(\n `Missing tools '${missingTools}' in the model.bindTools().` +\n `Tools in the model.bindTools() must match the tools passed to createReactAgent.`\n );\n }\n\n return false;\n}\n\nconst _simpleBindTools = (\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[]\n) => {\n if (_isChatModelWithBindTools(llm)) {\n return llm.bindTools(toolClasses);\n }\n\n if (\n RunnableBinding.isRunnableBinding(llm) &&\n _isChatModelWithBindTools(llm.bound)\n ) {\n const newBound = llm.bound.bindTools(toolClasses);\n\n if (RunnableBinding.isRunnableBinding(newBound)) {\n return new RunnableBinding({\n bound: newBound.bound,\n config: { ...llm.config, ...newBound.config },\n kwargs: { ...llm.kwargs, ...newBound.kwargs },\n configFactories: newBound.configFactories ?? llm.configFactories,\n });\n }\n\n return new RunnableBinding({\n bound: newBound,\n config: llm.config,\n kwargs: llm.kwargs,\n configFactories: llm.configFactories,\n });\n }\n\n return null;\n};\n\nexport async function _bindTools(\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[]\n) {\n const model = _simpleBindTools(llm, toolClasses);\n if (model) return model;\n\n if (_isConfigurableModel(llm)) {\n const model = _simpleBindTools(await llm._model(), toolClasses);\n if (model) return model;\n }\n\n if (RunnableSequence.isRunnableSequence(llm)) {\n const modelStep = llm.steps.findIndex(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n _isBaseChatModel(step) ||\n _isConfigurableModel(step)\n );\n\n if (modelStep >= 0) {\n const model = _simpleBindTools(llm.steps[modelStep], toolClasses);\n if (model) {\n const nextSteps: unknown[] = llm.steps.slice();\n nextSteps.splice(modelStep, 1, model);\n\n return RunnableSequence.from(\n nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n );\n }\n }\n }\n\n throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\nexport async function _getModel(\n llm: LanguageModelLike | ConfigurableModelInterface\n): Promise<LanguageModelLike> {\n // If model is a RunnableSequence, find a RunnableBinding or BaseChatModel in its steps\n let model = llm;\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n _isBaseChatModel(step) ||\n _isConfigurableModel(step)\n ) || model;\n }\n\n if (_isConfigurableModel(model)) {\n model = await model._model();\n }\n\n // Get the underlying model from a RunnableBinding\n if (RunnableBinding.isRunnableBinding(model)) {\n model = model.bound;\n }\n\n if (!_isBaseChatModel(model)) {\n throw new Error(\n `Expected \\`llm\\` to be a ChatModel or RunnableBinding (e.g. llm.bind_tools(...)) with invoke() and generate() methods, got ${model.constructor.name}`\n );\n }\n\n return model;\n}\n\nexport type Prompt =\n | SystemMessage\n | string\n | ((\n state: typeof MessagesAnnotation.State,\n config: LangGraphRunnableConfig\n ) => BaseMessageLike[])\n | ((\n state: typeof MessagesAnnotation.State,\n config: LangGraphRunnableConfig\n ) => Promise<BaseMessageLike[]>)\n | Runnable;\n\n/** @deprecated Use Prompt instead. */\nexport type StateModifier = Prompt;\n\n/** @deprecated Use Prompt instead. */\nexport type MessageModifier =\n | SystemMessage\n | string\n | ((messages: BaseMessage[]) => BaseMessage[])\n | ((messages: BaseMessage[]) => Promise<BaseMessage[]>)\n | Runnable;\n\nexport const createReactAgentAnnotation = <\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>\n>() =>\n Annotation.Root({\n messages: Annotation<BaseMessage[], Messages>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n structuredResponse: Annotation<T>,\n });\n\ntype WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<\n infer SD,\n infer S,\n infer U,\n infer N,\n infer I,\n infer O,\n infer C\n>\n ? StateGraph<SD, S, U, N | K, I, O, C>\n : never;\n\nconst PreHookAnnotation = Annotation.Root({\n llmInputMessages: Annotation<BaseMessage[], Messages>({\n reducer: (_, update) => messagesStateReducer([], update),\n default: () => [],\n }),\n});\n\ntype PreHookAnnotation = typeof PreHookAnnotation;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyAnnotationRoot = AnnotationRoot<any>;\n\ntype ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> =\n A extends AnyAnnotationRoot\n ? A\n : A extends InteropZodObject\n ? AnnotationRoot<InteropZodToStateDefinition<A>>\n : never;\n\n/**\n * @deprecated `CreateReactAgentParams` has been moved to {@link https://www.npmjs.com/package/langchain langchain} package.\n * Update your import to `import { CreateAgentParams } from \"langchain\";`\n */\nexport type CreateReactAgentParams<\n A extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n StructuredResponseType extends Record<string, any> = Record<string, any>,\n C extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> = {\n /** The chat model that can utilize OpenAI-style tool calling. */\n llm:\n | LanguageModelLike\n | ((\n state: ToAnnotationRoot<A>[\"State\"] & PreHookAnnotation[\"State\"],\n runtime: Runtime<ToAnnotationRoot<C>[\"State\"]>\n ) => Promise<LanguageModelLike> | LanguageModelLike);\n\n /** A list of tools or a ToolNode. */\n tools: ToolNode | (ServerTool | ClientTool)[];\n\n /**\n * @deprecated Use prompt instead.\n */\n messageModifier?: MessageModifier;\n\n /**\n * @deprecated Use prompt instead.\n */\n stateModifier?: StateModifier;\n\n /**\n * An optional prompt for the LLM. This takes full graph state BEFORE the LLM is called and prepares the input to LLM.\n *\n * Can take a few different forms:\n *\n * - str: This is converted to a SystemMessage and added to the beginning of the list of messages in state[\"messages\"].\n * - SystemMessage: this is added to the beginning of the list of messages in state[\"messages\"].\n * - Function: This function should take in full graph state and the output is then passed to the language model.\n * - Runnable: This runnable should take in full graph state and the output is then passed to the language model.\n *\n * Note:\n * Prior to `v0.2.46`, the prompt was set using `stateModifier` / `messagesModifier` parameters.\n * This is now deprecated and will be removed in a future release.\n */\n prompt?: Prompt;\n\n /**\n * Additional state schema for the agent.\n */\n stateSchema?: A;\n\n /**\n * An optional schema for the context.\n */\n contextSchema?: C;\n /** An optional checkpoint saver to persist the agent's state. */\n checkpointSaver?: BaseCheckpointSaver | boolean;\n /** An optional checkpoint saver to persist the agent's state. Alias of \"checkpointSaver\". */\n checkpointer?: BaseCheckpointSaver | boolean;\n /** An optional list of node names to interrupt before running. */\n interruptBefore?: N[] | All;\n /** An optional list of node names to interrupt after running. */\n interruptAfter?: N[] | All;\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * - JSON schema\n * - { prompt, schema }, where schema is one of the above.\n * The prompt will be used together with the model that is being used to generate the structured response.\n *\n * @remarks\n * **Important**: `responseFormat` requires the model to support `.withStructuredOutput()`.\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?:\n | InteropZodType<StructuredResponseType>\n | StructuredResponseSchemaOptions<StructuredResponseType>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>;\n\n /**\n * An optional name for the agent.\n */\n name?: string;\n\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string | undefined;\n\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n\n - undefined: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n\n /**\n * An optional node to add before the `agent` node (i.e., the node that calls the LLM).\n * Useful for managing long message histories (e.g., message trimming, summarization, etc.).\n */\n preModelHook?: RunnableLike<\n ToAnnotationRoot<A>[\"State\"] & PreHookAnnotation[\"State\"],\n ToAnnotationRoot<A>[\"Update\"] & PreHookAnnotation[\"Update\"],\n LangGraphRunnableConfig\n >;\n\n /**\n * An optional node to add after the `agent` node (i.e., the node that calls the LLM).\n * Useful for implementing human-in-the-loop, guardrails, validation, or other post-processing.\n */\n postModelHook?: RunnableLike<\n ToAnnotationRoot<A>[\"State\"],\n ToAnnotationRoot<A>[\"Update\"],\n LangGraphRunnableConfig\n >;\n\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v1\"`\n */\n version?: \"v1\" | \"v2\";\n};\n\n/**\n * @deprecated `createReactAgent` has been moved to {@link https://www.npmjs.com/package/langchain langchain} package.\n * Update your import to `import { createAgent } from \"langchain\";`\n *\n * Creates a StateGraph agent that relies on a chat model utilizing tool calling.\n *\n * @example\n * ```ts\n * import { ChatOpenAI } from \"@langchain/openai\";\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n * import { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n *\n * const model = new ChatOpenAI({\n * model: \"gpt-4o\",\n * });\n *\n * const getWeather = tool((input) => {\n * if ([\"sf\", \"san francisco\"].includes(input.location.toLowerCase())) {\n * return \"It's 60 degrees and foggy.\";\n * } else {\n * return \"It's 90 degrees and sunny.\";\n * }\n * }, {\n * name: \"get_weather\",\n * description: \"Call to get the current weather.\",\n * schema: z.object({\n * location: z.string().describe(\"Location to get the weather for.\"),\n * })\n * })\n *\n * const agent = createReactAgent({ llm: model, tools: [getWeather] });\n *\n * const inputs = {\n * messages: [{ role: \"user\", content: \"what is the weather in SF?\" }],\n * };\n *\n * const stream = await agent.stream(inputs, { streamMode: \"values\" });\n *\n * for await (const { messages } of stream) {\n * console.log(messages);\n * }\n * // Returns the messages in the state at each step of execution\n * ```\n */\nexport function createReactAgent<\n A extends AnyAnnotationRoot | InteropZodObject = typeof MessagesAnnotation,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n C extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n>(\n params: CreateReactAgentParams<A, StructuredResponseFormat, C>\n): CompiledStateGraph<\n ToAnnotationRoot<A>[\"State\"],\n ToAnnotationRoot<A>[\"Update\"],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n typeof MessagesAnnotation.spec & ToAnnotationRoot<A>[\"spec\"],\n ReturnType<\n typeof createReactAgentAnnotation<StructuredResponseFormat>\n >[\"spec\"] &\n ToAnnotationRoot<A>[\"spec\"]\n> {\n const {\n llm,\n tools,\n messageModifier,\n stateModifier,\n prompt,\n stateSchema,\n contextSchema,\n checkpointSaver,\n checkpointer,\n interruptBefore,\n interruptAfter,\n store,\n responseFormat,\n preModelHook,\n postModelHook,\n name,\n description,\n version = \"v1\",\n includeAgentName,\n } = params;\n\n let toolClasses: (ClientTool | ServerTool)[];\n\n let toolNode: ToolNode;\n if (!Array.isArray(tools)) {\n toolClasses = tools.tools;\n toolNode = tools;\n } else {\n toolClasses = tools;\n toolNode = new ToolNode(toolClasses.filter(isClientTool));\n }\n\n let cachedStaticModel: Runnable | null = null;\n\n const _getStaticModel = async (llm: LanguageModelLike): Promise<Runnable> => {\n if (cachedStaticModel) return cachedStaticModel;\n\n let modelWithTools: LanguageModelLike;\n if (await _shouldBindTools(llm, toolClasses)) {\n modelWithTools = await _bindTools(llm, toolClasses);\n } else {\n modelWithTools = llm;\n }\n\n const promptRunnable = _getPrompt(prompt, stateModifier, messageModifier);\n const modelRunnable =\n includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, includeAgentName)\n : modelWithTools;\n\n cachedStaticModel = promptRunnable.pipe(modelRunnable);\n return cachedStaticModel;\n };\n\n const _getDynamicModel = async (\n llm: (\n state: AgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n runtime: Runtime<ToAnnotationRoot<C>[\"State\"]>\n ) => Promise<LanguageModelLike> | LanguageModelLike,\n state: AgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n config: Runtime<ToAnnotationRoot<C>[\"State\"]>\n ) => {\n const model = await llm(state, config);\n\n return _getPrompt(prompt, stateModifier, messageModifier).pipe(\n includeAgentName === \"inline\"\n ? withAgentName(model, includeAgentName)\n : model\n );\n };\n\n // If any of the tools are configured to return_directly after running,\n // our graph needs to check if these were called\n const shouldReturnDirect = new Set(\n toolClasses\n .filter(isClientTool)\n .filter((tool) => \"returnDirect\" in tool && tool.returnDirect)\n .map((tool) => tool.name)\n );\n\n function getModelInputState(\n state: AgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"]\n ): Omit<AgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages != null && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest };\n }\n return { messages, ...rest };\n }\n\n const generateStructuredResponse = async (\n state: AgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n config: Runtime<ToAnnotationRoot<C>[\"State\"]>\n ) => {\n if (responseFormat == null) {\n throw new Error(\n \"Attempted to generate structured output with no passed response schema. Please contact us for help.\"\n );\n }\n const messages = [...state.messages];\n let modelWithStructuredOutput;\n\n const model: LanguageModelLike =\n typeof llm === \"function\"\n ? await llm(state, config)\n : await _getModel(llm);\n\n if (!_isBaseChatModel(model)) {\n throw new Error(\n `Expected \\`llm\\` to be a ChatModel with .withStructuredOutput() method, got ${model.constructor.name}`\n );\n }\n\n if (typeof responseFormat === \"object\" && \"schema\" in responseFormat) {\n const { prompt, schema, ...options } =\n responseFormat as StructuredResponseSchemaOptions<StructuredResponseFormat>;\n\n modelWithStructuredOutput = model.withStructuredOutput(schema, options);\n if (prompt != null) {\n messages.unshift(new SystemMessage({ content: prompt }));\n }\n } else {\n modelWithStructuredOutput = model.withStructuredOutput(responseFormat);\n }\n\n const response = await modelWithStructuredOutput.invoke(messages, config);\n return { structuredResponse: response };\n };\n\n const callModel = async (\n state: AgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n config: Runtime<ToAnnotationRoot<C>[\"State\"]>\n ) => {\n // NOTE: we're dynamically creating the model runnable here\n // to ensure that we can validate ConfigurableModel properly\n const modelRunnable: Runnable =\n typeof llm === \"function\"\n ? await _getDynamicModel(llm, state, config)\n : await _getStaticModel(llm);\n\n // TODO: Auto-promote streaming.\n const response = (await modelRunnable.invoke(\n getModelInputState(state),\n config\n )) as BaseMessage;\n // add agent name to the AIMessage\n // TODO: figure out if we can avoid mutating the message directly\n response.name = name;\n response.lc_kwargs.name = name;\n return { messages: [response] };\n };\n\n const schema =\n stateSchema ?? createReactAgentAnnotation<StructuredResponseFormat>();\n\n const workflow = new StateGraph(\n schema as AnyAnnotationRoot,\n contextSchema\n ).addNode(\"tools\", toolNode);\n\n if (!(\"messages\" in workflow._schemaDefinition)) {\n throw new Error(\"Missing required `messages` key in state schema.\");\n }\n\n const allNodeWorkflows = workflow as WithStateGraphNodes<\n | \"pre_model_hook\"\n | \"post_model_hook\"\n | \"generate_structured_response\"\n | \"agent\",\n typeof workflow\n >;\n\n const conditionalMap = <T extends string>(map: Record<string, T | null>) => {\n return Object.fromEntries(\n Object.entries(map).filter(([_, v]) => v != null) as [string, T][]\n );\n };\n\n let entrypoint: \"agent\" | \"pre_model_hook\" = \"agent\";\n let inputSchema: AnnotationRoot<ToAnnotationRoot<A>[\"spec\"]> | undefined;\n if (preModelHook != null) {\n allNodeWorkflows\n .addNode(\"pre_model_hook\", preModelHook)\n .addEdge(\"pre_model_hook\", \"agent\");\n entrypoint = \"pre_model_hook\";\n\n inputSchema = Annotation.Root({\n ...workflow._schemaDefinition,\n ...PreHookAnnotation.spec,\n });\n } else {\n entrypoint = \"agent\";\n }\n\n allNodeWorkflows\n .addNode(\"agent\", callModel, { input: inputSchema })\n .addEdge(START, entrypoint);\n\n if (postModelHook != null) {\n allNodeWorkflows\n .addNode(\"post_model_hook\", postModelHook)\n .addEdge(\"agent\", \"post_model_hook\")\n .addConditionalEdges(\n \"post_model_hook\",\n (state: AgentState<StructuredResponseFormat>) => {\n const { messages } = state;\n\n const toolMessageIds: Set<string> = new Set(\n messages.filter(isToolMessage).map((msg) => msg.tool_call_id)\n );\n\n let lastAiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (isAIMessage(message)) {\n lastAiMessage = message;\n break;\n }\n }\n\n const pendingToolCalls =\n lastAiMessage?.tool_calls?.filter(\n (i) => i.id == null || !toolMessageIds.has(i.id)\n ) ?? [];\n\n const lastMessage = messages.at(-1);\n if (pendingToolCalls.length > 0) {\n if (version === \"v2\") {\n return pendingToolCalls.map(\n (toolCall) =>\n new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n }\n return \"tools\";\n }\n\n if (lastMessage && isToolMessage(lastMessage)) return entrypoint;\n if (responseFormat != null) return \"generate_structured_response\";\n return END;\n },\n conditionalMap({\n tools: \"tools\",\n [entrypoint]: entrypoint,\n generate_structured_response:\n responseFormat != null ? \"generate_structured_response\" : null,\n [END]: responseFormat != null ? null : END,\n })\n );\n }\n\n if (responseFormat !== undefined) {\n workflow\n .addNode(\"generate_structured_response\", generateStructuredResponse)\n .addEdge(\"generate_structured_response\", END);\n }\n\n if (postModelHook == null) {\n allNodeWorkflows.addConditionalEdges(\n \"agent\",\n (state: AgentState<StructuredResponseFormat>) => {\n const { messages } = state;\n const lastMessage = messages[messages.length - 1];\n\n // if there's no function call, we finish\n if (!isAIMessage(lastMessage) || !lastMessage.tool_calls?.length) {\n if (responseFormat != null) return \"generate_structured_response\";\n return END;\n }\n\n // there are function calls, we continue\n if (version === \"v2\") {\n return lastMessage.tool_calls.map(\n (toolCall) =>\n new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n }\n\n return \"tools\";\n },\n conditionalMap({\n tools: \"tools\",\n generate_structured_response:\n responseFormat != null ? \"generate_structured_response\" : null,\n [END]: responseFormat != null ? null : END,\n })\n );\n }\n\n if (shouldReturnDirect.size > 0) {\n allNodeWorkflows.addConditionalEdges(\n \"tools\",\n (state: AgentState<StructuredResponseFormat>) => {\n // Check the last consecutive tool calls\n for (let i = state.messages.length - 1; i >= 0; i -= 1) {\n const message = state.messages[i];\n if (!isToolMessage(message)) break;\n\n // Check if this tool is configured to return directly\n if (\n message.name !== undefined &&\n shouldReturnDirect.has(message.name)\n ) {\n return END;\n }\n }\n\n return entrypoint;\n },\n conditionalMap({ [entrypoint]: entrypoint, [END]: END })\n );\n } else {\n allNodeWorkflows.addEdge(\"tools\", entrypoint);\n }\n\n return allNodeWorkflows.compile({\n checkpointer: checkpointer ?? checkpointSaver,\n interruptBefore,\n interruptAfter,\n store,\n name,\n description,\n });\n}\n"],"mappings":";;;;;;;;;;;AA2EA,SAAS,gCACP,iBACQ;AAER,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CAAC,YAAY,YAAY,IAAI,CAAC,YAAY,YAAY,QAAQ;AAChE,OAAI,kBAAkB,KAAM,QAAO;AACnC,UAAO;;AAIT,MAAI,YAAY,KACd,QAAO,YAAY,WAAW,KAC3B,aACC,IAAI,KAAK,SAAS;GAAE,GAAG;GAAO,cAAc;GAAU,CAAC,CAC1D;AAGH,SAAO;IAET,eAAe;EACb,OAAO;EACP,8BACE,kBAAkB,OAAO,iCAAiC;GAC3D,MAAM,kBAAkB,OAAO,OAAO;EACxC,CAAC,CACH;AAGH,KAAI,mBAAmB,OAAO,EAC5B,kBAAiB,oBACf,UACC,UAAgD;AAE/C,OAAK,IAAI,IAAI,MAAM,SAAS,SAAS,GAAG,KAAK,GAAG,KAAK,GAAG;GACtD,MAAM,UAAU,MAAM,SAAS;AAC/B,OAAI,CAAC,cAAc,QAAQ,CAAE;AAG7B,OACE,QAAQ,SAAS,UACjB,mBAAmB,IAAI,QAAQ,KAAK,CAEpC,QAAO;;AAIX,SAAO;IAET,eAAe;GAAG,aAAa;GAAa,MAAM;EAAK,CAAC,CACzD;KAED,kBAAiB,QAAQ,SAAS,WAAW;AAG/C,QAAO,iBAAiB,QAAQ;EAC9B,cAAc,gBAAgB;EAC9B;EACA;EACA;EACA;EACA;EACD,CAAC"}
@@ -0,0 +1,43 @@
1
+ let _langchain_core_runnables = require("@langchain/core/runnables");
2
+
3
+ //#region src/prebuilt/tool_executor.ts
4
+ const INVALID_TOOL_MSG_TEMPLATE = `{requestedToolName} is not a valid tool, try one of {availableToolNamesString}.`;
5
+ /** @deprecated Use {@link ToolNode} instead. */
6
+ var ToolExecutor = class extends _langchain_core_runnables.RunnableBinding {
7
+ lc_graph_name = "ToolExecutor";
8
+ tools;
9
+ toolMap;
10
+ invalidToolMsgTemplate;
11
+ constructor(fields) {
12
+ const fieldsWithDefaults = {
13
+ invalidToolMsgTemplate: INVALID_TOOL_MSG_TEMPLATE,
14
+ ...fields
15
+ };
16
+ const bound = _langchain_core_runnables.RunnableLambda.from(async (input, config) => this._execute(input, config));
17
+ super({
18
+ bound,
19
+ config: {}
20
+ });
21
+ this.tools = fieldsWithDefaults.tools;
22
+ this.invalidToolMsgTemplate = fieldsWithDefaults.invalidToolMsgTemplate;
23
+ this.toolMap = this.tools.reduce((acc, tool) => {
24
+ acc[tool.name] = tool;
25
+ return acc;
26
+ }, {});
27
+ }
28
+ /**
29
+ * Execute a tool invocation
30
+ *
31
+ * @param {ToolInvocationInterface} toolInvocation The tool to invoke and the input to pass to it.
32
+ * @param {RunnableConfig | undefined} config Optional configuration to pass to the tool when invoked.
33
+ * @returns Either the result of the tool invocation (`string` or `ToolMessage`, set by the `ToolOutput` generic) or a string error message.
34
+ */
35
+ async _execute(toolInvocation, config) {
36
+ if (!(toolInvocation.tool in this.toolMap)) return this.invalidToolMsgTemplate.replace("{requestedToolName}", toolInvocation.tool).replace("{availableToolNamesString}", Object.keys(this.toolMap).join(", "));
37
+ else return await this.toolMap[toolInvocation.tool].invoke(toolInvocation.toolInput, config);
38
+ }
39
+ };
40
+
41
+ //#endregion
42
+ exports.ToolExecutor = ToolExecutor;
43
+ //# sourceMappingURL=tool_executor.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool_executor.cjs","names":["RunnableBinding","RunnableLambda"],"sources":["../../src/prebuilt/tool_executor.ts"],"sourcesContent":["import {\n RunnableBinding,\n RunnableConfig,\n RunnableLambda,\n RunnableToolLike,\n} from \"@langchain/core/runnables\";\nimport { StructuredToolInterface } from \"@langchain/core/tools\";\n\nconst INVALID_TOOL_MSG_TEMPLATE = `{requestedToolName} is not a valid tool, try one of {availableToolNamesString}.`;\n\n/** @deprecated Use {@link ToolNode} instead. */\nexport interface ToolExecutorArgs {\n tools: Array<StructuredToolInterface | RunnableToolLike>;\n /**\n * @default {INVALID_TOOL_MSG_TEMPLATE}\n */\n invalidToolMsgTemplate?: string;\n}\n\n/**\n * Interface for invoking a tool\n */\nexport interface ToolInvocationInterface {\n tool: string;\n toolInput: string;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype ToolExecutorInputType = any;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype ToolExecutorOutputType = any;\n\n/** @deprecated Use {@link ToolNode} instead. */\nexport class ToolExecutor extends RunnableBinding<\n ToolExecutorInputType,\n ToolExecutorOutputType\n> {\n lc_graph_name = \"ToolExecutor\";\n\n tools: Array<StructuredToolInterface | RunnableToolLike>;\n\n toolMap: Record<string, StructuredToolInterface | RunnableToolLike>;\n\n invalidToolMsgTemplate: string;\n\n constructor(fields: ToolExecutorArgs) {\n const fieldsWithDefaults = {\n invalidToolMsgTemplate: INVALID_TOOL_MSG_TEMPLATE,\n ...fields,\n };\n const bound = RunnableLambda.from(\n async (input: ToolInvocationInterface, config?: RunnableConfig) =>\n this._execute(input, config)\n );\n super({\n bound,\n config: {},\n });\n this.tools = fieldsWithDefaults.tools;\n this.invalidToolMsgTemplate = fieldsWithDefaults.invalidToolMsgTemplate;\n this.toolMap = this.tools.reduce((acc, tool) => {\n acc[tool.name] = tool;\n return acc;\n }, {} as Record<string, StructuredToolInterface | RunnableToolLike>);\n }\n\n /**\n * Execute a tool invocation\n *\n * @param {ToolInvocationInterface} toolInvocation The tool to invoke and the input to pass to it.\n * @param {RunnableConfig | undefined} config Optional configuration to pass to the tool when invoked.\n * @returns Either the result of the tool invocation (`string` or `ToolMessage`, set by the `ToolOutput` generic) or a string error message.\n */\n async _execute(\n toolInvocation: ToolInvocationInterface,\n config?: RunnableConfig\n ): Promise<ToolExecutorOutputType> {\n if (!(toolInvocation.tool in this.toolMap)) {\n return this.invalidToolMsgTemplate\n .replace(\"{requestedToolName}\", toolInvocation.tool)\n .replace(\n \"{availableToolNamesString}\",\n Object.keys(this.toolMap).join(\", \")\n );\n } else {\n const tool = this.toolMap[toolInvocation.tool];\n const output = await tool.invoke(toolInvocation.toolInput, config);\n return output;\n }\n }\n}\n"],"mappings":";;;AAQA,MAAM,4BAA4B;;AA0BlC,IAAa,eAAb,cAAkCA,0CAGhC;CACA,gBAAgB;CAEhB;CAEA;CAEA;CAEA,YAAY,QAA0B;EACpC,MAAM,qBAAqB;GACzB,wBAAwB;GACxB,GAAG;GACJ;EACD,MAAM,QAAQC,yCAAe,KAC3B,OAAO,OAAgC,WACrC,KAAK,SAAS,OAAO,OAAO,CAC/B;AACD,QAAM;GACJ;GACA,QAAQ,EAAE;GACX,CAAC;AACF,OAAK,QAAQ,mBAAmB;AAChC,OAAK,yBAAyB,mBAAmB;AACjD,OAAK,UAAU,KAAK,MAAM,QAAQ,KAAK,SAAS;AAC9C,OAAI,KAAK,QAAQ;AACjB,UAAO;KACN,EAAE,CAA+D;;;;;;;;;CAUtE,MAAM,SACJ,gBACA,QACiC;AACjC,MAAI,EAAE,eAAe,QAAQ,KAAK,SAChC,QAAO,KAAK,uBACT,QAAQ,uBAAuB,eAAe,KAAK,CACnD,QACC,8BACA,OAAO,KAAK,KAAK,QAAQ,CAAC,KAAK,KAAK,CACrC;MAIH,QADe,MADF,KAAK,QAAQ,eAAe,MACf,OAAO,eAAe,WAAW,OAAO"}
@@ -0,0 +1,40 @@
1
+ import { RunnableBinding, RunnableConfig, RunnableToolLike } from "@langchain/core/runnables";
2
+ import { StructuredToolInterface } from "@langchain/core/tools";
3
+
4
+ //#region src/prebuilt/tool_executor.d.ts
5
+ /** @deprecated Use {@link ToolNode} instead. */
6
+ interface ToolExecutorArgs {
7
+ tools: Array<StructuredToolInterface | RunnableToolLike>;
8
+ /**
9
+ * @default {INVALID_TOOL_MSG_TEMPLATE}
10
+ */
11
+ invalidToolMsgTemplate?: string;
12
+ }
13
+ /**
14
+ * Interface for invoking a tool
15
+ */
16
+ interface ToolInvocationInterface {
17
+ tool: string;
18
+ toolInput: string;
19
+ }
20
+ type ToolExecutorInputType = any;
21
+ type ToolExecutorOutputType = any;
22
+ /** @deprecated Use {@link ToolNode} instead. */
23
+ declare class ToolExecutor extends RunnableBinding<ToolExecutorInputType, ToolExecutorOutputType> {
24
+ lc_graph_name: string;
25
+ tools: Array<StructuredToolInterface | RunnableToolLike>;
26
+ toolMap: Record<string, StructuredToolInterface | RunnableToolLike>;
27
+ invalidToolMsgTemplate: string;
28
+ constructor(fields: ToolExecutorArgs);
29
+ /**
30
+ * Execute a tool invocation
31
+ *
32
+ * @param {ToolInvocationInterface} toolInvocation The tool to invoke and the input to pass to it.
33
+ * @param {RunnableConfig | undefined} config Optional configuration to pass to the tool when invoked.
34
+ * @returns Either the result of the tool invocation (`string` or `ToolMessage`, set by the `ToolOutput` generic) or a string error message.
35
+ */
36
+ _execute(toolInvocation: ToolInvocationInterface, config?: RunnableConfig): Promise<ToolExecutorOutputType>;
37
+ }
38
+ //#endregion
39
+ export { ToolExecutor, ToolExecutorArgs, ToolInvocationInterface };
40
+ //# sourceMappingURL=tool_executor.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool_executor.d.cts","names":["RunnableBinding","RunnableConfig","RunnableToolLike","StructuredToolInterface","ToolExecutorArgs","Array","ToolInvocationInterface","ToolExecutorInputType","ToolExecutorOutputType","ToolExecutor","Record","Promise"],"sources":["../../src/prebuilt/tool_executor.d.ts"],"sourcesContent":["import { RunnableBinding, RunnableConfig, RunnableToolLike } from \"@langchain/core/runnables\";\nimport { StructuredToolInterface } from \"@langchain/core/tools\";\n/** @deprecated Use {@link ToolNode} instead. */\nexport interface ToolExecutorArgs {\n tools: Array<StructuredToolInterface | RunnableToolLike>;\n /**\n * @default {INVALID_TOOL_MSG_TEMPLATE}\n */\n invalidToolMsgTemplate?: string;\n}\n/**\n * Interface for invoking a tool\n */\nexport interface ToolInvocationInterface {\n tool: string;\n toolInput: string;\n}\ntype ToolExecutorInputType = any;\ntype ToolExecutorOutputType = any;\n/** @deprecated Use {@link ToolNode} instead. */\nexport declare class ToolExecutor extends RunnableBinding<ToolExecutorInputType, ToolExecutorOutputType> {\n lc_graph_name: string;\n tools: Array<StructuredToolInterface | RunnableToolLike>;\n toolMap: Record<string, StructuredToolInterface | RunnableToolLike>;\n invalidToolMsgTemplate: string;\n constructor(fields: ToolExecutorArgs);\n /**\n * Execute a tool invocation\n *\n * @param {ToolInvocationInterface} toolInvocation The tool to invoke and the input to pass to it.\n * @param {RunnableConfig | undefined} config Optional configuration to pass to the tool when invoked.\n * @returns Either the result of the tool invocation (`string` or `ToolMessage`, set by the `ToolOutput` generic) or a string error message.\n */\n _execute(toolInvocation: ToolInvocationInterface, config?: RunnableConfig): Promise<ToolExecutorOutputType>;\n}\nexport {};\n"],"mappings":";;;;;UAGiBI,gBAAAA;EAAAA,KAAAA,EACNC,KADMD,CACAD,uBADgB,GACUD,gBADV,CAAA;EAAA;;;wBACtBG,CAAAA,EAAAA,MAAAA;;AASX;AAGC;AACyB;AAGLI,UAPJH,uBAAAA,CAOgB;EAAA,IAAA,EAAA,MAAA;WAAyBC,EAAAA,MAAAA;;KAHrDA,qBAAAA,GAKYJ,GAAAA;KAJZK,sBAAAA,GAIsCN,GAAAA;;AACfC,cAHPM,YAAAA,SAAqBT,eAGdG,CAH8BI,qBAG9BJ,EAHqDK,sBAGrDL,CAAAA,CAAAA;eAA0BD,EAAAA,MAAAA;OAAzCQ,EADFL,KACEK,CADIP,uBACJO,GAD8BR,gBAC9BQ,CAAAA;SAEWN,EAFXM,MAEWN,CAAAA,MAAAA,EAFID,uBAEJC,GAF8BF,gBAE9BE,CAAAA;wBAQKE,EAAAA,MAAAA;aAAkCL,CAAAA,MAAAA,EARvCG,gBAQuCH;;;;;;;;2BAAlCK,kCAAkCL,iBAAiBU,QAAQH"}
@@ -0,0 +1,40 @@
1
+ import { RunnableBinding, RunnableConfig, RunnableToolLike } from "@langchain/core/runnables";
2
+ import { StructuredToolInterface } from "@langchain/core/tools";
3
+
4
+ //#region src/prebuilt/tool_executor.d.ts
5
+ /** @deprecated Use {@link ToolNode} instead. */
6
+ interface ToolExecutorArgs {
7
+ tools: Array<StructuredToolInterface | RunnableToolLike>;
8
+ /**
9
+ * @default {INVALID_TOOL_MSG_TEMPLATE}
10
+ */
11
+ invalidToolMsgTemplate?: string;
12
+ }
13
+ /**
14
+ * Interface for invoking a tool
15
+ */
16
+ interface ToolInvocationInterface {
17
+ tool: string;
18
+ toolInput: string;
19
+ }
20
+ type ToolExecutorInputType = any;
21
+ type ToolExecutorOutputType = any;
22
+ /** @deprecated Use {@link ToolNode} instead. */
23
+ declare class ToolExecutor extends RunnableBinding<ToolExecutorInputType, ToolExecutorOutputType> {
24
+ lc_graph_name: string;
25
+ tools: Array<StructuredToolInterface | RunnableToolLike>;
26
+ toolMap: Record<string, StructuredToolInterface | RunnableToolLike>;
27
+ invalidToolMsgTemplate: string;
28
+ constructor(fields: ToolExecutorArgs);
29
+ /**
30
+ * Execute a tool invocation
31
+ *
32
+ * @param {ToolInvocationInterface} toolInvocation The tool to invoke and the input to pass to it.
33
+ * @param {RunnableConfig | undefined} config Optional configuration to pass to the tool when invoked.
34
+ * @returns Either the result of the tool invocation (`string` or `ToolMessage`, set by the `ToolOutput` generic) or a string error message.
35
+ */
36
+ _execute(toolInvocation: ToolInvocationInterface, config?: RunnableConfig): Promise<ToolExecutorOutputType>;
37
+ }
38
+ //#endregion
39
+ export { ToolExecutor, ToolExecutorArgs, ToolInvocationInterface };
40
+ //# sourceMappingURL=tool_executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool_executor.d.ts","names":["RunnableBinding","RunnableConfig","RunnableToolLike","StructuredToolInterface","ToolExecutorArgs","Array","ToolInvocationInterface","ToolExecutorInputType","ToolExecutorOutputType","ToolExecutor","Record","Promise"],"sources":["../../src/prebuilt/tool_executor.d.ts"],"sourcesContent":["import { RunnableBinding, RunnableConfig, RunnableToolLike } from \"@langchain/core/runnables\";\nimport { StructuredToolInterface } from \"@langchain/core/tools\";\n/** @deprecated Use {@link ToolNode} instead. */\nexport interface ToolExecutorArgs {\n tools: Array<StructuredToolInterface | RunnableToolLike>;\n /**\n * @default {INVALID_TOOL_MSG_TEMPLATE}\n */\n invalidToolMsgTemplate?: string;\n}\n/**\n * Interface for invoking a tool\n */\nexport interface ToolInvocationInterface {\n tool: string;\n toolInput: string;\n}\ntype ToolExecutorInputType = any;\ntype ToolExecutorOutputType = any;\n/** @deprecated Use {@link ToolNode} instead. */\nexport declare class ToolExecutor extends RunnableBinding<ToolExecutorInputType, ToolExecutorOutputType> {\n lc_graph_name: string;\n tools: Array<StructuredToolInterface | RunnableToolLike>;\n toolMap: Record<string, StructuredToolInterface | RunnableToolLike>;\n invalidToolMsgTemplate: string;\n constructor(fields: ToolExecutorArgs);\n /**\n * Execute a tool invocation\n *\n * @param {ToolInvocationInterface} toolInvocation The tool to invoke and the input to pass to it.\n * @param {RunnableConfig | undefined} config Optional configuration to pass to the tool when invoked.\n * @returns Either the result of the tool invocation (`string` or `ToolMessage`, set by the `ToolOutput` generic) or a string error message.\n */\n _execute(toolInvocation: ToolInvocationInterface, config?: RunnableConfig): Promise<ToolExecutorOutputType>;\n}\nexport {};\n"],"mappings":";;;;;UAGiBI,gBAAAA;EAAAA,KAAAA,EACNC,KADMD,CACAD,uBADgB,GACUD,gBADV,CAAA;EAAA;;;wBACtBG,CAAAA,EAAAA,MAAAA;;AASX;AAGC;AACyB;AAGLI,UAPJH,uBAAAA,CAOgB;EAAA,IAAA,EAAA,MAAA;WAAyBC,EAAAA,MAAAA;;KAHrDA,qBAAAA,GAKYJ,GAAAA;KAJZK,sBAAAA,GAIsCN,GAAAA;;AACfC,cAHPM,YAAAA,SAAqBT,eAGdG,CAH8BI,qBAG9BJ,EAHqDK,sBAGrDL,CAAAA,CAAAA;eAA0BD,EAAAA,MAAAA;OAAzCQ,EADFL,KACEK,CADIP,uBACJO,GAD8BR,gBAC9BQ,CAAAA;SAEWN,EAFXM,MAEWN,CAAAA,MAAAA,EAFID,uBAEJC,GAF8BF,gBAE9BE,CAAAA;wBAQKE,EAAAA,MAAAA;aAAkCL,CAAAA,MAAAA,EARvCG,gBAQuCH;;;;;;;;2BAAlCK,kCAAkCL,iBAAiBU,QAAQH"}
@@ -0,0 +1,43 @@
1
+ import { RunnableBinding, RunnableLambda } from "@langchain/core/runnables";
2
+
3
+ //#region src/prebuilt/tool_executor.ts
4
+ const INVALID_TOOL_MSG_TEMPLATE = `{requestedToolName} is not a valid tool, try one of {availableToolNamesString}.`;
5
+ /** @deprecated Use {@link ToolNode} instead. */
6
+ var ToolExecutor = class extends RunnableBinding {
7
+ lc_graph_name = "ToolExecutor";
8
+ tools;
9
+ toolMap;
10
+ invalidToolMsgTemplate;
11
+ constructor(fields) {
12
+ const fieldsWithDefaults = {
13
+ invalidToolMsgTemplate: INVALID_TOOL_MSG_TEMPLATE,
14
+ ...fields
15
+ };
16
+ const bound = RunnableLambda.from(async (input, config) => this._execute(input, config));
17
+ super({
18
+ bound,
19
+ config: {}
20
+ });
21
+ this.tools = fieldsWithDefaults.tools;
22
+ this.invalidToolMsgTemplate = fieldsWithDefaults.invalidToolMsgTemplate;
23
+ this.toolMap = this.tools.reduce((acc, tool) => {
24
+ acc[tool.name] = tool;
25
+ return acc;
26
+ }, {});
27
+ }
28
+ /**
29
+ * Execute a tool invocation
30
+ *
31
+ * @param {ToolInvocationInterface} toolInvocation The tool to invoke and the input to pass to it.
32
+ * @param {RunnableConfig | undefined} config Optional configuration to pass to the tool when invoked.
33
+ * @returns Either the result of the tool invocation (`string` or `ToolMessage`, set by the `ToolOutput` generic) or a string error message.
34
+ */
35
+ async _execute(toolInvocation, config) {
36
+ if (!(toolInvocation.tool in this.toolMap)) return this.invalidToolMsgTemplate.replace("{requestedToolName}", toolInvocation.tool).replace("{availableToolNamesString}", Object.keys(this.toolMap).join(", "));
37
+ else return await this.toolMap[toolInvocation.tool].invoke(toolInvocation.toolInput, config);
38
+ }
39
+ };
40
+
41
+ //#endregion
42
+ export { ToolExecutor };
43
+ //# sourceMappingURL=tool_executor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool_executor.js","names":[],"sources":["../../src/prebuilt/tool_executor.ts"],"sourcesContent":["import {\n RunnableBinding,\n RunnableConfig,\n RunnableLambda,\n RunnableToolLike,\n} from \"@langchain/core/runnables\";\nimport { StructuredToolInterface } from \"@langchain/core/tools\";\n\nconst INVALID_TOOL_MSG_TEMPLATE = `{requestedToolName} is not a valid tool, try one of {availableToolNamesString}.`;\n\n/** @deprecated Use {@link ToolNode} instead. */\nexport interface ToolExecutorArgs {\n tools: Array<StructuredToolInterface | RunnableToolLike>;\n /**\n * @default {INVALID_TOOL_MSG_TEMPLATE}\n */\n invalidToolMsgTemplate?: string;\n}\n\n/**\n * Interface for invoking a tool\n */\nexport interface ToolInvocationInterface {\n tool: string;\n toolInput: string;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype ToolExecutorInputType = any;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype ToolExecutorOutputType = any;\n\n/** @deprecated Use {@link ToolNode} instead. */\nexport class ToolExecutor extends RunnableBinding<\n ToolExecutorInputType,\n ToolExecutorOutputType\n> {\n lc_graph_name = \"ToolExecutor\";\n\n tools: Array<StructuredToolInterface | RunnableToolLike>;\n\n toolMap: Record<string, StructuredToolInterface | RunnableToolLike>;\n\n invalidToolMsgTemplate: string;\n\n constructor(fields: ToolExecutorArgs) {\n const fieldsWithDefaults = {\n invalidToolMsgTemplate: INVALID_TOOL_MSG_TEMPLATE,\n ...fields,\n };\n const bound = RunnableLambda.from(\n async (input: ToolInvocationInterface, config?: RunnableConfig) =>\n this._execute(input, config)\n );\n super({\n bound,\n config: {},\n });\n this.tools = fieldsWithDefaults.tools;\n this.invalidToolMsgTemplate = fieldsWithDefaults.invalidToolMsgTemplate;\n this.toolMap = this.tools.reduce((acc, tool) => {\n acc[tool.name] = tool;\n return acc;\n }, {} as Record<string, StructuredToolInterface | RunnableToolLike>);\n }\n\n /**\n * Execute a tool invocation\n *\n * @param {ToolInvocationInterface} toolInvocation The tool to invoke and the input to pass to it.\n * @param {RunnableConfig | undefined} config Optional configuration to pass to the tool when invoked.\n * @returns Either the result of the tool invocation (`string` or `ToolMessage`, set by the `ToolOutput` generic) or a string error message.\n */\n async _execute(\n toolInvocation: ToolInvocationInterface,\n config?: RunnableConfig\n ): Promise<ToolExecutorOutputType> {\n if (!(toolInvocation.tool in this.toolMap)) {\n return this.invalidToolMsgTemplate\n .replace(\"{requestedToolName}\", toolInvocation.tool)\n .replace(\n \"{availableToolNamesString}\",\n Object.keys(this.toolMap).join(\", \")\n );\n } else {\n const tool = this.toolMap[toolInvocation.tool];\n const output = await tool.invoke(toolInvocation.toolInput, config);\n return output;\n }\n }\n}\n"],"mappings":";;;AAQA,MAAM,4BAA4B;;AA0BlC,IAAa,eAAb,cAAkC,gBAGhC;CACA,gBAAgB;CAEhB;CAEA;CAEA;CAEA,YAAY,QAA0B;EACpC,MAAM,qBAAqB;GACzB,wBAAwB;GACxB,GAAG;GACJ;EACD,MAAM,QAAQ,eAAe,KAC3B,OAAO,OAAgC,WACrC,KAAK,SAAS,OAAO,OAAO,CAC/B;AACD,QAAM;GACJ;GACA,QAAQ,EAAE;GACX,CAAC;AACF,OAAK,QAAQ,mBAAmB;AAChC,OAAK,yBAAyB,mBAAmB;AACjD,OAAK,UAAU,KAAK,MAAM,QAAQ,KAAK,SAAS;AAC9C,OAAI,KAAK,QAAQ;AACjB,UAAO;KACN,EAAE,CAA+D;;;;;;;;;CAUtE,MAAM,SACJ,gBACA,QACiC;AACjC,MAAI,EAAE,eAAe,QAAQ,KAAK,SAChC,QAAO,KAAK,uBACT,QAAQ,uBAAuB,eAAe,KAAK,CACnD,QACC,8BACA,OAAO,KAAK,KAAK,QAAQ,CAAC,KAAK,KAAK,CACrC;MAIH,QADe,MADF,KAAK,QAAQ,eAAe,MACf,OAAO,eAAe,WAAW,OAAO"}
@@ -0,0 +1,247 @@
1
+ const require_errors = require('../errors.cjs');
2
+ const require_constants = require('../constants.cjs');
3
+ const require_utils = require('../utils.cjs');
4
+ let _langchain_core_messages = require("@langchain/core/messages");
5
+
6
+ //#region src/prebuilt/tool_node.ts
7
+ const isBaseMessageArray = (input) => Array.isArray(input) && input.every(_langchain_core_messages.isBaseMessage);
8
+ const isMessagesState = (input) => typeof input === "object" && input != null && "messages" in input && isBaseMessageArray(input.messages);
9
+ const isSendInput = (input) => typeof input === "object" && input != null && "lg_tool_call" in input;
10
+ /**
11
+ * A node that runs the tools requested in the last AIMessage. It can be used
12
+ * either in StateGraph with a "messages" key or in MessageGraph. If multiple
13
+ * tool calls are requested, they will be run in parallel. The output will be
14
+ * a list of ToolMessages, one for each tool call.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * import { ToolNode } from "@langchain/langgraph/prebuilt";
19
+ * import { tool } from "@langchain/core/tools";
20
+ * import { z } from "zod";
21
+ * import { AIMessage } from "@langchain/core/messages";
22
+ *
23
+ * const getWeather = tool((input) => {
24
+ * if (["sf", "san francisco"].includes(input.location.toLowerCase())) {
25
+ * return "It's 60 degrees and foggy.";
26
+ * } else {
27
+ * return "It's 90 degrees and sunny.";
28
+ * }
29
+ * }, {
30
+ * name: "get_weather",
31
+ * description: "Call to get the current weather.",
32
+ * schema: z.object({
33
+ * location: z.string().describe("Location to get the weather for."),
34
+ * }),
35
+ * });
36
+ *
37
+ * const tools = [getWeather];
38
+ * const toolNode = new ToolNode(tools);
39
+ *
40
+ * const messageWithSingleToolCall = new AIMessage({
41
+ * content: "",
42
+ * tool_calls: [
43
+ * {
44
+ * name: "get_weather",
45
+ * args: { location: "sf" },
46
+ * id: "tool_call_id",
47
+ * type: "tool_call",
48
+ * }
49
+ * ]
50
+ * })
51
+ *
52
+ * await toolNode.invoke({ messages: [messageWithSingleToolCall] });
53
+ * // Returns tool invocation responses as:
54
+ * // { messages: ToolMessage[] }
55
+ * ```
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * import {
60
+ * StateGraph,
61
+ * MessagesAnnotation,
62
+ * } from "@langchain/langgraph";
63
+ * import { ToolNode } from "@langchain/langgraph/prebuilt";
64
+ * import { tool } from "@langchain/core/tools";
65
+ * import { z } from "zod";
66
+ * import { ChatAnthropic } from "@langchain/anthropic";
67
+ *
68
+ * const getWeather = tool((input) => {
69
+ * if (["sf", "san francisco"].includes(input.location.toLowerCase())) {
70
+ * return "It's 60 degrees and foggy.";
71
+ * } else {
72
+ * return "It's 90 degrees and sunny.";
73
+ * }
74
+ * }, {
75
+ * name: "get_weather",
76
+ * description: "Call to get the current weather.",
77
+ * schema: z.object({
78
+ * location: z.string().describe("Location to get the weather for."),
79
+ * }),
80
+ * });
81
+ *
82
+ * const tools = [getWeather];
83
+ * const modelWithTools = new ChatAnthropic({
84
+ * model: "claude-3-haiku-20240307",
85
+ * temperature: 0
86
+ * }).bindTools(tools);
87
+ *
88
+ * const toolNodeForGraph = new ToolNode(tools)
89
+ *
90
+ * const shouldContinue = (state: typeof MessagesAnnotation.State) => {
91
+ * const { messages } = state;
92
+ * const lastMessage = messages[messages.length - 1];
93
+ * if ("tool_calls" in lastMessage && Array.isArray(lastMessage.tool_calls) && lastMessage.tool_calls?.length) {
94
+ * return "tools";
95
+ * }
96
+ * return "__end__";
97
+ * }
98
+ *
99
+ * const callModel = async (state: typeof MessagesAnnotation.State) => {
100
+ * const { messages } = state;
101
+ * const response = await modelWithTools.invoke(messages);
102
+ * return { messages: response };
103
+ * }
104
+ *
105
+ * const graph = new StateGraph(MessagesAnnotation)
106
+ * .addNode("agent", callModel)
107
+ * .addNode("tools", toolNodeForGraph)
108
+ * .addEdge("__start__", "agent")
109
+ * .addConditionalEdges("agent", shouldContinue)
110
+ * .addEdge("tools", "agent")
111
+ * .compile();
112
+ *
113
+ * const inputs = {
114
+ * messages: [{ role: "user", content: "what is the weather in SF?" }],
115
+ * };
116
+ *
117
+ * const stream = await graph.stream(inputs, {
118
+ * streamMode: "values",
119
+ * });
120
+ *
121
+ * for await (const { messages } of stream) {
122
+ * console.log(messages);
123
+ * }
124
+ * // Returns the messages in the state at each step of execution
125
+ * ```
126
+ */
127
+ var ToolNode = class extends require_utils.RunnableCallable {
128
+ tools;
129
+ handleToolErrors = true;
130
+ trace = false;
131
+ constructor(tools, options) {
132
+ const { name, tags, handleToolErrors } = options ?? {};
133
+ super({
134
+ name,
135
+ tags,
136
+ func: (input, config) => this.run(input, config)
137
+ });
138
+ this.tools = tools;
139
+ this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;
140
+ }
141
+ async runTool(call, config) {
142
+ const tool = this.tools.find((tool$1) => tool$1.name === call.name);
143
+ try {
144
+ if (tool === void 0) throw new Error(`Tool "${call.name}" not found.`);
145
+ const output = await tool.invoke({
146
+ ...call,
147
+ type: "tool_call"
148
+ }, config);
149
+ if ((0, _langchain_core_messages.isBaseMessage)(output) && output.getType() === "tool" || require_constants.isCommand(output)) return output;
150
+ return new _langchain_core_messages.ToolMessage({
151
+ status: "success",
152
+ name: tool.name,
153
+ content: typeof output === "string" ? output : JSON.stringify(output),
154
+ tool_call_id: call.id
155
+ });
156
+ } catch (e) {
157
+ if (!this.handleToolErrors) throw e;
158
+ if (require_errors.isGraphInterrupt(e)) throw e;
159
+ return new _langchain_core_messages.ToolMessage({
160
+ status: "error",
161
+ content: `Error: ${e.message}\n Please fix your mistakes.`,
162
+ name: call.name,
163
+ tool_call_id: call.id ?? ""
164
+ });
165
+ }
166
+ }
167
+ async run(input, config) {
168
+ let outputs;
169
+ if (isSendInput(input)) outputs = [await this.runTool(input.lg_tool_call, config)];
170
+ else {
171
+ let messages;
172
+ if (isBaseMessageArray(input)) messages = input;
173
+ else if (isMessagesState(input)) messages = input.messages;
174
+ else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");
175
+ const toolMessageIds = new Set(messages.filter((msg) => msg.getType() === "tool").map((msg) => msg.tool_call_id));
176
+ let aiMessage;
177
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
178
+ const message = messages[i];
179
+ if ((0, _langchain_core_messages.isAIMessage)(message)) {
180
+ aiMessage = message;
181
+ break;
182
+ }
183
+ }
184
+ if (aiMessage == null || !(0, _langchain_core_messages.isAIMessage)(aiMessage)) throw new Error("ToolNode only accepts AIMessages as input.");
185
+ outputs = await Promise.all(aiMessage.tool_calls?.filter((call) => call.id == null || !toolMessageIds.has(call.id)).map((call) => this.runTool(call, config)) ?? []);
186
+ }
187
+ if (!outputs.some(require_constants.isCommand)) return Array.isArray(input) ? outputs : { messages: outputs };
188
+ const combinedOutputs = [];
189
+ let parentCommand = null;
190
+ for (const output of outputs) if (require_constants.isCommand(output)) if (output.graph === require_constants.Command.PARENT && Array.isArray(output.goto) && output.goto.every((send) => require_constants._isSend(send))) if (parentCommand) parentCommand.goto.push(...output.goto);
191
+ else parentCommand = new require_constants.Command({
192
+ graph: require_constants.Command.PARENT,
193
+ goto: output.goto
194
+ });
195
+ else combinedOutputs.push(output);
196
+ else combinedOutputs.push(Array.isArray(input) ? [output] : { messages: [output] });
197
+ if (parentCommand) combinedOutputs.push(parentCommand);
198
+ return combinedOutputs;
199
+ }
200
+ };
201
+ /**
202
+ * A conditional edge function that determines whether to route to a tools node or end the graph.
203
+ *
204
+ * This function is designed to be used as a conditional edge in a LangGraph state graph to implement
205
+ * the common pattern of checking if an AI message contains tool calls that need to be executed.
206
+ *
207
+ * @param state - The current state of the graph, which can be either:
208
+ * - An array of `BaseMessage` objects, where the last message is checked for tool calls
209
+ * - A state object conforming to `MessagesAnnotation.State`, which contains a `messages` array
210
+ *
211
+ * @returns A string indicating the next node to route to:
212
+ * - `"tools"` - If the last message contains tool calls that need to be executed
213
+ * - `END` - If there are no tool calls, indicating the graph should terminate
214
+ *
215
+ * @example
216
+ * ```typescript
217
+ * import { StateGraph, MessagesAnnotation, END, START } from "@langchain/langgraph";
218
+ * import { ToolNode, toolsCondition } from "@langchain/langgraph/prebuilt";
219
+ *
220
+ * const graph = new StateGraph(MessagesAnnotation)
221
+ * .addNode("agent", agentNode)
222
+ * .addNode("tools", new ToolNode([searchTool, calculatorTool]))
223
+ * .addEdge(START, "agent")
224
+ * .addConditionalEdges("agent", toolsCondition, ["tools", END])
225
+ * .addEdge("tools", "agent")
226
+ * .compile();
227
+ * ```
228
+ *
229
+ * @remarks
230
+ * The function checks the last message in the state for the presence of `tool_calls`.
231
+ * If the message is an `AIMessage` with one or more tool calls, it returns `"tools"`,
232
+ * indicating that the graph should route to a tools node (typically a `ToolNode`) to
233
+ * execute those tool calls. Otherwise, it returns `END` to terminate the graph execution.
234
+ *
235
+ * This is a common pattern in agentic workflows where an AI model decides whether to
236
+ * use tools or provide a final response.
237
+ */
238
+ function toolsCondition(state) {
239
+ const message = Array.isArray(state) ? state[state.length - 1] : state.messages[state.messages.length - 1];
240
+ if (message !== void 0 && "tool_calls" in message && (message.tool_calls?.length ?? 0) > 0) return "tools";
241
+ else return require_constants.END;
242
+ }
243
+
244
+ //#endregion
245
+ exports.ToolNode = ToolNode;
246
+ exports.toolsCondition = toolsCondition;
247
+ //# sourceMappingURL=tool_node.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool_node.cjs","names":["isBaseMessage","RunnableCallable","tool","isCommand","ToolMessage","isGraphInterrupt","Command","_isSend","END"],"sources":["../../src/prebuilt/tool_node.ts"],"sourcesContent":["import {\n BaseMessage,\n ToolMessage,\n AIMessage,\n isBaseMessage,\n isAIMessage,\n} from \"@langchain/core/messages\";\nimport { RunnableConfig, RunnableToolLike } from \"@langchain/core/runnables\";\nimport { DynamicTool, StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport { RunnableCallable } from \"../utils.js\";\nimport { MessagesAnnotation } from \"../graph/messages_annotation.js\";\nimport { isGraphInterrupt } from \"../errors.js\";\nimport { END, isCommand, Command, _isSend, Send } from \"../constants.js\";\n\nexport type ToolNodeOptions = {\n name?: string;\n tags?: string[];\n handleToolErrors?: boolean;\n};\n\nconst isBaseMessageArray = (input: unknown): input is BaseMessage[] =>\n Array.isArray(input) && input.every(isBaseMessage);\n\nconst isMessagesState = (\n input: unknown\n): input is { messages: BaseMessage[] } =>\n typeof input === \"object\" &&\n input != null &&\n \"messages\" in input &&\n isBaseMessageArray(input.messages);\n\nconst isSendInput = (input: unknown): input is { lg_tool_call: ToolCall } =>\n typeof input === \"object\" && input != null && \"lg_tool_call\" in input;\n\n/**\n * A node that runs the tools requested in the last AIMessage. It can be used\n * either in StateGraph with a \"messages\" key or in MessageGraph. If multiple\n * tool calls are requested, they will be run in parallel. The output will be\n * a list of ToolMessages, one for each tool call.\n *\n * @example\n * ```ts\n * import { ToolNode } from \"@langchain/langgraph/prebuilt\";\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n * import { AIMessage } from \"@langchain/core/messages\";\n *\n * const getWeather = tool((input) => {\n * if ([\"sf\", \"san francisco\"].includes(input.location.toLowerCase())) {\n * return \"It's 60 degrees and foggy.\";\n * } else {\n * return \"It's 90 degrees and sunny.\";\n * }\n * }, {\n * name: \"get_weather\",\n * description: \"Call to get the current weather.\",\n * schema: z.object({\n * location: z.string().describe(\"Location to get the weather for.\"),\n * }),\n * });\n *\n * const tools = [getWeather];\n * const toolNode = new ToolNode(tools);\n *\n * const messageWithSingleToolCall = new AIMessage({\n * content: \"\",\n * tool_calls: [\n * {\n * name: \"get_weather\",\n * args: { location: \"sf\" },\n * id: \"tool_call_id\",\n * type: \"tool_call\",\n * }\n * ]\n * })\n *\n * await toolNode.invoke({ messages: [messageWithSingleToolCall] });\n * // Returns tool invocation responses as:\n * // { messages: ToolMessage[] }\n * ```\n *\n * @example\n * ```ts\n * import {\n * StateGraph,\n * MessagesAnnotation,\n * } from \"@langchain/langgraph\";\n * import { ToolNode } from \"@langchain/langgraph/prebuilt\";\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n * import { ChatAnthropic } from \"@langchain/anthropic\";\n *\n * const getWeather = tool((input) => {\n * if ([\"sf\", \"san francisco\"].includes(input.location.toLowerCase())) {\n * return \"It's 60 degrees and foggy.\";\n * } else {\n * return \"It's 90 degrees and sunny.\";\n * }\n * }, {\n * name: \"get_weather\",\n * description: \"Call to get the current weather.\",\n * schema: z.object({\n * location: z.string().describe(\"Location to get the weather for.\"),\n * }),\n * });\n *\n * const tools = [getWeather];\n * const modelWithTools = new ChatAnthropic({\n * model: \"claude-3-haiku-20240307\",\n * temperature: 0\n * }).bindTools(tools);\n *\n * const toolNodeForGraph = new ToolNode(tools)\n *\n * const shouldContinue = (state: typeof MessagesAnnotation.State) => {\n * const { messages } = state;\n * const lastMessage = messages[messages.length - 1];\n * if (\"tool_calls\" in lastMessage && Array.isArray(lastMessage.tool_calls) && lastMessage.tool_calls?.length) {\n * return \"tools\";\n * }\n * return \"__end__\";\n * }\n *\n * const callModel = async (state: typeof MessagesAnnotation.State) => {\n * const { messages } = state;\n * const response = await modelWithTools.invoke(messages);\n * return { messages: response };\n * }\n *\n * const graph = new StateGraph(MessagesAnnotation)\n * .addNode(\"agent\", callModel)\n * .addNode(\"tools\", toolNodeForGraph)\n * .addEdge(\"__start__\", \"agent\")\n * .addConditionalEdges(\"agent\", shouldContinue)\n * .addEdge(\"tools\", \"agent\")\n * .compile();\n *\n * const inputs = {\n * messages: [{ role: \"user\", content: \"what is the weather in SF?\" }],\n * };\n *\n * const stream = await graph.stream(inputs, {\n * streamMode: \"values\",\n * });\n *\n * for await (const { messages } of stream) {\n * console.log(messages);\n * }\n * // Returns the messages in the state at each step of execution\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[];\n\n handleToolErrors = true;\n\n trace = false;\n\n constructor(\n tools: (StructuredToolInterface | DynamicTool | RunnableToolLike)[],\n options?: ToolNodeOptions\n ) {\n const { name, tags, handleToolErrors } = options ?? {};\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.tools = tools;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n }\n\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<ToolMessage | Command> {\n const tool = this.tools.find((tool) => tool.name === call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const output = await tool.invoke({ ...call, type: \"tool_call\" }, config);\n\n if (\n (isBaseMessage(output) && output.getType() === \"tool\") ||\n isCommand(output)\n ) {\n return output as ToolMessage | Command;\n }\n\n return new ToolMessage({\n status: \"success\",\n name: tool.name,\n content: typeof output === \"string\" ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n if (!this.handleToolErrors) throw e;\n\n if (isGraphInterrupt(e)) {\n // `NodeInterrupt` errors are a breakpoint to bring a human into the loop.\n // As such, they are not recoverable by the agent and shouldn't be fed\n // back. Instead, re-throw these errors even when `handleToolErrors = true`.\n throw e;\n }\n\n return new ToolMessage({\n status: \"error\",\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\n name: call.name,\n tool_call_id: call.id ?? \"\",\n });\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: unknown, config: RunnableConfig): Promise<T> {\n let outputs: (ToolMessage | Command)[];\n\n if (isSendInput(input)) {\n outputs = [await this.runTool(input.lg_tool_call, config)];\n } else {\n let messages: BaseMessage[];\n if (isBaseMessageArray(input)) {\n messages = input;\n } else if (isMessagesState(input)) {\n messages = input.messages;\n } else {\n throw new Error(\n \"ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.\"\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg.getType() === \"tool\")\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (isAIMessage(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (aiMessage == null || !isAIMessage(aiMessage)) {\n throw new Error(\"ToolNode only accepts AIMessages as input.\");\n }\n\n outputs = await Promise.all(\n aiMessage.tool_calls\n ?.filter((call) => call.id == null || !toolMessageIds.has(call.id))\n .map((call) => this.runTool(call, config)) ?? []\n );\n }\n\n // Preserve existing behavior for non-command tool outputs for backwards compatibility\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n // Handle mixed Command and non-Command outputs\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send) => _isSend(send))\n ) {\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else {\n combinedOutputs.push(output);\n }\n } else {\n combinedOutputs.push(\n Array.isArray(input) ? [output] : { messages: [output] }\n );\n }\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as T;\n }\n}\n\n/**\n * A conditional edge function that determines whether to route to a tools node or end the graph.\n *\n * This function is designed to be used as a conditional edge in a LangGraph state graph to implement\n * the common pattern of checking if an AI message contains tool calls that need to be executed.\n *\n * @param state - The current state of the graph, which can be either:\n * - An array of `BaseMessage` objects, where the last message is checked for tool calls\n * - A state object conforming to `MessagesAnnotation.State`, which contains a `messages` array\n *\n * @returns A string indicating the next node to route to:\n * - `\"tools\"` - If the last message contains tool calls that need to be executed\n * - `END` - If there are no tool calls, indicating the graph should terminate\n *\n * @example\n * ```typescript\n * import { StateGraph, MessagesAnnotation, END, START } from \"@langchain/langgraph\";\n * import { ToolNode, toolsCondition } from \"@langchain/langgraph/prebuilt\";\n *\n * const graph = new StateGraph(MessagesAnnotation)\n * .addNode(\"agent\", agentNode)\n * .addNode(\"tools\", new ToolNode([searchTool, calculatorTool]))\n * .addEdge(START, \"agent\")\n * .addConditionalEdges(\"agent\", toolsCondition, [\"tools\", END])\n * .addEdge(\"tools\", \"agent\")\n * .compile();\n * ```\n *\n * @remarks\n * The function checks the last message in the state for the presence of `tool_calls`.\n * If the message is an `AIMessage` with one or more tool calls, it returns `\"tools\"`,\n * indicating that the graph should route to a tools node (typically a `ToolNode`) to\n * execute those tool calls. Otherwise, it returns `END` to terminate the graph execution.\n *\n * This is a common pattern in agentic workflows where an AI model decides whether to\n * use tools or provide a final response.\n */\nexport function toolsCondition(\n state: BaseMessage[] | typeof MessagesAnnotation.State\n): \"tools\" | typeof END {\n const message = Array.isArray(state)\n ? state[state.length - 1]\n : state.messages[state.messages.length - 1];\n\n if (\n message !== undefined &&\n \"tool_calls\" in message &&\n ((message as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n return \"tools\";\n } else {\n return END;\n }\n}\n"],"mappings":";;;;;;AAqBA,MAAM,sBAAsB,UAC1B,MAAM,QAAQ,MAAM,IAAI,MAAM,MAAMA,uCAAc;AAEpD,MAAM,mBACJ,UAEA,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,mBAAmB,MAAM,SAAS;AAEpC,MAAM,eAAe,UACnB,OAAO,UAAU,YAAY,SAAS,QAAQ,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwHlE,IAAa,WAAb,cAAuCC,+BAAuB;CAC5D;CAEA,mBAAmB;CAEnB,QAAQ;CAER,YACE,OACA,SACA;EACA,MAAM,EAAE,MAAM,MAAM,qBAAqB,WAAW,EAAE;AACtD,QAAM;GAAE;GAAM;GAAM,OAAO,OAAO,WAAW,KAAK,IAAI,OAAO,OAAO;GAAE,CAAC;AACvE,OAAK,QAAQ;AACb,OAAK,mBAAmB,oBAAoB,KAAK;;CAGnD,MAAgB,QACd,MACA,QACgC;EAChC,MAAM,OAAO,KAAK,MAAM,MAAM,WAASC,OAAK,SAAS,KAAK,KAAK;AAC/D,MAAI;AAC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