langchain 1.0.0-alpha.5 → 1.0.0-alpha.6

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 (351) 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 +1 -3
  4. package/dist/agents/ReactAgent.d.cts.map +1 -1
  5. package/dist/agents/ReactAgent.d.ts +1 -3
  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 +4 -6
  11. package/dist/agents/annotation.d.cts.map +1 -1
  12. package/dist/agents/annotation.d.ts +4 -6
  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 +47 -47
  20. package/dist/agents/index.d.cts.map +1 -1
  21. package/dist/agents/index.d.ts +47 -47
  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/middlewareAgent/ReactAgent.cjs +18 -18
  26. package/dist/agents/middlewareAgent/ReactAgent.cjs.map +1 -1
  27. package/dist/agents/middlewareAgent/ReactAgent.d.cts +8 -9
  28. package/dist/agents/middlewareAgent/ReactAgent.d.cts.map +1 -1
  29. package/dist/agents/middlewareAgent/ReactAgent.d.ts +8 -9
  30. package/dist/agents/middlewareAgent/ReactAgent.d.ts.map +1 -1
  31. package/dist/agents/middlewareAgent/ReactAgent.js +18 -18
  32. package/dist/agents/middlewareAgent/ReactAgent.js.map +1 -1
  33. package/dist/agents/middlewareAgent/annotation.cjs +2 -2
  34. package/dist/agents/middlewareAgent/annotation.cjs.map +1 -1
  35. package/dist/agents/middlewareAgent/annotation.js +2 -2
  36. package/dist/agents/middlewareAgent/annotation.js.map +1 -1
  37. package/dist/agents/middlewareAgent/index.cjs.map +1 -1
  38. package/dist/agents/middlewareAgent/index.js.map +1 -1
  39. package/dist/agents/middlewareAgent/{middlewares → middleware}/hitl.cjs +8 -8
  40. package/dist/agents/middlewareAgent/middleware/hitl.cjs.map +1 -0
  41. package/dist/agents/middlewareAgent/{middlewares → middleware}/hitl.d.cts +3 -3
  42. package/dist/agents/middlewareAgent/middleware/hitl.d.cts.map +1 -0
  43. package/dist/agents/middlewareAgent/{middlewares → middleware}/hitl.d.ts +3 -3
  44. package/dist/agents/middlewareAgent/middleware/hitl.d.ts.map +1 -0
  45. package/dist/agents/middlewareAgent/{middlewares → middleware}/hitl.js +3 -3
  46. package/dist/agents/middlewareAgent/middleware/hitl.js.map +1 -0
  47. package/dist/agents/middlewareAgent/middleware/index.cjs +26 -0
  48. package/dist/agents/middlewareAgent/middleware/index.cjs.map +1 -0
  49. package/dist/agents/middlewareAgent/middleware/index.js +17 -0
  50. package/dist/agents/middlewareAgent/middleware/index.js.map +1 -0
  51. package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.cjs +51 -22
  52. package/dist/agents/middlewareAgent/middleware/promptCaching.cjs.map +1 -0
  53. package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.d.cts +9 -9
  54. package/dist/agents/middlewareAgent/middleware/promptCaching.d.cts.map +1 -0
  55. package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.d.ts +9 -9
  56. package/dist/agents/middlewareAgent/middleware/promptCaching.d.ts.map +1 -0
  57. package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.js +50 -21
  58. package/dist/agents/middlewareAgent/middleware/promptCaching.js.map +1 -0
  59. package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.cjs +11 -11
  60. package/dist/agents/middlewareAgent/middleware/summarization.cjs.map +1 -0
  61. package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.d.cts +3 -3
  62. package/dist/agents/middlewareAgent/middleware/summarization.d.cts.map +1 -0
  63. package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.d.ts +10 -10
  64. package/dist/agents/middlewareAgent/{middlewares/summarization.d.cts.map → middleware/summarization.d.ts.map} +1 -1
  65. package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.js +4 -4
  66. package/dist/agents/middlewareAgent/middleware/summarization.js.map +1 -0
  67. package/dist/agents/middlewareAgent/middleware.cjs.map +1 -1
  68. package/dist/agents/middlewareAgent/middleware.d.cts +1 -1
  69. package/dist/agents/middlewareAgent/middleware.d.cts.map +1 -1
  70. package/dist/agents/middlewareAgent/middleware.d.ts +1 -1
  71. package/dist/agents/middlewareAgent/middleware.d.ts.map +1 -1
  72. package/dist/agents/middlewareAgent/middleware.js.map +1 -1
  73. package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs.map +1 -1
  74. package/dist/agents/middlewareAgent/nodes/AfterModalNode.js.map +1 -1
  75. package/dist/agents/middlewareAgent/nodes/AgentNode.cjs +12 -19
  76. package/dist/agents/middlewareAgent/nodes/AgentNode.cjs.map +1 -1
  77. package/dist/agents/middlewareAgent/nodes/AgentNode.js +12 -19
  78. package/dist/agents/middlewareAgent/nodes/AgentNode.js.map +1 -1
  79. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs.map +1 -1
  80. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js.map +1 -1
  81. package/dist/agents/middlewareAgent/nodes/middleware.cjs.map +1 -1
  82. package/dist/agents/middlewareAgent/nodes/middleware.js.map +1 -1
  83. package/dist/agents/middlewareAgent/nodes/utils.cjs +7 -7
  84. package/dist/agents/middlewareAgent/nodes/utils.cjs.map +1 -1
  85. package/dist/agents/middlewareAgent/nodes/utils.js +3 -3
  86. package/dist/agents/middlewareAgent/nodes/utils.js.map +1 -1
  87. package/dist/agents/middlewareAgent/types.d.cts +10 -23
  88. package/dist/agents/middlewareAgent/types.d.cts.map +1 -1
  89. package/dist/agents/middlewareAgent/types.d.ts +10 -23
  90. package/dist/agents/middlewareAgent/types.d.ts.map +1 -1
  91. package/dist/agents/nodes/AgentNode.cjs +4 -4
  92. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  93. package/dist/agents/nodes/AgentNode.js +4 -4
  94. package/dist/agents/nodes/AgentNode.js.map +1 -1
  95. package/dist/agents/nodes/ToolNode.cjs +3 -3
  96. package/dist/agents/nodes/ToolNode.cjs.map +1 -1
  97. package/dist/agents/nodes/ToolNode.d.cts +1 -2
  98. package/dist/agents/nodes/ToolNode.d.cts.map +1 -1
  99. package/dist/agents/nodes/ToolNode.d.ts +1 -2
  100. package/dist/agents/nodes/ToolNode.d.ts.map +1 -1
  101. package/dist/agents/nodes/ToolNode.js +4 -4
  102. package/dist/agents/nodes/ToolNode.js.map +1 -1
  103. package/dist/agents/responses.cjs +1 -1
  104. package/dist/agents/responses.cjs.map +1 -1
  105. package/dist/agents/responses.d.cts.map +1 -1
  106. package/dist/agents/responses.d.ts.map +1 -1
  107. package/dist/agents/responses.js +1 -1
  108. package/dist/agents/responses.js.map +1 -1
  109. package/dist/agents/types.d.cts +1 -3
  110. package/dist/agents/types.d.cts.map +1 -1
  111. package/dist/agents/types.d.ts +1 -3
  112. package/dist/agents/types.d.ts.map +1 -1
  113. package/dist/agents/utils.cjs +6 -6
  114. package/dist/agents/utils.cjs.map +1 -1
  115. package/dist/agents/utils.js +7 -7
  116. package/dist/agents/utils.js.map +1 -1
  117. package/dist/agents/withAgentName.cjs.map +1 -1
  118. package/dist/agents/withAgentName.js.map +1 -1
  119. package/dist/chains/api/prompts.cjs.map +1 -1
  120. package/dist/chains/api/prompts.js.map +1 -1
  121. package/dist/chains/constitutional_ai/constitutional_chain.cjs.map +1 -1
  122. package/dist/chains/constitutional_ai/constitutional_chain.js.map +1 -1
  123. package/dist/chains/index.cjs +0 -3
  124. package/dist/chains/index.cjs.map +1 -1
  125. package/dist/chains/index.d.cts +1 -2
  126. package/dist/chains/index.d.ts +1 -2
  127. package/dist/chains/index.js +1 -3
  128. package/dist/chains/index.js.map +1 -1
  129. package/dist/chains/openai_functions/extraction.cjs.map +1 -1
  130. package/dist/chains/openai_functions/extraction.d.cts +1 -3
  131. package/dist/chains/openai_functions/extraction.d.cts.map +1 -1
  132. package/dist/chains/openai_functions/extraction.d.ts +1 -3
  133. package/dist/chains/openai_functions/extraction.d.ts.map +1 -1
  134. package/dist/chains/openai_functions/extraction.js.map +1 -1
  135. package/dist/chains/openai_functions/index.cjs +0 -5
  136. package/dist/chains/openai_functions/index.cjs.map +1 -1
  137. package/dist/chains/openai_functions/index.d.cts +1 -2
  138. package/dist/chains/openai_functions/index.d.ts +1 -2
  139. package/dist/chains/openai_functions/index.js +1 -4
  140. package/dist/chains/openai_functions/index.js.map +1 -1
  141. package/dist/chains/openai_functions/openapi.cjs +4 -4
  142. package/dist/chains/openai_functions/openapi.cjs.map +1 -1
  143. package/dist/chains/openai_functions/openapi.d.cts +1 -1
  144. package/dist/chains/openai_functions/openapi.js +4 -4
  145. package/dist/chains/openai_functions/openapi.js.map +1 -1
  146. package/dist/chains/openai_functions/tagging.cjs.map +1 -1
  147. package/dist/chains/openai_functions/tagging.d.cts +1 -3
  148. package/dist/chains/openai_functions/tagging.d.cts.map +1 -1
  149. package/dist/chains/openai_functions/tagging.d.ts +1 -3
  150. package/dist/chains/openai_functions/tagging.d.ts.map +1 -1
  151. package/dist/chains/openai_functions/tagging.js.map +1 -1
  152. package/dist/chains/query_constructor/index.cjs +4 -4
  153. package/dist/chains/query_constructor/index.cjs.map +1 -1
  154. package/dist/chains/query_constructor/index.d.cts +4 -2
  155. package/dist/chains/query_constructor/index.d.cts.map +1 -1
  156. package/dist/chains/query_constructor/index.d.ts +4 -2
  157. package/dist/chains/query_constructor/index.d.ts.map +1 -1
  158. package/dist/chains/query_constructor/index.js +1 -1
  159. package/dist/chains/query_constructor/index.js.map +1 -1
  160. package/dist/chains/question_answering/load.d.ts +2 -2
  161. package/dist/chains/question_answering/load.d.ts.map +1 -1
  162. package/dist/chains/question_answering/map_reduce_prompts.cjs.map +1 -1
  163. package/dist/chains/question_answering/map_reduce_prompts.js.map +1 -1
  164. package/dist/chains/question_answering/refine_prompts.cjs.map +1 -1
  165. package/dist/chains/question_answering/refine_prompts.js.map +1 -1
  166. package/dist/chains/question_answering/stuff_prompts.cjs.map +1 -1
  167. package/dist/chains/question_answering/stuff_prompts.js.map +1 -1
  168. package/dist/chains/router/multi_prompt.cjs +4 -4
  169. package/dist/chains/router/multi_prompt.cjs.map +1 -1
  170. package/dist/chains/router/multi_prompt.js +1 -1
  171. package/dist/chains/router/multi_prompt.js.map +1 -1
  172. package/dist/chains/router/multi_retrieval_qa.cjs +4 -4
  173. package/dist/chains/router/multi_retrieval_qa.cjs.map +1 -1
  174. package/dist/chains/router/multi_retrieval_qa.js +1 -1
  175. package/dist/chains/router/multi_retrieval_qa.js.map +1 -1
  176. package/dist/chains/sql_db/sql_db_prompt.cjs.map +1 -1
  177. package/dist/chains/sql_db/sql_db_prompt.d.cts.map +1 -1
  178. package/dist/chains/sql_db/sql_db_prompt.d.ts.map +1 -1
  179. package/dist/chains/sql_db/sql_db_prompt.js.map +1 -1
  180. package/dist/chains/summarization/load.d.ts +2 -2
  181. package/dist/chains/summarization/load.d.ts.map +1 -1
  182. package/dist/chains/summarization/stuff_prompts.cjs.map +1 -1
  183. package/dist/chains/summarization/stuff_prompts.js.map +1 -1
  184. package/dist/chat_models/universal.cjs +8 -5
  185. package/dist/chat_models/universal.cjs.map +1 -1
  186. package/dist/chat_models/universal.d.cts +2 -2
  187. package/dist/chat_models/universal.d.cts.map +1 -1
  188. package/dist/chat_models/universal.d.ts +2 -2
  189. package/dist/chat_models/universal.d.ts.map +1 -1
  190. package/dist/chat_models/universal.js +8 -5
  191. package/dist/chat_models/universal.js.map +1 -1
  192. package/dist/document_loaders/fs/directory.cjs.map +1 -1
  193. package/dist/document_loaders/fs/directory.d.cts +0 -1
  194. package/dist/document_loaders/fs/directory.d.cts.map +1 -1
  195. package/dist/document_loaders/fs/directory.d.ts +0 -1
  196. package/dist/document_loaders/fs/directory.d.ts.map +1 -1
  197. package/dist/document_loaders/fs/directory.js.map +1 -1
  198. package/dist/document_loaders/fs/json.cjs +7 -1
  199. package/dist/document_loaders/fs/json.cjs.map +1 -1
  200. package/dist/document_loaders/fs/json.js +7 -1
  201. package/dist/document_loaders/fs/json.js.map +1 -1
  202. package/dist/embeddings/cache_backed.cjs +1 -1
  203. package/dist/embeddings/cache_backed.cjs.map +1 -1
  204. package/dist/embeddings/cache_backed.d.cts +1 -1
  205. package/dist/embeddings/cache_backed.d.ts +1 -1
  206. package/dist/embeddings/cache_backed.js +2 -2
  207. package/dist/embeddings/cache_backed.js.map +1 -1
  208. package/dist/evaluation/agents/trajectory.d.cts.map +1 -1
  209. package/dist/evaluation/comparison/pairwise.d.ts.map +1 -1
  210. package/dist/evaluation/criteria/criteria.d.ts.map +1 -1
  211. package/dist/evaluation/embedding_distance/base.cjs +2 -4
  212. package/dist/evaluation/embedding_distance/base.cjs.map +1 -1
  213. package/dist/evaluation/embedding_distance/base.js +2 -3
  214. package/dist/evaluation/embedding_distance/base.js.map +1 -1
  215. package/dist/evaluation/loader.cjs +7 -12
  216. package/dist/evaluation/loader.cjs.map +1 -1
  217. package/dist/evaluation/loader.d.cts +8 -2
  218. package/dist/evaluation/loader.d.cts.map +1 -1
  219. package/dist/evaluation/loader.d.ts +8 -2
  220. package/dist/evaluation/loader.d.ts.map +1 -1
  221. package/dist/evaluation/loader.js +7 -12
  222. package/dist/evaluation/loader.js.map +1 -1
  223. package/dist/hub/base.cjs.map +1 -1
  224. package/dist/hub/base.js.map +1 -1
  225. package/dist/langchain-core/dist/load/serializable.d.cts.map +1 -1
  226. package/dist/langchain-core/dist/messages/base.d.cts +24 -33
  227. package/dist/langchain-core/dist/messages/base.d.cts.map +1 -1
  228. package/dist/langchain-core/dist/messages/content/index.d.cts +1 -1
  229. package/dist/langchain-core/dist/messages/content/index.d.cts.map +1 -1
  230. package/dist/langchain-core/dist/messages/message.d.cts +598 -0
  231. package/dist/langchain-core/dist/messages/message.d.cts.map +1 -0
  232. package/dist/langchain-core/dist/messages/metadata.d.cts +97 -0
  233. package/dist/langchain-core/dist/messages/metadata.d.cts.map +1 -0
  234. package/dist/langchain-core/dist/messages/utils.d.cts +75 -0
  235. package/dist/langchain-core/dist/messages/utils.d.cts.map +1 -0
  236. package/dist/langchain-core/dist/prompt_values.d.cts.map +1 -1
  237. package/dist/libs/langchain-core/dist/load/serializable.d.ts.map +1 -1
  238. package/dist/libs/langchain-core/dist/messages/base.d.ts +24 -33
  239. package/dist/libs/langchain-core/dist/messages/base.d.ts.map +1 -1
  240. package/dist/libs/langchain-core/dist/messages/content/index.d.ts +1 -1
  241. package/dist/libs/langchain-core/dist/messages/content/index.d.ts.map +1 -1
  242. package/dist/libs/langchain-core/dist/messages/message.d.ts +598 -0
  243. package/dist/libs/langchain-core/dist/messages/message.d.ts.map +1 -0
  244. package/dist/libs/langchain-core/dist/messages/metadata.d.ts +97 -0
  245. package/dist/libs/langchain-core/dist/messages/metadata.d.ts.map +1 -0
  246. package/dist/libs/langchain-core/dist/messages/utils.d.ts +75 -0
  247. package/dist/libs/langchain-core/dist/messages/utils.d.ts.map +1 -0
  248. package/dist/libs/langchain-core/dist/prompt_values.d.ts.map +1 -1
  249. package/dist/libs/langchain-core/dist/utils/types/index.d.ts +2 -0
  250. package/dist/libs/langchain-core/dist/utils/types/index.d.ts.map +1 -1
  251. package/dist/libs/langchain-core/dist/utils/types/zod.d.ts +1 -0
  252. package/dist/load/import_map.cjs +3 -14
  253. package/dist/load/import_map.cjs.map +1 -1
  254. package/dist/load/import_map.js +3 -14
  255. package/dist/load/import_map.js.map +1 -1
  256. package/dist/memory/prompt.cjs.map +1 -1
  257. package/dist/memory/prompt.d.cts.map +1 -1
  258. package/dist/memory/prompt.d.ts.map +1 -1
  259. package/dist/memory/prompt.js.map +1 -1
  260. package/dist/output_parsers/combining.cjs +1 -1
  261. package/dist/output_parsers/combining.cjs.map +1 -1
  262. package/dist/output_parsers/combining.js +1 -1
  263. package/dist/output_parsers/combining.js.map +1 -1
  264. package/dist/output_parsers/expression_type_handlers/array_literal_expression_handler.cjs.map +1 -1
  265. package/dist/output_parsers/expression_type_handlers/array_literal_expression_handler.js.map +1 -1
  266. package/dist/output_parsers/expression_type_handlers/base.cjs +1 -1
  267. package/dist/output_parsers/expression_type_handlers/base.cjs.map +1 -1
  268. package/dist/output_parsers/expression_type_handlers/base.js +1 -1
  269. package/dist/output_parsers/expression_type_handlers/base.js.map +1 -1
  270. package/dist/output_parsers/regex.cjs.map +1 -1
  271. package/dist/output_parsers/regex.js.map +1 -1
  272. package/dist/output_parsers/structured.cjs +4 -4
  273. package/dist/output_parsers/structured.cjs.map +1 -1
  274. package/dist/output_parsers/structured.d.cts +1 -1
  275. package/dist/output_parsers/structured.d.cts.map +1 -1
  276. package/dist/output_parsers/structured.d.ts +1 -1
  277. package/dist/output_parsers/structured.d.ts.map +1 -1
  278. package/dist/output_parsers/structured.js +2 -2
  279. package/dist/output_parsers/structured.js.map +1 -1
  280. package/dist/retrievers/ensemble.cjs.map +1 -1
  281. package/dist/retrievers/ensemble.js.map +1 -1
  282. package/dist/storage/file_system.cjs +1 -1
  283. package/dist/storage/file_system.cjs.map +1 -1
  284. package/dist/storage/file_system.js +1 -1
  285. package/dist/storage/file_system.js.map +1 -1
  286. package/dist/tools/fs.cjs +5 -5
  287. package/dist/tools/fs.cjs.map +1 -1
  288. package/dist/tools/fs.d.cts +1 -1
  289. package/dist/tools/fs.d.cts.map +1 -1
  290. package/dist/tools/fs.d.ts +1 -1
  291. package/dist/tools/fs.d.ts.map +1 -1
  292. package/dist/tools/fs.js +1 -1
  293. package/dist/tools/fs.js.map +1 -1
  294. package/dist/tools/retriever.cjs +2 -2
  295. package/dist/tools/retriever.cjs.map +1 -1
  296. package/dist/tools/retriever.d.cts +1 -1
  297. package/dist/tools/retriever.d.cts.map +1 -1
  298. package/dist/tools/retriever.d.ts +1 -1
  299. package/dist/tools/retriever.d.ts.map +1 -1
  300. package/dist/tools/retriever.js +1 -1
  301. package/dist/tools/retriever.js.map +1 -1
  302. package/dist/tools/sql.cjs +1 -2
  303. package/dist/tools/sql.cjs.map +1 -1
  304. package/dist/tools/sql.d.cts +1 -1
  305. package/dist/tools/sql.d.cts.map +1 -1
  306. package/dist/tools/sql.d.ts +1 -1
  307. package/dist/tools/sql.d.ts.map +1 -1
  308. package/dist/tools/sql.js +1 -2
  309. package/dist/tools/sql.js.map +1 -1
  310. package/dist/types/expression-parser.d.cts +2 -0
  311. package/dist/types/expression-parser.d.cts.map +1 -1
  312. package/dist/types/expression-parser.d.ts +2 -0
  313. package/dist/types/expression-parser.d.ts.map +1 -1
  314. package/dist/util/hub.cjs +1 -1
  315. package/dist/util/hub.js +1 -1
  316. package/dist/util/openapi.cjs +1 -1
  317. package/dist/util/openapi.cjs.map +1 -1
  318. package/dist/util/openapi.js +1 -1
  319. package/dist/util/openapi.js.map +1 -1
  320. package/package.json +15 -21
  321. package/dist/agents/middlewareAgent/middlewares/hitl.cjs.map +0 -1
  322. package/dist/agents/middlewareAgent/middlewares/hitl.d.cts.map +0 -1
  323. package/dist/agents/middlewareAgent/middlewares/hitl.d.ts.map +0 -1
  324. package/dist/agents/middlewareAgent/middlewares/hitl.js.map +0 -1
  325. package/dist/agents/middlewareAgent/middlewares/index.cjs +0 -8
  326. package/dist/agents/middlewareAgent/middlewares/index.js +0 -5
  327. package/dist/agents/middlewareAgent/middlewares/promptCaching.cjs.map +0 -1
  328. package/dist/agents/middlewareAgent/middlewares/promptCaching.d.cts.map +0 -1
  329. package/dist/agents/middlewareAgent/middlewares/promptCaching.d.ts.map +0 -1
  330. package/dist/agents/middlewareAgent/middlewares/promptCaching.js.map +0 -1
  331. package/dist/agents/middlewareAgent/middlewares/summarization.cjs.map +0 -1
  332. package/dist/agents/middlewareAgent/middlewares/summarization.d.ts.map +0 -1
  333. package/dist/agents/middlewareAgent/middlewares/summarization.js.map +0 -1
  334. package/dist/chains/openai_functions/structured_output.cjs +0 -107
  335. package/dist/chains/openai_functions/structured_output.cjs.map +0 -1
  336. package/dist/chains/openai_functions/structured_output.d.cts +0 -38
  337. package/dist/chains/openai_functions/structured_output.d.cts.map +0 -1
  338. package/dist/chains/openai_functions/structured_output.d.ts +0 -38
  339. package/dist/chains/openai_functions/structured_output.d.ts.map +0 -1
  340. package/dist/chains/openai_functions/structured_output.js +0 -105
  341. package/dist/chains/openai_functions/structured_output.js.map +0 -1
  342. package/dist/chains/openai_moderation.cjs +0 -107
  343. package/dist/chains/openai_moderation.cjs.map +0 -1
  344. package/dist/chains/openai_moderation.d.cts +0 -74
  345. package/dist/chains/openai_moderation.d.cts.map +0 -1
  346. package/dist/chains/openai_moderation.d.ts +0 -74
  347. package/dist/chains/openai_moderation.d.ts.map +0 -1
  348. package/dist/chains/openai_moderation.js +0 -106
  349. package/dist/chains/openai_moderation.js.map +0 -1
  350. /package/dist/agents/middlewareAgent/{middlewares → middleware}/index.d.cts +0 -0
  351. /package/dist/agents/middlewareAgent/{middlewares → middleware}/index.d.ts +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.js","names":["config: {\n name: string;\n stateSchema?: TSchema;\n contextSchema?: TContextSchema;\n prepareModelRequest?: (\n options: ModelRequest,\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >\n ) => Promise<ModelRequest | void> | ModelRequest | void;\n beforeModel?: (\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >,\n controls: Controls<\n (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState\n >\n ) =>\n | Promise<\n MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >\n >\n | MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >;\n afterModel?: (\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >,\n controls: Controls<\n (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState\n >\n ) =>\n | Promise<\n MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >\n >\n | MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >;\n}","middleware: AgentMiddleware<TSchema, TContextSchema, any>"],"sources":["../../../src/agents/middlewareAgent/middleware.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-types */\nimport { z } from \"zod\";\nimport type {\n AgentMiddleware,\n Runtime,\n Controls,\n MiddlewareResult,\n AgentBuiltInState,\n ModelRequest,\n} from \"./types.js\";\n\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.prepareModelRequest - The function to prepare the model request\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n */\nexport function createMiddleware<\n TSchema extends z.ZodObject<any> | undefined = undefined,\n TContextSchema extends z.ZodObject<any> | undefined = undefined\n>(config: {\n name: string;\n stateSchema?: TSchema;\n contextSchema?: TContextSchema;\n prepareModelRequest?: (\n options: ModelRequest,\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >\n ) => Promise<ModelRequest | void> | ModelRequest | void;\n beforeModel?: (\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >,\n controls: Controls<\n (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState\n >\n ) =>\n | Promise<\n MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >\n >\n | MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >;\n afterModel?: (\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >,\n controls: Controls<\n (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState\n >\n ) =>\n | Promise<\n MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >\n >\n | MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >;\n}): AgentMiddleware<TSchema, TContextSchema, any> {\n const middleware: AgentMiddleware<TSchema, TContextSchema, any> = {\n name: config.name,\n stateSchema: config.stateSchema,\n contextSchema: config.contextSchema,\n };\n\n if (config.prepareModelRequest) {\n middleware.prepareModelRequest = async (options, state, runtime) =>\n Promise.resolve(config.prepareModelRequest!(options, state, runtime));\n }\n\n if (config.beforeModel) {\n middleware.beforeModel = async (state, runtime, controls) =>\n Promise.resolve(config.beforeModel!(state, runtime, controls));\n }\n\n if (config.afterModel) {\n middleware.afterModel = async (state, runtime, controls) =>\n Promise.resolve(config.afterModel!(state, runtime, controls));\n }\n\n return middleware;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,iBAGdA,QAkDgD;CAChD,MAAMC,aAA4D;EAChE,MAAM,OAAO;EACb,aAAa,OAAO;EACpB,eAAe,OAAO;CACvB;AAED,KAAI,OAAO,qBACT,WAAW,sBAAsB,OAAO,SAAS,OAAO,YACtD,QAAQ,QAAQ,OAAO,oBAAqB,SAAS,OAAO,QAAQ,CAAC;AAGzE,KAAI,OAAO,aACT,WAAW,cAAc,OAAO,OAAO,SAAS,aAC9C,QAAQ,QAAQ,OAAO,YAAa,OAAO,SAAS,SAAS,CAAC;AAGlE,KAAI,OAAO,YACT,WAAW,aAAa,OAAO,OAAO,SAAS,aAC7C,QAAQ,QAAQ,OAAO,WAAY,OAAO,SAAS,SAAS,CAAC;AAGjE,QAAO;AACR"}
1
+ {"version":3,"file":"middleware.js","names":["config: {\n name: string;\n stateSchema?: TSchema;\n contextSchema?: TContextSchema;\n prepareModelRequest?: (\n options: ModelRequest,\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >\n ) => Promise<ModelRequest | void> | ModelRequest | void;\n beforeModel?: (\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >,\n controls: Controls<\n (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState\n >\n ) =>\n | Promise<\n MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >\n >\n | MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >;\n afterModel?: (\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >,\n controls: Controls<\n (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState\n >\n ) =>\n | Promise<\n MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >\n >\n | MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >;\n}","middleware: AgentMiddleware<TSchema, TContextSchema, any>"],"sources":["../../../src/agents/middlewareAgent/middleware.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { z } from \"zod/v3\";\nimport type {\n AgentMiddleware,\n Runtime,\n Controls,\n MiddlewareResult,\n AgentBuiltInState,\n ModelRequest,\n} from \"./types.js\";\n\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.prepareModelRequest - The function to prepare the model request\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n */\nexport function createMiddleware<\n TSchema extends z.ZodObject<any> | undefined = undefined,\n TContextSchema extends z.ZodObject<any> | undefined = undefined\n>(config: {\n name: string;\n stateSchema?: TSchema;\n contextSchema?: TContextSchema;\n prepareModelRequest?: (\n options: ModelRequest,\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >\n ) => Promise<ModelRequest | void> | ModelRequest | void;\n beforeModel?: (\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >,\n controls: Controls<\n (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState\n >\n ) =>\n | Promise<\n MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >\n >\n | MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >;\n afterModel?: (\n state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState,\n runtime: Runtime<\n TContextSchema extends z.ZodObject<any> ? z.infer<TContextSchema> : {}\n >,\n controls: Controls<\n (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) &\n AgentBuiltInState\n >\n ) =>\n | Promise<\n MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >\n >\n | MiddlewareResult<\n Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>\n >;\n}): AgentMiddleware<TSchema, TContextSchema, any> {\n const middleware: AgentMiddleware<TSchema, TContextSchema, any> = {\n name: config.name,\n stateSchema: config.stateSchema,\n contextSchema: config.contextSchema,\n };\n\n if (config.prepareModelRequest) {\n middleware.prepareModelRequest = async (options, state, runtime) =>\n Promise.resolve(config.prepareModelRequest!(options, state, runtime));\n }\n\n if (config.beforeModel) {\n middleware.beforeModel = async (state, runtime, controls) =>\n Promise.resolve(config.beforeModel!(state, runtime, controls));\n }\n\n if (config.afterModel) {\n middleware.afterModel = async (state, runtime, controls) =>\n Promise.resolve(config.afterModel!(state, runtime, controls));\n }\n\n return middleware;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,iBAGdA,QAkDgD;CAChD,MAAMC,aAA4D;EAChE,MAAM,OAAO;EACb,aAAa,OAAO;EACpB,eAAe,OAAO;CACvB;AAED,KAAI,OAAO,qBACT,WAAW,sBAAsB,OAAO,SAAS,OAAO,YACtD,QAAQ,QAAQ,OAAO,oBAAqB,SAAS,OAAO,QAAQ,CAAC;AAGzE,KAAI,OAAO,aACT,WAAW,cAAc,OAAO,OAAO,SAAS,aAC9C,QAAQ,QAAQ,OAAO,YAAa,OAAO,SAAS,SAAS,CAAC;AAGlE,KAAI,OAAO,YACT,WAAW,aAAa,OAAO,OAAO,SAAS,aAC7C,QAAQ,QAAQ,OAAO,WAAY,OAAO,SAAS,SAAS,CAAC;AAGjE,QAAO;AACR"}
@@ -1 +1 @@
1
- {"version":3,"file":"AfterModalNode.cjs","names":["MiddlewareNode","middleware: AgentMiddleware<any, any, any>","state: TStateSchema","config?: LangGraphRunnableConfig","runtime: Runtime<TContextSchema>","controls: Controls<TStateSchema>"],"sources":["../../../../src/agents/middlewareAgent/nodes/AfterModalNode.ts"],"sourcesContent":["import { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { MiddlewareNode } from \"./middleware.js\";\nimport type {\n Controls,\n AgentMiddleware,\n MiddlewareResult,\n Runtime,\n} from \"../types.js\";\n\n/**\n * Node for executing a single middleware's afterModel hook.\n */\nexport class AfterModelNode<\n TStateSchema extends Record<string, any> = Record<string, any>,\n TContextSchema extends Record<string, any> = Record<string, any>\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"afterModalNodes\"];\n\n name: string;\n\n constructor(public middleware: AgentMiddleware<any, any, any>) {\n super({\n name: `AfterModelNode_${middleware.name}`,\n func: async (state: TStateSchema, config?: LangGraphRunnableConfig) =>\n this.invokeMiddleware(state, config),\n });\n this.name = `AfterModelNode_${middleware.name}`;\n }\n\n runHook(\n state: TStateSchema,\n runtime: Runtime<TContextSchema>,\n controls: Controls<TStateSchema>\n ) {\n return this.middleware.afterModel!(state, runtime, controls) as Promise<\n MiddlewareResult<TStateSchema>\n >;\n }\n}\n"],"mappings":";;;;;;AAYA,IAAa,iBAAb,cAGUA,kCAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;CAAkB;CAEzD;CAEA,YAAmBC,YAA4C;EAC7D,MAAM;GACJ,MAAM,CAAC,eAAe,EAAE,WAAW,MAAM;GACzC,MAAM,OAAOC,OAAqBC,WAChC,KAAK,iBAAiB,OAAO,OAAO;EACvC,EAAC;EALe;EAMjB,KAAK,OAAO,CAAC,eAAe,EAAE,WAAW,MAAM;CAChD;CAED,QACED,OACAE,SACAC,UACA;AACA,SAAO,KAAK,WAAW,WAAY,OAAO,SAAS,SAAS;CAG7D;AACF"}
1
+ {"version":3,"file":"AfterModalNode.cjs","names":["MiddlewareNode","middleware: AgentMiddleware<any, any, any>","state: TStateSchema","config?: LangGraphRunnableConfig","runtime: Runtime<TContextSchema>","controls: Controls<TStateSchema>"],"sources":["../../../../src/agents/middlewareAgent/nodes/AfterModalNode.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { MiddlewareNode } from \"./middleware.js\";\nimport type {\n Controls,\n AgentMiddleware,\n MiddlewareResult,\n Runtime,\n} from \"../types.js\";\n\n/**\n * Node for executing a single middleware's afterModel hook.\n */\nexport class AfterModelNode<\n TStateSchema extends Record<string, any> = Record<string, any>,\n TContextSchema extends Record<string, any> = Record<string, any>\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"afterModalNodes\"];\n\n name: string;\n\n constructor(public middleware: AgentMiddleware<any, any, any>) {\n super({\n name: `AfterModelNode_${middleware.name}`,\n func: async (state: TStateSchema, config?: LangGraphRunnableConfig) =>\n this.invokeMiddleware(state, config),\n });\n this.name = `AfterModelNode_${middleware.name}`;\n }\n\n runHook(\n state: TStateSchema,\n runtime: Runtime<TContextSchema>,\n controls: Controls<TStateSchema>\n ) {\n return this.middleware.afterModel!(state, runtime, controls) as Promise<\n MiddlewareResult<TStateSchema>\n >;\n }\n}\n"],"mappings":";;;;;;AAaA,IAAa,iBAAb,cAGUA,kCAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;CAAkB;CAEzD;CAEA,YAAmBC,YAA4C;EAC7D,MAAM;GACJ,MAAM,CAAC,eAAe,EAAE,WAAW,MAAM;GACzC,MAAM,OAAOC,OAAqBC,WAChC,KAAK,iBAAiB,OAAO,OAAO;EACvC,EAAC;EALe;EAMjB,KAAK,OAAO,CAAC,eAAe,EAAE,WAAW,MAAM;CAChD;CAED,QACED,OACAE,SACAC,UACA;AACA,SAAO,KAAK,WAAW,WAAY,OAAO,SAAS,SAAS;CAG7D;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"AfterModalNode.js","names":["middleware: AgentMiddleware<any, any, any>","state: TStateSchema","config?: LangGraphRunnableConfig","runtime: Runtime<TContextSchema>","controls: Controls<TStateSchema>"],"sources":["../../../../src/agents/middlewareAgent/nodes/AfterModalNode.ts"],"sourcesContent":["import { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { MiddlewareNode } from \"./middleware.js\";\nimport type {\n Controls,\n AgentMiddleware,\n MiddlewareResult,\n Runtime,\n} from \"../types.js\";\n\n/**\n * Node for executing a single middleware's afterModel hook.\n */\nexport class AfterModelNode<\n TStateSchema extends Record<string, any> = Record<string, any>,\n TContextSchema extends Record<string, any> = Record<string, any>\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"afterModalNodes\"];\n\n name: string;\n\n constructor(public middleware: AgentMiddleware<any, any, any>) {\n super({\n name: `AfterModelNode_${middleware.name}`,\n func: async (state: TStateSchema, config?: LangGraphRunnableConfig) =>\n this.invokeMiddleware(state, config),\n });\n this.name = `AfterModelNode_${middleware.name}`;\n }\n\n runHook(\n state: TStateSchema,\n runtime: Runtime<TContextSchema>,\n controls: Controls<TStateSchema>\n ) {\n return this.middleware.afterModel!(state, runtime, controls) as Promise<\n MiddlewareResult<TStateSchema>\n >;\n }\n}\n"],"mappings":";;;;;;AAYA,IAAa,iBAAb,cAGU,eAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;CAAkB;CAEzD;CAEA,YAAmBA,YAA4C;EAC7D,MAAM;GACJ,MAAM,CAAC,eAAe,EAAE,WAAW,MAAM;GACzC,MAAM,OAAOC,OAAqBC,WAChC,KAAK,iBAAiB,OAAO,OAAO;EACvC,EAAC;EALe;EAMjB,KAAK,OAAO,CAAC,eAAe,EAAE,WAAW,MAAM;CAChD;CAED,QACED,OACAE,SACAC,UACA;AACA,SAAO,KAAK,WAAW,WAAY,OAAO,SAAS,SAAS;CAG7D;AACF"}
1
+ {"version":3,"file":"AfterModalNode.js","names":["middleware: AgentMiddleware<any, any, any>","state: TStateSchema","config?: LangGraphRunnableConfig","runtime: Runtime<TContextSchema>","controls: Controls<TStateSchema>"],"sources":["../../../../src/agents/middlewareAgent/nodes/AfterModalNode.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { MiddlewareNode } from \"./middleware.js\";\nimport type {\n Controls,\n AgentMiddleware,\n MiddlewareResult,\n Runtime,\n} from \"../types.js\";\n\n/**\n * Node for executing a single middleware's afterModel hook.\n */\nexport class AfterModelNode<\n TStateSchema extends Record<string, any> = Record<string, any>,\n TContextSchema extends Record<string, any> = Record<string, any>\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"afterModalNodes\"];\n\n name: string;\n\n constructor(public middleware: AgentMiddleware<any, any, any>) {\n super({\n name: `AfterModelNode_${middleware.name}`,\n func: async (state: TStateSchema, config?: LangGraphRunnableConfig) =>\n this.invokeMiddleware(state, config),\n });\n this.name = `AfterModelNode_${middleware.name}`;\n }\n\n runHook(\n state: TStateSchema,\n runtime: Runtime<TContextSchema>,\n controls: Controls<TStateSchema>\n ) {\n return this.middleware.afterModel!(state, runtime, controls) as Promise<\n MiddlewareResult<TStateSchema>\n >;\n }\n}\n"],"mappings":";;;;;;AAaA,IAAa,iBAAb,cAGU,eAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;CAAkB;CAEzD;CAEA,YAAmBA,YAA4C;EAC7D,MAAM;GACJ,MAAM,CAAC,eAAe,EAAE,WAAW,MAAM;GACzC,MAAM,OAAOC,OAAqBC,WAChC,KAAK,iBAAiB,OAAO,OAAO;EACvC,EAAC;EALe;EAMjB,KAAK,OAAO,CAAC,eAAe,EAAE,WAAW,MAAM;CAChD;CAED,QACED,OACAE,SACAC,UACA;AACA,SAAO,KAAK,WAAW,WAAY,OAAO,SAAS,SAAS;CAG7D;AACF"}
@@ -10,7 +10,7 @@ const require_utils$2 = require('./utils.cjs');
10
10
  const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
11
11
  const __langchain_langgraph = require_rolldown_runtime.__toESM(require("@langchain/langgraph"));
12
12
  const __langchain_core_utils_types = require_rolldown_runtime.__toESM(require("@langchain/core/utils/types"));
13
- const zod = require_rolldown_runtime.__toESM(require("zod"));
13
+ const zod_v3 = require_rolldown_runtime.__toESM(require("zod/v3"));
14
14
 
15
15
  //#region src/agents/middlewareAgent/nodes/AgentNode.ts
16
16
  var AgentNode = class extends require_RunnableCallable.RunnableCallable {
@@ -36,7 +36,7 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
36
36
  * If so, we should generate structured response (if needed) and stop
37
37
  */
38
38
  const lastMessage = state.messages.at(-1);
39
- if (lastMessage && (0, __langchain_core_messages.isToolMessage)(lastMessage) && lastMessage.name && this.#options.shouldReturnDirect.has(lastMessage.name))
39
+ if (lastMessage && __langchain_core_messages.ToolMessage.isInstance(lastMessage) && lastMessage.name && this.#options.shouldReturnDirect.has(lastMessage.name))
40
40
  /**
41
41
  * return directly without invoking the model again
42
42
  */
@@ -55,9 +55,9 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
55
55
  if (response instanceof __langchain_langgraph.Command) return response;
56
56
  response.name = this.name;
57
57
  response.lc_kwargs.name = this.name;
58
- if (this.#areMoreStepsNeeded(state, response)) return { messages: [new __langchain_core_messages.AIMessage("Sorry, need more steps to process this request.", {
58
+ if (this.#areMoreStepsNeeded(state, response)) return { messages: [new __langchain_core_messages.AIMessage({
59
+ content: "Sorry, need more steps to process this request.",
59
60
  name: this.name,
60
- lc_kwargs: { name: this.name },
61
61
  id: response.id
62
62
  })] };
63
63
  return { messages: [response] };
@@ -102,13 +102,6 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
102
102
  ...modelInput,
103
103
  messages: preparedOptions.messages
104
104
  };
105
- if (preparedOptions?.systemMessage) {
106
- const systemMsg = new __langchain_core_messages.SystemMessage(preparedOptions.systemMessage);
107
- modelInput = {
108
- ...modelInput,
109
- messages: [systemMsg, ...modelInput.messages]
110
- };
111
- }
112
105
  const signal = require_utils$1.mergeAbortSignals(this.#options.signal, config.signal);
113
106
  const invokeConfig = {
114
107
  ...config,
@@ -223,7 +216,7 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
223
216
  throw error;
224
217
  }
225
218
  #areMoreStepsNeeded(state, response) {
226
- const allToolsReturnDirect = response instanceof __langchain_core_messages.AIMessage && response.tool_calls?.every((call) => this.#options.shouldReturnDirect.has(call.name));
219
+ const allToolsReturnDirect = __langchain_core_messages.AIMessage.isInstance(response) && response.tool_calls?.every((call) => this.#options.shouldReturnDirect.has(call.name));
227
220
  const remainingSteps = "remainingSteps" in state ? state.remainingSteps : void 0;
228
221
  return Boolean(remainingSteps && (remainingSteps < 1 && allToolsReturnDirect || remainingSteps < 2 && require_utils.hasToolCalls(state.messages)));
229
222
  }
@@ -239,18 +232,18 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
239
232
  };
240
233
  }
241
234
  async #executePrepareModelRequestHooks(model, state, config) {
242
- if (!this.#options.prepareModelRequestHookMiddlewares || this.#options.prepareModelRequestHookMiddlewares.length === 0) return void 0;
235
+ if (!this.#options.prepareModelRequestHookMiddleware || this.#options.prepareModelRequestHookMiddleware.length === 0) return void 0;
243
236
  let systemMessage;
244
237
  if (typeof this.#options.prompt === "string") systemMessage = new __langchain_core_messages.SystemMessage(this.#options.prompt);
245
- else if ((0, __langchain_core_messages.isBaseMessage)(this.#options.prompt)) systemMessage = this.#options.prompt;
238
+ else if (__langchain_core_messages.BaseMessage.isInstance(this.#options.prompt)) systemMessage = this.#options.prompt;
246
239
  let currentOptions = {
247
240
  model,
248
241
  systemMessage,
249
242
  messages: state.messages,
250
243
  tools: []
251
244
  };
252
- const middlewares = this.#options.prepareModelRequestHookMiddlewares;
253
- for (const [middleware, getMiddlewareState] of middlewares) {
245
+ const middlewareList = this.#options.prepareModelRequestHookMiddleware;
246
+ for (const [middleware, getMiddlewareState] of middlewareList) {
254
247
  const context = {
255
248
  ...middleware.contextSchema?.parse({}) || {},
256
249
  ...config?.context || {}
@@ -275,7 +268,7 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
275
268
  return currentOptions;
276
269
  }
277
270
  async #bindTools(model, preparedOptions) {
278
- const options = { ...preparedOptions?.modelSettings };
271
+ const options = {};
279
272
  const structuredTools = Object.values(this.#structuredToolInfo);
280
273
  const allTools = this.#options.toolClasses.concat(...structuredTools.map((toolStrategy) => toolStrategy.tool), ...preparedOptions?.tools || []);
281
274
  /**
@@ -319,11 +312,11 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
319
312
  /**
320
313
  * Create a model runnable with the prompt and agent name
321
314
  */
322
- const modelRunnable = require_utils.getPromptRunnable(this.#options.prompt).pipe(this.#options.includeAgentName === "inline" ? require_withAgentName.withAgentName(modelWithTools, this.#options.includeAgentName) : modelWithTools);
315
+ const modelRunnable = require_utils.getPromptRunnable(preparedOptions?.systemMessage ?? this.#options.prompt).pipe(this.#options.includeAgentName === "inline" ? require_withAgentName.withAgentName(modelWithTools, this.#options.includeAgentName) : modelWithTools);
323
316
  return modelRunnable;
324
317
  }
325
318
  static get nodeOptions() {
326
- return { input: zod.z.object({ messages: zod.z.array(zod.z.custom()) }) };
319
+ return { input: zod_v3.z.object({ messages: zod_v3.z.array(zod_v3.z.custom()) }) };
327
320
  }
328
321
  };
329
322
 
@@ -1 +1 @@
1
- {"version":3,"file":"AgentNode.cjs","names":["RunnableCallable","options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>","#run","#options","#structuredToolInfo","transformResponseFormat","ToolStrategy","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","#invokeModel","Command","#areMoreStepsNeeded","AIMessage","initChatModel","options: {\n lastMessage?: string;\n }","#deriveModel","#executePrepareModelRequestHooks","validateLLMHasNoBoundTools","#bindTools","#getModelInputState","SystemMessage","mergeAbortSignals","ProviderStrategy","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","response: AIMessage","toolCalls: ToolCall[]","MultipleStructuredOutputsError","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","ToolMessage","response: BaseMessage","hasToolCalls","model: LanguageModelLike","config: LangGraphRunnableConfig","systemMessage: BaseMessage | undefined","currentOptions: ModelRequest","runtime: Runtime<any>","parseToolCalls","parseToolResults","preparedOptions?: ModelRequest","options: Partial<BaseChatModelCallOptions & AnthropicModelSettings>","hasSupportForJsonSchemaOutput","bindTools","getPromptRunnable","withAgentName","z"],"sources":["../../../../src/agents/middlewareAgent/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseMessage,\n AIMessage,\n ToolMessage,\n SystemMessage,\n isBaseMessage,\n isToolMessage,\n} from \"@langchain/core/messages\";\nimport { z } from \"zod\";\nimport { Command, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\n\nimport { initChatModel } from \"../../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../../errors.js\";\nimport { RunnableCallable } from \"../../RunnableCallable.js\";\nimport { PreHookAnnotation, AnyAnnotationRoot } from \"../../annotation.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n hasSupportForJsonSchemaOutput,\n} from \"../../utils.js\";\nimport { mergeAbortSignals } from \"../../nodes/utils.js\";\nimport {\n ModelRequest,\n CreateAgentParams,\n InternalAgentState,\n AnthropicModelSettings,\n Runtime,\n AgentMiddleware,\n} from \"../types.js\";\nimport type { ClientTool, ServerTool } from \"../../types.js\";\nimport { withAgentName } from \"../../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../../responses.js\";\nimport { parseToolCalls, parseToolResults } from \"./utils.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, ContextSchema>,\n | \"llm\"\n | \"model\"\n | \"prompt\"\n | \"includeAgentName\"\n | \"name\"\n | \"responseFormat\"\n | \"middlewares\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n prepareModelRequestHookMiddlewares?: [\n AgentMiddleware<any, any, any>,\n () => any\n ][];\n}\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n { messages: BaseMessage[] } | { structuredResponse: StructuredResponseFormat }\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n\n #structuredToolInfo: Record<string, ToolStrategy> = {};\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) =>\n this.#run(input, config as RunnableConfig) as any,\n });\n\n this.#options = options;\n\n /**\n * Populate a list of structured tool info.\n */\n this.#structuredToolInfo = (\n transformResponseFormat(this.#options.responseFormat).filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>);\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n isToolMessage(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage(\"Sorry, need more steps to process this request.\", {\n name: this.name,\n lc_kwargs: { name: this.name },\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n if (this.#options.model) {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n throw new Error(\"`model` option must be a string.\");\n }\n\n const model = this.#options.llm;\n\n /**\n * If the model is a function, call it to get the model.\n */\n if (typeof model === \"function\") {\n return model(state, config);\n }\n\n if (model) {\n return model;\n }\n\n throw new Error(\n \"No model option was provided, either via `model` or via `llm` option.\"\n );\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel(state, config);\n\n /**\n * Execute prepareModelRequest hooks from beforeModelNodes\n */\n const preparedOptions = await this.#executePrepareModelRequestHooks(\n model,\n state,\n config\n );\n\n /**\n * If user provides a model in the preparedOptions, use it,\n * otherwise use the model from the options\n */\n const finalModel = preparedOptions?.model ?? model;\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(finalModel);\n\n const modelWithTools = await this.#bindTools(finalModel, preparedOptions);\n let modelInput = this.#getModelInputState(state);\n\n // Use messages from preparedOptions if provided\n if (preparedOptions?.messages) {\n modelInput = { ...modelInput, messages: preparedOptions.messages };\n }\n\n // Add system message if provided\n if (preparedOptions?.systemMessage) {\n // Prepend a system message if needed\n const systemMsg = new SystemMessage(preparedOptions.systemMessage);\n modelInput = {\n ...modelInput,\n messages: [systemMsg, ...modelInput.messages],\n };\n }\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = {\n ...config,\n signal,\n };\n\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n const structuredResponse = this.#options.responseFormat.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n }\n\n if (!response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in this.#structuredToolInfo\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(response, toolCalls);\n }\n\n const toolStrategy = this.#structuredToolInfo[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n toolMessageContent ?? options.lastMessage\n );\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[]\n ): Promise<Command> {\n /**\n * the following should never happen, let's throw an error if it does\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n throw new Error(\n \"Multiple structured outputs should not apply to native structured output responses\"\n );\n }\n\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0]\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = this.#structuredToolInfo[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(this.#structuredToolInfo).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n response instanceof AIMessage &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages)))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #executePrepareModelRequestHooks(\n model: LanguageModelLike,\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: LangGraphRunnableConfig\n ): Promise<ModelRequest | undefined> {\n if (\n !this.#options.prepareModelRequestHookMiddlewares ||\n this.#options.prepareModelRequestHookMiddlewares.length === 0\n ) {\n return undefined;\n }\n\n // Get the prompt for system message\n let systemMessage: BaseMessage | undefined;\n if (typeof this.#options.prompt === \"string\") {\n systemMessage = new SystemMessage(this.#options.prompt);\n } else if (isBaseMessage(this.#options.prompt)) {\n systemMessage = this.#options.prompt;\n }\n\n // Prepare the initial call options\n let currentOptions: ModelRequest = {\n model,\n systemMessage,\n messages: state.messages,\n tools: [],\n };\n\n // Execute prepareModelRequest hooks from all middlewares\n const middlewares = this.#options.prepareModelRequestHookMiddlewares;\n for (const [middleware, getMiddlewareState] of middlewares) {\n // Merge context with default context of middleware\n const context = {\n ...(middleware.contextSchema?.parse({}) || {}),\n ...(config?.context || {}),\n };\n\n // Create runtime\n const runtime: Runtime<any> = {\n toolCalls: parseToolCalls(state.messages),\n toolResults: parseToolResults(state.messages),\n context,\n };\n\n const result = await middleware.prepareModelRequest!(\n currentOptions,\n {\n messages: state.messages,\n ...getMiddlewareState(),\n },\n {\n ...runtime,\n context,\n }\n );\n\n if (result) {\n currentOptions = { ...currentOptions, ...result };\n }\n }\n\n return currentOptions;\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions?: ModelRequest\n ): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions & AnthropicModelSettings> =\n {\n ...preparedOptions?.modelSettings,\n };\n const structuredTools = Object.values(this.#structuredToolInfo);\n\n // Use tools from preparedOptions if provided, otherwise use default tools\n const allTools = this.#options.toolClasses.concat(\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ...(preparedOptions?.tools || [])\n );\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n /**\n * if the model does not support JSON schema output, throw an error\n */\n if (!hasSupportForJsonSchemaOutput(model)) {\n throw new Error(\n \"Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.\"\n );\n }\n\n const jsonSchemaParams = {\n name: this.#options.responseFormat.schema?.name ?? \"extract\",\n description: getSchemaDescription(this.#options.responseFormat.schema),\n schema: this.#options.responseFormat.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: this.#options.responseFormat.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(this.#options.prompt).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n\n static get nodeOptions() {\n return {\n input: z.object({\n messages: z.array(z.custom<BaseMessage>()),\n }),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkFA,IAAa,YAAb,cAMUA,0CAGR;CACA;CAEA,sBAAoD,CAAE;CAEtD,YACEC,SACA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WACZ,KAAKC,KAAK,OAAO,OAAyB;EAC7C,EAAC;EAEF,KAAKC,WAAW;;;;EAKhB,KAAKC,sBACHC,0CAAwB,KAAKF,SAAS,eAAe,CAAC,OACpD,CAAC,WAAW,kBAAkBG,+BAC/B,CACD,OAAO,CAAC,KAAK,WAAW;GACxB,IAAI,OAAO,QAAQ;AACnB,UAAO;EACR,GAAE,CAAE,EAAiC;CACvC;CAED,MAAMJ,KACJK,OAEAC,QACA;;;;;EAKA,MAAM,cAAc,MAAM,SAAS,GAAG,GAAG;AACzC,MACE,4DACc,YAAY,IAC1B,YAAY,QACZ,KAAKL,SAAS,mBAAmB,IAAI,YAAY,KAAK;;;;AAKtD,SAAO,EAAE,UAAU,CAAE,EAAE;EAGzB,MAAM,WAAW,MAAM,KAAKM,aAAa,OAAO,OAAO;;;;AAKvD,MAAI,wBAAwB,SAC1B,QAAO;GACL,UAAU,CAAC,GAAG,MAAM,UAAU,GAAI,SAAS,YAAY,CAAE,CA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;;;AAKxC,MAAI,KAAKA,SAAS,0BAA0BmB,oCAAkB;;;;AAI5D,OAAI,CAACsB,4CAA8B,MAAM,CACvC,OAAM,IAAI,MACR;GAIJ,MAAM,mBAAmB;IACvB,MAAM,KAAKzC,SAAS,eAAe,QAAQ,QAAQ;IACnD,oEAAkC,KAAKA,SAAS,eAAe,OAAO;IACtE,QAAQ,KAAKA,SAAS,eAAe;IACrC,QAAQ;GACT;GAED,OAAO,OAAO,SAAS;IACrB,iBAAiB;KACf,MAAM;KACN,aAAa;IACd;IACD,6BAA6B;KAC3B,QAAQ,EAAE,QAAQ,cAAe;KACjC,QAAQ,KAAKA,SAAS,eAAe;IACtC;IACD,QAAQ;GACT,EAAC;EACH;;;;EAKD,MAAM,iBAAiB,MAAM0C,wBAAU,OAAO,UAAU;GACtD,GAAG;GACH,aAAa;EACd,EAAC;;;;EAKF,MAAM,gBAAgBC,gCAAkB,KAAK3C,SAAS,OAAO,CAAC,KAC5D,KAAKA,SAAS,qBAAqB,WAC/B4C,oCAAc,gBAAgB,KAAK5C,SAAS,iBAAiB,GAC7D,eACL;AAED,SAAO;CACR;CAED,WAAW,cAAc;AACvB,SAAO,EACL,OAAO6C,MAAE,OAAO,EACd,UAAUA,MAAE,MAAMA,MAAE,QAAqB,CAAC,CAC3C,EAAC,CACH;CACF;AACF"}
1
+ {"version":3,"file":"AgentNode.cjs","names":["RunnableCallable","options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>","#run","#options","#structuredToolInfo","transformResponseFormat","ToolStrategy","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","ToolMessage","#invokeModel","Command","#areMoreStepsNeeded","AIMessage","initChatModel","options: {\n lastMessage?: string;\n }","#deriveModel","#executePrepareModelRequestHooks","validateLLMHasNoBoundTools","#bindTools","#getModelInputState","mergeAbortSignals","ProviderStrategy","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","response: AIMessage","toolCalls: ToolCall[]","MultipleStructuredOutputsError","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","hasToolCalls","model: LanguageModelLike","config: LangGraphRunnableConfig","systemMessage: BaseMessage | undefined","SystemMessage","BaseMessage","currentOptions: ModelRequest","runtime: Runtime<any>","parseToolCalls","parseToolResults","preparedOptions?: ModelRequest","options: Partial<BaseChatModelCallOptions>","hasSupportForJsonSchemaOutput","bindTools","getPromptRunnable","withAgentName","z"],"sources":["../../../../src/agents/middlewareAgent/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseMessage,\n AIMessage,\n ToolMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport { z } from \"zod/v3\";\nimport { Command, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\n\nimport { initChatModel } from \"../../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../../errors.js\";\nimport { RunnableCallable } from \"../../RunnableCallable.js\";\nimport { PreHookAnnotation, AnyAnnotationRoot } from \"../../annotation.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n hasSupportForJsonSchemaOutput,\n} from \"../../utils.js\";\nimport { mergeAbortSignals } from \"../../nodes/utils.js\";\nimport {\n ModelRequest,\n CreateAgentParams,\n InternalAgentState,\n Runtime,\n AgentMiddleware,\n} from \"../types.js\";\nimport type { ClientTool, ServerTool } from \"../../types.js\";\nimport { withAgentName } from \"../../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../../responses.js\";\nimport { parseToolCalls, parseToolResults } from \"./utils.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, ContextSchema>,\n | \"llm\"\n | \"model\"\n | \"prompt\"\n | \"includeAgentName\"\n | \"name\"\n | \"responseFormat\"\n | \"middleware\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n prepareModelRequestHookMiddleware?: [\n AgentMiddleware<any, any, any>,\n () => any\n ][];\n}\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n { messages: BaseMessage[] } | { structuredResponse: StructuredResponseFormat }\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n\n #structuredToolInfo: Record<string, ToolStrategy> = {};\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) =>\n this.#run(input, config as RunnableConfig) as any,\n });\n\n this.#options = options;\n\n /**\n * Populate a list of structured tool info.\n */\n this.#structuredToolInfo = (\n transformResponseFormat(this.#options.responseFormat).filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>);\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage({\n content: \"Sorry, need more steps to process this request.\",\n name: this.name,\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n if (this.#options.model) {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n throw new Error(\"`model` option must be a string.\");\n }\n\n const model = this.#options.llm;\n\n /**\n * If the model is a function, call it to get the model.\n */\n if (typeof model === \"function\") {\n return model(state, config);\n }\n\n if (model) {\n return model;\n }\n\n throw new Error(\n \"No model option was provided, either via `model` or via `llm` option.\"\n );\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel(state, config);\n\n /**\n * Execute prepareModelRequest hooks from beforeModelNodes\n */\n const preparedOptions = await this.#executePrepareModelRequestHooks(\n model,\n state,\n config\n );\n\n /**\n * If user provides a model in the preparedOptions, use it,\n * otherwise use the model from the options\n */\n const finalModel = preparedOptions?.model ?? model;\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(finalModel);\n\n const modelWithTools = await this.#bindTools(finalModel, preparedOptions);\n let modelInput = this.#getModelInputState(state);\n\n // Use messages from preparedOptions if provided\n if (preparedOptions?.messages) {\n modelInput = { ...modelInput, messages: preparedOptions.messages };\n }\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = { ...config, signal };\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n const structuredResponse = this.#options.responseFormat.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n }\n\n if (!response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in this.#structuredToolInfo\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(response, toolCalls);\n }\n\n const toolStrategy = this.#structuredToolInfo[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n toolMessageContent ?? options.lastMessage\n );\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[]\n ): Promise<Command> {\n /**\n * the following should never happen, let's throw an error if it does\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n throw new Error(\n \"Multiple structured outputs should not apply to native structured output responses\"\n );\n }\n\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0]\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = this.#structuredToolInfo[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(this.#structuredToolInfo).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n AIMessage.isInstance(response) &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages)))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #executePrepareModelRequestHooks(\n model: LanguageModelLike,\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: LangGraphRunnableConfig\n ): Promise<ModelRequest | undefined> {\n if (\n !this.#options.prepareModelRequestHookMiddleware ||\n this.#options.prepareModelRequestHookMiddleware.length === 0\n ) {\n return undefined;\n }\n\n // Get the prompt for system message\n let systemMessage: BaseMessage | undefined;\n if (typeof this.#options.prompt === \"string\") {\n systemMessage = new SystemMessage(this.#options.prompt);\n } else if (BaseMessage.isInstance(this.#options.prompt)) {\n systemMessage = this.#options.prompt;\n }\n\n // Prepare the initial call options\n let currentOptions: ModelRequest = {\n model,\n systemMessage,\n messages: state.messages,\n tools: [],\n };\n\n // Execute prepareModelRequest hooks from all middleware\n const middlewareList = this.#options.prepareModelRequestHookMiddleware;\n for (const [middleware, getMiddlewareState] of middlewareList) {\n // Merge context with default context of middleware\n const context = {\n ...(middleware.contextSchema?.parse({}) || {}),\n ...(config?.context || {}),\n };\n\n // Create runtime\n const runtime: Runtime<any> = {\n toolCalls: parseToolCalls(state.messages),\n toolResults: parseToolResults(state.messages),\n context,\n };\n\n const result = await middleware.prepareModelRequest!(\n currentOptions,\n {\n messages: state.messages,\n ...getMiddlewareState(),\n },\n {\n ...runtime,\n context,\n }\n );\n\n if (result) {\n currentOptions = { ...currentOptions, ...result };\n }\n }\n\n return currentOptions;\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions?: ModelRequest\n ): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(this.#structuredToolInfo);\n\n // Use tools from preparedOptions if provided, otherwise use default tools\n const allTools = this.#options.toolClasses.concat(\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ...(preparedOptions?.tools || [])\n );\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n /**\n * if the model does not support JSON schema output, throw an error\n */\n if (!hasSupportForJsonSchemaOutput(model)) {\n throw new Error(\n \"Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.\"\n );\n }\n\n const jsonSchemaParams = {\n name: this.#options.responseFormat.schema?.name ?? \"extract\",\n description: getSchemaDescription(this.#options.responseFormat.schema),\n schema: this.#options.responseFormat.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: this.#options.responseFormat.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(\n (preparedOptions?.systemMessage as SystemMessage) ?? this.#options.prompt\n ).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n\n static get nodeOptions(): {\n input: z.ZodObject<{ messages: z.ZodArray<z.ZodType<BaseMessage>> }>;\n } {\n return {\n input: z.object({\n messages: z.array(z.custom<BaseMessage>()),\n }),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgFA,IAAa,YAAb,cAMUA,0CAGR;CACA;CAEA,sBAAoD,CAAE;CAEtD,YACEC,SACA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WACZ,KAAKC,KAAK,OAAO,OAAyB;EAC7C,EAAC;EAEF,KAAKC,WAAW;;;;EAKhB,KAAKC,sBACHC,0CAAwB,KAAKF,SAAS,eAAe,CAAC,OACpD,CAAC,WAAW,kBAAkBG,+BAC/B,CACD,OAAO,CAAC,KAAK,WAAW;GACxB,IAAI,OAAO,QAAQ;AACnB,UAAO;EACR,GAAE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AAO,KAAKxC,oBAAoB;EAG/D,MAAM,WAAW,KAAKD,SAAS,YAAY,OACzC,GAAG,gBAAgB,IAAI,CAAC,iBAAiB,aAAa,KAAK,EAC3D,GAAI,iBAAiB,SAAS,CAAE,EACjC;;;;;EAMD,MAAM,aACJ,iBAAiB,eAChB,gBAAgB,SAAS,IAAI,QAAQ;;;;AAKxC,MAAI,KAAKA,SAAS,0BAA0BmB,oCAAkB;;;;AAI5D,OAAI,CAACuB,4CAA8B,MAAM,CACvC,OAAM,IAAI,MACR;GAIJ,MAAM,mBAAmB;IACvB,MAAM,KAAK1C,SAAS,eAAe,QAAQ,QAAQ;IACnD,oEAAkC,KAAKA,SAAS,eAAe,OAAO;IACtE,QAAQ,KAAKA,SAAS,eAAe;IACrC,QAAQ;GACT;GAED,OAAO,OAAO,SAAS;IACrB,iBAAiB;KACf,MAAM;KACN,aAAa;IACd;IACD,6BAA6B;KAC3B,QAAQ,EAAE,QAAQ,cAAe;KACjC,QAAQ,KAAKA,SAAS,eAAe;IACtC;IACD,QAAQ;GACT,EAAC;EACH;;;;EAKD,MAAM,iBAAiB,MAAM2C,wBAAU,OAAO,UAAU;GACtD,GAAG;GACH,aAAa;EACd,EAAC;;;;EAKF,MAAM,gBAAgBC,gCACnB,iBAAiB,iBAAmC,KAAK5C,SAAS,OACpE,CAAC,KACA,KAAKA,SAAS,qBAAqB,WAC/B6C,oCAAc,gBAAgB,KAAK7C,SAAS,iBAAiB,GAC7D,eACL;AAED,SAAO;CACR;CAED,WAAW,cAET;AACA,SAAO,EACL,OAAO8C,SAAE,OAAO,EACd,UAAUA,SAAE,MAAMA,SAAE,QAAqB,CAAC,CAC3C,EAAC,CACH;CACF;AACF"}
@@ -6,10 +6,10 @@ import { mergeAbortSignals } from "../../nodes/utils.js";
6
6
  import { withAgentName } from "../../withAgentName.js";
7
7
  import { ProviderStrategy, ToolStrategy, transformResponseFormat } from "../../responses.js";
8
8
  import { parseToolCalls, parseToolResults } from "./utils.js";
9
- import { AIMessage, SystemMessage, ToolMessage, isBaseMessage, isToolMessage } from "@langchain/core/messages";
9
+ import { AIMessage, BaseMessage, SystemMessage, ToolMessage } from "@langchain/core/messages";
10
10
  import { Command } from "@langchain/langgraph";
11
11
  import { getSchemaDescription } from "@langchain/core/utils/types";
12
- import { z } from "zod";
12
+ import { z } from "zod/v3";
13
13
 
14
14
  //#region src/agents/middlewareAgent/nodes/AgentNode.ts
15
15
  var AgentNode = class extends RunnableCallable {
@@ -35,7 +35,7 @@ var AgentNode = class extends RunnableCallable {
35
35
  * If so, we should generate structured response (if needed) and stop
36
36
  */
37
37
  const lastMessage = state.messages.at(-1);
38
- if (lastMessage && isToolMessage(lastMessage) && lastMessage.name && this.#options.shouldReturnDirect.has(lastMessage.name))
38
+ if (lastMessage && ToolMessage.isInstance(lastMessage) && lastMessage.name && this.#options.shouldReturnDirect.has(lastMessage.name))
39
39
  /**
40
40
  * return directly without invoking the model again
41
41
  */
@@ -54,9 +54,9 @@ var AgentNode = class extends RunnableCallable {
54
54
  if (response instanceof Command) return response;
55
55
  response.name = this.name;
56
56
  response.lc_kwargs.name = this.name;
57
- if (this.#areMoreStepsNeeded(state, response)) return { messages: [new AIMessage("Sorry, need more steps to process this request.", {
57
+ if (this.#areMoreStepsNeeded(state, response)) return { messages: [new AIMessage({
58
+ content: "Sorry, need more steps to process this request.",
58
59
  name: this.name,
59
- lc_kwargs: { name: this.name },
60
60
  id: response.id
61
61
  })] };
62
62
  return { messages: [response] };
@@ -101,13 +101,6 @@ var AgentNode = class extends RunnableCallable {
101
101
  ...modelInput,
102
102
  messages: preparedOptions.messages
103
103
  };
104
- if (preparedOptions?.systemMessage) {
105
- const systemMsg = new SystemMessage(preparedOptions.systemMessage);
106
- modelInput = {
107
- ...modelInput,
108
- messages: [systemMsg, ...modelInput.messages]
109
- };
110
- }
111
104
  const signal = mergeAbortSignals(this.#options.signal, config.signal);
112
105
  const invokeConfig = {
113
106
  ...config,
@@ -222,7 +215,7 @@ var AgentNode = class extends RunnableCallable {
222
215
  throw error;
223
216
  }
224
217
  #areMoreStepsNeeded(state, response) {
225
- const allToolsReturnDirect = response instanceof AIMessage && response.tool_calls?.every((call) => this.#options.shouldReturnDirect.has(call.name));
218
+ const allToolsReturnDirect = AIMessage.isInstance(response) && response.tool_calls?.every((call) => this.#options.shouldReturnDirect.has(call.name));
226
219
  const remainingSteps = "remainingSteps" in state ? state.remainingSteps : void 0;
227
220
  return Boolean(remainingSteps && (remainingSteps < 1 && allToolsReturnDirect || remainingSteps < 2 && hasToolCalls(state.messages)));
228
221
  }
@@ -238,18 +231,18 @@ var AgentNode = class extends RunnableCallable {
238
231
  };
239
232
  }
240
233
  async #executePrepareModelRequestHooks(model, state, config) {
241
- if (!this.#options.prepareModelRequestHookMiddlewares || this.#options.prepareModelRequestHookMiddlewares.length === 0) return void 0;
234
+ if (!this.#options.prepareModelRequestHookMiddleware || this.#options.prepareModelRequestHookMiddleware.length === 0) return void 0;
242
235
  let systemMessage;
243
236
  if (typeof this.#options.prompt === "string") systemMessage = new SystemMessage(this.#options.prompt);
244
- else if (isBaseMessage(this.#options.prompt)) systemMessage = this.#options.prompt;
237
+ else if (BaseMessage.isInstance(this.#options.prompt)) systemMessage = this.#options.prompt;
245
238
  let currentOptions = {
246
239
  model,
247
240
  systemMessage,
248
241
  messages: state.messages,
249
242
  tools: []
250
243
  };
251
- const middlewares = this.#options.prepareModelRequestHookMiddlewares;
252
- for (const [middleware, getMiddlewareState] of middlewares) {
244
+ const middlewareList = this.#options.prepareModelRequestHookMiddleware;
245
+ for (const [middleware, getMiddlewareState] of middlewareList) {
253
246
  const context = {
254
247
  ...middleware.contextSchema?.parse({}) || {},
255
248
  ...config?.context || {}
@@ -274,7 +267,7 @@ var AgentNode = class extends RunnableCallable {
274
267
  return currentOptions;
275
268
  }
276
269
  async #bindTools(model, preparedOptions) {
277
- const options = { ...preparedOptions?.modelSettings };
270
+ const options = {};
278
271
  const structuredTools = Object.values(this.#structuredToolInfo);
279
272
  const allTools = this.#options.toolClasses.concat(...structuredTools.map((toolStrategy) => toolStrategy.tool), ...preparedOptions?.tools || []);
280
273
  /**
@@ -318,7 +311,7 @@ var AgentNode = class extends RunnableCallable {
318
311
  /**
319
312
  * Create a model runnable with the prompt and agent name
320
313
  */
321
- const modelRunnable = getPromptRunnable(this.#options.prompt).pipe(this.#options.includeAgentName === "inline" ? withAgentName(modelWithTools, this.#options.includeAgentName) : modelWithTools);
314
+ const modelRunnable = getPromptRunnable(preparedOptions?.systemMessage ?? this.#options.prompt).pipe(this.#options.includeAgentName === "inline" ? withAgentName(modelWithTools, this.#options.includeAgentName) : modelWithTools);
322
315
  return modelRunnable;
323
316
  }
324
317
  static get nodeOptions() {
@@ -1 +1 @@
1
- {"version":3,"file":"AgentNode.js","names":["options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>","#run","#options","#structuredToolInfo","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","#invokeModel","#areMoreStepsNeeded","options: {\n lastMessage?: string;\n }","#deriveModel","#executePrepareModelRequestHooks","#bindTools","#getModelInputState","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","response: AIMessage","toolCalls: ToolCall[]","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","model: LanguageModelLike","config: LangGraphRunnableConfig","systemMessage: BaseMessage | undefined","currentOptions: ModelRequest","runtime: Runtime<any>","preparedOptions?: ModelRequest","options: Partial<BaseChatModelCallOptions & AnthropicModelSettings>"],"sources":["../../../../src/agents/middlewareAgent/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseMessage,\n AIMessage,\n ToolMessage,\n SystemMessage,\n isBaseMessage,\n isToolMessage,\n} from \"@langchain/core/messages\";\nimport { z } from \"zod\";\nimport { Command, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\n\nimport { initChatModel } from \"../../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../../errors.js\";\nimport { RunnableCallable } from \"../../RunnableCallable.js\";\nimport { PreHookAnnotation, AnyAnnotationRoot } from \"../../annotation.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n hasSupportForJsonSchemaOutput,\n} from \"../../utils.js\";\nimport { mergeAbortSignals } from \"../../nodes/utils.js\";\nimport {\n ModelRequest,\n CreateAgentParams,\n InternalAgentState,\n AnthropicModelSettings,\n Runtime,\n AgentMiddleware,\n} from \"../types.js\";\nimport type { ClientTool, ServerTool } from \"../../types.js\";\nimport { withAgentName } from \"../../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../../responses.js\";\nimport { parseToolCalls, parseToolResults } from \"./utils.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, ContextSchema>,\n | \"llm\"\n | \"model\"\n | \"prompt\"\n | \"includeAgentName\"\n | \"name\"\n | \"responseFormat\"\n | \"middlewares\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n prepareModelRequestHookMiddlewares?: [\n AgentMiddleware<any, any, any>,\n () => any\n ][];\n}\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n { messages: BaseMessage[] } | { structuredResponse: StructuredResponseFormat }\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n\n #structuredToolInfo: Record<string, ToolStrategy> = {};\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) =>\n this.#run(input, config as RunnableConfig) as any,\n });\n\n this.#options = options;\n\n /**\n * Populate a list of structured tool info.\n */\n this.#structuredToolInfo = (\n transformResponseFormat(this.#options.responseFormat).filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>);\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n isToolMessage(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage(\"Sorry, need more steps to process this request.\", {\n name: this.name,\n lc_kwargs: { name: this.name },\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n if (this.#options.model) {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n throw new Error(\"`model` option must be a string.\");\n }\n\n const model = this.#options.llm;\n\n /**\n * If the model is a function, call it to get the model.\n */\n if (typeof model === \"function\") {\n return model(state, config);\n }\n\n if (model) {\n return model;\n }\n\n throw new Error(\n \"No model option was provided, either via `model` or via `llm` option.\"\n );\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel(state, config);\n\n /**\n * Execute prepareModelRequest hooks from beforeModelNodes\n */\n const preparedOptions = await this.#executePrepareModelRequestHooks(\n model,\n state,\n config\n );\n\n /**\n * If user provides a model in the preparedOptions, use it,\n * otherwise use the model from the options\n */\n const finalModel = preparedOptions?.model ?? model;\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(finalModel);\n\n const modelWithTools = await this.#bindTools(finalModel, preparedOptions);\n let modelInput = this.#getModelInputState(state);\n\n // Use messages from preparedOptions if provided\n if (preparedOptions?.messages) {\n modelInput = { ...modelInput, messages: preparedOptions.messages };\n }\n\n // Add system message if provided\n if (preparedOptions?.systemMessage) {\n // Prepend a system message if needed\n const systemMsg = new SystemMessage(preparedOptions.systemMessage);\n modelInput = {\n ...modelInput,\n messages: [systemMsg, ...modelInput.messages],\n };\n }\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = {\n ...config,\n signal,\n };\n\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n const structuredResponse = this.#options.responseFormat.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n }\n\n if (!response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in this.#structuredToolInfo\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(response, toolCalls);\n }\n\n const toolStrategy = this.#structuredToolInfo[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n toolMessageContent ?? options.lastMessage\n );\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[]\n ): Promise<Command> {\n /**\n * the following should never happen, let's throw an error if it does\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n throw new Error(\n \"Multiple structured outputs should not apply to native structured output responses\"\n );\n }\n\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0]\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = this.#structuredToolInfo[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(this.#structuredToolInfo).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n response instanceof AIMessage &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages)))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #executePrepareModelRequestHooks(\n model: LanguageModelLike,\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: LangGraphRunnableConfig\n ): Promise<ModelRequest | undefined> {\n if (\n !this.#options.prepareModelRequestHookMiddlewares ||\n this.#options.prepareModelRequestHookMiddlewares.length === 0\n ) {\n return undefined;\n }\n\n // Get the prompt for system message\n let systemMessage: BaseMessage | undefined;\n if (typeof this.#options.prompt === \"string\") {\n systemMessage = new SystemMessage(this.#options.prompt);\n } else if (isBaseMessage(this.#options.prompt)) {\n systemMessage = this.#options.prompt;\n }\n\n // Prepare the initial call options\n let currentOptions: ModelRequest = {\n model,\n systemMessage,\n messages: state.messages,\n tools: [],\n };\n\n // Execute prepareModelRequest hooks from all middlewares\n const middlewares = this.#options.prepareModelRequestHookMiddlewares;\n for (const [middleware, getMiddlewareState] of middlewares) {\n // Merge context with default context of middleware\n const context = {\n ...(middleware.contextSchema?.parse({}) || {}),\n ...(config?.context || {}),\n };\n\n // Create runtime\n const runtime: Runtime<any> = {\n toolCalls: parseToolCalls(state.messages),\n toolResults: parseToolResults(state.messages),\n context,\n };\n\n const result = await middleware.prepareModelRequest!(\n currentOptions,\n {\n messages: state.messages,\n ...getMiddlewareState(),\n },\n {\n ...runtime,\n context,\n }\n );\n\n if (result) {\n currentOptions = { ...currentOptions, ...result };\n }\n }\n\n return currentOptions;\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions?: ModelRequest\n ): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions & AnthropicModelSettings> =\n {\n ...preparedOptions?.modelSettings,\n };\n const structuredTools = Object.values(this.#structuredToolInfo);\n\n // Use tools from preparedOptions if provided, otherwise use default tools\n const allTools = this.#options.toolClasses.concat(\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ...(preparedOptions?.tools || [])\n );\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n /**\n * if the model does not support JSON schema output, throw an error\n */\n if (!hasSupportForJsonSchemaOutput(model)) {\n throw new Error(\n \"Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.\"\n );\n }\n\n const jsonSchemaParams = {\n name: this.#options.responseFormat.schema?.name ?? \"extract\",\n description: getSchemaDescription(this.#options.responseFormat.schema),\n schema: this.#options.responseFormat.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: this.#options.responseFormat.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(this.#options.prompt).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n\n static get nodeOptions() {\n return {\n input: z.object({\n messages: z.array(z.custom<BaseMessage>()),\n }),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAkFA,IAAa,YAAb,cAMU,iBAGR;CACA;CAEA,sBAAoD,CAAE;CAEtD,YACEA,SACA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WACZ,KAAKC,KAAK,OAAO,OAAyB;EAC7C,EAAC;EAEF,KAAKC,WAAW;;;;EAKhB,KAAKC,sBACH,wBAAwB,KAAKD,SAAS,eAAe,CAAC,OACpD,CAAC,WAAW,kBAAkB,aAC/B,CACD,OAAO,CAAC,KAAK,WAAW;GACxB,IAAI,OAAO,QAAQ;AACnB,UAAO;EACR,GAAE,CAAE,EAAiC;CACvC;CAED,MAAMD,KACJG,OAEAC,QACA;;;;;EAKA,MAAM,cAAc,MAAM,SAAS,GAAG,GAAG;AACzC,MACE,eACA,cAAc,YAAY,IAC1B,YAAY,QACZ,KAAKH,SAAS,mBAAmB,IAAI,YAAY,KAAK;;;;AAKtD,SAAO,EAAE,UAAU,CAAE,EAAE;EAGzB,MAAM,WAAW,MAAM,KAAKI,aAAa,OAAO,OAAO;;;;AAKvD,MAAI,wBAAwB,SAC1B,QAAO;GACL,UAAU,CAAC,GAAG,MAAM,UAAU,GAAI,SAAS,YAAY,CAAE,CAAE;GAC3D,oBAAoB,SAAS;EAC9B;;;;AAMH,MAAI,oBAAoB,QACtB,QAAO;EAGT,SAAS,OAAO,K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,eAAe,QAAQ,QAAQ;IACnD,aAAa,qBAAqB,KAAKA,SAAS,eAAe,OAAO;IACtE,QAAQ,KAAKA,SAAS,eAAe;IACrC,QAAQ;GACT;GAED,OAAO,OAAO,SAAS;IACrB,iBAAiB;KACf,MAAM;KACN,aAAa;IACd;IACD,6BAA6B;KAC3B,QAAQ,EAAE,QAAQ,cAAe;KACjC,QAAQ,KAAKA,SAAS,eAAe;IACtC;IACD,QAAQ;GACT,EAAC;EACH;;;;EAKD,MAAM,iBAAiB,MAAM,UAAU,OAAO,UAAU;GACtD,GAAG;GACH,aAAa;EACd,EAAC;;;;EAKF,MAAM,gBAAgB,kBAAkB,KAAKA,SAAS,OAAO,CAAC,KAC5D,KAAKA,SAAS,qBAAqB,WAC/B,cAAc,gBAAgB,KAAKA,SAAS,iBAAiB,GAC7D,eACL;AAED,SAAO;CACR;CAED,WAAW,cAAc;AACvB,SAAO,EACL,OAAO,EAAE,OAAO,EACd,UAAU,EAAE,MAAM,EAAE,QAAqB,CAAC,CAC3C,EAAC,CACH;CACF;AACF"}
1
+ {"version":3,"file":"AgentNode.js","names":["options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>","#run","#options","#structuredToolInfo","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","#invokeModel","#areMoreStepsNeeded","options: {\n lastMessage?: string;\n }","#deriveModel","#executePrepareModelRequestHooks","#bindTools","#getModelInputState","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","response: AIMessage","toolCalls: ToolCall[]","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","model: LanguageModelLike","config: LangGraphRunnableConfig","systemMessage: BaseMessage | undefined","currentOptions: ModelRequest","runtime: Runtime<any>","preparedOptions?: ModelRequest","options: Partial<BaseChatModelCallOptions>"],"sources":["../../../../src/agents/middlewareAgent/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseMessage,\n AIMessage,\n ToolMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport { z } from \"zod/v3\";\nimport { Command, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\n\nimport { initChatModel } from \"../../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../../errors.js\";\nimport { RunnableCallable } from \"../../RunnableCallable.js\";\nimport { PreHookAnnotation, AnyAnnotationRoot } from \"../../annotation.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n hasSupportForJsonSchemaOutput,\n} from \"../../utils.js\";\nimport { mergeAbortSignals } from \"../../nodes/utils.js\";\nimport {\n ModelRequest,\n CreateAgentParams,\n InternalAgentState,\n Runtime,\n AgentMiddleware,\n} from \"../types.js\";\nimport type { ClientTool, ServerTool } from \"../../types.js\";\nimport { withAgentName } from \"../../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../../responses.js\";\nimport { parseToolCalls, parseToolResults } from \"./utils.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, ContextSchema>,\n | \"llm\"\n | \"model\"\n | \"prompt\"\n | \"includeAgentName\"\n | \"name\"\n | \"responseFormat\"\n | \"middleware\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n prepareModelRequestHookMiddleware?: [\n AgentMiddleware<any, any, any>,\n () => any\n ][];\n}\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n { messages: BaseMessage[] } | { structuredResponse: StructuredResponseFormat }\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n\n #structuredToolInfo: Record<string, ToolStrategy> = {};\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) =>\n this.#run(input, config as RunnableConfig) as any,\n });\n\n this.#options = options;\n\n /**\n * Populate a list of structured tool info.\n */\n this.#structuredToolInfo = (\n transformResponseFormat(this.#options.responseFormat).filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>);\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage({\n content: \"Sorry, need more steps to process this request.\",\n name: this.name,\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n if (this.#options.model) {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n throw new Error(\"`model` option must be a string.\");\n }\n\n const model = this.#options.llm;\n\n /**\n * If the model is a function, call it to get the model.\n */\n if (typeof model === \"function\") {\n return model(state, config);\n }\n\n if (model) {\n return model;\n }\n\n throw new Error(\n \"No model option was provided, either via `model` or via `llm` option.\"\n );\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel(state, config);\n\n /**\n * Execute prepareModelRequest hooks from beforeModelNodes\n */\n const preparedOptions = await this.#executePrepareModelRequestHooks(\n model,\n state,\n config\n );\n\n /**\n * If user provides a model in the preparedOptions, use it,\n * otherwise use the model from the options\n */\n const finalModel = preparedOptions?.model ?? model;\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(finalModel);\n\n const modelWithTools = await this.#bindTools(finalModel, preparedOptions);\n let modelInput = this.#getModelInputState(state);\n\n // Use messages from preparedOptions if provided\n if (preparedOptions?.messages) {\n modelInput = { ...modelInput, messages: preparedOptions.messages };\n }\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = { ...config, signal };\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n const structuredResponse = this.#options.responseFormat.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n }\n\n if (!response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in this.#structuredToolInfo\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(response, toolCalls);\n }\n\n const toolStrategy = this.#structuredToolInfo[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n toolMessageContent ?? options.lastMessage\n );\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[]\n ): Promise<Command> {\n /**\n * the following should never happen, let's throw an error if it does\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n throw new Error(\n \"Multiple structured outputs should not apply to native structured output responses\"\n );\n }\n\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0]\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = this.#structuredToolInfo[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(this.#structuredToolInfo).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n AIMessage.isInstance(response) &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages)))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #executePrepareModelRequestHooks(\n model: LanguageModelLike,\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: LangGraphRunnableConfig\n ): Promise<ModelRequest | undefined> {\n if (\n !this.#options.prepareModelRequestHookMiddleware ||\n this.#options.prepareModelRequestHookMiddleware.length === 0\n ) {\n return undefined;\n }\n\n // Get the prompt for system message\n let systemMessage: BaseMessage | undefined;\n if (typeof this.#options.prompt === \"string\") {\n systemMessage = new SystemMessage(this.#options.prompt);\n } else if (BaseMessage.isInstance(this.#options.prompt)) {\n systemMessage = this.#options.prompt;\n }\n\n // Prepare the initial call options\n let currentOptions: ModelRequest = {\n model,\n systemMessage,\n messages: state.messages,\n tools: [],\n };\n\n // Execute prepareModelRequest hooks from all middleware\n const middlewareList = this.#options.prepareModelRequestHookMiddleware;\n for (const [middleware, getMiddlewareState] of middlewareList) {\n // Merge context with default context of middleware\n const context = {\n ...(middleware.contextSchema?.parse({}) || {}),\n ...(config?.context || {}),\n };\n\n // Create runtime\n const runtime: Runtime<any> = {\n toolCalls: parseToolCalls(state.messages),\n toolResults: parseToolResults(state.messages),\n context,\n };\n\n const result = await middleware.prepareModelRequest!(\n currentOptions,\n {\n messages: state.messages,\n ...getMiddlewareState(),\n },\n {\n ...runtime,\n context,\n }\n );\n\n if (result) {\n currentOptions = { ...currentOptions, ...result };\n }\n }\n\n return currentOptions;\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions?: ModelRequest\n ): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(this.#structuredToolInfo);\n\n // Use tools from preparedOptions if provided, otherwise use default tools\n const allTools = this.#options.toolClasses.concat(\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ...(preparedOptions?.tools || [])\n );\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n /**\n * if the model does not support JSON schema output, throw an error\n */\n if (!hasSupportForJsonSchemaOutput(model)) {\n throw new Error(\n \"Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.\"\n );\n }\n\n const jsonSchemaParams = {\n name: this.#options.responseFormat.schema?.name ?? \"extract\",\n description: getSchemaDescription(this.#options.responseFormat.schema),\n schema: this.#options.responseFormat.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: this.#options.responseFormat.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(\n (preparedOptions?.systemMessage as SystemMessage) ?? this.#options.prompt\n ).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n\n static get nodeOptions(): {\n input: z.ZodObject<{ messages: z.ZodArray<z.ZodType<BaseMessage>> }>;\n } {\n return {\n input: z.object({\n messages: z.array(z.custom<BaseMessage>()),\n }),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAgFA,IAAa,YAAb,cAMU,iBAGR;CACA;CAEA,sBAAoD,CAAE;CAEtD,YACEA,SACA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WACZ,KAAKC,KAAK,OAAO,OAAyB;EAC7C,EAAC;EAEF,KAAKC,WAAW;;;;EAKhB,KAAKC,sBACH,wBAAwB,KAAKD,SAAS,eAAe,CAAC,OACpD,CAAC,WAAW,kBAAkB,aAC/B,CACD,OAAO,CAAC,KAAK,WAAW;GACxB,IAAI,OAAO,QAAQ;AACnB,UAAO;EACR,GAAE,CAAE,EAAiC;CACvC;CAED,MAAMD,KACJG,OAEAC,QACA;;;;;EAKA,MAAM,cAAc,MAAM,SAAS,GAAG,GAAG;AACzC,MACE,eACA,YAAY,WAAW,YAAY,IACnC,YAAY,QACZ,KAAKH,SAAS,mBAAmB,IAAI,YAAY,KAAK;;;;AAKtD,SAAO,EAAE,UAAU,CAAE,EAAE;EAGzB,MAAM,WAAW,MAAM,KAAKI,aAAa,OAAO,OAAO;;;;AAKvD,MAAI,wBAAwB,SAC1B,QAAO;GACL,UAAU,CAAC,GAAG,MAAM,UAAU,GAAI,SAAS,YAAY,CAAE,CAA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,KAAKA,SAAS,eAAe;IACrC,QAAQ;GACT;GAED,OAAO,OAAO,SAAS;IACrB,iBAAiB;KACf,MAAM;KACN,aAAa;IACd;IACD,6BAA6B;KAC3B,QAAQ,EAAE,QAAQ,cAAe;KACjC,QAAQ,KAAKA,SAAS,eAAe;IACtC;IACD,QAAQ;GACT,EAAC;EACH;;;;EAKD,MAAM,iBAAiB,MAAM,UAAU,OAAO,UAAU;GACtD,GAAG;GACH,aAAa;EACd,EAAC;;;;EAKF,MAAM,gBAAgB,kBACnB,iBAAiB,iBAAmC,KAAKA,SAAS,OACpE,CAAC,KACA,KAAKA,SAAS,qBAAqB,WAC/B,cAAc,gBAAgB,KAAKA,SAAS,iBAAiB,GAC7D,eACL;AAED,SAAO;CACR;CAED,WAAW,cAET;AACA,SAAO,EACL,OAAO,EAAE,OAAO,EACd,UAAU,EAAE,MAAM,EAAE,QAAqB,CAAC,CAC3C,EAAC,CACH;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"BeforeModalNode.cjs","names":["MiddlewareNode","middleware: AgentMiddleware<any, any, any>","state: TStateSchema","config?: RunnableConfig<TContextSchema>","runtime: Runtime<TContextSchema>","controls: Controls<TStateSchema>"],"sources":["../../../../src/agents/middlewareAgent/nodes/BeforeModalNode.ts"],"sourcesContent":["import { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode } from \"./middleware.js\";\nimport type {\n Controls,\n AgentMiddleware,\n MiddlewareResult,\n Runtime,\n} from \"../types.js\";\n\n/**\n * Node for executing a single middleware's beforeModel hook.\n */\nexport class BeforeModelNode<\n TStateSchema extends Record<string, any> = Record<string, any>,\n TContextSchema extends Record<string, any> = Record<string, any>\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"beforeModalNodes\"];\n\n constructor(public middleware: AgentMiddleware<any, any, any>) {\n super({\n name: `BeforeModelNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n });\n }\n\n runHook(\n state: TStateSchema,\n runtime: Runtime<TContextSchema>,\n controls: Controls<TStateSchema>\n ) {\n return this.middleware.beforeModel!(state, runtime, controls) as Promise<\n MiddlewareResult<TStateSchema>\n >;\n }\n}\n"],"mappings":";;;;;;AAYA,IAAa,kBAAb,cAGUA,kCAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;CAAmB;CAE1D,YAAmBC,YAA4C;EAC7D,MAAM;GACJ,MAAM,CAAC,gBAAgB,EAAE,WAAW,MAAM;GAC1C,MAAM,OACJC,OACAC,WACG,KAAK,iBAAiB,OAAO,OAAO;EAC1C,EAAC;EAPe;CAQlB;CAED,QACED,OACAE,SACAC,UACA;AACA,SAAO,KAAK,WAAW,YAAa,OAAO,SAAS,SAAS;CAG9D;AACF"}
1
+ {"version":3,"file":"BeforeModalNode.cjs","names":["MiddlewareNode","middleware: AgentMiddleware<any, any, any>","state: TStateSchema","config?: RunnableConfig<TContextSchema>","runtime: Runtime<TContextSchema>","controls: Controls<TStateSchema>"],"sources":["../../../../src/agents/middlewareAgent/nodes/BeforeModalNode.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode } from \"./middleware.js\";\nimport type {\n Controls,\n AgentMiddleware,\n MiddlewareResult,\n Runtime,\n} from \"../types.js\";\n\n/**\n * Node for executing a single middleware's beforeModel hook.\n */\nexport class BeforeModelNode<\n TStateSchema extends Record<string, any> = Record<string, any>,\n TContextSchema extends Record<string, any> = Record<string, any>\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"beforeModalNodes\"];\n\n constructor(public middleware: AgentMiddleware<any, any, any>) {\n super({\n name: `BeforeModelNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n });\n }\n\n runHook(\n state: TStateSchema,\n runtime: Runtime<TContextSchema>,\n controls: Controls<TStateSchema>\n ) {\n return this.middleware.beforeModel!(state, runtime, controls) as Promise<\n MiddlewareResult<TStateSchema>\n >;\n }\n}\n"],"mappings":";;;;;;AAaA,IAAa,kBAAb,cAGUA,kCAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;CAAmB;CAE1D,YAAmBC,YAA4C;EAC7D,MAAM;GACJ,MAAM,CAAC,gBAAgB,EAAE,WAAW,MAAM;GAC1C,MAAM,OACJC,OACAC,WACG,KAAK,iBAAiB,OAAO,OAAO;EAC1C,EAAC;EAPe;CAQlB;CAED,QACED,OACAE,SACAC,UACA;AACA,SAAO,KAAK,WAAW,YAAa,OAAO,SAAS,SAAS;CAG9D;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"BeforeModalNode.js","names":["middleware: AgentMiddleware<any, any, any>","state: TStateSchema","config?: RunnableConfig<TContextSchema>","runtime: Runtime<TContextSchema>","controls: Controls<TStateSchema>"],"sources":["../../../../src/agents/middlewareAgent/nodes/BeforeModalNode.ts"],"sourcesContent":["import { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode } from \"./middleware.js\";\nimport type {\n Controls,\n AgentMiddleware,\n MiddlewareResult,\n Runtime,\n} from \"../types.js\";\n\n/**\n * Node for executing a single middleware's beforeModel hook.\n */\nexport class BeforeModelNode<\n TStateSchema extends Record<string, any> = Record<string, any>,\n TContextSchema extends Record<string, any> = Record<string, any>\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"beforeModalNodes\"];\n\n constructor(public middleware: AgentMiddleware<any, any, any>) {\n super({\n name: `BeforeModelNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n });\n }\n\n runHook(\n state: TStateSchema,\n runtime: Runtime<TContextSchema>,\n controls: Controls<TStateSchema>\n ) {\n return this.middleware.beforeModel!(state, runtime, controls) as Promise<\n MiddlewareResult<TStateSchema>\n >;\n }\n}\n"],"mappings":";;;;;;AAYA,IAAa,kBAAb,cAGU,eAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;CAAmB;CAE1D,YAAmBA,YAA4C;EAC7D,MAAM;GACJ,MAAM,CAAC,gBAAgB,EAAE,WAAW,MAAM;GAC1C,MAAM,OACJC,OACAC,WACG,KAAK,iBAAiB,OAAO,OAAO;EAC1C,EAAC;EAPe;CAQlB;CAED,QACED,OACAE,SACAC,UACA;AACA,SAAO,KAAK,WAAW,YAAa,OAAO,SAAS,SAAS;CAG9D;AACF"}
1
+ {"version":3,"file":"BeforeModalNode.js","names":["middleware: AgentMiddleware<any, any, any>","state: TStateSchema","config?: RunnableConfig<TContextSchema>","runtime: Runtime<TContextSchema>","controls: Controls<TStateSchema>"],"sources":["../../../../src/agents/middlewareAgent/nodes/BeforeModalNode.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode } from \"./middleware.js\";\nimport type {\n Controls,\n AgentMiddleware,\n MiddlewareResult,\n Runtime,\n} from \"../types.js\";\n\n/**\n * Node for executing a single middleware's beforeModel hook.\n */\nexport class BeforeModelNode<\n TStateSchema extends Record<string, any> = Record<string, any>,\n TContextSchema extends Record<string, any> = Record<string, any>\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"beforeModalNodes\"];\n\n constructor(public middleware: AgentMiddleware<any, any, any>) {\n super({\n name: `BeforeModelNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n });\n }\n\n runHook(\n state: TStateSchema,\n runtime: Runtime<TContextSchema>,\n controls: Controls<TStateSchema>\n ) {\n return this.middleware.beforeModel!(state, runtime, controls) as Promise<\n MiddlewareResult<TStateSchema>\n >;\n }\n}\n"],"mappings":";;;;;;AAaA,IAAa,kBAAb,cAGU,eAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;CAAmB;CAE1D,YAAmBA,YAA4C;EAC7D,MAAM;GACJ,MAAM,CAAC,gBAAgB,EAAE,WAAW,MAAM;GAC1C,MAAM,OACJC,OACAC,WACG,KAAK,iBAAiB,OAAO,OAAO;EAC1C,EAAC;EAPe;CAQlB;CAED,QACED,OACAE,SACAC,UACA;AACA,SAAO,KAAK,WAAW,YAAa,OAAO,SAAS,SAAS;CAG9D;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.cjs","names":["RunnableCallable","state: TStateSchema","config?: LangGraphRunnableConfig","relevantContext: Record<string, unknown>","runtime: Runtime<TContextSchema>","parseToolCalls","parseToolResults","controls: Controls<TStateSchema>","target: \"model\" | \"tools\"","stateUpdate?: Partial<TStateSchema>","result?: Partial<TStateSchema> | Error","result","derivePrivateState"],"sources":["../../../../src/agents/middlewareAgent/nodes/middleware.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { z } from \"zod\";\nimport { LangGraphRunnableConfig, Command } from \"@langchain/langgraph\";\n\nimport { RunnableCallable } from \"../../RunnableCallable.js\";\nimport type {\n Runtime,\n Controls,\n ControlAction,\n AgentMiddleware,\n MiddlewareResult,\n} from \"../types.js\";\nimport {\n derivePrivateState,\n parseToolCalls,\n parseToolResults,\n} from \"./utils.js\";\n\ntype NodeOutput<TStateSchema extends Record<string, any>> =\n | TStateSchema\n | Command<any, TStateSchema, string>;\n\nexport abstract class MiddlewareNode<\n TStateSchema extends Record<string, any>,\n TContextSchema extends Record<string, any>\n> extends RunnableCallable<TStateSchema, NodeOutput<TStateSchema>> {\n abstract middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >;\n\n abstract runHook(\n state: TStateSchema,\n config?: Runtime<TContextSchema>,\n controls?: Controls<TStateSchema>\n ): Promise<MiddlewareResult<TStateSchema>>;\n\n async invokeMiddleware(\n state: TStateSchema,\n config?: LangGraphRunnableConfig\n ): Promise<NodeOutput<TStateSchema>> {\n /**\n * Filter context based on middleware's contextSchema\n */\n let filteredContext = {} as TContextSchema;\n /**\n * Check both config.context and config.configurable.context\n */\n if (this.middleware.contextSchema && config?.context) {\n /**\n * Extract only the fields relevant to this middleware's schema\n */\n const schemaShape = this.middleware.contextSchema?.shape;\n if (schemaShape) {\n const relevantContext: Record<string, unknown> = {};\n for (const key of Object.keys(schemaShape)) {\n if (key in config.context) {\n relevantContext[key] = config.context[key];\n }\n }\n /**\n * Parse to apply defaults and validation\n */\n filteredContext = this.middleware.contextSchema.parse(\n relevantContext\n ) as TContextSchema;\n }\n }\n\n /**\n * ToDo: implement later\n */\n const runtime: Runtime<TContextSchema> = {\n toolCalls: parseToolCalls(state.messages),\n toolResults: parseToolResults(state.messages),\n context: filteredContext,\n };\n\n const controls: Controls<TStateSchema> = {\n jumpTo: (\n target: \"model\" | \"tools\",\n stateUpdate?: Partial<TStateSchema>\n ): ControlAction<TStateSchema> => ({\n type: \"jump\",\n target,\n stateUpdate,\n }),\n terminate: (\n result?: Partial<TStateSchema> | Error\n ): ControlAction<TStateSchema> => {\n if (result instanceof Error) {\n throw result;\n }\n return { type: \"terminate\", result };\n },\n };\n\n const result = await this.runHook(state, runtime, controls);\n\n /**\n * If result is undefined, return current state\n */\n if (!result) {\n return state;\n }\n\n /**\n * If result is a control action, handle it\n */\n // if (typeof result === \"object\" && \"type\" in result) {\n // // Handle control actions\n // const action = result as ControlAction<TStateSchema>;\n // if (action.type === \"terminate\") {\n // if (action.error) {\n // throw action.error;\n // }\n // return { ...state, ...(action.result || {}) };\n // }\n\n // if (action.type === \"jump\") {\n // return new Command<any, TStateSchema, string>({\n // goto: action.target,\n // update: { ...state, ...(action.stateUpdate || {}) },\n // });\n // }\n\n // throw new Error(`Invalid control action: ${JSON.stringify(action)}`);\n // }\n\n /**\n * If result is a state update, merge it with current state\n */\n return { ...state, ...result };\n }\n\n get nodeOptions(): {\n input: z.ZodObject<TStateSchema>;\n } {\n return {\n input: derivePrivateState(\n this.middleware.stateSchema\n ) as z.ZodObject<TStateSchema>,\n };\n }\n}\n"],"mappings":";;;;AAsBA,IAAsB,iBAAtB,cAGUA,0CAAyD;CAYjE,MAAM,iBACJC,OACAC,QACmC;;;;EAInC,IAAI,kBAAkB,CAAE;;;;AAIxB,MAAI,KAAK,WAAW,iBAAiB,QAAQ,SAAS;;;;GAIpD,MAAM,cAAc,KAAK,WAAW,eAAe;AACnD,OAAI,aAAa;IACf,MAAMC,kBAA2C,CAAE;AACnD,SAAK,MAAM,OAAO,OAAO,KAAK,YAAY,CACxC,KAAI,OAAO,OAAO,SAChB,gBAAgB,OAAO,OAAO,QAAQ;;;;IAM1C,kBAAkB,KAAK,WAAW,cAAc,MAC9C,gBACD;GACF;EACF;;;;EAKD,MAAMC,UAAmC;GACvC,WAAWC,6BAAe,MAAM,SAAS;GACzC,aAAaC,+BAAiB,MAAM,SAAS;GAC7C,SAAS;EACV;EAED,MAAMC,WAAmC;GACvC,QAAQ,CACNC,QACAC,iBACiC;IACjC,MAAM;IACN;IACA;GACD;GACD,WAAW,CACTC,aACgC;AAChC,QAAIC,oBAAkB,MACpB,OAAMA;AAER,WAAO;KAAE,MAAM;KAAa;IAAQ;GACrC;EACF;EAED,MAAM,SAAS,MAAM,KAAK,QAAQ,OAAO,SAAS,SAAS;;;;AAK3D,MAAI,CAAC,OACH,QAAO;;;;;;;AA6BT,SAAO;GAAE,GAAG;GAAO,GAAG;EAAQ;CAC/B;CAED,IAAI,cAEF;AACA,SAAO,EACL,OAAOC,iCACL,KAAK,WAAW,YACjB,CACF;CACF;AACF"}
1
+ {"version":3,"file":"middleware.cjs","names":["RunnableCallable","state: TStateSchema","config?: LangGraphRunnableConfig","relevantContext: Record<string, unknown>","runtime: Runtime<TContextSchema>","parseToolCalls","parseToolResults","controls: Controls<TStateSchema>","target: \"model\" | \"tools\"","stateUpdate?: Partial<TStateSchema>","result?: Partial<TStateSchema> | Error","result","derivePrivateState"],"sources":["../../../../src/agents/middlewareAgent/nodes/middleware.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport { z } from \"zod/v3\";\nimport { LangGraphRunnableConfig, Command } from \"@langchain/langgraph\";\n\nimport { RunnableCallable } from \"../../RunnableCallable.js\";\nimport type {\n Runtime,\n Controls,\n ControlAction,\n AgentMiddleware,\n MiddlewareResult,\n} from \"../types.js\";\nimport {\n derivePrivateState,\n parseToolCalls,\n parseToolResults,\n} from \"./utils.js\";\n\ntype NodeOutput<TStateSchema extends Record<string, any>> =\n | TStateSchema\n | Command<any, TStateSchema, string>;\n\nexport abstract class MiddlewareNode<\n TStateSchema extends Record<string, any>,\n TContextSchema extends Record<string, any>\n> extends RunnableCallable<TStateSchema, NodeOutput<TStateSchema>> {\n abstract middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >;\n\n abstract runHook(\n state: TStateSchema,\n config?: Runtime<TContextSchema>,\n controls?: Controls<TStateSchema>\n ): Promise<MiddlewareResult<TStateSchema>>;\n\n async invokeMiddleware(\n state: TStateSchema,\n config?: LangGraphRunnableConfig\n ): Promise<NodeOutput<TStateSchema>> {\n /**\n * Filter context based on middleware's contextSchema\n */\n let filteredContext = {} as TContextSchema;\n /**\n * Check both config.context and config.configurable.context\n */\n if (this.middleware.contextSchema && config?.context) {\n /**\n * Extract only the fields relevant to this middleware's schema\n */\n const schemaShape = this.middleware.contextSchema?.shape;\n if (schemaShape) {\n const relevantContext: Record<string, unknown> = {};\n for (const key of Object.keys(schemaShape)) {\n if (key in config.context) {\n relevantContext[key] = config.context[key];\n }\n }\n /**\n * Parse to apply defaults and validation\n */\n filteredContext = this.middleware.contextSchema.parse(\n relevantContext\n ) as TContextSchema;\n }\n }\n\n /**\n * ToDo: implement later\n */\n const runtime: Runtime<TContextSchema> = {\n toolCalls: parseToolCalls(state.messages),\n toolResults: parseToolResults(state.messages),\n context: filteredContext,\n };\n\n const controls: Controls<TStateSchema> = {\n jumpTo: (\n target: \"model\" | \"tools\",\n stateUpdate?: Partial<TStateSchema>\n ): ControlAction<TStateSchema> => ({\n type: \"jump\",\n target,\n stateUpdate,\n }),\n terminate: (\n result?: Partial<TStateSchema> | Error\n ): ControlAction<TStateSchema> => {\n if (result instanceof Error) {\n throw result;\n }\n return { type: \"terminate\", result };\n },\n };\n\n const result = await this.runHook(state, runtime, controls);\n\n /**\n * If result is undefined, return current state\n */\n if (!result) {\n return state;\n }\n\n /**\n * If result is a control action, handle it\n */\n // if (typeof result === \"object\" && \"type\" in result) {\n // // Handle control actions\n // const action = result as ControlAction<TStateSchema>;\n // if (action.type === \"terminate\") {\n // if (action.error) {\n // throw action.error;\n // }\n // return { ...state, ...(action.result || {}) };\n // }\n\n // if (action.type === \"jump\") {\n // return new Command<any, TStateSchema, string>({\n // goto: action.target,\n // update: { ...state, ...(action.stateUpdate || {}) },\n // });\n // }\n\n // throw new Error(`Invalid control action: ${JSON.stringify(action)}`);\n // }\n\n /**\n * If result is a state update, merge it with current state\n */\n return { ...state, ...result };\n }\n\n get nodeOptions(): {\n input: z.ZodObject<TStateSchema>;\n } {\n return {\n input: derivePrivateState(\n this.middleware.stateSchema\n ) as z.ZodObject<TStateSchema>,\n };\n }\n}\n"],"mappings":";;;;AAuBA,IAAsB,iBAAtB,cAGUA,0CAAyD;CAYjE,MAAM,iBACJC,OACAC,QACmC;;;;EAInC,IAAI,kBAAkB,CAAE;;;;AAIxB,MAAI,KAAK,WAAW,iBAAiB,QAAQ,SAAS;;;;GAIpD,MAAM,cAAc,KAAK,WAAW,eAAe;AACnD,OAAI,aAAa;IACf,MAAMC,kBAA2C,CAAE;AACnD,SAAK,MAAM,OAAO,OAAO,KAAK,YAAY,CACxC,KAAI,OAAO,OAAO,SAChB,gBAAgB,OAAO,OAAO,QAAQ;;;;IAM1C,kBAAkB,KAAK,WAAW,cAAc,MAC9C,gBACD;GACF;EACF;;;;EAKD,MAAMC,UAAmC;GACvC,WAAWC,6BAAe,MAAM,SAAS;GACzC,aAAaC,+BAAiB,MAAM,SAAS;GAC7C,SAAS;EACV;EAED,MAAMC,WAAmC;GACvC,QAAQ,CACNC,QACAC,iBACiC;IACjC,MAAM;IACN;IACA;GACD;GACD,WAAW,CACTC,aACgC;AAChC,QAAIC,oBAAkB,MACpB,OAAMA;AAER,WAAO;KAAE,MAAM;KAAa;IAAQ;GACrC;EACF;EAED,MAAM,SAAS,MAAM,KAAK,QAAQ,OAAO,SAAS,SAAS;;;;AAK3D,MAAI,CAAC,OACH,QAAO;;;;;;;AA6BT,SAAO;GAAE,GAAG;GAAO,GAAG;EAAQ;CAC/B;CAED,IAAI,cAEF;AACA,SAAO,EACL,OAAOC,iCACL,KAAK,WAAW,YACjB,CACF;CACF;AACF"}