langchain 1.0.0-alpha.5 → 1.0.0-alpha.7

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 (405) hide show
  1. package/dist/agents/ReactAgent.cjs +5 -5
  2. package/dist/agents/ReactAgent.cjs.map +1 -1
  3. package/dist/agents/ReactAgent.d.cts +2 -5
  4. package/dist/agents/ReactAgent.d.cts.map +1 -1
  5. package/dist/agents/ReactAgent.d.ts +2 -5
  6. package/dist/agents/ReactAgent.d.ts.map +1 -1
  7. package/dist/agents/ReactAgent.js +6 -6
  8. package/dist/agents/ReactAgent.js.map +1 -1
  9. package/dist/agents/annotation.cjs.map +1 -1
  10. package/dist/agents/annotation.d.cts +13 -8
  11. package/dist/agents/annotation.d.cts.map +1 -1
  12. package/dist/agents/annotation.d.ts +13 -8
  13. package/dist/agents/annotation.d.ts.map +1 -1
  14. package/dist/agents/annotation.js.map +1 -1
  15. package/dist/agents/createAgent.cjs.map +1 -1
  16. package/dist/agents/createAgent.js.map +1 -1
  17. package/dist/agents/index.cjs +2 -2
  18. package/dist/agents/index.cjs.map +1 -1
  19. package/dist/agents/index.d.cts +50 -50
  20. package/dist/agents/index.d.cts.map +1 -1
  21. package/dist/agents/index.d.ts +50 -50
  22. package/dist/agents/index.d.ts.map +1 -1
  23. package/dist/agents/index.js +2 -2
  24. package/dist/agents/index.js.map +1 -1
  25. package/dist/agents/interrupt.d.cts +14 -1
  26. package/dist/agents/interrupt.d.cts.map +1 -1
  27. package/dist/agents/interrupt.d.ts +14 -1
  28. package/dist/agents/interrupt.d.ts.map +1 -1
  29. package/dist/agents/middlewareAgent/ReactAgent.cjs +273 -66
  30. package/dist/agents/middlewareAgent/ReactAgent.cjs.map +1 -1
  31. package/dist/agents/middlewareAgent/ReactAgent.d.cts +102 -16
  32. package/dist/agents/middlewareAgent/ReactAgent.d.cts.map +1 -1
  33. package/dist/agents/middlewareAgent/ReactAgent.d.ts +102 -16
  34. package/dist/agents/middlewareAgent/ReactAgent.d.ts.map +1 -1
  35. package/dist/agents/middlewareAgent/ReactAgent.js +275 -68
  36. package/dist/agents/middlewareAgent/ReactAgent.js.map +1 -1
  37. package/dist/agents/middlewareAgent/annotation.cjs +12 -6
  38. package/dist/agents/middlewareAgent/annotation.cjs.map +1 -1
  39. package/dist/agents/middlewareAgent/annotation.js +12 -6
  40. package/dist/agents/middlewareAgent/annotation.js.map +1 -1
  41. package/dist/agents/middlewareAgent/constants.d.cts +5 -0
  42. package/dist/agents/middlewareAgent/constants.d.cts.map +1 -0
  43. package/dist/agents/middlewareAgent/constants.d.ts +5 -0
  44. package/dist/agents/middlewareAgent/constants.d.ts.map +1 -0
  45. package/dist/agents/middlewareAgent/index.cjs.map +1 -1
  46. package/dist/agents/middlewareAgent/index.js.map +1 -1
  47. package/dist/agents/middlewareAgent/middleware/bigTool.cjs +162 -0
  48. package/dist/agents/middlewareAgent/middleware/bigTool.cjs.map +1 -0
  49. package/dist/agents/middlewareAgent/middleware/bigTool.d.cts +113 -0
  50. package/dist/agents/middlewareAgent/middleware/bigTool.d.cts.map +1 -0
  51. package/dist/agents/middlewareAgent/middleware/bigTool.d.ts +113 -0
  52. package/dist/agents/middlewareAgent/middleware/bigTool.d.ts.map +1 -0
  53. package/dist/agents/middlewareAgent/middleware/bigTool.js +161 -0
  54. package/dist/agents/middlewareAgent/middleware/bigTool.js.map +1 -0
  55. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.cjs +58 -0
  56. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.cjs.map +1 -0
  57. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.cts +46 -0
  58. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.cts.map +1 -0
  59. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.ts +46 -0
  60. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.ts.map +1 -0
  61. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.js +58 -0
  62. package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.js.map +1 -0
  63. package/dist/agents/middlewareAgent/middleware/hitl.cjs +311 -0
  64. package/dist/agents/middlewareAgent/middleware/hitl.cjs.map +1 -0
  65. package/dist/agents/middlewareAgent/middleware/hitl.d.cts +419 -0
  66. package/dist/agents/middlewareAgent/middleware/hitl.d.cts.map +1 -0
  67. package/dist/agents/middlewareAgent/middleware/hitl.d.ts +419 -0
  68. package/dist/agents/middlewareAgent/middleware/hitl.d.ts.map +1 -0
  69. package/dist/agents/middlewareAgent/middleware/hitl.js +310 -0
  70. package/dist/agents/middlewareAgent/middleware/hitl.js.map +1 -0
  71. package/dist/agents/middlewareAgent/middleware/index.cjs +32 -0
  72. package/dist/agents/middlewareAgent/middleware/index.cjs.map +1 -0
  73. package/dist/agents/middlewareAgent/middleware/index.d.cts +6 -0
  74. package/dist/agents/middlewareAgent/middleware/index.d.ts +6 -0
  75. package/dist/agents/middlewareAgent/middleware/index.js +21 -0
  76. package/dist/agents/middlewareAgent/middleware/index.js.map +1 -0
  77. package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.cjs +72 -27
  78. package/dist/agents/middlewareAgent/middleware/promptCaching.cjs.map +1 -0
  79. package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.d.cts +60 -15
  80. package/dist/agents/middlewareAgent/middleware/promptCaching.d.cts.map +1 -0
  81. package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.d.ts +60 -15
  82. package/dist/agents/middlewareAgent/middleware/promptCaching.d.ts.map +1 -0
  83. package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.js +71 -26
  84. package/dist/agents/middlewareAgent/middleware/promptCaching.js.map +1 -0
  85. package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.cjs +35 -23
  86. package/dist/agents/middlewareAgent/middleware/summarization.cjs.map +1 -0
  87. package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.d.cts +7 -5
  88. package/dist/agents/middlewareAgent/middleware/summarization.d.cts.map +1 -0
  89. package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.d.ts +7 -5
  90. package/dist/agents/middlewareAgent/middleware/summarization.d.ts.map +1 -0
  91. package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.js +29 -17
  92. package/dist/agents/middlewareAgent/middleware/summarization.js.map +1 -0
  93. package/dist/agents/middlewareAgent/middleware.cjs +8 -5
  94. package/dist/agents/middlewareAgent/middleware.cjs.map +1 -1
  95. package/dist/agents/middlewareAgent/middleware.d.cts +67 -7
  96. package/dist/agents/middlewareAgent/middleware.d.cts.map +1 -1
  97. package/dist/agents/middlewareAgent/middleware.d.ts +67 -7
  98. package/dist/agents/middlewareAgent/middleware.d.ts.map +1 -1
  99. package/dist/agents/middlewareAgent/middleware.js +8 -5
  100. package/dist/agents/middlewareAgent/middleware.js.map +1 -1
  101. package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs +2 -2
  102. package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs.map +1 -1
  103. package/dist/agents/middlewareAgent/nodes/AfterModalNode.js +2 -2
  104. package/dist/agents/middlewareAgent/nodes/AfterModalNode.js.map +1 -1
  105. package/dist/agents/middlewareAgent/nodes/AgentNode.cjs +125 -83
  106. package/dist/agents/middlewareAgent/nodes/AgentNode.cjs.map +1 -1
  107. package/dist/agents/middlewareAgent/nodes/AgentNode.js +128 -86
  108. package/dist/agents/middlewareAgent/nodes/AgentNode.js.map +1 -1
  109. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs +2 -2
  110. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs.map +1 -1
  111. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js +2 -2
  112. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js.map +1 -1
  113. package/dist/agents/middlewareAgent/nodes/middleware.cjs +42 -17
  114. package/dist/agents/middlewareAgent/nodes/middleware.cjs.map +1 -1
  115. package/dist/agents/middlewareAgent/nodes/middleware.js +42 -18
  116. package/dist/agents/middlewareAgent/nodes/middleware.js.map +1 -1
  117. package/dist/agents/middlewareAgent/nodes/utils.cjs +30 -16
  118. package/dist/agents/middlewareAgent/nodes/utils.cjs.map +1 -1
  119. package/dist/agents/middlewareAgent/nodes/utils.js +28 -14
  120. package/dist/agents/middlewareAgent/nodes/utils.js.map +1 -1
  121. package/dist/agents/middlewareAgent/types.d.cts +162 -88
  122. package/dist/agents/middlewareAgent/types.d.cts.map +1 -1
  123. package/dist/agents/middlewareAgent/types.d.ts +162 -88
  124. package/dist/agents/middlewareAgent/types.d.ts.map +1 -1
  125. package/dist/agents/model.cjs +13 -0
  126. package/dist/agents/model.cjs.map +1 -0
  127. package/dist/agents/model.js +11 -0
  128. package/dist/agents/model.js.map +1 -0
  129. package/dist/agents/nodes/AgentNode.cjs +60 -32
  130. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  131. package/dist/agents/nodes/AgentNode.js +61 -33
  132. package/dist/agents/nodes/AgentNode.js.map +1 -1
  133. package/dist/agents/nodes/ToolNode.cjs +4 -4
  134. package/dist/agents/nodes/ToolNode.cjs.map +1 -1
  135. package/dist/agents/nodes/ToolNode.d.cts +2 -3
  136. package/dist/agents/nodes/ToolNode.d.cts.map +1 -1
  137. package/dist/agents/nodes/ToolNode.d.ts +1 -2
  138. package/dist/agents/nodes/ToolNode.d.ts.map +1 -1
  139. package/dist/agents/nodes/ToolNode.js +5 -5
  140. package/dist/agents/nodes/ToolNode.js.map +1 -1
  141. package/dist/agents/responses.cjs +53 -11
  142. package/dist/agents/responses.cjs.map +1 -1
  143. package/dist/agents/responses.d.cts +12 -20
  144. package/dist/agents/responses.d.cts.map +1 -1
  145. package/dist/agents/responses.d.ts +12 -20
  146. package/dist/agents/responses.d.ts.map +1 -1
  147. package/dist/agents/responses.js +53 -12
  148. package/dist/agents/responses.js.map +1 -1
  149. package/dist/agents/types.d.cts +3 -6
  150. package/dist/agents/types.d.cts.map +1 -1
  151. package/dist/agents/types.d.ts +3 -6
  152. package/dist/agents/types.d.ts.map +1 -1
  153. package/dist/agents/utils.cjs +11 -29
  154. package/dist/agents/utils.cjs.map +1 -1
  155. package/dist/agents/utils.js +9 -26
  156. package/dist/agents/utils.js.map +1 -1
  157. package/dist/agents/withAgentName.cjs.map +1 -1
  158. package/dist/agents/withAgentName.js.map +1 -1
  159. package/dist/chains/api/prompts.cjs.map +1 -1
  160. package/dist/chains/api/prompts.js.map +1 -1
  161. package/dist/chains/constitutional_ai/constitutional_chain.cjs.map +1 -1
  162. package/dist/chains/constitutional_ai/constitutional_chain.js.map +1 -1
  163. package/dist/chains/index.cjs +0 -3
  164. package/dist/chains/index.cjs.map +1 -1
  165. package/dist/chains/index.d.cts +1 -2
  166. package/dist/chains/index.d.ts +1 -2
  167. package/dist/chains/index.js +1 -3
  168. package/dist/chains/index.js.map +1 -1
  169. package/dist/chains/openai_functions/extraction.cjs.map +1 -1
  170. package/dist/chains/openai_functions/extraction.d.cts +1 -3
  171. package/dist/chains/openai_functions/extraction.d.cts.map +1 -1
  172. package/dist/chains/openai_functions/extraction.d.ts +1 -3
  173. package/dist/chains/openai_functions/extraction.d.ts.map +1 -1
  174. package/dist/chains/openai_functions/extraction.js.map +1 -1
  175. package/dist/chains/openai_functions/index.cjs +0 -5
  176. package/dist/chains/openai_functions/index.cjs.map +1 -1
  177. package/dist/chains/openai_functions/index.d.cts +1 -2
  178. package/dist/chains/openai_functions/index.d.ts +1 -2
  179. package/dist/chains/openai_functions/index.js +1 -4
  180. package/dist/chains/openai_functions/index.js.map +1 -1
  181. package/dist/chains/openai_functions/openapi.cjs +4 -4
  182. package/dist/chains/openai_functions/openapi.cjs.map +1 -1
  183. package/dist/chains/openai_functions/openapi.d.cts +1 -1
  184. package/dist/chains/openai_functions/openapi.js +4 -4
  185. package/dist/chains/openai_functions/openapi.js.map +1 -1
  186. package/dist/chains/openai_functions/tagging.cjs.map +1 -1
  187. package/dist/chains/openai_functions/tagging.d.cts +1 -3
  188. package/dist/chains/openai_functions/tagging.d.cts.map +1 -1
  189. package/dist/chains/openai_functions/tagging.d.ts +1 -3
  190. package/dist/chains/openai_functions/tagging.d.ts.map +1 -1
  191. package/dist/chains/openai_functions/tagging.js.map +1 -1
  192. package/dist/chains/query_constructor/index.cjs +4 -4
  193. package/dist/chains/query_constructor/index.cjs.map +1 -1
  194. package/dist/chains/query_constructor/index.d.cts +4 -2
  195. package/dist/chains/query_constructor/index.d.cts.map +1 -1
  196. package/dist/chains/query_constructor/index.d.ts +4 -2
  197. package/dist/chains/query_constructor/index.d.ts.map +1 -1
  198. package/dist/chains/query_constructor/index.js +1 -1
  199. package/dist/chains/query_constructor/index.js.map +1 -1
  200. package/dist/chains/question_answering/load.d.ts +2 -2
  201. package/dist/chains/question_answering/load.d.ts.map +1 -1
  202. package/dist/chains/question_answering/map_reduce_prompts.cjs.map +1 -1
  203. package/dist/chains/question_answering/map_reduce_prompts.js.map +1 -1
  204. package/dist/chains/question_answering/refine_prompts.cjs.map +1 -1
  205. package/dist/chains/question_answering/refine_prompts.js.map +1 -1
  206. package/dist/chains/question_answering/stuff_prompts.cjs.map +1 -1
  207. package/dist/chains/question_answering/stuff_prompts.js.map +1 -1
  208. package/dist/chains/router/multi_prompt.cjs +4 -4
  209. package/dist/chains/router/multi_prompt.cjs.map +1 -1
  210. package/dist/chains/router/multi_prompt.js +1 -1
  211. package/dist/chains/router/multi_prompt.js.map +1 -1
  212. package/dist/chains/router/multi_retrieval_qa.cjs +4 -4
  213. package/dist/chains/router/multi_retrieval_qa.cjs.map +1 -1
  214. package/dist/chains/router/multi_retrieval_qa.js +1 -1
  215. package/dist/chains/router/multi_retrieval_qa.js.map +1 -1
  216. package/dist/chains/sql_db/sql_db_prompt.cjs.map +1 -1
  217. package/dist/chains/sql_db/sql_db_prompt.d.cts.map +1 -1
  218. package/dist/chains/sql_db/sql_db_prompt.d.ts.map +1 -1
  219. package/dist/chains/sql_db/sql_db_prompt.js.map +1 -1
  220. package/dist/chains/summarization/stuff_prompts.cjs.map +1 -1
  221. package/dist/chains/summarization/stuff_prompts.js.map +1 -1
  222. package/dist/chat_models/universal.cjs +8 -5
  223. package/dist/chat_models/universal.cjs.map +1 -1
  224. package/dist/chat_models/universal.d.cts +2 -2
  225. package/dist/chat_models/universal.d.cts.map +1 -1
  226. package/dist/chat_models/universal.d.ts +2 -2
  227. package/dist/chat_models/universal.d.ts.map +1 -1
  228. package/dist/chat_models/universal.js +8 -5
  229. package/dist/chat_models/universal.js.map +1 -1
  230. package/dist/document_loaders/fs/directory.cjs.map +1 -1
  231. package/dist/document_loaders/fs/directory.d.cts +0 -1
  232. package/dist/document_loaders/fs/directory.d.cts.map +1 -1
  233. package/dist/document_loaders/fs/directory.d.ts +0 -1
  234. package/dist/document_loaders/fs/directory.d.ts.map +1 -1
  235. package/dist/document_loaders/fs/directory.js.map +1 -1
  236. package/dist/document_loaders/fs/json.cjs +7 -1
  237. package/dist/document_loaders/fs/json.cjs.map +1 -1
  238. package/dist/document_loaders/fs/json.js +7 -1
  239. package/dist/document_loaders/fs/json.js.map +1 -1
  240. package/dist/embeddings/cache_backed.cjs +1 -1
  241. package/dist/embeddings/cache_backed.cjs.map +1 -1
  242. package/dist/embeddings/cache_backed.d.cts +1 -1
  243. package/dist/embeddings/cache_backed.d.ts +2 -2
  244. package/dist/embeddings/cache_backed.js +2 -2
  245. package/dist/embeddings/cache_backed.js.map +1 -1
  246. package/dist/evaluation/agents/trajectory.d.cts.map +1 -1
  247. package/dist/evaluation/comparison/pairwise.d.cts.map +1 -1
  248. package/dist/evaluation/criteria/criteria.d.cts.map +1 -1
  249. package/dist/evaluation/embedding_distance/base.cjs +2 -4
  250. package/dist/evaluation/embedding_distance/base.cjs.map +1 -1
  251. package/dist/evaluation/embedding_distance/base.js +2 -3
  252. package/dist/evaluation/embedding_distance/base.js.map +1 -1
  253. package/dist/evaluation/loader.cjs +7 -12
  254. package/dist/evaluation/loader.cjs.map +1 -1
  255. package/dist/evaluation/loader.d.cts +8 -2
  256. package/dist/evaluation/loader.d.cts.map +1 -1
  257. package/dist/evaluation/loader.d.ts +8 -2
  258. package/dist/evaluation/loader.d.ts.map +1 -1
  259. package/dist/evaluation/loader.js +7 -12
  260. package/dist/evaluation/loader.js.map +1 -1
  261. package/dist/hub/base.cjs.map +1 -1
  262. package/dist/hub/base.js.map +1 -1
  263. package/dist/index.cjs +38 -6
  264. package/dist/index.cjs.map +1 -1
  265. package/dist/index.d.cts +11 -4
  266. package/dist/index.d.ts +11 -4
  267. package/dist/index.js +18 -4
  268. package/dist/index.js.map +1 -1
  269. package/dist/langchain-core/dist/load/serializable.d.cts.map +1 -1
  270. package/dist/langchain-core/dist/messages/base.d.cts +24 -33
  271. package/dist/langchain-core/dist/messages/base.d.cts.map +1 -1
  272. package/dist/langchain-core/dist/messages/content/index.d.cts +21 -2
  273. package/dist/langchain-core/dist/messages/content/index.d.cts.map +1 -1
  274. package/dist/langchain-core/dist/messages/content/tools.d.cts +67 -6
  275. package/dist/langchain-core/dist/messages/content/tools.d.cts.map +1 -1
  276. package/dist/langchain-core/dist/messages/message.d.cts +598 -0
  277. package/dist/langchain-core/dist/messages/message.d.cts.map +1 -0
  278. package/dist/langchain-core/dist/messages/metadata.d.cts +97 -0
  279. package/dist/langchain-core/dist/messages/metadata.d.cts.map +1 -0
  280. package/dist/langchain-core/dist/messages/utils.d.cts +75 -0
  281. package/dist/langchain-core/dist/messages/utils.d.cts.map +1 -0
  282. package/dist/langchain-core/dist/prompt_values.d.cts.map +1 -1
  283. package/dist/langchain-core/dist/utils/types/index.d.cts.map +1 -1
  284. package/dist/libs/langchain-core/dist/load/serializable.d.ts.map +1 -1
  285. package/dist/libs/langchain-core/dist/messages/base.d.ts +24 -33
  286. package/dist/libs/langchain-core/dist/messages/base.d.ts.map +1 -1
  287. package/dist/libs/langchain-core/dist/messages/content/index.d.ts +21 -2
  288. package/dist/libs/langchain-core/dist/messages/content/index.d.ts.map +1 -1
  289. package/dist/libs/langchain-core/dist/messages/content/tools.d.ts +67 -6
  290. package/dist/libs/langchain-core/dist/messages/content/tools.d.ts.map +1 -1
  291. package/dist/libs/langchain-core/dist/messages/message.d.ts +598 -0
  292. package/dist/libs/langchain-core/dist/messages/message.d.ts.map +1 -0
  293. package/dist/libs/langchain-core/dist/messages/metadata.d.ts +97 -0
  294. package/dist/libs/langchain-core/dist/messages/metadata.d.ts.map +1 -0
  295. package/dist/libs/langchain-core/dist/messages/utils.d.ts +75 -0
  296. package/dist/libs/langchain-core/dist/messages/utils.d.ts.map +1 -0
  297. package/dist/libs/langchain-core/dist/prompt_values.d.ts.map +1 -1
  298. package/dist/libs/langchain-core/dist/utils/types/index.d.ts +2 -0
  299. package/dist/libs/langchain-core/dist/utils/types/index.d.ts.map +1 -1
  300. package/dist/libs/langchain-core/dist/utils/types/zod.d.ts +1 -0
  301. package/dist/load/import_map.cjs +3 -14
  302. package/dist/load/import_map.cjs.map +1 -1
  303. package/dist/load/import_map.js +3 -14
  304. package/dist/load/import_map.js.map +1 -1
  305. package/dist/memory/prompt.cjs.map +1 -1
  306. package/dist/memory/prompt.d.cts.map +1 -1
  307. package/dist/memory/prompt.d.ts.map +1 -1
  308. package/dist/memory/prompt.js.map +1 -1
  309. package/dist/output_parsers/combining.cjs +1 -1
  310. package/dist/output_parsers/combining.cjs.map +1 -1
  311. package/dist/output_parsers/combining.js +1 -1
  312. package/dist/output_parsers/combining.js.map +1 -1
  313. package/dist/output_parsers/expression_type_handlers/array_literal_expression_handler.cjs.map +1 -1
  314. package/dist/output_parsers/expression_type_handlers/array_literal_expression_handler.js.map +1 -1
  315. package/dist/output_parsers/expression_type_handlers/base.cjs +1 -1
  316. package/dist/output_parsers/expression_type_handlers/base.cjs.map +1 -1
  317. package/dist/output_parsers/expression_type_handlers/base.js +1 -1
  318. package/dist/output_parsers/expression_type_handlers/base.js.map +1 -1
  319. package/dist/output_parsers/regex.cjs.map +1 -1
  320. package/dist/output_parsers/regex.js.map +1 -1
  321. package/dist/output_parsers/structured.cjs +4 -4
  322. package/dist/output_parsers/structured.cjs.map +1 -1
  323. package/dist/output_parsers/structured.d.cts +1 -1
  324. package/dist/output_parsers/structured.d.cts.map +1 -1
  325. package/dist/output_parsers/structured.d.ts +1 -1
  326. package/dist/output_parsers/structured.d.ts.map +1 -1
  327. package/dist/output_parsers/structured.js +2 -2
  328. package/dist/output_parsers/structured.js.map +1 -1
  329. package/dist/retrievers/ensemble.cjs.map +1 -1
  330. package/dist/retrievers/ensemble.js.map +1 -1
  331. package/dist/storage/file_system.cjs +1 -1
  332. package/dist/storage/file_system.cjs.map +1 -1
  333. package/dist/storage/file_system.js +1 -1
  334. package/dist/storage/file_system.js.map +1 -1
  335. package/dist/tools/fs.cjs +5 -5
  336. package/dist/tools/fs.cjs.map +1 -1
  337. package/dist/tools/fs.d.cts +1 -1
  338. package/dist/tools/fs.d.cts.map +1 -1
  339. package/dist/tools/fs.d.ts +1 -1
  340. package/dist/tools/fs.d.ts.map +1 -1
  341. package/dist/tools/fs.js +1 -1
  342. package/dist/tools/fs.js.map +1 -1
  343. package/dist/tools/retriever.cjs +2 -2
  344. package/dist/tools/retriever.cjs.map +1 -1
  345. package/dist/tools/retriever.d.cts +1 -1
  346. package/dist/tools/retriever.d.cts.map +1 -1
  347. package/dist/tools/retriever.d.ts +1 -1
  348. package/dist/tools/retriever.d.ts.map +1 -1
  349. package/dist/tools/retriever.js +1 -1
  350. package/dist/tools/retriever.js.map +1 -1
  351. package/dist/tools/sql.cjs +1 -2
  352. package/dist/tools/sql.cjs.map +1 -1
  353. package/dist/tools/sql.d.cts +1 -1
  354. package/dist/tools/sql.d.cts.map +1 -1
  355. package/dist/tools/sql.d.ts +1 -1
  356. package/dist/tools/sql.d.ts.map +1 -1
  357. package/dist/tools/sql.js +1 -2
  358. package/dist/tools/sql.js.map +1 -1
  359. package/dist/types/expression-parser.d.cts +2 -0
  360. package/dist/types/expression-parser.d.cts.map +1 -1
  361. package/dist/types/expression-parser.d.ts +2 -0
  362. package/dist/types/expression-parser.d.ts.map +1 -1
  363. package/dist/util/hub.cjs +1 -1
  364. package/dist/util/hub.js +1 -1
  365. package/dist/util/openapi.cjs +1 -1
  366. package/dist/util/openapi.cjs.map +1 -1
  367. package/dist/util/openapi.js +1 -1
  368. package/dist/util/openapi.js.map +1 -1
  369. package/package.json +15 -21
  370. package/dist/agents/middlewareAgent/middlewares/hitl.cjs +0 -235
  371. package/dist/agents/middlewareAgent/middlewares/hitl.cjs.map +0 -1
  372. package/dist/agents/middlewareAgent/middlewares/hitl.d.cts +0 -199
  373. package/dist/agents/middlewareAgent/middlewares/hitl.d.cts.map +0 -1
  374. package/dist/agents/middlewareAgent/middlewares/hitl.d.ts +0 -199
  375. package/dist/agents/middlewareAgent/middlewares/hitl.d.ts.map +0 -1
  376. package/dist/agents/middlewareAgent/middlewares/hitl.js +0 -234
  377. package/dist/agents/middlewareAgent/middlewares/hitl.js.map +0 -1
  378. package/dist/agents/middlewareAgent/middlewares/index.cjs +0 -8
  379. package/dist/agents/middlewareAgent/middlewares/index.d.cts +0 -4
  380. package/dist/agents/middlewareAgent/middlewares/index.d.ts +0 -4
  381. package/dist/agents/middlewareAgent/middlewares/index.js +0 -5
  382. package/dist/agents/middlewareAgent/middlewares/promptCaching.cjs.map +0 -1
  383. package/dist/agents/middlewareAgent/middlewares/promptCaching.d.cts.map +0 -1
  384. package/dist/agents/middlewareAgent/middlewares/promptCaching.d.ts.map +0 -1
  385. package/dist/agents/middlewareAgent/middlewares/promptCaching.js.map +0 -1
  386. package/dist/agents/middlewareAgent/middlewares/summarization.cjs.map +0 -1
  387. package/dist/agents/middlewareAgent/middlewares/summarization.d.cts.map +0 -1
  388. package/dist/agents/middlewareAgent/middlewares/summarization.d.ts.map +0 -1
  389. package/dist/agents/middlewareAgent/middlewares/summarization.js.map +0 -1
  390. package/dist/chains/openai_functions/structured_output.cjs +0 -107
  391. package/dist/chains/openai_functions/structured_output.cjs.map +0 -1
  392. package/dist/chains/openai_functions/structured_output.d.cts +0 -38
  393. package/dist/chains/openai_functions/structured_output.d.cts.map +0 -1
  394. package/dist/chains/openai_functions/structured_output.d.ts +0 -38
  395. package/dist/chains/openai_functions/structured_output.d.ts.map +0 -1
  396. package/dist/chains/openai_functions/structured_output.js +0 -105
  397. package/dist/chains/openai_functions/structured_output.js.map +0 -1
  398. package/dist/chains/openai_moderation.cjs +0 -107
  399. package/dist/chains/openai_moderation.cjs.map +0 -1
  400. package/dist/chains/openai_moderation.d.cts +0 -74
  401. package/dist/chains/openai_moderation.d.cts.map +0 -1
  402. package/dist/chains/openai_moderation.d.ts +0 -74
  403. package/dist/chains/openai_moderation.d.ts.map +0 -1
  404. package/dist/chains/openai_moderation.js +0 -106
  405. package/dist/chains/openai_moderation.js.map +0 -1
@@ -1,7 +1,7 @@
1
- import { isClientTool, validateLLMHasNoBoundTools } from "../utils.js";
1
+ import { isClientTool } from "../utils.js";
2
2
  import { ToolNode } from "../nodes/ToolNode.js";
3
3
  import { createAgentAnnotationConditional } from "./annotation.js";
4
- import { initializeMiddlewareStates } from "./nodes/utils.js";
4
+ import { initializeMiddlewareStates, parseJumpToTarget } from "./nodes/utils.js";
5
5
  import { AgentNode } from "./nodes/AgentNode.js";
6
6
  import { BeforeModelNode } from "./nodes/BeforeModalNode.js";
7
7
  import { AfterModelNode } from "./nodes/AfterModalNode.js";
@@ -16,53 +16,50 @@ var ReactAgent = class {
16
16
  this.options = options;
17
17
  this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion;
18
18
  /**
19
- * Check if the LLM already has bound tools and throw if it does.
19
+ * define complete list of tools based on options and middleware
20
20
  */
21
- if (options.llm && typeof options.llm !== "function") validateLLMHasNoBoundTools(options.llm);
22
- /**
23
- * validate that model and llm options are not provided together
24
- */
25
- if (options.llm && options.model) throw new Error("Cannot provide both `model` and `llm` options.");
26
- /**
27
- * validate that either model or llm option is provided
28
- */
29
- if (!options.llm && !options.model) throw new Error("Either `model` or `llm` option must be provided to create an agent.");
30
- const toolClasses = (Array.isArray(options.tools) ? options.tools : options.tools?.tools) ?? [];
21
+ const middlewareTools = this.options.middleware?.filter((m) => m.tools).flatMap((m) => m.tools) ?? [];
22
+ const toolClasses = [...(Array.isArray(options.tools) ? options.tools : options.tools?.tools) ?? [], ...middlewareTools];
31
23
  /**
32
24
  * If any of the tools are configured to return_directly after running,
33
25
  * our graph needs to check if these were called
34
26
  */
35
27
  const shouldReturnDirect = new Set(toolClasses.filter(isClientTool).filter((tool) => "returnDirect" in tool && tool.returnDirect).map((tool) => tool.name));
36
- const schema = createAgentAnnotationConditional(this.options.responseFormat !== void 0, this.options.middlewares);
28
+ const schema = createAgentAnnotationConditional(this.options.responseFormat !== void 0, this.options.middleware);
37
29
  const workflow = new StateGraph(schema, this.options.contextSchema);
38
30
  const allNodeWorkflows = workflow;
39
31
  const beforeModelNodes = [];
40
32
  const afterModelNodes = [];
41
- const prepareModelRequestHookMiddlewares = [];
42
- const middlewares = this.options.middlewares ?? [];
43
- for (let i = 0; i < middlewares.length; i++) {
33
+ const modifyModelRequestHookMiddleware = [];
34
+ const middlewareNames = /* @__PURE__ */ new Set();
35
+ const middleware = this.options.middleware ?? [];
36
+ for (let i = 0; i < middleware.length; i++) {
44
37
  let beforeModelNode;
45
38
  let afterModelNode;
46
- const middleware = middlewares[i];
47
- if (middleware.beforeModel) {
48
- beforeModelNode = new BeforeModelNode(middleware);
49
- const name = `before_model_${middleware.name}_${i}`;
39
+ const m = middleware[i];
40
+ if (middlewareNames.has(m.name)) throw new Error(`Middleware ${m.name} is defined multiple times`);
41
+ middlewareNames.add(m.name);
42
+ if (m.beforeModel) {
43
+ beforeModelNode = new BeforeModelNode(m);
44
+ const name = `${m.name}.before_model`;
50
45
  beforeModelNodes.push({
51
46
  index: i,
52
- name
47
+ name,
48
+ allowed: m.beforeModelJumpTo
53
49
  });
54
50
  allNodeWorkflows.addNode(name, beforeModelNode, beforeModelNode.nodeOptions);
55
51
  }
56
- if (middleware.afterModel) {
57
- afterModelNode = new AfterModelNode(middleware);
58
- const name = `after_model_${middleware.name}_${i}`;
52
+ if (m.afterModel) {
53
+ afterModelNode = new AfterModelNode(m);
54
+ const name = `${m.name}.after_model`;
59
55
  afterModelNodes.push({
60
56
  index: i,
61
- name
57
+ name,
58
+ allowed: m.afterModelJumpTo
62
59
  });
63
60
  allNodeWorkflows.addNode(name, afterModelNode, afterModelNode.nodeOptions);
64
61
  }
65
- if (middleware.prepareModelRequest) prepareModelRequestHookMiddlewares.push([middleware, () => ({
62
+ if (m.modifyModelRequest) modifyModelRequestHookMiddleware.push([m, () => ({
66
63
  ...beforeModelNode?.getState(),
67
64
  ...afterModelNode?.getState()
68
65
  })]);
@@ -71,17 +68,16 @@ var ReactAgent = class {
71
68
  * Add Nodes
72
69
  */
73
70
  allNodeWorkflows.addNode("model_request", new AgentNode({
74
- llm: this.options.llm,
75
71
  model: this.options.model,
76
- prompt: this.options.prompt,
72
+ systemPrompt: this.options.systemPrompt,
77
73
  includeAgentName: this.options.includeAgentName,
78
74
  name: this.options.name,
79
75
  responseFormat: this.options.responseFormat,
80
- middlewares: this.options.middlewares,
76
+ middleware: this.options.middleware,
81
77
  toolClasses,
82
78
  shouldReturnDirect,
83
79
  signal: this.options.signal,
84
- prepareModelRequestHookMiddlewares
80
+ modifyModelRequestHookMiddleware
85
81
  }), AgentNode.nodeOptions);
86
82
  /**
87
83
  * add single tool node for all tools
@@ -95,9 +91,18 @@ var ReactAgent = class {
95
91
  */
96
92
  if (beforeModelNodes.length > 0) allNodeWorkflows.addEdge(START, beforeModelNodes[0].name);
97
93
  else allNodeWorkflows.addEdge(START, "model_request");
98
- for (let i = 0; i < beforeModelNodes.length - 1; i++) allNodeWorkflows.addEdge(beforeModelNodes[i].name, beforeModelNodes[i + 1].name);
99
- const lastBeforeModelNode = beforeModelNodes.at(-1);
100
- if (beforeModelNodes.length > 0 && lastBeforeModelNode) allNodeWorkflows.addEdge(lastBeforeModelNode.name, "model_request");
94
+ for (let i = 0; i < beforeModelNodes.length; i++) {
95
+ const node = beforeModelNodes[i];
96
+ const current = node.name;
97
+ const isLast = i === beforeModelNodes.length - 1;
98
+ const nextDefault = isLast ? "model_request" : beforeModelNodes[i + 1].name;
99
+ if (node.allowed && node.allowed.length > 0) {
100
+ const hasTools = toolClasses.filter(isClientTool).length > 0;
101
+ const allowedMapped = node.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasTools);
102
+ const destinations = Array.from(new Set([nextDefault, ...allowedMapped]));
103
+ allNodeWorkflows.addConditionalEdges(current, this.#createBeforeModelRouter(toolClasses.filter(isClientTool), nextDefault), destinations);
104
+ } else allNodeWorkflows.addEdge(current, nextDefault);
105
+ }
101
106
  const lastAfterModelNode = afterModelNodes.at(-1);
102
107
  if (afterModelNodes.length > 0 && lastAfterModelNode) allNodeWorkflows.addEdge("model_request", lastAfterModelNode.name);
103
108
  else {
@@ -105,12 +110,24 @@ var ReactAgent = class {
105
110
  if (modelPaths.length === 1) allNodeWorkflows.addEdge("model_request", modelPaths[0]);
106
111
  else allNodeWorkflows.addConditionalEdges("model_request", this.#createModelRouter(), modelPaths);
107
112
  }
108
- for (let i = afterModelNodes.length - 1; i > 0; i--) allNodeWorkflows.addEdge(afterModelNodes[i].name, afterModelNodes[i - 1].name);
113
+ for (let i = afterModelNodes.length - 1; i > 0; i--) {
114
+ const node = afterModelNodes[i];
115
+ const current = node.name;
116
+ const nextDefault = afterModelNodes[i - 1].name;
117
+ if (node.allowed && node.allowed.length > 0) {
118
+ const hasTools = toolClasses.filter(isClientTool).length > 0;
119
+ const allowedMapped = node.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasTools);
120
+ const destinations = Array.from(new Set([nextDefault, ...allowedMapped]));
121
+ allNodeWorkflows.addConditionalEdges(current, this.#createAfterModelSequenceRouter(toolClasses.filter(isClientTool), node.allowed, nextDefault), destinations);
122
+ } else allNodeWorkflows.addEdge(current, nextDefault);
123
+ }
109
124
  if (afterModelNodes.length > 0) {
110
- const firstAfterModelNode = afterModelNodes[0].name;
111
- const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool));
112
- if (modelPaths.length === 1) allNodeWorkflows.addEdge(firstAfterModelNode, modelPaths[0]);
113
- else allNodeWorkflows.addConditionalEdges(firstAfterModelNode, this.#createModelRouter(), modelPaths);
125
+ const firstAfterModel = afterModelNodes[0];
126
+ const firstAfterModelNode = firstAfterModel.name;
127
+ const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool), true).filter((p) => p !== "tools" || toolClasses.filter(isClientTool).length > 0);
128
+ const allowJump = Boolean(firstAfterModel.allowed && firstAfterModel.allowed.length > 0);
129
+ const destinations = modelPaths;
130
+ allNodeWorkflows.addConditionalEdges(firstAfterModelNode, this.#createAfterModelRouter(toolClasses.filter(isClientTool), allowJump), destinations);
114
131
  }
115
132
  /**
116
133
  * add edges for tools node
@@ -127,15 +144,13 @@ var ReactAgent = class {
127
144
  */
128
145
  this.#graph = allNodeWorkflows.compile({
129
146
  checkpointer: this.options.checkpointer ?? this.options.checkpointSaver,
130
- interruptBefore: this.options.interruptBefore,
131
- interruptAfter: this.options.interruptAfter,
132
147
  store: this.options.store,
133
148
  name: this.options.name,
134
149
  description: this.options.description
135
150
  });
136
151
  }
137
152
  /**
138
- * Get the compiled graph.
153
+ * Get the compiled {@link https://docs.langchain.com/oss/javascript/langgraph/use-graph-api | StateGraph}.
139
154
  */
140
155
  get graph() {
141
156
  return this.#graph;
@@ -143,79 +158,271 @@ var ReactAgent = class {
143
158
  /**
144
159
  * Get possible edge destinations from model node.
145
160
  * @param toolClasses names of tools to call
161
+ * @param includeModelRequest whether to include "model_request" as a valid path (for jumpTo routing)
146
162
  * @returns list of possible edge destinations
147
163
  */
148
- #getModelPaths(toolClasses) {
164
+ #getModelPaths(toolClasses, includeModelRequest = false) {
149
165
  const paths = [];
150
166
  if (toolClasses.length > 0) paths.push("tools");
167
+ if (includeModelRequest) paths.push("model_request");
151
168
  paths.push(END);
152
169
  return paths;
153
170
  }
154
171
  /**
172
+ * Create routing function for tools node conditional edges.
173
+ */
174
+ #createToolsRouter(shouldReturnDirect) {
175
+ /**
176
+ * ToDo: fix type
177
+ */
178
+ return (state) => {
179
+ const messages = state.messages;
180
+ const lastMessage = messages[messages.length - 1];
181
+ if (ToolMessage.isInstance(lastMessage) && lastMessage.name && shouldReturnDirect.has(lastMessage.name)) return this.options.responseFormat ? "model_request" : END;
182
+ return "model_request";
183
+ };
184
+ }
185
+ /**
155
186
  * Create routing function for model node conditional edges.
156
187
  */
157
188
  #createModelRouter() {
158
189
  /**
159
190
  * determine if the agent should continue or not
160
191
  */
161
- /**
162
- * ToDo: fix type
163
- */
164
192
  return (state) => {
165
193
  const messages = state.messages;
166
194
  const lastMessage = messages.at(-1);
167
- if (!(lastMessage instanceof AIMessage) || !lastMessage.tool_calls || lastMessage.tool_calls.length === 0) return END;
195
+ if (!AIMessage.isInstance(lastMessage) || !lastMessage.tool_calls || lastMessage.tool_calls.length === 0) return END;
196
+ const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every((toolCall) => toolCall.name.startsWith("extract-"));
197
+ if (hasOnlyStructuredResponseCalls) return END;
168
198
  /**
169
199
  * The tool node processes a single message.
170
200
  */
171
201
  if (this.#toolBehaviorVersion === "v1") return "tools";
172
202
  /**
173
- * Route to tools node
203
+ * Route to tools node (filter out any structured response tool calls)
174
204
  */
175
- return lastMessage.tool_calls.map((toolCall) => new Send("tools", {
205
+ const regularToolCalls = lastMessage.tool_calls.filter((toolCall) => !toolCall.name.startsWith("extract-"));
206
+ if (regularToolCalls.length === 0) return END;
207
+ return regularToolCalls.map((toolCall) => new Send("tools", {
176
208
  ...state,
177
209
  lg_tool_call: toolCall
178
210
  }));
179
211
  };
180
212
  }
181
213
  /**
182
- * Create routing function for tools node conditional edges.
214
+ * Create routing function for jumpTo functionality after afterModel hooks.
215
+ *
216
+ * This router checks if the `jumpTo` property is set in the state after afterModel middleware
217
+ * execution. If set, it routes to the specified target ("model_request" or "tools").
218
+ * If not set, it falls back to the normal model routing logic for afterModel context.
219
+ *
220
+ * The jumpTo property is automatically cleared after use to prevent infinite loops.
221
+ *
222
+ * @param toolClasses - Available tool classes for validation
223
+ * @returns Router function that handles jumpTo logic and normal routing
183
224
  */
184
- #createToolsRouter(shouldReturnDirect) {
185
- /**
186
- * ToDo: fix type
187
- */
225
+ #createAfterModelRouter(toolClasses, allowJump) {
226
+ const hasStructuredResponse = Boolean(this.options.responseFormat);
188
227
  return (state) => {
189
228
  const messages = state.messages;
190
- const lastMessage = messages[messages.length - 1];
191
- if (lastMessage instanceof ToolMessage && lastMessage.name && shouldReturnDirect.has(lastMessage.name)) return this.options.responseFormat ? "model_request" : END;
192
- return "model_request";
229
+ const lastMessage = messages.at(-1);
230
+ if (AIMessage.isInstance(lastMessage) && (!lastMessage.tool_calls || lastMessage.tool_calls.length === 0)) return END;
231
+ if (allowJump && state.jumpTo) {
232
+ if (state.jumpTo === END) return END;
233
+ if (state.jumpTo === "tools") {
234
+ if (toolClasses.length === 0) return END;
235
+ return new Send("tools", {
236
+ ...state,
237
+ jumpTo: void 0
238
+ });
239
+ }
240
+ return new Send("model_request", {
241
+ ...state,
242
+ jumpTo: void 0
243
+ });
244
+ }
245
+ const toolMessages = messages.filter(ToolMessage.isInstance);
246
+ const lastAiMessage = messages.filter(AIMessage.isInstance).at(-1);
247
+ const pendingToolCalls = lastAiMessage?.tool_calls?.filter((call) => !toolMessages.some((m) => m.tool_call_id === call.id));
248
+ if (pendingToolCalls && pendingToolCalls.length > 0) return pendingToolCalls.map((toolCall) => new Send("tools", {
249
+ ...state,
250
+ lg_tool_call: toolCall
251
+ }));
252
+ const hasStructuredResponseCalls = lastAiMessage?.tool_calls?.some((toolCall) => toolCall.name.startsWith("extract-"));
253
+ if (pendingToolCalls && pendingToolCalls.length === 0 && !hasStructuredResponseCalls && hasStructuredResponse) return "model_request";
254
+ if (!AIMessage.isInstance(lastMessage) || !lastMessage.tool_calls || lastMessage.tool_calls.length === 0) return END;
255
+ const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every((toolCall) => toolCall.name.startsWith("extract-"));
256
+ const hasRegularToolCalls = lastMessage.tool_calls.some((toolCall) => !toolCall.name.startsWith("extract-"));
257
+ if (hasOnlyStructuredResponseCalls || !hasRegularToolCalls) return END;
258
+ /**
259
+ * For routing from afterModel nodes, always use simple string paths
260
+ * The Send API is handled at the model_request node level
261
+ */
262
+ return "tools";
263
+ };
264
+ }
265
+ /**
266
+ * Router for afterModel sequence nodes (connecting later middlewares to earlier ones),
267
+ * honoring allowed jump targets and defaulting to the next node.
268
+ */
269
+ #createAfterModelSequenceRouter(toolClasses, allowed, nextDefault) {
270
+ const allowedSet = new Set(allowed.map((t) => parseJumpToTarget(t)));
271
+ return (state) => {
272
+ if (state.jumpTo) {
273
+ const dest = parseJumpToTarget(state.jumpTo);
274
+ if (dest === END && allowedSet.has(END)) return END;
275
+ if (dest === "tools" && allowedSet.has("tools")) {
276
+ if (toolClasses.length === 0) return END;
277
+ return new Send("tools", {
278
+ ...state,
279
+ jumpTo: void 0
280
+ });
281
+ }
282
+ if (dest === "model_request" && allowedSet.has("model_request")) return new Send("model_request", {
283
+ ...state,
284
+ jumpTo: void 0
285
+ });
286
+ }
287
+ return nextDefault;
288
+ };
289
+ }
290
+ /**
291
+ * Create routing function for jumpTo functionality after beforeModel hooks.
292
+ * Falls back to the default next node if no jumpTo is present.
293
+ */
294
+ #createBeforeModelRouter(toolClasses, nextDefault) {
295
+ return (state) => {
296
+ if (!state.jumpTo) return nextDefault;
297
+ const destination = parseJumpToTarget(state.jumpTo);
298
+ if (destination === END) return END;
299
+ if (destination === "tools") {
300
+ if (toolClasses.length === 0) return END;
301
+ return new Send("tools", {
302
+ ...state,
303
+ jumpTo: void 0
304
+ });
305
+ }
306
+ return new Send("model_request", {
307
+ ...state,
308
+ jumpTo: void 0
309
+ });
193
310
  };
194
311
  }
195
312
  /**
196
313
  * Initialize middleware states if not already present in the input state.
197
314
  */
198
- #initializeMiddlewareStates(state) {
199
- if (!this.options.middlewares || this.options.middlewares.length === 0 || state instanceof Command || !state) return state;
200
- const defaultStates = initializeMiddlewareStates(this.options.middlewares, state);
315
+ async #initializeMiddlewareStates(state) {
316
+ if (!this.options.middleware || this.options.middleware.length === 0 || state instanceof Command || !state) return state;
317
+ const defaultStates = await initializeMiddlewareStates(this.options.middleware, state);
201
318
  const updatedState = { ...state };
202
319
  if (!updatedState) return updatedState;
203
320
  for (const [key, value] of Object.entries(defaultStates)) if (!(key in updatedState)) updatedState[key] = value;
204
321
  return updatedState;
205
322
  }
206
323
  /**
207
- * @inheritdoc
324
+ * Executes the agent with the given state and returns the final state after all processing.
325
+ *
326
+ * This method runs the agent's entire workflow synchronously, including:
327
+ * - Processing the input messages through any configured middleware
328
+ * - Calling the language model to generate responses
329
+ * - Executing any tool calls made by the model
330
+ * - Running all middleware hooks (beforeModel, afterModel, etc.)
331
+ *
332
+ * @param state - The initial state for the agent execution. Can be:
333
+ * - An object containing `messages` array and any middleware-specific state properties
334
+ * - A Command object for more advanced control flow
335
+ *
336
+ * @param config - Optional runtime configuration including:
337
+ * @param config.context - The context for the agent execution.
338
+ * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.
339
+ * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}.
340
+ * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution.
341
+ * @param config.recursionLimit - The recursion limit for the agent execution.
342
+ *
343
+ * @returns A Promise that resolves to the final agent state after execution completes.
344
+ * The returned state includes:
345
+ * - a `messages` property containing an array with all messages (input, AI responses, tool calls/results)
346
+ * - a `structuredResponse` property containing the structured response (if configured)
347
+ * - all state values defined in the middleware
348
+ *
349
+ * @example
350
+ * ```typescript
351
+ * const agent = new ReactAgent({
352
+ * llm: myModel,
353
+ * tools: [calculator, webSearch],
354
+ * responseFormat: z.object({
355
+ * weather: z.string(),
356
+ * }),
357
+ * });
358
+ *
359
+ * const result = await agent.invoke({
360
+ * messages: [{ role: "human", content: "What's the weather in Paris?" }]
361
+ * });
362
+ *
363
+ * console.log(result.structuredResponse.weather); // outputs: "It's sunny and 75°F."
364
+ * ```
208
365
  */
209
- get invoke() {
210
- const invokeFunc = async (state, config) => {
211
- const initializedState = this.#initializeMiddlewareStates(state);
212
- return this.#graph.invoke(initializedState, config);
213
- };
214
- return invokeFunc;
366
+ async invoke(state, config) {
367
+ const initializedState = await this.#initializeMiddlewareStates(state);
368
+ return this.#graph.invoke(initializedState, config);
215
369
  }
216
370
  /**
217
- * ToDo(@christian-bromann): Add stream and streamEvents methods
371
+ * Executes the agent with streaming, returning an async iterable of events as they occur.
372
+ *
373
+ * This method runs the agent's workflow similar to `invoke`, but instead of waiting for
374
+ * completion, it streams events in real-time. This allows you to:
375
+ * - Display intermediate results to users as they're generated
376
+ * - Monitor the agent's progress through each step
377
+ * - Handle tool calls and results as they happen
378
+ * - Update UI with streaming responses from the LLM
379
+ *
380
+ * @param state - The initial state for the agent execution. Can be:
381
+ * - An object containing `messages` array and any middleware-specific state properties
382
+ * - A Command object for more advanced control flow
383
+ *
384
+ * @param config - Optional runtime configuration including:
385
+ * @param config.context - The context for the agent execution.
386
+ * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.
387
+ * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}.
388
+ * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution.
389
+ * @param config.streamMode - The streaming mode for the agent execution, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/streaming#supported-stream-modes | Supported stream modes}.
390
+ * @param config.recursionLimit - The recursion limit for the agent execution.
391
+ *
392
+ * @returns A Promise that resolves to an IterableReadableStream of events.
393
+ * Events include:
394
+ * - `on_chat_model_start`: When the LLM begins processing
395
+ * - `on_chat_model_stream`: Streaming tokens from the LLM
396
+ * - `on_chat_model_end`: When the LLM completes
397
+ * - `on_tool_start`: When a tool execution begins
398
+ * - `on_tool_end`: When a tool execution completes
399
+ * - `on_chain_start`: When middleware chains begin
400
+ * - `on_chain_end`: When middleware chains complete
401
+ * - And other LangGraph v2 stream events
402
+ *
403
+ * @example
404
+ * ```typescript
405
+ * const agent = new ReactAgent({
406
+ * llm: myModel,
407
+ * tools: [calculator, webSearch]
408
+ * });
409
+ *
410
+ * const stream = await agent.stream({
411
+ * messages: [{ role: "human", content: "What's 2+2 and the weather in NYC?" }]
412
+ * });
413
+ *
414
+ * for await (const event of stream) {
415
+ * //
416
+ * }
417
+ * ```
218
418
  */
419
+ async stream(state, config) {
420
+ const initializedState = await this.#initializeMiddlewareStates(state);
421
+ return this.#graph.streamEvents(initializedState, {
422
+ ...config,
423
+ version: "v2"
424
+ });
425
+ }
219
426
  /**
220
427
  * Visualize the graph as a PNG image.
221
428
  * @param params - Parameters for the drawMermaidPng method.
@@ -1 +1 @@
1
- {"version":3,"file":"ReactAgent.js","names":["options: CreateAgentParams<StructuredResponseFormat, ContextSchema>","#toolBehaviorVersion","beforeModelNodes: { index: number; name: string }[]","afterModelNodes: { index: number; name: string }[]","prepareModelRequestHookMiddlewares: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any\n ][]","beforeModelNode: BeforeModelNode | undefined","afterModelNode: AfterModelNode | undefined","#getModelPaths","#createModelRouter","toolReturnTarget: string","#createToolsRouter","#graph","toolClasses: (ClientTool | ServerTool)[]","paths: (\"tools\" | typeof END)[]","state: any","shouldReturnDirect: Set<string>","state: InvokeStateParameter<TMiddlewares>","invokeFunc: InvokeFunction","config?: LangGraphRunnableConfig<FullContext>","#initializeMiddlewareStates","params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }"],"sources":["../../../src/agents/middlewareAgent/ReactAgent.ts"],"sourcesContent":["/* eslint-disable prefer-destructuring, no-instanceof/no-instanceof, @typescript-eslint/ban-types */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\n\nimport {\n AnnotationRoot,\n StateGraph,\n END,\n START,\n Send,\n Command,\n CompiledStateGraph,\n type LangGraphRunnableConfig,\n} from \"@langchain/langgraph\";\nimport { ToolMessage, AIMessage } from \"@langchain/core/messages\";\n\nimport { createAgentAnnotationConditional } from \"./annotation.js\";\nimport { isClientTool, validateLLMHasNoBoundTools } from \"../utils.js\";\n\nimport { AgentNode } from \"./nodes/AgentNode.js\";\nimport { ToolNode } from \"../nodes/ToolNode.js\";\nimport { BeforeModelNode } from \"./nodes/BeforeModalNode.js\";\nimport { AfterModelNode } from \"./nodes/AfterModalNode.js\";\nimport { initializeMiddlewareStates } from \"./nodes/utils.js\";\n\nimport type { ClientTool, ServerTool, WithStateGraphNodes } from \"../types.js\";\n\nimport {\n CreateAgentParams,\n AgentMiddleware,\n InferMiddlewareStates,\n InferMiddlewareInputStates,\n BuiltInState,\n InferMiddlewareContextInputs,\n IsAllOptional,\n InferContextInput,\n} from \"./types.js\";\n\nimport {\n type AnyAnnotationRoot,\n type ToAnnotationRoot,\n} from \"../annotation.js\";\nimport type { ResponseFormatUndefined } from \"../responses.js\";\n\n// Helper type to get the state definition with middleware states\ntype MergedAgentState<\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined,\n TMiddlewares extends readonly AgentMiddleware<any, any, any>[]\n> = (StructuredResponseFormat extends ResponseFormatUndefined\n ? BuiltInState\n : BuiltInState & { structuredResponse: StructuredResponseFormat }) &\n InferMiddlewareStates<TMiddlewares>;\n\ntype InvokeStateParameter<\n TMiddlewares extends readonly AgentMiddleware<any, any, any>[]\n> =\n | (BuiltInState & InferMiddlewareInputStates<TMiddlewares>)\n | Command<any, any, any>\n | null;\n\ntype AgentGraph<\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<any, any, any>[] = []\n> = CompiledStateGraph<\n any,\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n any,\n MergedAgentState<StructuredResponseFormat, TMiddlewares>,\n ToAnnotationRoot<ContextSchema>[\"spec\"],\n unknown\n>;\n\nexport class ReactAgent<\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddlewares extends readonly AgentMiddleware<any, any, any>[] = []\n> {\n #graph: AgentGraph<StructuredResponseFormat, ContextSchema, TMiddlewares>;\n\n #toolBehaviorVersion: \"v1\" | \"v2\" = \"v2\";\n\n constructor(\n public options: CreateAgentParams<StructuredResponseFormat, ContextSchema>\n ) {\n this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion;\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n if (options.llm && typeof options.llm !== \"function\") {\n validateLLMHasNoBoundTools(options.llm);\n }\n\n /**\n * validate that model and llm options are not provided together\n */\n if (options.llm && options.model) {\n throw new Error(\"Cannot provide both `model` and `llm` options.\");\n }\n\n /**\n * validate that either model or llm option is provided\n */\n if (!options.llm && !options.model) {\n throw new Error(\n \"Either `model` or `llm` option must be provided to create an agent.\"\n );\n }\n\n const toolClasses =\n (Array.isArray(options.tools) ? options.tools : options.tools?.tools) ??\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 */\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 // Create a schema that merges agent base schema with middleware state schemas\n const schema = createAgentAnnotationConditional<\n StructuredResponseFormat,\n TMiddlewares\n >(\n this.options.responseFormat !== undefined,\n this.options.middlewares as TMiddlewares\n );\n\n const workflow = new StateGraph(\n schema as AnnotationRoot<any>,\n this.options.contextSchema\n );\n\n const allNodeWorkflows = workflow as WithStateGraphNodes<\n \"tools\" | \"model_request\" | string,\n typeof workflow\n >;\n\n // Generate node names for middleware nodes that have hooks\n const beforeModelNodes: { index: number; name: string }[] = [];\n const afterModelNodes: { index: number; name: string }[] = [];\n const prepareModelRequestHookMiddlewares: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any\n ][] = [];\n\n const middlewares = this.options.middlewares ?? [];\n for (let i = 0; i < middlewares.length; i++) {\n let beforeModelNode: BeforeModelNode | undefined;\n let afterModelNode: AfterModelNode | undefined;\n const middleware = middlewares[i];\n if (middleware.beforeModel) {\n beforeModelNode = new BeforeModelNode(middleware);\n const name = `before_model_${middleware.name}_${i}`;\n beforeModelNodes.push({\n index: i,\n name,\n });\n allNodeWorkflows.addNode(\n name,\n beforeModelNode,\n beforeModelNode.nodeOptions\n );\n }\n if (middleware.afterModel) {\n afterModelNode = new AfterModelNode(middleware);\n const name = `after_model_${middleware.name}_${i}`;\n afterModelNodes.push({\n index: i,\n name,\n });\n allNodeWorkflows.addNode(\n name,\n afterModelNode,\n afterModelNode.nodeOptions\n );\n }\n\n if (middleware.prepareModelRequest) {\n prepareModelRequestHookMiddlewares.push([\n middleware,\n () => ({\n ...beforeModelNode?.getState(),\n ...afterModelNode?.getState(),\n }),\n ]);\n }\n }\n\n /**\n * Add Nodes\n */\n allNodeWorkflows.addNode(\n \"model_request\",\n new AgentNode({\n llm: this.options.llm,\n model: this.options.model,\n prompt: this.options.prompt,\n includeAgentName: this.options.includeAgentName,\n name: this.options.name,\n responseFormat: this.options.responseFormat,\n middlewares: this.options.middlewares,\n toolClasses,\n shouldReturnDirect,\n signal: this.options.signal,\n prepareModelRequestHookMiddlewares,\n }),\n AgentNode.nodeOptions\n );\n\n /**\n * add single tool node for all tools\n */\n if (toolClasses.length > 0) {\n const toolNode = new ToolNode(toolClasses.filter(isClientTool), {\n signal: this.options.signal,\n });\n allNodeWorkflows.addNode(\"tools\", toolNode);\n }\n\n /**\n * Add Edges\n */\n // Determine starting point based on what nodes exist\n if (beforeModelNodes.length > 0) {\n // If we have beforeModel nodes, start with the first one\n allNodeWorkflows.addEdge(START, beforeModelNodes[0].name);\n } else {\n // If no beforeModel nodes, go directly to agent\n allNodeWorkflows.addEdge(START, \"model_request\");\n }\n\n // Connect beforeModel nodes in sequence\n for (let i = 0; i < beforeModelNodes.length - 1; i++) {\n allNodeWorkflows.addEdge(\n beforeModelNodes[i].name,\n beforeModelNodes[i + 1].name\n );\n }\n\n // Connect last beforeModel node to agent\n const lastBeforeModelNode = beforeModelNodes.at(-1);\n if (beforeModelNodes.length > 0 && lastBeforeModelNode) {\n allNodeWorkflows.addEdge(lastBeforeModelNode.name, \"model_request\");\n }\n\n // Connect agent to last afterModel node (for reverse order execution)\n const lastAfterModelNode = afterModelNodes.at(-1);\n if (afterModelNodes.length > 0 && lastAfterModelNode) {\n allNodeWorkflows.addEdge(\"model_request\", lastAfterModelNode.name);\n } else {\n const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool));\n if (modelPaths.length === 1) {\n allNodeWorkflows.addEdge(\"model_request\", modelPaths[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n \"model_request\",\n this.#createModelRouter(),\n modelPaths\n );\n }\n }\n\n // Connect afterModel nodes in reverse sequence\n for (let i = afterModelNodes.length - 1; i > 0; i--) {\n allNodeWorkflows.addEdge(\n afterModelNodes[i].name,\n afterModelNodes[i - 1].name\n );\n }\n\n // Connect first afterModel node (last to execute) to model paths\n if (afterModelNodes.length > 0) {\n const firstAfterModelNode = afterModelNodes[0].name;\n const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool));\n if (modelPaths.length === 1) {\n allNodeWorkflows.addEdge(firstAfterModelNode, modelPaths[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n firstAfterModelNode,\n this.#createModelRouter(),\n modelPaths\n );\n }\n }\n\n /**\n * add edges for tools node\n */\n if (toolClasses.length > 0) {\n // Tools should return to first beforeModel node or agent\n let toolReturnTarget: string;\n if (beforeModelNodes.length > 0) {\n toolReturnTarget = beforeModelNodes[0].name;\n } else {\n toolReturnTarget = \"model_request\";\n }\n\n if (shouldReturnDirect.size > 0) {\n allNodeWorkflows.addConditionalEdges(\n \"tools\",\n this.#createToolsRouter(shouldReturnDirect),\n [toolReturnTarget, END]\n );\n } else {\n allNodeWorkflows.addEdge(\"tools\", toolReturnTarget);\n }\n }\n\n /**\n * compile the graph\n */\n this.#graph = allNodeWorkflows.compile({\n checkpointer: this.options.checkpointer ?? this.options.checkpointSaver,\n interruptBefore: this.options.interruptBefore,\n interruptAfter: this.options.interruptAfter,\n store: this.options.store,\n name: this.options.name,\n description: this.options.description,\n }) as AgentGraph<StructuredResponseFormat, ContextSchema, TMiddlewares>;\n }\n\n /**\n * Get the compiled graph.\n */\n get graph(): AgentGraph<\n StructuredResponseFormat,\n ContextSchema,\n TMiddlewares\n > {\n return this.#graph;\n }\n\n /**\n * Get possible edge destinations from model node.\n * @param toolClasses names of tools to call\n * @returns list of possible edge destinations\n */\n #getModelPaths(\n toolClasses: (ClientTool | ServerTool)[]\n ): (\"tools\" | typeof END)[] {\n const paths: (\"tools\" | typeof END)[] = [];\n if (toolClasses.length > 0) {\n paths.push(\"tools\");\n }\n\n paths.push(END);\n\n return paths;\n }\n\n /**\n * Create routing function for model node conditional edges.\n */\n #createModelRouter() {\n /**\n * determine if the agent should continue or not\n */\n /**\n * ToDo: fix type\n */\n return (state: any) => {\n const messages = state.messages;\n const lastMessage = messages.at(-1);\n\n if (\n !(lastMessage instanceof AIMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n return END;\n }\n\n /**\n * The tool node processes a single message.\n */\n if (this.#toolBehaviorVersion === \"v1\") {\n return \"tools\";\n }\n\n /**\n * Route to tools node\n */\n return lastMessage.tool_calls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n };\n }\n\n /**\n * Create routing function for tools node conditional edges.\n */\n #createToolsRouter(shouldReturnDirect: Set<string>) {\n /**\n * ToDo: fix type\n */\n return (state: any) => {\n const messages = state.messages;\n const lastMessage = messages[messages.length - 1];\n\n // Check if we just executed a returnDirect tool\n if (\n lastMessage instanceof ToolMessage &&\n lastMessage.name &&\n shouldReturnDirect.has(lastMessage.name)\n ) {\n // If we have a response format, route to agent to generate structured response\n // Otherwise, return directly\n return this.options.responseFormat ? \"model_request\" : END;\n }\n\n // For non-returnDirect tools, always route back to agent\n return \"model_request\";\n };\n }\n\n /**\n * Initialize middleware states if not already present in the input state.\n */\n #initializeMiddlewareStates(\n state: InvokeStateParameter<TMiddlewares>\n ): InvokeStateParameter<TMiddlewares> {\n if (\n !this.options.middlewares ||\n this.options.middlewares.length === 0 ||\n state instanceof Command ||\n !state\n ) {\n return state;\n }\n\n const defaultStates = initializeMiddlewareStates(\n this.options.middlewares,\n state\n );\n const updatedState = { ...state } as InvokeStateParameter<TMiddlewares>;\n if (!updatedState) {\n return updatedState;\n }\n\n // Only add defaults for keys that don't exist in current state\n for (const [key, value] of Object.entries(defaultStates)) {\n if (!(key in updatedState)) {\n // @ts-expect-error - ToDo: fix type\n updatedState[key as keyof InvokeStateParameter<TMiddlewares>] = value;\n }\n }\n\n return updatedState;\n }\n\n /**\n * @inheritdoc\n */\n get invoke() {\n type FullState = MergedAgentState<StructuredResponseFormat, TMiddlewares>;\n type FullContext = InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddlewares>;\n\n // Create overloaded function type based on whether context has required fields\n type InvokeFunction = IsAllOptional<FullContext> extends true\n ? (\n state: InvokeStateParameter<TMiddlewares>,\n config?: LangGraphRunnableConfig<FullContext>\n ) => Promise<FullState>\n : (\n state: InvokeStateParameter<TMiddlewares>,\n config?: LangGraphRunnableConfig<FullContext>\n ) => Promise<FullState>;\n\n const invokeFunc: InvokeFunction = async (\n state: InvokeStateParameter<TMiddlewares>,\n config?: LangGraphRunnableConfig<FullContext>\n ): Promise<FullState> => {\n const initializedState = this.#initializeMiddlewareStates(state);\n return this.#graph.invoke(\n initializedState,\n config as any\n ) as Promise<FullState>;\n };\n\n return invokeFunc;\n }\n\n /**\n * ToDo(@christian-bromann): Add stream and streamEvents methods\n */\n\n /**\n * Visualize the graph as a PNG image.\n * @param params - Parameters for the drawMermaidPng method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns PNG image as a buffer\n */\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n const image = await representation.drawMermaidPng(params);\n const arrayBuffer = await image.arrayBuffer();\n const buffer = new Uint8Array(arrayBuffer);\n return buffer;\n }\n\n /**\n * Draw the graph as a Mermaid string.\n * @param params - Parameters for the drawMermaid method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns Mermaid string\n */\n async drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n return representation.drawMermaid(params);\n }\n}\n"],"mappings":";;;;;;;;;;;AAgFA,IAAa,aAAb,MAQE;CACA;CAEA,uBAAoC;CAEpC,YACSA,SACP;EADO;EAEP,KAAKC,uBAAuB,QAAQ,WAAW,KAAKA;;;;AAKpD,MAAI,QAAQ,OAAO,OAAO,QAAQ,QAAQ,YACxC,2BAA2B,QAAQ,IAA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AAO,eAAe,YAAY,OAAO;CAC1C;AACF"}
1
+ {"version":3,"file":"ReactAgent.js","names":["options: CreateAgentParams<StructuredResponseFormat, ContextSchema>","#toolBehaviorVersion","beforeModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[]","afterModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[]","modifyModelRequestHookMiddleware: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any\n ][]","beforeModelNode: BeforeModelNode | undefined","afterModelNode: AfterModelNode | undefined","#createBeforeModelRouter","#getModelPaths","#createModelRouter","#createAfterModelSequenceRouter","#createAfterModelRouter","toolReturnTarget: string","#createToolsRouter","#graph","toolClasses: (ClientTool | ServerTool)[]","includeModelRequest: boolean","paths: (\"tools\" | \"model_request\" | typeof END)[]","shouldReturnDirect: Set<string>","state: any","state: BuiltInState","allowJump: boolean","state: Omit<BuiltInState, \"jumpTo\"> & { jumpTo?: JumpTo }","allowed: string[]","nextDefault: string","#initializeMiddlewareStates","state: InvokeStateParameter<TMiddleware>","config?: InvokeConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >","config?: StreamConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >","params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }"],"sources":["../../../src/agents/middlewareAgent/ReactAgent.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\n\nimport {\n AnnotationRoot,\n StateGraph,\n END,\n START,\n Send,\n Command,\n CompiledStateGraph,\n} from \"@langchain/langgraph\";\nimport { ToolMessage, AIMessage } from \"@langchain/core/messages\";\nimport { IterableReadableStream } from \"@langchain/core/utils/stream\";\n\nimport { createAgentAnnotationConditional } from \"./annotation.js\";\nimport { isClientTool } from \"../utils.js\";\n\nimport { AgentNode } from \"./nodes/AgentNode.js\";\nimport { ToolNode } from \"../nodes/ToolNode.js\";\nimport { BeforeModelNode } from \"./nodes/BeforeModalNode.js\";\nimport { AfterModelNode } from \"./nodes/AfterModalNode.js\";\nimport {\n initializeMiddlewareStates,\n parseJumpToTarget,\n} from \"./nodes/utils.js\";\n\nimport type { ClientTool, ServerTool, WithStateGraphNodes } from \"../types.js\";\n\nimport type {\n CreateAgentParams,\n AgentMiddleware,\n InferMiddlewareStates,\n InferMiddlewareInputStates,\n BuiltInState,\n InferMiddlewareContextInputs,\n InferContextInput,\n InvokeConfiguration,\n StreamConfiguration,\n JumpTo,\n} from \"./types.js\";\n\nimport {\n type AnyAnnotationRoot,\n type ToAnnotationRoot,\n type ResponseFormatUndefined,\n} from \"../annotation.js\";\n\n// Helper type to get the state definition with middleware states\ntype MergedAgentState<\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined,\n TMiddleware extends readonly AgentMiddleware<any, any, any>[]\n> = (StructuredResponseFormat extends ResponseFormatUndefined\n ? Omit<BuiltInState, \"jumpTo\">\n : Omit<BuiltInState, \"jumpTo\"> & {\n structuredResponse: StructuredResponseFormat;\n }) &\n InferMiddlewareStates<TMiddleware>;\n\ntype InvokeStateParameter<\n TMiddleware extends readonly AgentMiddleware<any, any, any>[]\n> =\n | (BuiltInState & InferMiddlewareInputStates<TMiddleware>)\n | Command<any, any, any>\n | null;\n\ntype AgentGraph<\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<any, any, any>[] = []\n> = CompiledStateGraph<\n any,\n any,\n any,\n any,\n MergedAgentState<StructuredResponseFormat, TMiddleware>,\n ToAnnotationRoot<ContextSchema>[\"spec\"],\n unknown\n>;\n\nexport class ReactAgent<\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n> {\n #graph: AgentGraph<StructuredResponseFormat, ContextSchema, TMiddleware>;\n\n #toolBehaviorVersion: \"v1\" | \"v2\" = \"v2\";\n\n constructor(\n public options: CreateAgentParams<StructuredResponseFormat, ContextSchema>\n ) {\n this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion;\n\n /**\n * define complete list of tools based on options and middleware\n */\n const middlewareTools = (this.options.middleware\n ?.filter((m) => m.tools)\n .flatMap((m) => m.tools) ?? []) as (ClientTool | ServerTool)[];\n const toolClasses = [\n ...((Array.isArray(options.tools)\n ? options.tools\n : options.tools?.tools) ?? []),\n ...middlewareTools,\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 */\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 // Create a schema that merges agent base schema with middleware state schemas\n const schema = createAgentAnnotationConditional<\n StructuredResponseFormat,\n TMiddleware\n >(\n this.options.responseFormat !== undefined,\n this.options.middleware as TMiddleware\n );\n\n const workflow = new StateGraph(\n schema as AnnotationRoot<any>,\n this.options.contextSchema\n );\n\n const allNodeWorkflows = workflow as WithStateGraphNodes<\n \"tools\" | \"model_request\" | string,\n typeof workflow\n >;\n\n // Generate node names for middleware nodes that have hooks\n const beforeModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const afterModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const modifyModelRequestHookMiddleware: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any\n ][] = [];\n\n const middlewareNames = new Set<string>();\n const middleware = this.options.middleware ?? [];\n for (let i = 0; i < middleware.length; i++) {\n let beforeModelNode: BeforeModelNode | undefined;\n let afterModelNode: AfterModelNode | undefined;\n const m = middleware[i];\n if (middlewareNames.has(m.name)) {\n throw new Error(`Middleware ${m.name} is defined multiple times`);\n }\n\n middlewareNames.add(m.name);\n if (m.beforeModel) {\n beforeModelNode = new BeforeModelNode(m);\n const name = `${m.name}.before_model`;\n beforeModelNodes.push({\n index: i,\n name,\n allowed: m.beforeModelJumpTo,\n });\n allNodeWorkflows.addNode(\n name,\n beforeModelNode,\n beforeModelNode.nodeOptions\n );\n }\n if (m.afterModel) {\n afterModelNode = new AfterModelNode(m);\n const name = `${m.name}.after_model`;\n afterModelNodes.push({\n index: i,\n name,\n allowed: m.afterModelJumpTo,\n });\n allNodeWorkflows.addNode(\n name,\n afterModelNode,\n afterModelNode.nodeOptions\n );\n }\n\n if (m.modifyModelRequest) {\n modifyModelRequestHookMiddleware.push([\n m,\n () => ({\n ...beforeModelNode?.getState(),\n ...afterModelNode?.getState(),\n }),\n ]);\n }\n }\n\n /**\n * Add Nodes\n */\n allNodeWorkflows.addNode(\n \"model_request\",\n new AgentNode({\n model: this.options.model,\n systemPrompt: this.options.systemPrompt,\n includeAgentName: this.options.includeAgentName,\n name: this.options.name,\n responseFormat: this.options.responseFormat,\n middleware: this.options.middleware,\n toolClasses,\n shouldReturnDirect,\n signal: this.options.signal,\n modifyModelRequestHookMiddleware,\n }),\n AgentNode.nodeOptions\n );\n\n /**\n * add single tool node for all tools\n */\n if (toolClasses.length > 0) {\n const toolNode = new ToolNode(toolClasses.filter(isClientTool), {\n signal: this.options.signal,\n });\n allNodeWorkflows.addNode(\"tools\", toolNode);\n }\n\n /**\n * Add Edges\n */\n // Determine starting point based on what nodes exist\n if (beforeModelNodes.length > 0) {\n // If we have beforeModel nodes, start with the first one\n allNodeWorkflows.addEdge(START, beforeModelNodes[0].name);\n } else {\n // If no beforeModel nodes, go directly to agent\n allNodeWorkflows.addEdge(START, \"model_request\");\n }\n\n // Connect beforeModel nodes; add conditional routing ONLY if allowed jumps are specified\n for (let i = 0; i < beforeModelNodes.length; i++) {\n const node = beforeModelNodes[i];\n const current = node.name;\n const isLast = i === beforeModelNodes.length - 1;\n const nextDefault = isLast\n ? \"model_request\"\n : beforeModelNodes[i + 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const hasTools = toolClasses.filter(isClientTool).length > 0;\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== \"tools\" || hasTools);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createBeforeModelRouter(\n toolClasses.filter(isClientTool),\n nextDefault\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect agent to last afterModel node (for reverse order execution)\n const lastAfterModelNode = afterModelNodes.at(-1);\n if (afterModelNodes.length > 0 && lastAfterModelNode) {\n allNodeWorkflows.addEdge(\"model_request\", lastAfterModelNode.name);\n } else {\n // If no afterModel nodes, connect model_request directly to model paths\n const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool));\n if (modelPaths.length === 1) {\n allNodeWorkflows.addEdge(\"model_request\", modelPaths[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n \"model_request\",\n this.#createModelRouter(),\n modelPaths\n );\n }\n }\n\n // Connect afterModel nodes in reverse sequence; add conditional routing ONLY if allowed jumps are specified per node\n for (let i = afterModelNodes.length - 1; i > 0; i--) {\n const node = afterModelNodes[i];\n const current = node.name;\n const nextDefault = afterModelNodes[i - 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const hasTools = toolClasses.filter(isClientTool).length > 0;\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== \"tools\" || hasTools);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createAfterModelSequenceRouter(\n toolClasses.filter(isClientTool),\n node.allowed,\n nextDefault\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect first afterModel node (last to execute) to model paths with jumpTo support\n if (afterModelNodes.length > 0) {\n const firstAfterModel = afterModelNodes[0];\n const firstAfterModelNode = firstAfterModel.name;\n const modelPaths = this.#getModelPaths(\n toolClasses.filter(isClientTool),\n true\n ).filter(\n (p) => p !== \"tools\" || toolClasses.filter(isClientTool).length > 0\n );\n\n const allowJump = Boolean(\n firstAfterModel.allowed && firstAfterModel.allowed.length > 0\n );\n\n const destinations = modelPaths;\n\n allNodeWorkflows.addConditionalEdges(\n firstAfterModelNode,\n this.#createAfterModelRouter(\n toolClasses.filter(isClientTool),\n allowJump\n ),\n destinations\n );\n }\n\n /**\n * add edges for tools node\n */\n if (toolClasses.length > 0) {\n // Tools should return to first beforeModel node or agent\n let toolReturnTarget: string;\n if (beforeModelNodes.length > 0) {\n toolReturnTarget = beforeModelNodes[0].name;\n } else {\n toolReturnTarget = \"model_request\";\n }\n\n if (shouldReturnDirect.size > 0) {\n allNodeWorkflows.addConditionalEdges(\n \"tools\",\n this.#createToolsRouter(shouldReturnDirect),\n [toolReturnTarget, END]\n );\n } else {\n allNodeWorkflows.addEdge(\"tools\", toolReturnTarget);\n }\n }\n\n /**\n * compile the graph\n */\n this.#graph = allNodeWorkflows.compile({\n checkpointer: this.options.checkpointer ?? this.options.checkpointSaver,\n store: this.options.store,\n name: this.options.name,\n description: this.options.description,\n }) as AgentGraph<StructuredResponseFormat, ContextSchema, TMiddleware>;\n }\n\n /**\n * Get the compiled {@link https://docs.langchain.com/oss/javascript/langgraph/use-graph-api | StateGraph}.\n */\n get graph(): AgentGraph<\n StructuredResponseFormat,\n ContextSchema,\n TMiddleware\n > {\n return this.#graph;\n }\n\n /**\n * Get possible edge destinations from model node.\n * @param toolClasses names of tools to call\n * @param includeModelRequest whether to include \"model_request\" as a valid path (for jumpTo routing)\n * @returns list of possible edge destinations\n */\n #getModelPaths(\n toolClasses: (ClientTool | ServerTool)[],\n includeModelRequest: boolean = false\n ): (\"tools\" | \"model_request\" | typeof END)[] {\n const paths: (\"tools\" | \"model_request\" | typeof END)[] = [];\n if (toolClasses.length > 0) {\n paths.push(\"tools\");\n }\n\n if (includeModelRequest) {\n paths.push(\"model_request\");\n }\n\n paths.push(END);\n\n return paths;\n }\n\n /**\n * Create routing function for tools node conditional edges.\n */\n #createToolsRouter(shouldReturnDirect: Set<string>) {\n /**\n * ToDo: fix type\n */\n return (state: any) => {\n const messages = state.messages;\n const lastMessage = messages[messages.length - 1];\n\n // Check if we just executed a returnDirect tool\n if (\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n shouldReturnDirect.has(lastMessage.name)\n ) {\n // If we have a response format, route to agent to generate structured response\n // Otherwise, return directly\n return this.options.responseFormat ? \"model_request\" : END;\n }\n\n // For non-returnDirect tools, always route back to agent\n return \"model_request\";\n };\n }\n\n /**\n * Create routing function for model node conditional edges.\n */\n #createModelRouter() {\n /**\n * determine if the agent should continue or not\n */\n return (state: BuiltInState) => {\n const messages = state.messages;\n const lastMessage = messages.at(-1);\n\n if (\n !AIMessage.isInstance(lastMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n return END;\n }\n\n // Check if all tool calls are for structured response extraction\n const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n if (hasOnlyStructuredResponseCalls) {\n // If all tool calls are for structured response extraction, go to END\n // The AgentNode will handle these internally and return the structured response\n return END;\n }\n\n /**\n * The tool node processes a single message.\n */\n if (this.#toolBehaviorVersion === \"v1\") {\n return \"tools\";\n }\n\n /**\n * Route to tools node (filter out any structured response tool calls)\n */\n const regularToolCalls = lastMessage.tool_calls.filter(\n (toolCall) => !toolCall.name.startsWith(\"extract-\")\n );\n\n if (regularToolCalls.length === 0) {\n return END;\n }\n\n return regularToolCalls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after afterModel hooks.\n *\n * This router checks if the `jumpTo` property is set in the state after afterModel middleware\n * execution. If set, it routes to the specified target (\"model_request\" or \"tools\").\n * If not set, it falls back to the normal model routing logic for afterModel context.\n *\n * The jumpTo property is automatically cleared after use to prevent infinite loops.\n *\n * @param toolClasses - Available tool classes for validation\n * @returns Router function that handles jumpTo logic and normal routing\n */\n #createAfterModelRouter(\n toolClasses: (ClientTool | ServerTool)[],\n allowJump: boolean\n ) {\n const hasStructuredResponse = Boolean(this.options.responseFormat);\n\n return (state: Omit<BuiltInState, \"jumpTo\"> & { jumpTo?: JumpTo }) => {\n // First, check if we just processed a structured response\n // If so, ignore any existing jumpTo and go to END\n const messages = state.messages;\n const lastMessage = messages.at(-1);\n if (\n AIMessage.isInstance(lastMessage) &&\n (!lastMessage.tool_calls || lastMessage.tool_calls.length === 0)\n ) {\n return END;\n }\n\n // Check if jumpTo is set in the state and allowed\n if (allowJump && state.jumpTo) {\n if (state.jumpTo === END) {\n return END;\n }\n if (state.jumpTo === \"tools\") {\n // If trying to jump to tools but no tools are available, go to END\n if (toolClasses.length === 0) {\n return END;\n }\n return new Send(\"tools\", { ...state, jumpTo: undefined });\n }\n // destination === \"model_request\"\n return new Send(\"model_request\", { ...state, jumpTo: undefined });\n }\n\n // check if there are pending tool calls\n const toolMessages = messages.filter(ToolMessage.isInstance);\n const lastAiMessage = messages.filter(AIMessage.isInstance).at(-1);\n const pendingToolCalls = lastAiMessage?.tool_calls?.filter(\n (call) => !toolMessages.some((m) => m.tool_call_id === call.id)\n );\n if (pendingToolCalls && pendingToolCalls.length > 0) {\n return pendingToolCalls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n }\n\n // if we exhausted all tool calls, but still have no structured response tool calls,\n // go back to model_request\n const hasStructuredResponseCalls = lastAiMessage?.tool_calls?.some(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n if (\n pendingToolCalls &&\n pendingToolCalls.length === 0 &&\n !hasStructuredResponseCalls &&\n hasStructuredResponse\n ) {\n return \"model_request\";\n }\n\n if (\n !AIMessage.isInstance(lastMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n return END;\n }\n\n // Check if all tool calls are for structured response extraction\n const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n // Check if there are any regular tool calls (non-structured response)\n const hasRegularToolCalls = lastMessage.tool_calls.some(\n (toolCall) => !toolCall.name.startsWith(\"extract-\")\n );\n\n if (hasOnlyStructuredResponseCalls || !hasRegularToolCalls) {\n return END;\n }\n\n /**\n * For routing from afterModel nodes, always use simple string paths\n * The Send API is handled at the model_request node level\n */\n return \"tools\";\n };\n }\n\n /**\n * Router for afterModel sequence nodes (connecting later middlewares to earlier ones),\n * honoring allowed jump targets and defaulting to the next node.\n */\n #createAfterModelSequenceRouter(\n toolClasses: (ClientTool | ServerTool)[],\n allowed: string[],\n nextDefault: string\n ) {\n const allowedSet = new Set(allowed.map((t) => parseJumpToTarget(t)));\n return (state: BuiltInState) => {\n if (state.jumpTo) {\n const dest = parseJumpToTarget(state.jumpTo);\n if (dest === END && allowedSet.has(END)) {\n return END;\n }\n if (dest === \"tools\" && allowedSet.has(\"tools\")) {\n if (toolClasses.length === 0) return END;\n return new Send(\"tools\", { ...state, jumpTo: undefined });\n }\n if (dest === \"model_request\" && allowedSet.has(\"model_request\")) {\n return new Send(\"model_request\", { ...state, jumpTo: undefined });\n }\n }\n return nextDefault as any;\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after beforeModel hooks.\n * Falls back to the default next node if no jumpTo is present.\n */\n #createBeforeModelRouter(\n toolClasses: (ClientTool | ServerTool)[],\n nextDefault: string\n ) {\n return (state: BuiltInState) => {\n if (!state.jumpTo) {\n return nextDefault;\n }\n const destination = parseJumpToTarget(state.jumpTo);\n if (destination === END) {\n return END;\n }\n if (destination === \"tools\") {\n if (toolClasses.length === 0) {\n return END;\n }\n return new Send(\"tools\", { ...state, jumpTo: undefined });\n }\n // destination === \"model_request\"\n return new Send(\"model_request\", { ...state, jumpTo: undefined });\n };\n }\n\n /**\n * Initialize middleware states if not already present in the input state.\n */\n async #initializeMiddlewareStates(\n state: InvokeStateParameter<TMiddleware>\n ): Promise<InvokeStateParameter<TMiddleware>> {\n if (\n !this.options.middleware ||\n this.options.middleware.length === 0 ||\n state instanceof Command ||\n !state\n ) {\n return state;\n }\n\n const defaultStates = await initializeMiddlewareStates(\n this.options.middleware,\n state\n );\n const updatedState = { ...state } as InvokeStateParameter<TMiddleware>;\n if (!updatedState) {\n return updatedState;\n }\n\n // Only add defaults for keys that don't exist in current state\n for (const [key, value] of Object.entries(defaultStates)) {\n if (!(key in updatedState)) {\n updatedState[key as keyof typeof updatedState] = value;\n }\n }\n\n return updatedState;\n }\n\n /**\n * Executes the agent with the given state and returns the final state after all processing.\n *\n * This method runs the agent's entire workflow synchronously, including:\n * - Processing the input messages through any configured middleware\n * - Calling the language model to generate responses\n * - Executing any tool calls made by the model\n * - Running all middleware hooks (beforeModel, afterModel, etc.)\n *\n * @param state - The initial state for the agent execution. Can be:\n * - An object containing `messages` array and any middleware-specific state properties\n * - A Command object for more advanced control flow\n *\n * @param config - Optional runtime configuration including:\n * @param config.context - The context for the agent execution.\n * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.\n * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}.\n * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution.\n * @param config.recursionLimit - The recursion limit for the agent execution.\n *\n * @returns A Promise that resolves to the final agent state after execution completes.\n * The returned state includes:\n * - a `messages` property containing an array with all messages (input, AI responses, tool calls/results)\n * - a `structuredResponse` property containing the structured response (if configured)\n * - all state values defined in the middleware\n *\n * @example\n * ```typescript\n * const agent = new ReactAgent({\n * llm: myModel,\n * tools: [calculator, webSearch],\n * responseFormat: z.object({\n * weather: z.string(),\n * }),\n * });\n *\n * const result = await agent.invoke({\n * messages: [{ role: \"human\", content: \"What's the weather in Paris?\" }]\n * });\n *\n * console.log(result.structuredResponse.weather); // outputs: \"It's sunny and 75°F.\"\n * ```\n */\n async invoke(\n state: InvokeStateParameter<TMiddleware>,\n config?: InvokeConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >\n ) {\n type FullState = MergedAgentState<StructuredResponseFormat, TMiddleware>;\n const initializedState = await this.#initializeMiddlewareStates(state);\n return this.#graph.invoke(\n initializedState,\n config as unknown as InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n ) as Promise<FullState>;\n }\n\n /**\n * Executes the agent with streaming, returning an async iterable of events as they occur.\n *\n * This method runs the agent's workflow similar to `invoke`, but instead of waiting for\n * completion, it streams events in real-time. This allows you to:\n * - Display intermediate results to users as they're generated\n * - Monitor the agent's progress through each step\n * - Handle tool calls and results as they happen\n * - Update UI with streaming responses from the LLM\n *\n * @param state - The initial state for the agent execution. Can be:\n * - An object containing `messages` array and any middleware-specific state properties\n * - A Command object for more advanced control flow\n *\n * @param config - Optional runtime configuration including:\n * @param config.context - The context for the agent execution.\n * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.\n * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}.\n * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution.\n * @param config.streamMode - The streaming mode for the agent execution, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/streaming#supported-stream-modes | Supported stream modes}.\n * @param config.recursionLimit - The recursion limit for the agent execution.\n *\n * @returns A Promise that resolves to an IterableReadableStream of events.\n * Events include:\n * - `on_chat_model_start`: When the LLM begins processing\n * - `on_chat_model_stream`: Streaming tokens from the LLM\n * - `on_chat_model_end`: When the LLM completes\n * - `on_tool_start`: When a tool execution begins\n * - `on_tool_end`: When a tool execution completes\n * - `on_chain_start`: When middleware chains begin\n * - `on_chain_end`: When middleware chains complete\n * - And other LangGraph v2 stream events\n *\n * @example\n * ```typescript\n * const agent = new ReactAgent({\n * llm: myModel,\n * tools: [calculator, webSearch]\n * });\n *\n * const stream = await agent.stream({\n * messages: [{ role: \"human\", content: \"What's 2+2 and the weather in NYC?\" }]\n * });\n *\n * for await (const event of stream) {\n * //\n * }\n * ```\n */\n async stream(\n state: InvokeStateParameter<TMiddleware>,\n config?: StreamConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >\n ): Promise<IterableReadableStream<any>> {\n const initializedState = await this.#initializeMiddlewareStates(state);\n return this.#graph.streamEvents(initializedState, {\n ...config,\n version: \"v2\",\n } as any) as IterableReadableStream<any>;\n }\n\n /**\n * Visualize the graph as a PNG image.\n * @param params - Parameters for the drawMermaidPng method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns PNG image as a buffer\n */\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n const image = await representation.drawMermaidPng(params);\n const arrayBuffer = await image.arrayBuffer();\n const buffer = new Uint8Array(arrayBuffer);\n return buffer;\n }\n\n /**\n * Draw the graph as a Mermaid string.\n * @param params - Parameters for the drawMermaid method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns Mermaid string\n */\n async drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n return representation.drawMermaid(params);\n }\n}\n"],"mappings":";;;;;;;;;;;AAuFA,IAAa,aAAb,MAYE;CACA;CAEA,uBAAoC;CAEpC,YACSA,SACP;EADO;EAEP,KAAKC,uBAAuB,QAAQ,WAAW,KAAKA;;;;EAKpD,MAAM,kBAAmB,KAAK,QAAQ,YAClC,OAAO,CAAC,MAAM,EAAE,MAAM,CACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,IAAI,CAAE;EAChC,MAAM,cAAc,CAClB,IAAK,MAAM,QAAQ,QAAQ,MAAM,GAC7B,QAAQ,QACR,QAAQ,OAAO,UAAU,CAAE,GAC/B,GAAG,eACJ;;;;;EAMD,MAAM,qBAAqB,IAAI,IAC7B,YACG,OAAO,aAAa,CACpB,OAAO,CAAC,SAAS,kBAAkB,QAAQ,KAAK,aAAa,CAC7D,IAAI,CAAC,SAAS,KAAK,KAAK;EAI7B,MAAM,SAAS,iCAIb,KAAK,QAAQ,mBAAmB,QAChC,KAAK,QAAQ,WACd;EAED,MAAM,WAAW,IAAI,WACnB,QACA,KAAK,QAAQ;EAGf,MAAM,mBAAmB;EAMzB,MAAMC,mBAIA,CAAE;EACR,MAAMC,kBAIA,CAAE;EACR,MAAMC,mCAMA,CAAE;EAER,MAAM,kCAAkB,IAAI;EAC5B,MAAM,aAAa,KAAK,QAAQ,cAAc,CAAE;AAChD,OAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK;GAC1C,IAAIC;GACJ,IAAIC;GACJ,MAAM,IAAI,WAAW;AACrB,OAAI,gBAAgB,IAAI,EAAE,KAAK,CAC7B,OAAM,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