langchain 1.2.24 → 1.2.25

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 (325) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/_virtual/{rolldown_runtime.cjs → _rolldown/runtime.cjs} +24 -13
  3. package/dist/_virtual/_rolldown/runtime.js +36 -0
  4. package/dist/agents/ReactAgent.cjs +52 -65
  5. package/dist/agents/ReactAgent.cjs.map +1 -1
  6. package/dist/agents/ReactAgent.d.cts.map +1 -1
  7. package/dist/agents/ReactAgent.d.ts.map +1 -1
  8. package/dist/agents/ReactAgent.js +11 -24
  9. package/dist/agents/ReactAgent.js.map +1 -1
  10. package/dist/agents/RunnableCallable.cjs +7 -7
  11. package/dist/agents/RunnableCallable.cjs.map +1 -1
  12. package/dist/agents/RunnableCallable.js.map +1 -1
  13. package/dist/agents/annotation.cjs +41 -37
  14. package/dist/agents/annotation.cjs.map +1 -1
  15. package/dist/agents/annotation.js +21 -17
  16. package/dist/agents/annotation.js.map +1 -1
  17. package/dist/agents/constants.d.cts.map +1 -1
  18. package/dist/agents/constants.d.ts.map +1 -1
  19. package/dist/agents/errors.cjs +3 -3
  20. package/dist/agents/errors.cjs.map +1 -1
  21. package/dist/agents/errors.d.cts.map +1 -1
  22. package/dist/agents/errors.d.ts.map +1 -1
  23. package/dist/agents/errors.js.map +1 -1
  24. package/dist/agents/index.cjs.map +1 -1
  25. package/dist/agents/index.d.cts +2 -2
  26. package/dist/agents/index.d.cts.map +1 -1
  27. package/dist/agents/index.d.ts +2 -2
  28. package/dist/agents/index.d.ts.map +1 -1
  29. package/dist/agents/index.js.map +1 -1
  30. package/dist/agents/middleware/constants.cjs +2 -2
  31. package/dist/agents/middleware/constants.cjs.map +1 -1
  32. package/dist/agents/middleware/constants.js.map +1 -1
  33. package/dist/agents/middleware/contextEditing.cjs +14 -27
  34. package/dist/agents/middleware/contextEditing.cjs.map +1 -1
  35. package/dist/agents/middleware/contextEditing.d.cts +2 -3
  36. package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
  37. package/dist/agents/middleware/contextEditing.d.ts +2 -3
  38. package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
  39. package/dist/agents/middleware/contextEditing.js +5 -18
  40. package/dist/agents/middleware/contextEditing.js.map +1 -1
  41. package/dist/agents/middleware/dynamicSystemPrompt.cjs +3 -4
  42. package/dist/agents/middleware/dynamicSystemPrompt.cjs.map +1 -1
  43. package/dist/agents/middleware/dynamicSystemPrompt.d.cts +2 -2
  44. package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -1
  45. package/dist/agents/middleware/dynamicSystemPrompt.d.ts +2 -2
  46. package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
  47. package/dist/agents/middleware/dynamicSystemPrompt.js +1 -2
  48. package/dist/agents/middleware/dynamicSystemPrompt.js.map +1 -1
  49. package/dist/agents/middleware/error.cjs +2 -2
  50. package/dist/agents/middleware/error.cjs.map +1 -1
  51. package/dist/agents/middleware/error.js.map +1 -1
  52. package/dist/agents/middleware/hitl.cjs +16 -26
  53. package/dist/agents/middleware/hitl.cjs.map +1 -1
  54. package/dist/agents/middleware/hitl.d.cts.map +1 -1
  55. package/dist/agents/middleware/hitl.d.ts.map +1 -1
  56. package/dist/agents/middleware/hitl.js +8 -18
  57. package/dist/agents/middleware/hitl.js.map +1 -1
  58. package/dist/agents/middleware/index.js +2 -0
  59. package/dist/agents/middleware/llmToolSelector.cjs +9 -10
  60. package/dist/agents/middleware/llmToolSelector.cjs.map +1 -1
  61. package/dist/agents/middleware/llmToolSelector.d.cts +4 -4
  62. package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
  63. package/dist/agents/middleware/llmToolSelector.d.ts +4 -4
  64. package/dist/agents/middleware/llmToolSelector.d.ts.map +1 -1
  65. package/dist/agents/middleware/llmToolSelector.js +3 -4
  66. package/dist/agents/middleware/llmToolSelector.js.map +1 -1
  67. package/dist/agents/middleware/modelCallLimit.cjs +5 -5
  68. package/dist/agents/middleware/modelCallLimit.cjs.map +1 -1
  69. package/dist/agents/middleware/modelCallLimit.d.cts +2 -2
  70. package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -1
  71. package/dist/agents/middleware/modelCallLimit.d.ts +2 -2
  72. package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -1
  73. package/dist/agents/middleware/modelCallLimit.js.map +1 -1
  74. package/dist/agents/middleware/modelFallback.cjs.map +1 -1
  75. package/dist/agents/middleware/modelFallback.d.cts +0 -1
  76. package/dist/agents/middleware/modelFallback.d.cts.map +1 -1
  77. package/dist/agents/middleware/modelFallback.d.ts +0 -1
  78. package/dist/agents/middleware/modelFallback.d.ts.map +1 -1
  79. package/dist/agents/middleware/modelFallback.js.map +1 -1
  80. package/dist/agents/middleware/modelRetry.cjs +19 -17
  81. package/dist/agents/middleware/modelRetry.cjs.map +1 -1
  82. package/dist/agents/middleware/modelRetry.d.cts +0 -1
  83. package/dist/agents/middleware/modelRetry.d.cts.map +1 -1
  84. package/dist/agents/middleware/modelRetry.d.ts +0 -1
  85. package/dist/agents/middleware/modelRetry.d.ts.map +1 -1
  86. package/dist/agents/middleware/modelRetry.js +15 -13
  87. package/dist/agents/middleware/modelRetry.js.map +1 -1
  88. package/dist/agents/middleware/pii.cjs +21 -32
  89. package/dist/agents/middleware/pii.cjs.map +1 -1
  90. package/dist/agents/middleware/pii.d.cts +0 -1
  91. package/dist/agents/middleware/pii.d.cts.map +1 -1
  92. package/dist/agents/middleware/pii.d.ts +0 -1
  93. package/dist/agents/middleware/pii.d.ts.map +1 -1
  94. package/dist/agents/middleware/pii.js +10 -21
  95. package/dist/agents/middleware/pii.js.map +1 -1
  96. package/dist/agents/middleware/piiRedaction.cjs +22 -28
  97. package/dist/agents/middleware/piiRedaction.cjs.map +1 -1
  98. package/dist/agents/middleware/piiRedaction.d.cts +0 -1
  99. package/dist/agents/middleware/piiRedaction.d.cts.map +1 -1
  100. package/dist/agents/middleware/piiRedaction.d.ts +0 -1
  101. package/dist/agents/middleware/piiRedaction.d.ts.map +1 -1
  102. package/dist/agents/middleware/piiRedaction.js +8 -14
  103. package/dist/agents/middleware/piiRedaction.js.map +1 -1
  104. package/dist/agents/middleware/provider/anthropic/promptCaching.cjs +5 -8
  105. package/dist/agents/middleware/provider/anthropic/promptCaching.cjs.map +1 -1
  106. package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts +2 -2
  107. package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts.map +1 -1
  108. package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts +2 -2
  109. package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts.map +1 -1
  110. package/dist/agents/middleware/provider/anthropic/promptCaching.js +3 -6
  111. package/dist/agents/middleware/provider/anthropic/promptCaching.js.map +1 -1
  112. package/dist/agents/middleware/provider/openai/moderation.cjs +17 -22
  113. package/dist/agents/middleware/provider/openai/moderation.cjs.map +1 -1
  114. package/dist/agents/middleware/provider/openai/moderation.d.cts +0 -2
  115. package/dist/agents/middleware/provider/openai/moderation.d.cts.map +1 -1
  116. package/dist/agents/middleware/provider/openai/moderation.d.ts +0 -2
  117. package/dist/agents/middleware/provider/openai/moderation.d.ts.map +1 -1
  118. package/dist/agents/middleware/provider/openai/moderation.js +10 -15
  119. package/dist/agents/middleware/provider/openai/moderation.js.map +1 -1
  120. package/dist/agents/middleware/summarization.cjs +39 -62
  121. package/dist/agents/middleware/summarization.cjs.map +1 -1
  122. package/dist/agents/middleware/summarization.d.cts +2 -2
  123. package/dist/agents/middleware/summarization.d.cts.map +1 -1
  124. package/dist/agents/middleware/summarization.d.ts +2 -2
  125. package/dist/agents/middleware/summarization.d.ts.map +1 -1
  126. package/dist/agents/middleware/summarization.js +17 -40
  127. package/dist/agents/middleware/summarization.js.map +1 -1
  128. package/dist/agents/middleware/todoListMiddleware.cjs +21 -27
  129. package/dist/agents/middleware/todoListMiddleware.cjs.map +1 -1
  130. package/dist/agents/middleware/todoListMiddleware.d.cts +4 -4
  131. package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
  132. package/dist/agents/middleware/todoListMiddleware.d.ts +4 -4
  133. package/dist/agents/middleware/todoListMiddleware.d.ts.map +1 -1
  134. package/dist/agents/middleware/todoListMiddleware.js +12 -18
  135. package/dist/agents/middleware/todoListMiddleware.js.map +1 -1
  136. package/dist/agents/middleware/toolCallLimit.cjs +24 -46
  137. package/dist/agents/middleware/toolCallLimit.cjs.map +1 -1
  138. package/dist/agents/middleware/toolCallLimit.d.cts +2 -3
  139. package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
  140. package/dist/agents/middleware/toolCallLimit.d.ts +2 -3
  141. package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
  142. package/dist/agents/middleware/toolCallLimit.js +17 -39
  143. package/dist/agents/middleware/toolCallLimit.js.map +1 -1
  144. package/dist/agents/middleware/toolEmulator.cjs +8 -13
  145. package/dist/agents/middleware/toolEmulator.cjs.map +1 -1
  146. package/dist/agents/middleware/toolEmulator.d.cts +0 -1
  147. package/dist/agents/middleware/toolEmulator.d.cts.map +1 -1
  148. package/dist/agents/middleware/toolEmulator.d.ts +0 -1
  149. package/dist/agents/middleware/toolEmulator.d.ts.map +1 -1
  150. package/dist/agents/middleware/toolEmulator.js +5 -10
  151. package/dist/agents/middleware/toolEmulator.js.map +1 -1
  152. package/dist/agents/middleware/toolRetry.cjs +19 -17
  153. package/dist/agents/middleware/toolRetry.cjs.map +1 -1
  154. package/dist/agents/middleware/toolRetry.d.cts +0 -1
  155. package/dist/agents/middleware/toolRetry.d.cts.map +1 -1
  156. package/dist/agents/middleware/toolRetry.d.ts +0 -1
  157. package/dist/agents/middleware/toolRetry.d.ts.map +1 -1
  158. package/dist/agents/middleware/toolRetry.js +15 -13
  159. package/dist/agents/middleware/toolRetry.js.map +1 -1
  160. package/dist/agents/middleware/types.cjs.map +1 -1
  161. package/dist/agents/middleware/types.d.cts +33 -33
  162. package/dist/agents/middleware/types.d.cts.map +1 -1
  163. package/dist/agents/middleware/types.d.ts +33 -33
  164. package/dist/agents/middleware/types.d.ts.map +1 -1
  165. package/dist/agents/middleware/types.js.map +1 -1
  166. package/dist/agents/middleware/utils.cjs +8 -8
  167. package/dist/agents/middleware/utils.cjs.map +1 -1
  168. package/dist/agents/middleware/utils.d.cts +0 -1
  169. package/dist/agents/middleware/utils.d.cts.map +1 -1
  170. package/dist/agents/middleware/utils.d.ts +0 -1
  171. package/dist/agents/middleware/utils.d.ts.map +1 -1
  172. package/dist/agents/middleware/utils.js +3 -3
  173. package/dist/agents/middleware/utils.js.map +1 -1
  174. package/dist/agents/middleware.cjs +1 -2
  175. package/dist/agents/middleware.cjs.map +1 -1
  176. package/dist/agents/middleware.d.cts +0 -1
  177. package/dist/agents/middleware.d.cts.map +1 -1
  178. package/dist/agents/middleware.d.ts +0 -1
  179. package/dist/agents/middleware.d.ts.map +1 -1
  180. package/dist/agents/middleware.js +1 -2
  181. package/dist/agents/middleware.js.map +1 -1
  182. package/dist/agents/model.cjs.map +1 -1
  183. package/dist/agents/model.js.map +1 -1
  184. package/dist/agents/nodes/AfterAgentNode.cjs +1 -2
  185. package/dist/agents/nodes/AfterAgentNode.cjs.map +1 -1
  186. package/dist/agents/nodes/AfterAgentNode.js +1 -2
  187. package/dist/agents/nodes/AfterAgentNode.js.map +1 -1
  188. package/dist/agents/nodes/AfterModelNode.cjs +1 -2
  189. package/dist/agents/nodes/AfterModelNode.cjs.map +1 -1
  190. package/dist/agents/nodes/AfterModelNode.js +1 -2
  191. package/dist/agents/nodes/AfterModelNode.js.map +1 -1
  192. package/dist/agents/nodes/AgentNode.cjs +46 -58
  193. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  194. package/dist/agents/nodes/AgentNode.js +16 -28
  195. package/dist/agents/nodes/AgentNode.js.map +1 -1
  196. package/dist/agents/nodes/BeforeAgentNode.cjs +1 -2
  197. package/dist/agents/nodes/BeforeAgentNode.cjs.map +1 -1
  198. package/dist/agents/nodes/BeforeAgentNode.js +1 -2
  199. package/dist/agents/nodes/BeforeAgentNode.js.map +1 -1
  200. package/dist/agents/nodes/BeforeModelNode.cjs +1 -2
  201. package/dist/agents/nodes/BeforeModelNode.cjs.map +1 -1
  202. package/dist/agents/nodes/BeforeModelNode.js +1 -2
  203. package/dist/agents/nodes/BeforeModelNode.js.map +1 -1
  204. package/dist/agents/nodes/ToolNode.cjs +25 -25
  205. package/dist/agents/nodes/ToolNode.cjs.map +1 -1
  206. package/dist/agents/nodes/ToolNode.js +6 -6
  207. package/dist/agents/nodes/ToolNode.js.map +1 -1
  208. package/dist/agents/nodes/middleware.cjs +3 -3
  209. package/dist/agents/nodes/middleware.cjs.map +1 -1
  210. package/dist/agents/nodes/middleware.js.map +1 -1
  211. package/dist/agents/nodes/types.d.cts +0 -1
  212. package/dist/agents/nodes/types.d.cts.map +1 -1
  213. package/dist/agents/nodes/types.d.ts +0 -1
  214. package/dist/agents/nodes/types.d.ts.map +1 -1
  215. package/dist/agents/nodes/utils.cjs +16 -17
  216. package/dist/agents/nodes/utils.cjs.map +1 -1
  217. package/dist/agents/nodes/utils.js +2 -3
  218. package/dist/agents/nodes/utils.js.map +1 -1
  219. package/dist/agents/responses.cjs +20 -30
  220. package/dist/agents/responses.cjs.map +1 -1
  221. package/dist/agents/responses.d.cts +0 -1
  222. package/dist/agents/responses.d.cts.map +1 -1
  223. package/dist/agents/responses.d.ts +0 -1
  224. package/dist/agents/responses.d.ts.map +1 -1
  225. package/dist/agents/responses.js +12 -22
  226. package/dist/agents/responses.js.map +1 -1
  227. package/dist/agents/runtime.d.cts +0 -1
  228. package/dist/agents/runtime.d.cts.map +1 -1
  229. package/dist/agents/runtime.d.ts +0 -1
  230. package/dist/agents/runtime.d.ts.map +1 -1
  231. package/dist/agents/state.cjs +1 -2
  232. package/dist/agents/state.cjs.map +1 -1
  233. package/dist/agents/state.js +1 -2
  234. package/dist/agents/state.js.map +1 -1
  235. package/dist/agents/tests/utils.cjs +21 -26
  236. package/dist/agents/tests/utils.cjs.map +1 -1
  237. package/dist/agents/tests/utils.d.cts +0 -1
  238. package/dist/agents/tests/utils.d.cts.map +1 -1
  239. package/dist/agents/tests/utils.d.ts +0 -1
  240. package/dist/agents/tests/utils.d.ts.map +1 -1
  241. package/dist/agents/tests/utils.js +12 -17
  242. package/dist/agents/tests/utils.js.map +1 -1
  243. package/dist/agents/types.d.cts +4 -5
  244. package/dist/agents/types.d.cts.map +1 -1
  245. package/dist/agents/types.d.ts +4 -5
  246. package/dist/agents/types.d.ts.map +1 -1
  247. package/dist/agents/utils.cjs +32 -32
  248. package/dist/agents/utils.cjs.map +1 -1
  249. package/dist/agents/utils.js +6 -6
  250. package/dist/agents/utils.js.map +1 -1
  251. package/dist/agents/withAgentName.cjs +5 -5
  252. package/dist/agents/withAgentName.cjs.map +1 -1
  253. package/dist/agents/withAgentName.js.map +1 -1
  254. package/dist/chat_models/universal.cjs +34 -41
  255. package/dist/chat_models/universal.cjs.map +1 -1
  256. package/dist/chat_models/universal.d.cts.map +1 -1
  257. package/dist/chat_models/universal.d.ts.map +1 -1
  258. package/dist/chat_models/universal.js +21 -29
  259. package/dist/chat_models/universal.js.map +1 -1
  260. package/dist/hub/base.cjs +3 -4
  261. package/dist/hub/base.cjs.map +1 -1
  262. package/dist/hub/base.d.cts +0 -1
  263. package/dist/hub/base.d.cts.map +1 -1
  264. package/dist/hub/base.d.ts +0 -1
  265. package/dist/hub/base.d.ts.map +1 -1
  266. package/dist/hub/base.js +1 -2
  267. package/dist/hub/base.js.map +1 -1
  268. package/dist/hub/index.cjs +2 -2
  269. package/dist/hub/index.cjs.map +1 -1
  270. package/dist/hub/index.d.cts +0 -1
  271. package/dist/hub/index.d.cts.map +1 -1
  272. package/dist/hub/index.d.ts +0 -1
  273. package/dist/hub/index.d.ts.map +1 -1
  274. package/dist/hub/index.js +1 -2
  275. package/dist/hub/index.js.map +1 -1
  276. package/dist/hub/node.cjs +7 -13
  277. package/dist/hub/node.cjs.map +1 -1
  278. package/dist/hub/node.d.cts +0 -1
  279. package/dist/hub/node.d.cts.map +1 -1
  280. package/dist/hub/node.d.ts +0 -1
  281. package/dist/hub/node.d.ts.map +1 -1
  282. package/dist/hub/node.js +6 -13
  283. package/dist/hub/node.js.map +1 -1
  284. package/dist/index.cjs +48 -48
  285. package/dist/index.d.cts +2 -1
  286. package/dist/index.d.ts +2 -1
  287. package/dist/index.js +2 -3
  288. package/dist/load/import_constants.cjs.map +1 -1
  289. package/dist/load/import_constants.js.map +1 -1
  290. package/dist/load/import_map.cjs +46 -47
  291. package/dist/load/import_map.cjs.map +1 -1
  292. package/dist/load/import_map.js +2 -3
  293. package/dist/load/import_map.js.map +1 -1
  294. package/dist/load/import_type.d.cts.map +1 -1
  295. package/dist/load/import_type.d.ts.map +1 -1
  296. package/dist/load/index.cjs +13 -3
  297. package/dist/load/index.cjs.map +1 -1
  298. package/dist/load/index.d.cts +9 -1
  299. package/dist/load/index.d.cts.map +1 -1
  300. package/dist/load/index.d.ts +9 -1
  301. package/dist/load/index.d.ts.map +1 -1
  302. package/dist/load/index.js +9 -0
  303. package/dist/load/index.js.map +1 -1
  304. package/dist/load/serializable.cjs +7 -6
  305. package/dist/load/serializable.js +4 -4
  306. package/dist/storage/encoder_backed.cjs +9 -10
  307. package/dist/storage/encoder_backed.cjs.map +1 -1
  308. package/dist/storage/encoder_backed.d.cts +0 -1
  309. package/dist/storage/encoder_backed.d.cts.map +1 -1
  310. package/dist/storage/encoder_backed.d.ts +0 -1
  311. package/dist/storage/encoder_backed.d.ts.map +1 -1
  312. package/dist/storage/encoder_backed.js +4 -6
  313. package/dist/storage/encoder_backed.js.map +1 -1
  314. package/dist/storage/file_system.cjs +12 -11
  315. package/dist/storage/file_system.cjs.map +1 -1
  316. package/dist/storage/file_system.d.cts +0 -1
  317. package/dist/storage/file_system.d.cts.map +1 -1
  318. package/dist/storage/file_system.d.ts +0 -1
  319. package/dist/storage/file_system.d.ts.map +1 -1
  320. package/dist/storage/file_system.js +5 -7
  321. package/dist/storage/file_system.js.map +1 -1
  322. package/dist/storage/in_memory.cjs +5 -5
  323. package/dist/storage/in_memory.js +2 -3
  324. package/package.json +6 -6
  325. package/dist/_virtual/rolldown_runtime.js +0 -25
@@ -1,7 +1,7 @@
1
1
  import { createMiddleware } from "../middleware.js";
2
2
  import { InferInteropZodInput } from "@langchain/core/utils/types";
3
3
  import { z } from "zod/v3";
4
- import * as _langchain_core_language_models_base8 from "@langchain/core/language_models/base";
4
+ import * as _langchain_core_language_models_base0 from "@langchain/core/language_models/base";
5
5
  import { BaseLanguageModel } from "@langchain/core/language_models/base";
6
6
 
7
7
  //#region src/agents/middleware/llmToolSelector.d.ts
@@ -12,7 +12,7 @@ declare const LLMToolSelectorOptionsSchema: z.ZodObject<{
12
12
  /**
13
13
  * The language model to use for tool selection (default: the provided model from the agent options).
14
14
  */
15
- model: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodType<BaseLanguageModel<unknown, _langchain_core_language_models_base8.BaseLanguageModelCallOptions>, z.ZodTypeDef, BaseLanguageModel<unknown, _langchain_core_language_models_base8.BaseLanguageModelCallOptions>>]>>;
15
+ model: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodType<BaseLanguageModel<unknown, _langchain_core_language_models_base0.BaseLanguageModelCallOptions>, z.ZodTypeDef, BaseLanguageModel<unknown, _langchain_core_language_models_base0.BaseLanguageModelCallOptions>>]>>;
16
16
  /**
17
17
  * System prompt for the tool selection model.
18
18
  */
@@ -28,12 +28,12 @@ declare const LLMToolSelectorOptionsSchema: z.ZodObject<{
28
28
  */
29
29
  alwaysInclude: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
30
30
  }, "strip", z.ZodTypeAny, {
31
- model?: string | BaseLanguageModel<unknown, _langchain_core_language_models_base8.BaseLanguageModelCallOptions> | undefined;
31
+ model?: string | BaseLanguageModel<unknown, _langchain_core_language_models_base0.BaseLanguageModelCallOptions> | undefined;
32
32
  systemPrompt?: string | undefined;
33
33
  maxTools?: number | undefined;
34
34
  alwaysInclude?: string[] | undefined;
35
35
  }, {
36
- model?: string | BaseLanguageModel<unknown, _langchain_core_language_models_base8.BaseLanguageModelCallOptions> | undefined;
36
+ model?: string | BaseLanguageModel<unknown, _langchain_core_language_models_base0.BaseLanguageModelCallOptions> | undefined;
37
37
  systemPrompt?: string | undefined;
38
38
  maxTools?: number | undefined;
39
39
  alwaysInclude?: string[] | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"llmToolSelector.d.ts","names":["z","BaseLanguageModel","InferInteropZodInput","createMiddleware","LLMToolSelectorOptionsSchema","ZodString","_langchain_core_language_models_base8","BaseLanguageModelCallOptions","ZodTypeDef","ZodType","ZodUnion","ZodOptional","ZodNumber","ZodArray","ZodTypeAny","ZodObject","LLMToolSelectorConfig","llmToolSelectorMiddleware","ReturnType"],"sources":["../../../src/agents/middleware/llmToolSelector.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport { createMiddleware } from \"../middleware.js\";\n/**\n * Options for configuring the LLM Tool Selector middleware.\n */\nexport declare const LLMToolSelectorOptionsSchema: z.ZodObject<{\n /**\n * The language model to use for tool selection (default: the provided model from the agent options).\n */\n model: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodType<BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>, z.ZodTypeDef, BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>>]>>;\n /**\n * System prompt for the tool selection model.\n */\n systemPrompt: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n */\n maxTools: z.ZodOptional<z.ZodNumber>;\n /**\n * Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n */\n alwaysInclude: z.ZodOptional<z.ZodArray<z.ZodString, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n model?: string | BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions> | undefined;\n systemPrompt?: string | undefined;\n maxTools?: number | undefined;\n alwaysInclude?: string[] | undefined;\n}, {\n model?: string | BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions> | undefined;\n systemPrompt?: string | undefined;\n maxTools?: number | undefined;\n alwaysInclude?: string[] | undefined;\n}>;\nexport type LLMToolSelectorConfig = InferInteropZodInput<typeof LLMToolSelectorOptionsSchema>;\n/**\n * Middleware for selecting tools using an LLM-based strategy.\n *\n * When an agent has many tools available, this middleware filters them down\n * to only the most relevant ones for the user's query. This reduces token usage\n * and helps the main model focus on the right tools.\n *\n * @param options - Configuration options for the middleware\n * @param options.model - The language model to use for tool selection (default: the provided model from the agent options).\n * @param options.systemPrompt - Instructions for the selection model.\n * @param options.maxTools - Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n * @param options.alwaysInclude - Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n *\n * @example\n * Limit to 3 tools:\n * ```ts\n * import { llmToolSelectorMiddleware } from \"langchain/agents/middleware\";\n *\n * const middleware = llmToolSelectorMiddleware({ maxTools: 3 });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [tool1, tool2, tool3, tool4, tool5],\n * middleware: [middleware],\n * });\n * ```\n *\n * @example\n * Use a smaller model for selection:\n * ```ts\n * const middleware = llmToolSelectorMiddleware({\n * model: \"openai:gpt-4o-mini\",\n * maxTools: 2\n * });\n * ```\n */\nexport declare function llmToolSelectorMiddleware(options: LLMToolSelectorConfig): ReturnType<typeof createMiddleware>;\n//# sourceMappingURL=llmToolSelector.d.ts.map"],"mappings":";;;;;;;;;;AAOqBI,cAAAA,4BA6BnB,EA7BiDJ,CAAAA,CAAEe,SA6BnD,CAAA;EAzBqCV;;;EAAgIG,KAAAA,EAA5JR,CAAAA,CAA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AAAA,EAAAA,MAAAA,EAAAA,GAAAA,SAAAA;AAAU,CAAA,CAAA;KAvCjFF,qBAAAA,GAAwBd,4BAA4BE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAuCxCa,yBAAAA,UAAmCD,wBAAwBE,kBAAkBf"}
1
+ {"version":3,"file":"llmToolSelector.d.ts","names":[],"sources":["../../../src/agents/middleware/llmToolSelector.ts"],"mappings":";;;;;;;;;;cAwDa,4BAAA,EAA4B,CAAA,CAAA,SAAA;EAmBvC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KACU,qBAAA,GAAwB,oBAAA,QAC3B,4BAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyCO,yBAAA,CACd,OAAA,EAAS,qBAAA,GACR,UAAA,QAAkB,gBAAA"}
@@ -73,8 +73,7 @@ function llmToolSelectorMiddleware(options) {
73
73
  const selectionRequest = await prepareSelectionRequest(request, options, request.runtime);
74
74
  if (!selectionRequest) return handler(request);
75
75
  const toolSelectionSchema = createToolSelectionResponse(selectionRequest.availableTools);
76
- const structuredModel = await selectionRequest.model.withStructuredOutput?.(toolSelectionSchema);
77
- const response = await structuredModel?.invoke([{
76
+ const response = await (await selectionRequest.model.withStructuredOutput?.(toolSelectionSchema))?.invoke([{
78
77
  role: "system",
79
78
  content: selectionRequest.systemMessage
80
79
  }, selectionRequest.lastUserMessage]);
@@ -99,7 +98,7 @@ async function prepareSelectionRequest(request, options, runtime) {
99
98
  /**
100
99
  * If no tools available, return null
101
100
  */
102
- if (!request.tools || request.tools.length === 0) return void 0;
101
+ if (!request.tools || request.tools.length === 0) return;
103
102
  /**
104
103
  * Filter to only StructuredToolInterface instances (exclude provider-specific tool dicts)
105
104
  */
@@ -119,7 +118,7 @@ async function prepareSelectionRequest(request, options, runtime) {
119
118
  /**
120
119
  * If no tools available for selection, return null
121
120
  */
122
- if (availableTools.length === 0) return void 0;
121
+ if (availableTools.length === 0) return;
123
122
  let systemMessage = systemPrompt;
124
123
  /**
125
124
  * If there's a maxTools limit, append instructions to the system prompt
@@ -1 +1 @@
1
- {"version":3,"file":"llmToolSelector.js","names":["tools: StructuredToolInterface[]","options: LLMToolSelectorConfig","request: ModelRequest<TState, TContext>","runtime: Runtime<LLMToolSelectorConfig>","lastUserMessage: HumanMessage | undefined","response: { tools: string[] }","availableTools: StructuredToolInterface[]","validToolNames: string[]","selectedToolNames: string[]","invalidToolSelections: string[]"],"sources":["../../../src/agents/middleware/llmToolSelector.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport { HumanMessage } from \"@langchain/core/messages\";\nimport type { StructuredToolInterface } from \"@langchain/core/tools\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport type { Runtime } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\n\nconst DEFAULT_SYSTEM_PROMPT =\n \"Your goal is to select the most relevant tools for answering the user's query.\";\n\n/**\n * Prepared inputs for tool selection.\n */\ninterface SelectionRequest {\n availableTools: StructuredToolInterface[];\n systemMessage: string;\n lastUserMessage: HumanMessage;\n model: BaseLanguageModel;\n validToolNames: string[];\n}\n\n/**\n * Create a structured output schema for tool selection.\n *\n * @param tools - Available tools to include in the schema.\n * @returns Zod schema where each tool name is a literal with its description.\n */\nfunction createToolSelectionResponse(tools: StructuredToolInterface[]) {\n if (!tools || tools.length === 0) {\n throw new Error(\"Invalid usage: tools must be non-empty\");\n }\n\n // Create a union of literals for each tool name\n const toolLiterals = tools.map((tool) => z.literal(tool.name));\n const toolEnum = z.union(\n toolLiterals as [\n z.ZodLiteral<string>,\n z.ZodLiteral<string>,\n ...z.ZodLiteral<string>[],\n ]\n );\n\n return z.object({\n tools: z\n .array(toolEnum)\n .describe(\"Tools to use. Place the most relevant tools first.\"),\n });\n}\n\n/**\n * Options for configuring the LLM Tool Selector middleware.\n */\nexport const LLMToolSelectorOptionsSchema = z.object({\n /**\n * The language model to use for tool selection (default: the provided model from the agent options).\n */\n model: z.string().or(z.instanceof(BaseLanguageModel)).optional(),\n /**\n * System prompt for the tool selection model.\n */\n systemPrompt: z.string().optional(),\n /**\n * Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n */\n maxTools: z.number().optional(),\n /**\n * Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n */\n alwaysInclude: z.array(z.string()).optional(),\n});\nexport type LLMToolSelectorConfig = InferInteropZodInput<\n typeof LLMToolSelectorOptionsSchema\n>;\n\n/**\n * Middleware for selecting tools using an LLM-based strategy.\n *\n * When an agent has many tools available, this middleware filters them down\n * to only the most relevant ones for the user's query. This reduces token usage\n * and helps the main model focus on the right tools.\n *\n * @param options - Configuration options for the middleware\n * @param options.model - The language model to use for tool selection (default: the provided model from the agent options).\n * @param options.systemPrompt - Instructions for the selection model.\n * @param options.maxTools - Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n * @param options.alwaysInclude - Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n *\n * @example\n * Limit to 3 tools:\n * ```ts\n * import { llmToolSelectorMiddleware } from \"langchain/agents/middleware\";\n *\n * const middleware = llmToolSelectorMiddleware({ maxTools: 3 });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [tool1, tool2, tool3, tool4, tool5],\n * middleware: [middleware],\n * });\n * ```\n *\n * @example\n * Use a smaller model for selection:\n * ```ts\n * const middleware = llmToolSelectorMiddleware({\n * model: \"openai:gpt-4o-mini\",\n * maxTools: 2\n * });\n * ```\n */\nexport function llmToolSelectorMiddleware(\n options: LLMToolSelectorConfig\n): ReturnType<typeof createMiddleware> {\n return createMiddleware({\n name: \"LLMToolSelector\",\n contextSchema: LLMToolSelectorOptionsSchema,\n async wrapModelCall(request, handler) {\n const selectionRequest = await prepareSelectionRequest(\n request,\n options,\n request.runtime\n );\n if (!selectionRequest) {\n return handler(request);\n }\n\n // Create dynamic response model with union of literal tool names\n const toolSelectionSchema = createToolSelectionResponse(\n selectionRequest.availableTools\n );\n const structuredModel =\n await selectionRequest.model.withStructuredOutput?.(\n toolSelectionSchema\n );\n\n const response = await structuredModel?.invoke([\n { role: \"system\", content: selectionRequest.systemMessage },\n selectionRequest.lastUserMessage,\n ]);\n\n // Response should be an object with a tools array\n if (!response || typeof response !== \"object\" || !(\"tools\" in response)) {\n throw new Error(\n `Expected object response with tools array, got ${typeof response}`\n );\n }\n\n return handler(\n processSelectionResponse(\n response as { tools: string[] },\n selectionRequest.availableTools,\n selectionRequest.validToolNames,\n request,\n options\n )\n );\n },\n });\n}\n\n/**\n * Prepare inputs for tool selection.\n *\n * @param request - The model request to process.\n * @param options - Configuration options.\n * @param runtime - Runtime context.\n * @returns SelectionRequest with prepared inputs, or null if no selection is needed.\n */\nasync function prepareSelectionRequest<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown,\n>(\n request: ModelRequest<TState, TContext>,\n options: LLMToolSelectorConfig,\n runtime: Runtime<LLMToolSelectorConfig>\n): Promise<SelectionRequest | undefined> {\n const model = runtime.context.model ?? options.model;\n const maxTools = runtime.context.maxTools ?? options.maxTools;\n const alwaysInclude =\n runtime.context.alwaysInclude ?? options.alwaysInclude ?? [];\n const systemPrompt =\n runtime.context.systemPrompt ??\n options.systemPrompt ??\n DEFAULT_SYSTEM_PROMPT;\n\n /**\n * If no tools available, return null\n */\n if (!request.tools || request.tools.length === 0) {\n return undefined;\n }\n\n /**\n * Filter to only StructuredToolInterface instances (exclude provider-specific tool dicts)\n */\n const baseTools = request.tools.filter(\n (tool): tool is StructuredToolInterface =>\n typeof tool === \"object\" &&\n \"name\" in tool &&\n \"description\" in tool &&\n typeof tool.name === \"string\"\n );\n\n /**\n * Validate that alwaysInclude tools exist\n */\n if (alwaysInclude.length > 0) {\n const availableToolNames = new Set(baseTools.map((tool) => tool.name));\n const missingTools = alwaysInclude.filter(\n (name) => !availableToolNames.has(name)\n );\n if (missingTools.length > 0) {\n throw new Error(\n `Tools in alwaysInclude not found in request: ${missingTools.join(\n \", \"\n )}. ` +\n `Available tools: ${Array.from(availableToolNames).sort().join(\", \")}`\n );\n }\n }\n\n /**\n * Separate tools that are always included from those available for selection\n */\n const availableTools = baseTools.filter(\n (tool) => !alwaysInclude.includes(tool.name)\n );\n\n /**\n * If no tools available for selection, return null\n */\n if (availableTools.length === 0) {\n return undefined;\n }\n\n let systemMessage = systemPrompt;\n /**\n * If there's a maxTools limit, append instructions to the system prompt\n */\n if (maxTools !== undefined) {\n systemMessage +=\n `\\nIMPORTANT: List the tool names in order of relevance, ` +\n `with the most relevant first. ` +\n `If you exceed the maximum number of tools, ` +\n `only the first ${maxTools} will be used.`;\n }\n\n /**\n * Get the last user message from the conversation history\n */\n let lastUserMessage: HumanMessage | undefined;\n for (const message of request.messages) {\n if (HumanMessage.isInstance(message)) {\n lastUserMessage = message;\n }\n }\n\n if (!lastUserMessage) {\n throw new Error(\"No user message found in request messages\");\n }\n\n const modelInstance = !model\n ? (request.model as BaseLanguageModel)\n : typeof model === \"string\"\n ? await initChatModel(model)\n : model;\n\n const validToolNames = availableTools.map((tool) => tool.name);\n\n return {\n availableTools,\n systemMessage,\n lastUserMessage,\n model: modelInstance,\n validToolNames,\n };\n}\n\n/**\n * Process the selection response and return filtered ModelRequest.\n *\n * @param response - The structured output response from the model.\n * @param availableTools - Tools available for selection.\n * @param validToolNames - Valid tool names that can be selected.\n * @param request - Original model request.\n * @param options - Configuration options.\n * @returns Modified ModelRequest with filtered tools.\n */\nfunction processSelectionResponse<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown,\n>(\n response: { tools: string[] },\n availableTools: StructuredToolInterface[],\n validToolNames: string[],\n request: ModelRequest<TState, TContext>,\n options: LLMToolSelectorConfig\n): ModelRequest<TState, TContext> {\n const maxTools = options.maxTools;\n const alwaysInclude = options.alwaysInclude ?? [];\n\n const selectedToolNames: string[] = [];\n const invalidToolSelections: string[] = [];\n\n for (const toolName of response.tools) {\n if (!validToolNames.includes(toolName)) {\n invalidToolSelections.push(toolName);\n continue;\n }\n\n /**\n * Only add if not already selected and within maxTools limit\n */\n if (\n !selectedToolNames.includes(toolName) &&\n (maxTools === undefined || selectedToolNames.length < maxTools)\n ) {\n selectedToolNames.push(toolName);\n }\n }\n\n if (invalidToolSelections.length > 0) {\n throw new Error(\n `Model selected invalid tools: ${invalidToolSelections.join(\", \")}`\n );\n }\n\n /**\n * Filter tools based on selection\n */\n const selectedTools = availableTools.filter((tool) =>\n selectedToolNames.includes(tool.name)\n );\n\n /**\n * Append always-included tools\n */\n const alwaysIncludedTools = (request.tools ?? []).filter(\n (tool): tool is StructuredToolInterface =>\n typeof tool === \"object\" &&\n \"name\" in tool &&\n typeof tool.name === \"string\" &&\n alwaysInclude.includes(tool.name)\n );\n selectedTools.push(...alwaysIncludedTools);\n\n /**\n * Also preserve any provider-specific tool dicts from the original request\n */\n const providerTools = (request.tools ?? []).filter(\n (tool) =>\n !(\n typeof tool === \"object\" &&\n \"name\" in tool &&\n \"description\" in tool &&\n typeof tool.name === \"string\"\n )\n );\n\n return {\n ...request,\n tools: [...selectedTools, ...providerTools],\n };\n}\n"],"mappings":";;;;;;;AAWA,MAAM,wBACJ;;;;;;;AAmBF,SAAS,4BAA4BA,OAAkC;AACrE,KAAI,CAAC,SAAS,MAAM,WAAW,EAC7B,OAAM,IAAI,MAAM;CAIlB,MAAM,eAAe,MAAM,IAAI,CAAC,SAAS,EAAE,QAAQ,KAAK,KAAK,CAAC;CAC9D,MAAM,WAAW,EAAE,MACjB,aAKD;AAED,QAAO,EAAE,OAAO,EACd,OAAO,EACJ,MAAM,SAAS,CACf,SAAS,qDAAqD,CAClE,EAAC;AACH;;;;AAKD,MAAa,+BAA+B,EAAE,OAAO;CAInD,OAAO,EAAE,QAAQ,CAAC,GAAG,EAAE,WAAW,kBAAkB,CAAC,CAAC,U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;;;;AAKD,MACE,CAAC,kBAAkB,SAAS,SAAS,KACpC,aAAa,UAAa,kBAAkB,SAAS,WAEtD,kBAAkB,KAAK,SAAS;CAEnC;AAED,KAAI,sBAAsB,SAAS,EACjC,OAAM,IAAI,MACR,CAAC,8BAA8B,EAAE,sBAAsB,KAAK,KAAK,EAAE;;;;CAOvE,MAAM,gBAAgB,eAAe,OAAO,CAAC,SAC3C,kBAAkB,SAAS,KAAK,KAAK,CACtC;;;;CAKD,MAAM,uBAAuB,QAAQ,SAAS,CAAE,GAAE,OAChD,CAAC,SACC,OAAO,SAAS,YAChB,UAAU,QACV,OAAO,KAAK,SAAS,YACrB,cAAc,SAAS,KAAK,KAAK,CACpC;CACD,cAAc,KAAK,GAAG,oBAAoB;;;;CAK1C,MAAM,iBAAiB,QAAQ,SAAS,CAAE,GAAE,OAC1C,CAAC,SACC,EACE,OAAO,SAAS,YAChB,UAAU,QACV,iBAAiB,QACjB,OAAO,KAAK,SAAS,UAE1B;AAED,QAAO;EACL,GAAG;EACH,OAAO,CAAC,GAAG,eAAe,GAAG,aAAc;CAC5C;AACF"}
1
+ {"version":3,"file":"llmToolSelector.js","names":[],"sources":["../../../src/agents/middleware/llmToolSelector.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport { HumanMessage } from \"@langchain/core/messages\";\nimport type { StructuredToolInterface } from \"@langchain/core/tools\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport type { Runtime } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\n\nconst DEFAULT_SYSTEM_PROMPT =\n \"Your goal is to select the most relevant tools for answering the user's query.\";\n\n/**\n * Prepared inputs for tool selection.\n */\ninterface SelectionRequest {\n availableTools: StructuredToolInterface[];\n systemMessage: string;\n lastUserMessage: HumanMessage;\n model: BaseLanguageModel;\n validToolNames: string[];\n}\n\n/**\n * Create a structured output schema for tool selection.\n *\n * @param tools - Available tools to include in the schema.\n * @returns Zod schema where each tool name is a literal with its description.\n */\nfunction createToolSelectionResponse(tools: StructuredToolInterface[]) {\n if (!tools || tools.length === 0) {\n throw new Error(\"Invalid usage: tools must be non-empty\");\n }\n\n // Create a union of literals for each tool name\n const toolLiterals = tools.map((tool) => z.literal(tool.name));\n const toolEnum = z.union(\n toolLiterals as [\n z.ZodLiteral<string>,\n z.ZodLiteral<string>,\n ...z.ZodLiteral<string>[],\n ]\n );\n\n return z.object({\n tools: z\n .array(toolEnum)\n .describe(\"Tools to use. Place the most relevant tools first.\"),\n });\n}\n\n/**\n * Options for configuring the LLM Tool Selector middleware.\n */\nexport const LLMToolSelectorOptionsSchema = z.object({\n /**\n * The language model to use for tool selection (default: the provided model from the agent options).\n */\n model: z.string().or(z.instanceof(BaseLanguageModel)).optional(),\n /**\n * System prompt for the tool selection model.\n */\n systemPrompt: z.string().optional(),\n /**\n * Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n */\n maxTools: z.number().optional(),\n /**\n * Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n */\n alwaysInclude: z.array(z.string()).optional(),\n});\nexport type LLMToolSelectorConfig = InferInteropZodInput<\n typeof LLMToolSelectorOptionsSchema\n>;\n\n/**\n * Middleware for selecting tools using an LLM-based strategy.\n *\n * When an agent has many tools available, this middleware filters them down\n * to only the most relevant ones for the user's query. This reduces token usage\n * and helps the main model focus on the right tools.\n *\n * @param options - Configuration options for the middleware\n * @param options.model - The language model to use for tool selection (default: the provided model from the agent options).\n * @param options.systemPrompt - Instructions for the selection model.\n * @param options.maxTools - Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n * @param options.alwaysInclude - Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n *\n * @example\n * Limit to 3 tools:\n * ```ts\n * import { llmToolSelectorMiddleware } from \"langchain/agents/middleware\";\n *\n * const middleware = llmToolSelectorMiddleware({ maxTools: 3 });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [tool1, tool2, tool3, tool4, tool5],\n * middleware: [middleware],\n * });\n * ```\n *\n * @example\n * Use a smaller model for selection:\n * ```ts\n * const middleware = llmToolSelectorMiddleware({\n * model: \"openai:gpt-4o-mini\",\n * maxTools: 2\n * });\n * ```\n */\nexport function llmToolSelectorMiddleware(\n options: LLMToolSelectorConfig\n): ReturnType<typeof createMiddleware> {\n return createMiddleware({\n name: \"LLMToolSelector\",\n contextSchema: LLMToolSelectorOptionsSchema,\n async wrapModelCall(request, handler) {\n const selectionRequest = await prepareSelectionRequest(\n request,\n options,\n request.runtime\n );\n if (!selectionRequest) {\n return handler(request);\n }\n\n // Create dynamic response model with union of literal tool names\n const toolSelectionSchema = createToolSelectionResponse(\n selectionRequest.availableTools\n );\n const structuredModel =\n await selectionRequest.model.withStructuredOutput?.(\n toolSelectionSchema\n );\n\n const response = await structuredModel?.invoke([\n { role: \"system\", content: selectionRequest.systemMessage },\n selectionRequest.lastUserMessage,\n ]);\n\n // Response should be an object with a tools array\n if (!response || typeof response !== \"object\" || !(\"tools\" in response)) {\n throw new Error(\n `Expected object response with tools array, got ${typeof response}`\n );\n }\n\n return handler(\n processSelectionResponse(\n response as { tools: string[] },\n selectionRequest.availableTools,\n selectionRequest.validToolNames,\n request,\n options\n )\n );\n },\n });\n}\n\n/**\n * Prepare inputs for tool selection.\n *\n * @param request - The model request to process.\n * @param options - Configuration options.\n * @param runtime - Runtime context.\n * @returns SelectionRequest with prepared inputs, or null if no selection is needed.\n */\nasync function prepareSelectionRequest<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown,\n>(\n request: ModelRequest<TState, TContext>,\n options: LLMToolSelectorConfig,\n runtime: Runtime<LLMToolSelectorConfig>\n): Promise<SelectionRequest | undefined> {\n const model = runtime.context.model ?? options.model;\n const maxTools = runtime.context.maxTools ?? options.maxTools;\n const alwaysInclude =\n runtime.context.alwaysInclude ?? options.alwaysInclude ?? [];\n const systemPrompt =\n runtime.context.systemPrompt ??\n options.systemPrompt ??\n DEFAULT_SYSTEM_PROMPT;\n\n /**\n * If no tools available, return null\n */\n if (!request.tools || request.tools.length === 0) {\n return undefined;\n }\n\n /**\n * Filter to only StructuredToolInterface instances (exclude provider-specific tool dicts)\n */\n const baseTools = request.tools.filter(\n (tool): tool is StructuredToolInterface =>\n typeof tool === \"object\" &&\n \"name\" in tool &&\n \"description\" in tool &&\n typeof tool.name === \"string\"\n );\n\n /**\n * Validate that alwaysInclude tools exist\n */\n if (alwaysInclude.length > 0) {\n const availableToolNames = new Set(baseTools.map((tool) => tool.name));\n const missingTools = alwaysInclude.filter(\n (name) => !availableToolNames.has(name)\n );\n if (missingTools.length > 0) {\n throw new Error(\n `Tools in alwaysInclude not found in request: ${missingTools.join(\n \", \"\n )}. ` +\n `Available tools: ${Array.from(availableToolNames).sort().join(\", \")}`\n );\n }\n }\n\n /**\n * Separate tools that are always included from those available for selection\n */\n const availableTools = baseTools.filter(\n (tool) => !alwaysInclude.includes(tool.name)\n );\n\n /**\n * If no tools available for selection, return null\n */\n if (availableTools.length === 0) {\n return undefined;\n }\n\n let systemMessage = systemPrompt;\n /**\n * If there's a maxTools limit, append instructions to the system prompt\n */\n if (maxTools !== undefined) {\n systemMessage +=\n `\\nIMPORTANT: List the tool names in order of relevance, ` +\n `with the most relevant first. ` +\n `If you exceed the maximum number of tools, ` +\n `only the first ${maxTools} will be used.`;\n }\n\n /**\n * Get the last user message from the conversation history\n */\n let lastUserMessage: HumanMessage | undefined;\n for (const message of request.messages) {\n if (HumanMessage.isInstance(message)) {\n lastUserMessage = message;\n }\n }\n\n if (!lastUserMessage) {\n throw new Error(\"No user message found in request messages\");\n }\n\n const modelInstance = !model\n ? (request.model as BaseLanguageModel)\n : typeof model === \"string\"\n ? await initChatModel(model)\n : model;\n\n const validToolNames = availableTools.map((tool) => tool.name);\n\n return {\n availableTools,\n systemMessage,\n lastUserMessage,\n model: modelInstance,\n validToolNames,\n };\n}\n\n/**\n * Process the selection response and return filtered ModelRequest.\n *\n * @param response - The structured output response from the model.\n * @param availableTools - Tools available for selection.\n * @param validToolNames - Valid tool names that can be selected.\n * @param request - Original model request.\n * @param options - Configuration options.\n * @returns Modified ModelRequest with filtered tools.\n */\nfunction processSelectionResponse<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown,\n>(\n response: { tools: string[] },\n availableTools: StructuredToolInterface[],\n validToolNames: string[],\n request: ModelRequest<TState, TContext>,\n options: LLMToolSelectorConfig\n): ModelRequest<TState, TContext> {\n const maxTools = options.maxTools;\n const alwaysInclude = options.alwaysInclude ?? [];\n\n const selectedToolNames: string[] = [];\n const invalidToolSelections: string[] = [];\n\n for (const toolName of response.tools) {\n if (!validToolNames.includes(toolName)) {\n invalidToolSelections.push(toolName);\n continue;\n }\n\n /**\n * Only add if not already selected and within maxTools limit\n */\n if (\n !selectedToolNames.includes(toolName) &&\n (maxTools === undefined || selectedToolNames.length < maxTools)\n ) {\n selectedToolNames.push(toolName);\n }\n }\n\n if (invalidToolSelections.length > 0) {\n throw new Error(\n `Model selected invalid tools: ${invalidToolSelections.join(\", \")}`\n );\n }\n\n /**\n * Filter tools based on selection\n */\n const selectedTools = availableTools.filter((tool) =>\n selectedToolNames.includes(tool.name)\n );\n\n /**\n * Append always-included tools\n */\n const alwaysIncludedTools = (request.tools ?? []).filter(\n (tool): tool is StructuredToolInterface =>\n typeof tool === \"object\" &&\n \"name\" in tool &&\n typeof tool.name === \"string\" &&\n alwaysInclude.includes(tool.name)\n );\n selectedTools.push(...alwaysIncludedTools);\n\n /**\n * Also preserve any provider-specific tool dicts from the original request\n */\n const providerTools = (request.tools ?? []).filter(\n (tool) =>\n !(\n typeof tool === \"object\" &&\n \"name\" in tool &&\n \"description\" in tool &&\n typeof tool.name === \"string\"\n )\n );\n\n return {\n ...request,\n tools: [...selectedTools, ...providerTools],\n };\n}\n"],"mapp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;EACP;EACD;;;;;;;;;;;;AAaH,SAAS,yBAIP,UACA,gBACA,gBACA,SACA,SACgC;CAChC,MAAM,WAAW,QAAQ;CACzB,MAAM,gBAAgB,QAAQ,iBAAiB,EAAE;CAEjD,MAAM,oBAA8B,EAAE;CACtC,MAAM,wBAAkC,EAAE;AAE1C,MAAK,MAAM,YAAY,SAAS,OAAO;AACrC,MAAI,CAAC,eAAe,SAAS,SAAS,EAAE;AACtC,yBAAsB,KAAK,SAAS;AACpC;;;;;AAMF,MACE,CAAC,kBAAkB,SAAS,SAAS,KACpC,aAAa,UAAa,kBAAkB,SAAS,UAEtD,mBAAkB,KAAK,SAAS;;AAIpC,KAAI,sBAAsB,SAAS,EACjC,OAAM,IAAI,MACR,iCAAiC,sBAAsB,KAAK,KAAK,GAClE;;;;CAMH,MAAM,gBAAgB,eAAe,QAAQ,SAC3C,kBAAkB,SAAS,KAAK,KAAK,CACtC;;;;CAKD,MAAM,uBAAuB,QAAQ,SAAS,EAAE,EAAE,QAC/C,SACC,OAAO,SAAS,YAChB,UAAU,QACV,OAAO,KAAK,SAAS,YACrB,cAAc,SAAS,KAAK,KAAK,CACpC;AACD,eAAc,KAAK,GAAG,oBAAoB;;;;CAK1C,MAAM,iBAAiB,QAAQ,SAAS,EAAE,EAAE,QACzC,SACC,EACE,OAAO,SAAS,YAChB,UAAU,QACV,iBAAiB,QACjB,OAAO,KAAK,SAAS,UAE1B;AAED,QAAO;EACL,GAAG;EACH,OAAO,CAAC,GAAG,eAAe,GAAG,cAAc;EAC5C"}
@@ -1,7 +1,7 @@
1
- const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
1
+ const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
2
2
  const require_middleware = require('../middleware.cjs');
3
- const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
4
- const zod_v3 = require_rolldown_runtime.__toESM(require("zod/v3"));
3
+ let _langchain_core_messages = require("@langchain/core/messages");
4
+ let zod_v3 = require("zod/v3");
5
5
 
6
6
  //#region src/agents/middleware/modelCallLimit.ts
7
7
  const DEFAULT_EXIT_BEHAVIOR = "end";
@@ -118,7 +118,7 @@ function modelCallLimitMiddleware(middlewareOptions) {
118
118
  });
119
119
  if (exitBehavior === "end") return {
120
120
  jumpTo: "end",
121
- messages: [new __langchain_core_messages.AIMessage(error.message)]
121
+ messages: [new _langchain_core_messages.AIMessage(error.message)]
122
122
  };
123
123
  throw error;
124
124
  }
@@ -129,7 +129,7 @@ function modelCallLimitMiddleware(middlewareOptions) {
129
129
  });
130
130
  if (exitBehavior === "end") return {
131
131
  jumpTo: "end",
132
- messages: [new __langchain_core_messages.AIMessage(error.message)]
132
+ messages: [new _langchain_core_messages.AIMessage(error.message)]
133
133
  };
134
134
  throw error;
135
135
  }
@@ -1 +1 @@
1
- {"version":3,"file":"modelCallLimit.cjs","names":["z","exceededHint: string[]","middlewareOptions?: ModelCallLimitMiddlewareConfig","createMiddleware","AIMessage"],"sources":["../../../src/agents/middleware/modelCallLimit.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { AIMessage } from \"@langchain/core/messages\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\n\nimport { createMiddleware } from \"../middleware.js\";\n\nconst DEFAULT_EXIT_BEHAVIOR = \"end\";\n\nconst contextSchema = z.object({\n /**\n * The maximum number of model calls allowed per thread.\n */\n threadLimit: z.number().optional(),\n /**\n * The maximum number of model calls allowed per run.\n */\n runLimit: z.number().optional(),\n /**\n * The behavior to take when the limit is exceeded.\n * - \"error\" will throw an error and stop the agent.\n * - \"end\" will end the agent.\n * @default \"end\"\n */\n exitBehavior: z.enum([\"error\", \"end\"]).optional(),\n});\nexport type ModelCallLimitMiddlewareConfig = Partial<\n InferInteropZodInput<typeof contextSchema>\n>;\n\n/**\n * Middleware state schema to track the number of model calls made at the thread and run level.\n */\nconst stateSchema = z.object({\n threadModelCallCount: z.number().default(0),\n runModelCallCount: z.number().default(0),\n});\n\n/**\n * Error thrown when the model call limit is exceeded.\n *\n * @param threadLimit - The maximum number of model calls allowed per thread.\n * @param runLimit - The maximum number of model calls allowed per run.\n * @param threadCount - The number of model calls made at the thread level.\n * @param runCount - The number of model calls made at the run level.\n */\nclass ModelCallLimitMiddlewareError extends Error {\n constructor({\n threadLimit,\n runLimit,\n threadCount,\n runCount,\n }: {\n threadLimit?: number;\n runLimit?: number;\n threadCount?: number;\n runCount?: number;\n }) {\n const exceededHint: string[] = [];\n if (typeof threadLimit === \"number\" && typeof threadCount === \"number\") {\n exceededHint.push(\n `thread level call limit reached with ${threadCount} model calls`\n );\n }\n if (typeof runLimit === \"number\" && typeof runCount === \"number\") {\n exceededHint.push(\n `run level call limit reached with ${runCount} model calls`\n );\n }\n super(\n `Model call limits exceeded${\n exceededHint.length > 0 ? `: ${exceededHint.join(\", \")}` : \"\"\n }`\n );\n this.name = \"ModelCallLimitMiddlewareError\";\n }\n}\n\n/**\n * Creates a middleware to limit the number of model calls at both thread and run levels.\n *\n * This middleware helps prevent excessive model API calls by enforcing limits on how many\n * times the model can be invoked. It supports two types of limits:\n *\n * - **Thread-level limit**: Restricts the total number of model calls across an entire conversation thread\n * - **Run-level limit**: Restricts the number of model calls within a single agent run/invocation\n *\n * ## How It Works\n *\n * The middleware intercepts model requests before they are sent and checks the current call counts\n * against the configured limits. If either limit is exceeded, it throws a `ModelCallLimitMiddlewareError`\n * to stop execution and prevent further API calls.\n *\n * ## Use Cases\n *\n * - **Cost Control**: Prevent runaway costs from excessive model calls in production\n * - **Testing**: Ensure agents don't make too many calls during development/testing\n * - **Safety**: Limit potential infinite loops or recursive agent behaviors\n * - **Rate Limiting**: Enforce organizational policies on model usage per conversation\n *\n * @param middlewareOptions - Configuration options for the call limits\n * @param middlewareOptions.threadLimit - Maximum number of model calls allowed per thread (optional)\n * @param middlewareOptions.runLimit - Maximum number of model calls allowed per run (optional)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {ModelCallLimitMiddlewareError} When either the thread or run limit is exceeded\n *\n * @example\n * ```typescript\n * import { createAgent, modelCallLimitMiddleware } from \"langchain\";\n *\n * // Limit to 10 calls per thread and 3 calls per run\n * const agent = createAgent({\n * model: \"openai:gpt-4o-mini\",\n * tools: [myTool],\n * middleware: [\n * modelCallLimitMiddleware({\n * threadLimit: 10,\n * runLimit: 3\n * })\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Limits can also be configured at runtime via context\n * const result = await agent.invoke(\n * { messages: [\"Hello\"] },\n * {\n * configurable: {\n * threadLimit: 5 // Override the default limit for this run\n * }\n * }\n * );\n * ```\n */\nexport function modelCallLimitMiddleware(\n middlewareOptions?: ModelCallLimitMiddlewareConfig\n) {\n return createMiddleware({\n name: \"ModelCallLimitMiddleware\",\n contextSchema,\n stateSchema,\n beforeModel: {\n canJumpTo: [\"end\"],\n hook: (state, runtime) => {\n let exitBehavior =\n runtime.context.exitBehavior ??\n middlewareOptions?.exitBehavior ??\n DEFAULT_EXIT_BEHAVIOR;\n\n // @ts-expect-error - throw is deprecated\n if (exitBehavior === \"throw\") {\n console.warn(\n \"The 'throw' exit behavior is deprecated. Please use 'error' instead.\"\n );\n exitBehavior = \"error\";\n }\n\n const threadLimit =\n runtime.context.threadLimit ?? middlewareOptions?.threadLimit;\n const runLimit =\n runtime.context.runLimit ?? middlewareOptions?.runLimit;\n\n const threadCount = state.threadModelCallCount;\n const runCount = state.runModelCallCount;\n if (typeof threadLimit === \"number\" && threadLimit <= threadCount) {\n const error = new ModelCallLimitMiddlewareError({\n threadLimit,\n threadCount,\n });\n if (exitBehavior === \"end\") {\n return {\n jumpTo: \"end\",\n messages: [new AIMessage(error.message)],\n };\n }\n\n throw error;\n }\n if (typeof runLimit === \"number\" && runLimit <= runCount) {\n const error = new ModelCallLimitMiddlewareError({\n runLimit,\n runCount,\n });\n if (exitBehavior === \"end\") {\n return {\n jumpTo: \"end\",\n messages: [new AIMessage(error.message)],\n };\n }\n\n throw error;\n }\n\n return state;\n },\n },\n afterModel: (state) => ({\n runModelCallCount: state.runModelCallCount + 1,\n threadModelCallCount: state.threadModelCallCount + 1,\n }),\n afterAgent: () => ({\n runModelCallCount: 0,\n }),\n });\n}\n"],"mappings":";;;;;;AAMA,MAAM,wBAAwB;AAE9B,MAAM,gBAAgBA,SAAE,OAAO;CAI7B,aAAaA,SAAE,QAAQ,CAAC,UAAU;CAIlC,UAAUA,SAAE,QAAQ,CAAC,UAAU;CAO/B,cAAcA,SAAE,KAAK,CAAC,SAAS,KAAM,EAAC,CAAC,UAAU;AAClD,EAAC;;;;AAQF,MAAM,cAAcA,SAAE,OAAO;CAC3B,sBAAsBA,SAAE,QAAQ,CAAC,QAAQ,EAAE;CAC3C,mBAAmBA,SAAE,QAAQ,CAAC,QAAQ,EAAE;AACzC,EAAC;;;;;;;;;AAUF,IAAM,gCAAN,cAA4C,MAAM;CAChD,YAAY,EACV,aACA,UACA,aACA,UAMD,EAAE;EACD,MAAMC,eAAyB,CAAE;AACjC,MAAI,OAAO,gBAAgB,YAAY,OAAO,gBAAgB,UAC5D,aAAa,KACX,CAAC,qCAAqC,EAAE,YAAY,YAAY,CAAC,CAClE;AAEH,MAAI,OAAO,aAAa,YAAY,OAAO,aAAa,UACtD,aAAa,KACX,CAAC,kCAAkC,EAAE,SAAS,YAAY,CAAC,CAC5D;EAEH,MACE,CAAC,0BAA0B,EACzB,aAAa,SAAS,IAAI,CAAC,EAAE,EAAE,aAAa,KAAK,KAAK,EAAE,GAAG,IAC3D,CACH;EACD,KAAK,OAAO;CACb;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DD,SAAgB,yBACdC,mBACA;AACA,QAAOC,oCAAiB;EACtB,MAAM;EACN;EACA;EACA,aAAa;GACX,WAAW,CAAC,KAAM;GAClB,MAAM,CAAC,OAAO,YAAY;IACxB,IAAI,eACF,QAAQ,QAAQ,gBAChB,mBAAmB,gBACnB;AAGF,QAAI,iBAAiB,SAAS;KAC5B,QAAQ,KACN,uEACD;KACD,eAAe;IAChB;IAED,MAAM,cACJ,QAAQ,QAAQ,eAAe,mBAAmB;IACpD,MAAM,WACJ,QAAQ,QAAQ,YAAY,mBAAmB;IAEjD,MAAM,cAAc,MAAM;IAC1B,MAAM,WAAW,MAAM;AACvB,QAAI,OAAO,gBAAgB,YAAY,eAAe,aAAa;KACjE,MAAM,QAAQ,IAAI,8BAA8B;MAC9C;MACA;KACD;AACD,SAAI,iBAAiB,MACnB,QAAO;MACL,QAAQ;MACR,UAAU,CAAC,IAAIC,oCAAU,MAAM,QAAS;KACzC;AAGH,WAAM;IACP;AACD,QAAI,OAAO,aAAa,YAAY,YAAY,UAAU;KACxD,MAAM,QAAQ,IAAI,8BAA8B;MAC9C;MACA;KACD;AACD,SAAI,iBAAiB,MACnB,QAAO;MACL,QAAQ;MACR,UAAU,CAAC,IAAIA,oCAAU,MAAM,QAAS;KACzC;AAGH,WAAM;IACP;AAED,WAAO;GACR;EACF;EACD,YAAY,CAAC,WAAW;GACtB,mBAAmB,MAAM,oBAAoB;GAC7C,sBAAsB,MAAM,uBAAuB;EACpD;EACD,YAAY,OAAO,EACjB,mBAAmB,EACpB;CACF,EAAC;AACH"}
1
+ {"version":3,"file":"modelCallLimit.cjs","names":["z","createMiddleware","AIMessage"],"sources":["../../../src/agents/middleware/modelCallLimit.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { AIMessage } from \"@langchain/core/messages\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\n\nimport { createMiddleware } from \"../middleware.js\";\n\nconst DEFAULT_EXIT_BEHAVIOR = \"end\";\n\nconst contextSchema = z.object({\n /**\n * The maximum number of model calls allowed per thread.\n */\n threadLimit: z.number().optional(),\n /**\n * The maximum number of model calls allowed per run.\n */\n runLimit: z.number().optional(),\n /**\n * The behavior to take when the limit is exceeded.\n * - \"error\" will throw an error and stop the agent.\n * - \"end\" will end the agent.\n * @default \"end\"\n */\n exitBehavior: z.enum([\"error\", \"end\"]).optional(),\n});\nexport type ModelCallLimitMiddlewareConfig = Partial<\n InferInteropZodInput<typeof contextSchema>\n>;\n\n/**\n * Middleware state schema to track the number of model calls made at the thread and run level.\n */\nconst stateSchema = z.object({\n threadModelCallCount: z.number().default(0),\n runModelCallCount: z.number().default(0),\n});\n\n/**\n * Error thrown when the model call limit is exceeded.\n *\n * @param threadLimit - The maximum number of model calls allowed per thread.\n * @param runLimit - The maximum number of model calls allowed per run.\n * @param threadCount - The number of model calls made at the thread level.\n * @param runCount - The number of model calls made at the run level.\n */\nclass ModelCallLimitMiddlewareError extends Error {\n constructor({\n threadLimit,\n runLimit,\n threadCount,\n runCount,\n }: {\n threadLimit?: number;\n runLimit?: number;\n threadCount?: number;\n runCount?: number;\n }) {\n const exceededHint: string[] = [];\n if (typeof threadLimit === \"number\" && typeof threadCount === \"number\") {\n exceededHint.push(\n `thread level call limit reached with ${threadCount} model calls`\n );\n }\n if (typeof runLimit === \"number\" && typeof runCount === \"number\") {\n exceededHint.push(\n `run level call limit reached with ${runCount} model calls`\n );\n }\n super(\n `Model call limits exceeded${\n exceededHint.length > 0 ? `: ${exceededHint.join(\", \")}` : \"\"\n }`\n );\n this.name = \"ModelCallLimitMiddlewareError\";\n }\n}\n\n/**\n * Creates a middleware to limit the number of model calls at both thread and run levels.\n *\n * This middleware helps prevent excessive model API calls by enforcing limits on how many\n * times the model can be invoked. It supports two types of limits:\n *\n * - **Thread-level limit**: Restricts the total number of model calls across an entire conversation thread\n * - **Run-level limit**: Restricts the number of model calls within a single agent run/invocation\n *\n * ## How It Works\n *\n * The middleware intercepts model requests before they are sent and checks the current call counts\n * against the configured limits. If either limit is exceeded, it throws a `ModelCallLimitMiddlewareError`\n * to stop execution and prevent further API calls.\n *\n * ## Use Cases\n *\n * - **Cost Control**: Prevent runaway costs from excessive model calls in production\n * - **Testing**: Ensure agents don't make too many calls during development/testing\n * - **Safety**: Limit potential infinite loops or recursive agent behaviors\n * - **Rate Limiting**: Enforce organizational policies on model usage per conversation\n *\n * @param middlewareOptions - Configuration options for the call limits\n * @param middlewareOptions.threadLimit - Maximum number of model calls allowed per thread (optional)\n * @param middlewareOptions.runLimit - Maximum number of model calls allowed per run (optional)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {ModelCallLimitMiddlewareError} When either the thread or run limit is exceeded\n *\n * @example\n * ```typescript\n * import { createAgent, modelCallLimitMiddleware } from \"langchain\";\n *\n * // Limit to 10 calls per thread and 3 calls per run\n * const agent = createAgent({\n * model: \"openai:gpt-4o-mini\",\n * tools: [myTool],\n * middleware: [\n * modelCallLimitMiddleware({\n * threadLimit: 10,\n * runLimit: 3\n * })\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Limits can also be configured at runtime via context\n * const result = await agent.invoke(\n * { messages: [\"Hello\"] },\n * {\n * configurable: {\n * threadLimit: 5 // Override the default limit for this run\n * }\n * }\n * );\n * ```\n */\nexport function modelCallLimitMiddleware(\n middlewareOptions?: ModelCallLimitMiddlewareConfig\n) {\n return createMiddleware({\n name: \"ModelCallLimitMiddleware\",\n contextSchema,\n stateSchema,\n beforeModel: {\n canJumpTo: [\"end\"],\n hook: (state, runtime) => {\n let exitBehavior =\n runtime.context.exitBehavior ??\n middlewareOptions?.exitBehavior ??\n DEFAULT_EXIT_BEHAVIOR;\n\n // @ts-expect-error - throw is deprecated\n if (exitBehavior === \"throw\") {\n console.warn(\n \"The 'throw' exit behavior is deprecated. Please use 'error' instead.\"\n );\n exitBehavior = \"error\";\n }\n\n const threadLimit =\n runtime.context.threadLimit ?? middlewareOptions?.threadLimit;\n const runLimit =\n runtime.context.runLimit ?? middlewareOptions?.runLimit;\n\n const threadCount = state.threadModelCallCount;\n const runCount = state.runModelCallCount;\n if (typeof threadLimit === \"number\" && threadLimit <= threadCount) {\n const error = new ModelCallLimitMiddlewareError({\n threadLimit,\n threadCount,\n });\n if (exitBehavior === \"end\") {\n return {\n jumpTo: \"end\",\n messages: [new AIMessage(error.message)],\n };\n }\n\n throw error;\n }\n if (typeof runLimit === \"number\" && runLimit <= runCount) {\n const error = new ModelCallLimitMiddlewareError({\n runLimit,\n runCount,\n });\n if (exitBehavior === \"end\") {\n return {\n jumpTo: \"end\",\n messages: [new AIMessage(error.message)],\n };\n }\n\n throw error;\n }\n\n return state;\n },\n },\n afterModel: (state) => ({\n runModelCallCount: state.runModelCallCount + 1,\n threadModelCallCount: state.threadModelCallCount + 1,\n }),\n afterAgent: () => ({\n runModelCallCount: 0,\n }),\n });\n}\n"],"mappings":";;;;;;AAMA,MAAM,wBAAwB;AAE9B,MAAM,gBAAgBA,SAAE,OAAO;CAI7B,aAAaA,SAAE,QAAQ,CAAC,UAAU;CAIlC,UAAUA,SAAE,QAAQ,CAAC,UAAU;CAO/B,cAAcA,SAAE,KAAK,CAAC,SAAS,MAAM,CAAC,CAAC,UAAU;CAClD,CAAC;;;;AAQF,MAAM,cAAcA,SAAE,OAAO;CAC3B,sBAAsBA,SAAE,QAAQ,CAAC,QAAQ,EAAE;CAC3C,mBAAmBA,SAAE,QAAQ,CAAC,QAAQ,EAAE;CACzC,CAAC;;;;;;;;;AAUF,IAAM,gCAAN,cAA4C,MAAM;CAChD,YAAY,EACV,aACA,UACA,aACA,YAMC;EACD,MAAM,eAAyB,EAAE;AACjC,MAAI,OAAO,gBAAgB,YAAY,OAAO,gBAAgB,SAC5D,cAAa,KACX,wCAAwC,YAAY,cACrD;AAEH,MAAI,OAAO,aAAa,YAAY,OAAO,aAAa,SACtD,cAAa,KACX,qCAAqC,SAAS,cAC/C;AAEH,QACE,6BACE,aAAa,SAAS,IAAI,KAAK,aAAa,KAAK,KAAK,KAAK,KAE9D;AACD,OAAK,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEhB,SAAgB,yBACd,mBACA;AACA,QAAOC,oCAAiB;EACtB,MAAM;EACN;EACA;EACA,aAAa;GACX,WAAW,CAAC,MAAM;GAClB,OAAO,OAAO,YAAY;IACxB,IAAI,eACF,QAAQ,QAAQ,gBAChB,mBAAmB,gBACnB;AAGF,QAAI,iBAAiB,SAAS;AAC5B,aAAQ,KACN,uEACD;AACD,oBAAe;;IAGjB,MAAM,cACJ,QAAQ,QAAQ,eAAe,mBAAmB;IACpD,MAAM,WACJ,QAAQ,QAAQ,YAAY,mBAAmB;IAEjD,MAAM,cAAc,MAAM;IAC1B,MAAM,WAAW,MAAM;AACvB,QAAI,OAAO,gBAAgB,YAAY,eAAe,aAAa;KACjE,MAAM,QAAQ,IAAI,8BAA8B;MAC9C;MACA;MACD,CAAC;AACF,SAAI,iBAAiB,MACnB,QAAO;MACL,QAAQ;MACR,UAAU,CAAC,IAAIC,mCAAU,MAAM,QAAQ,CAAC;MACzC;AAGH,WAAM;;AAER,QAAI,OAAO,aAAa,YAAY,YAAY,UAAU;KACxD,MAAM,QAAQ,IAAI,8BAA8B;MAC9C;MACA;MACD,CAAC;AACF,SAAI,iBAAiB,MACnB,QAAO;MACL,QAAQ;MACR,UAAU,CAAC,IAAIA,mCAAU,MAAM,QAAQ,CAAC;MACzC;AAGH,WAAM;;AAGR,WAAO;;GAEV;EACD,aAAa,WAAW;GACtB,mBAAmB,MAAM,oBAAoB;GAC7C,sBAAsB,MAAM,uBAAuB;GACpD;EACD,mBAAmB,EACjB,mBAAmB,GACpB;EACF,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { AgentMiddleware } from "./types.cjs";
2
- import * as _langchain_core_tools10 from "@langchain/core/tools";
2
+ import * as _langchain_core_tools0 from "@langchain/core/tools";
3
3
  import { InferInteropZodInput } from "@langchain/core/utils/types";
4
4
  import { z } from "zod/v3";
5
5
 
@@ -127,7 +127,7 @@ declare function modelCallLimitMiddleware(middlewareOptions?: ModelCallLimitMidd
127
127
  threadLimit?: number | undefined;
128
128
  runLimit?: number | undefined;
129
129
  exitBehavior?: "end" | "error" | undefined;
130
- }, readonly (_langchain_core_tools10.ServerTool | _langchain_core_tools10.ClientTool)[]>;
130
+ }, readonly (_langchain_core_tools0.ServerTool | _langchain_core_tools0.ClientTool)[]>;
131
131
  //#endregion
132
132
  export { ModelCallLimitMiddlewareConfig, modelCallLimitMiddleware };
133
133
  //# sourceMappingURL=modelCallLimit.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"modelCallLimit.d.cts","names":["__types_js13","z","InferInteropZodInput","contextSchema","ZodNumber","ZodOptional","ZodEnum","ZodTypeAny","ZodObject","ModelCallLimitMiddlewareConfig","Partial","modelCallLimitMiddleware","ZodDefault","_langchain_core_tools10","ServerTool","ClientTool","AgentMiddleware"],"sources":["../../../src/agents/middleware/modelCallLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\ndeclare const contextSchema: z.ZodObject<{\n /**\n * The maximum number of model calls allowed per thread.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The maximum number of model calls allowed per run.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The behavior to take when the limit is exceeded.\n * - \"error\" will throw an error and stop the agent.\n * - \"end\" will end the agent.\n * @default \"end\"\n */\n exitBehavior: z.ZodOptional<z.ZodEnum<[\"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"error\" | undefined;\n}, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"error\" | undefined;\n}>;\nexport type ModelCallLimitMiddlewareConfig = Partial<InferInteropZodInput<typeof contextSchema>>;\n/**\n * Creates a middleware to limit the number of model calls at both thread and run levels.\n *\n * This middleware helps prevent excessive model API calls by enforcing limits on how many\n * times the model can be invoked. It supports two types of limits:\n *\n * - **Thread-level limit**: Restricts the total number of model calls across an entire conversation thread\n * - **Run-level limit**: Restricts the number of model calls within a single agent run/invocation\n *\n * ## How It Works\n *\n * The middleware intercepts model requests before they are sent and checks the current call counts\n * against the configured limits. If either limit is exceeded, it throws a `ModelCallLimitMiddlewareError`\n * to stop execution and prevent further API calls.\n *\n * ## Use Cases\n *\n * - **Cost Control**: Prevent runaway costs from excessive model calls in production\n * - **Testing**: Ensure agents don't make too many calls during development/testing\n * - **Safety**: Limit potential infinite loops or recursive agent behaviors\n * - **Rate Limiting**: Enforce organizational policies on model usage per conversation\n *\n * @param middlewareOptions - Configuration options for the call limits\n * @param middlewareOptions.threadLimit - Maximum number of model calls allowed per thread (optional)\n * @param middlewareOptions.runLimit - Maximum number of model calls allowed per run (optional)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {ModelCallLimitMiddlewareError} When either the thread or run limit is exceeded\n *\n * @example\n * ```typescript\n * import { createAgent, modelCallLimitMiddleware } from \"langchain\";\n *\n * // Limit to 10 calls per thread and 3 calls per run\n * const agent = createAgent({\n * model: \"openai:gpt-4o-mini\",\n * tools: [myTool],\n * middleware: [\n * modelCallLimitMiddleware({\n * threadLimit: 10,\n * runLimit: 3\n * })\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Limits can also be configured at runtime via context\n * const result = await agent.invoke(\n * { messages: [\"Hello\"] },\n * {\n * configurable: {\n * threadLimit: 5 // Override the default limit for this run\n * }\n * }\n * );\n * ```\n */\nexport declare function modelCallLimitMiddleware(middlewareOptions?: ModelCallLimitMiddlewareConfig): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n threadModelCallCount: z.ZodDefault<z.ZodNumber>;\n runModelCallCount: z.ZodDefault<z.ZodNumber>;\n}, \"strip\", z.ZodTypeAny, {\n threadModelCallCount: number;\n runModelCallCount: number;\n}, {\n threadModelCallCount?: number | undefined;\n runModelCallCount?: number | undefined;\n}>, z.ZodObject<{\n /**\n * The maximum number of model calls allowed per thread.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The maximum number of model calls allowed per run.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The behavior to take when the limit is exceeded.\n * - \"error\" will throw an error and stop the agent.\n * - \"end\" will end the agent.\n * @default \"end\"\n */\n exitBehavior: z.ZodOptional<z.ZodEnum<[\"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"error\" | undefined;\n}, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"error\" | undefined;\n}>, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"error\" | undefined;\n}, readonly (import(\"@langchain/core/tools\").ServerTool | import(\"@langchain/core/tools\").ClientTool)[]>;\nexport {};\n//# sourceMappingURL=modelCallLimit.d.ts.map"],"mappings":";;;;;;cAEcG,eAAeF,CAAAA,CAAEO;;;;EAAjBL,WAAAA,EAIGF,CAAAA,CAAEI,WAoBjB,CApB6BJ,CAAAA,CAAEG,SAoB/B,CAAA;EApB+BA;;;EAIjBC,QAAAA,EAAFJ,CAAAA,CAAEI,WAAAA,CAAYJ,CAAAA,CAAEG,SAAdC,CAAAA;EAOkBC;;;;AAfM;AAyBxC;EAAiFH,YAAAA,EAV/DF,CAAAA,CAAEI,WAU6DF,CAVjDF,CAAAA,CAAEK,OAU+CH,CAAAA,CAAAA,OAAAA,EAAAA,KAAAA,CAAAA,CAAAA,CAAAA;CAA5BD,EAAAA,OAAAA,EATzCD,CAAAA,CAAEM,UASuCL,EAAAA;EAARQ,WAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAO,QAAA,CAAA,EAAA,MAAA,GAAA,SAAA;EA6D5BC,YAAAA,CAAAA,EAAAA,KAAAA,GAAAA,OAAwB,GAAA,SAAA;CAAqBF,EAAAA;EAC5BL,WAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAbQ,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EACUR,YAAAA,CAAAA,EAAAA,KAAAA,GAAAA,OAAAA,GAAAA,SAAAA;CAAfH,CAAAA;AACTM,KAhEFE,8BAAAA,GAAiCC,OAgE/BH,CAhEuCL,oBAgEvCK,CAAAA,OAhEmEJ,aAgEnEI,CAAAA,CAAAA;;;;;;;;;;;;;AAH4H;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAlHI,wBAAAA,qBAA6CF,iDAAsER,CAAAA,CAAEO;wBACnHP,CAAAA,CAAEW,WAAWX,CAAAA,CAAEG;qBAClBH,CAAAA,CAAEW,WAAWX,CAAAA,CAAEG;YAC1BH,CAAAA,CAAEM;;;;;;IAMVN,CAAAA,CAAEO;;;;eAIWP,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEG;;;;YAInBH,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEG;;;;;;;gBAOZH,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEK;YACtBL,CAAAA,CAAEM;;;;;;;;;;;;aAhBCM,uBAAAA,CA4B8BC,UAAAA,GAAUD,uBAAAA,CAAmCE"}
1
+ {"version":3,"file":"modelCallLimit.d.cts","names":[],"sources":["../../../src/agents/middleware/modelCallLimit.ts"],"mappings":";;;;;;cAQM,aAAA,EAAa,CAAA,CAAA,SAAA;;;;;EAgBjB;;;;;;;;;;;;;;;;;;;;KACU,8BAAA,GAAiC,OAAA,CAC3C,oBAAA,QAA4B,aAAA;;;;;;;;;;;;;;;;;;;AAD9B;;;;;;;;;;;;;AAgHA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,wBAAA,CACd,iBAAA,GAAoB,8BAAA,mBAA8B,CAAA,CAAA,SAAA"}
@@ -1,5 +1,5 @@
1
1
  import { AgentMiddleware } from "./types.js";
2
- import * as _langchain_core_tools10 from "@langchain/core/tools";
2
+ import * as _langchain_core_tools0 from "@langchain/core/tools";
3
3
  import { InferInteropZodInput } from "@langchain/core/utils/types";
4
4
  import { z } from "zod/v3";
5
5
 
@@ -127,7 +127,7 @@ declare function modelCallLimitMiddleware(middlewareOptions?: ModelCallLimitMidd
127
127
  threadLimit?: number | undefined;
128
128
  runLimit?: number | undefined;
129
129
  exitBehavior?: "end" | "error" | undefined;
130
- }, readonly (_langchain_core_tools10.ServerTool | _langchain_core_tools10.ClientTool)[]>;
130
+ }, readonly (_langchain_core_tools0.ServerTool | _langchain_core_tools0.ClientTool)[]>;
131
131
  //#endregion
132
132
  export { ModelCallLimitMiddlewareConfig, modelCallLimitMiddleware };
133
133
  //# sourceMappingURL=modelCallLimit.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"modelCallLimit.d.ts","names":["__types_js13","z","InferInteropZodInput","contextSchema","ZodNumber","ZodOptional","ZodEnum","ZodTypeAny","ZodObject","ModelCallLimitMiddlewareConfig","Partial","modelCallLimitMiddleware","ZodDefault","_langchain_core_tools10","ServerTool","ClientTool","AgentMiddleware"],"sources":["../../../src/agents/middleware/modelCallLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\ndeclare const contextSchema: z.ZodObject<{\n /**\n * The maximum number of model calls allowed per thread.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The maximum number of model calls allowed per run.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The behavior to take when the limit is exceeded.\n * - \"error\" will throw an error and stop the agent.\n * - \"end\" will end the agent.\n * @default \"end\"\n */\n exitBehavior: z.ZodOptional<z.ZodEnum<[\"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"error\" | undefined;\n}, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"error\" | undefined;\n}>;\nexport type ModelCallLimitMiddlewareConfig = Partial<InferInteropZodInput<typeof contextSchema>>;\n/**\n * Creates a middleware to limit the number of model calls at both thread and run levels.\n *\n * This middleware helps prevent excessive model API calls by enforcing limits on how many\n * times the model can be invoked. It supports two types of limits:\n *\n * - **Thread-level limit**: Restricts the total number of model calls across an entire conversation thread\n * - **Run-level limit**: Restricts the number of model calls within a single agent run/invocation\n *\n * ## How It Works\n *\n * The middleware intercepts model requests before they are sent and checks the current call counts\n * against the configured limits. If either limit is exceeded, it throws a `ModelCallLimitMiddlewareError`\n * to stop execution and prevent further API calls.\n *\n * ## Use Cases\n *\n * - **Cost Control**: Prevent runaway costs from excessive model calls in production\n * - **Testing**: Ensure agents don't make too many calls during development/testing\n * - **Safety**: Limit potential infinite loops or recursive agent behaviors\n * - **Rate Limiting**: Enforce organizational policies on model usage per conversation\n *\n * @param middlewareOptions - Configuration options for the call limits\n * @param middlewareOptions.threadLimit - Maximum number of model calls allowed per thread (optional)\n * @param middlewareOptions.runLimit - Maximum number of model calls allowed per run (optional)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {ModelCallLimitMiddlewareError} When either the thread or run limit is exceeded\n *\n * @example\n * ```typescript\n * import { createAgent, modelCallLimitMiddleware } from \"langchain\";\n *\n * // Limit to 10 calls per thread and 3 calls per run\n * const agent = createAgent({\n * model: \"openai:gpt-4o-mini\",\n * tools: [myTool],\n * middleware: [\n * modelCallLimitMiddleware({\n * threadLimit: 10,\n * runLimit: 3\n * })\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Limits can also be configured at runtime via context\n * const result = await agent.invoke(\n * { messages: [\"Hello\"] },\n * {\n * configurable: {\n * threadLimit: 5 // Override the default limit for this run\n * }\n * }\n * );\n * ```\n */\nexport declare function modelCallLimitMiddleware(middlewareOptions?: ModelCallLimitMiddlewareConfig): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n threadModelCallCount: z.ZodDefault<z.ZodNumber>;\n runModelCallCount: z.ZodDefault<z.ZodNumber>;\n}, \"strip\", z.ZodTypeAny, {\n threadModelCallCount: number;\n runModelCallCount: number;\n}, {\n threadModelCallCount?: number | undefined;\n runModelCallCount?: number | undefined;\n}>, z.ZodObject<{\n /**\n * The maximum number of model calls allowed per thread.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The maximum number of model calls allowed per run.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The behavior to take when the limit is exceeded.\n * - \"error\" will throw an error and stop the agent.\n * - \"end\" will end the agent.\n * @default \"end\"\n */\n exitBehavior: z.ZodOptional<z.ZodEnum<[\"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"error\" | undefined;\n}, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"error\" | undefined;\n}>, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"error\" | undefined;\n}, readonly (import(\"@langchain/core/tools\").ServerTool | import(\"@langchain/core/tools\").ClientTool)[]>;\nexport {};\n//# sourceMappingURL=modelCallLimit.d.ts.map"],"mappings":";;;;;;cAEcG,eAAeF,CAAAA,CAAEO;;;;EAAjBL,WAAAA,EAIGF,CAAAA,CAAEI,WAoBjB,CApB6BJ,CAAAA,CAAEG,SAoB/B,CAAA;EApB+BA;;;EAIjBC,QAAAA,EAAFJ,CAAAA,CAAEI,WAAAA,CAAYJ,CAAAA,CAAEG,SAAdC,CAAAA;EAOkBC;;;;AAfM;AAyBxC;EAAiFH,YAAAA,EAV/DF,CAAAA,CAAEI,WAU6DF,CAVjDF,CAAAA,CAAEK,OAU+CH,CAAAA,CAAAA,OAAAA,EAAAA,KAAAA,CAAAA,CAAAA,CAAAA;CAA5BD,EAAAA,OAAAA,EATzCD,CAAAA,CAAEM,UASuCL,EAAAA;EAARQ,WAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAO,QAAA,CAAA,EAAA,MAAA,GAAA,SAAA;EA6D5BC,YAAAA,CAAAA,EAAAA,KAAAA,GAAAA,OAAwB,GAAA,SAAA;CAAqBF,EAAAA;EAC5BL,WAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAbQ,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EACUR,YAAAA,CAAAA,EAAAA,KAAAA,GAAAA,OAAAA,GAAAA,SAAAA;CAAfH,CAAAA;AACTM,KAhEFE,8BAAAA,GAAiCC,OAgE/BH,CAhEuCL,oBAgEvCK,CAAAA,OAhEmEJ,aAgEnEI,CAAAA,CAAAA;;;;;;;;;;;;;AAH4H;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAlHI,wBAAAA,qBAA6CF,iDAAsER,CAAAA,CAAEO;wBACnHP,CAAAA,CAAEW,WAAWX,CAAAA,CAAEG;qBAClBH,CAAAA,CAAEW,WAAWX,CAAAA,CAAEG;YAC1BH,CAAAA,CAAEM;;;;;;IAMVN,CAAAA,CAAEO;;;;eAIWP,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEG;;;;YAInBH,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEG;;;;;;;gBAOZH,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEK;YACtBL,CAAAA,CAAEM;;;;;;;;;;;;aAhBCM,uBAAAA,CA4B8BC,UAAAA,GAAUD,uBAAAA,CAAmCE"}
1
+ {"version":3,"file":"modelCallLimit.d.ts","names":[],"sources":["../../../src/agents/middleware/modelCallLimit.ts"],"mappings":";;;;;;cAQM,aAAA,EAAa,CAAA,CAAA,SAAA;;;;;EAgBjB;;;;;;;;;;;;;;;;;;;;KACU,8BAAA,GAAiC,OAAA,CAC3C,oBAAA,QAA4B,aAAA;;;;;;;;;;;;;;;;;;;AAD9B;;;;;;;;;;;;;AAgHA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,wBAAA,CACd,iBAAA,GAAoB,8BAAA,mBAA8B,CAAA,CAAA,SAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"modelCallLimit.js","names":["exceededHint: string[]","middlewareOptions?: ModelCallLimitMiddlewareConfig"],"sources":["../../../src/agents/middleware/modelCallLimit.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { AIMessage } from \"@langchain/core/messages\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\n\nimport { createMiddleware } from \"../middleware.js\";\n\nconst DEFAULT_EXIT_BEHAVIOR = \"end\";\n\nconst contextSchema = z.object({\n /**\n * The maximum number of model calls allowed per thread.\n */\n threadLimit: z.number().optional(),\n /**\n * The maximum number of model calls allowed per run.\n */\n runLimit: z.number().optional(),\n /**\n * The behavior to take when the limit is exceeded.\n * - \"error\" will throw an error and stop the agent.\n * - \"end\" will end the agent.\n * @default \"end\"\n */\n exitBehavior: z.enum([\"error\", \"end\"]).optional(),\n});\nexport type ModelCallLimitMiddlewareConfig = Partial<\n InferInteropZodInput<typeof contextSchema>\n>;\n\n/**\n * Middleware state schema to track the number of model calls made at the thread and run level.\n */\nconst stateSchema = z.object({\n threadModelCallCount: z.number().default(0),\n runModelCallCount: z.number().default(0),\n});\n\n/**\n * Error thrown when the model call limit is exceeded.\n *\n * @param threadLimit - The maximum number of model calls allowed per thread.\n * @param runLimit - The maximum number of model calls allowed per run.\n * @param threadCount - The number of model calls made at the thread level.\n * @param runCount - The number of model calls made at the run level.\n */\nclass ModelCallLimitMiddlewareError extends Error {\n constructor({\n threadLimit,\n runLimit,\n threadCount,\n runCount,\n }: {\n threadLimit?: number;\n runLimit?: number;\n threadCount?: number;\n runCount?: number;\n }) {\n const exceededHint: string[] = [];\n if (typeof threadLimit === \"number\" && typeof threadCount === \"number\") {\n exceededHint.push(\n `thread level call limit reached with ${threadCount} model calls`\n );\n }\n if (typeof runLimit === \"number\" && typeof runCount === \"number\") {\n exceededHint.push(\n `run level call limit reached with ${runCount} model calls`\n );\n }\n super(\n `Model call limits exceeded${\n exceededHint.length > 0 ? `: ${exceededHint.join(\", \")}` : \"\"\n }`\n );\n this.name = \"ModelCallLimitMiddlewareError\";\n }\n}\n\n/**\n * Creates a middleware to limit the number of model calls at both thread and run levels.\n *\n * This middleware helps prevent excessive model API calls by enforcing limits on how many\n * times the model can be invoked. It supports two types of limits:\n *\n * - **Thread-level limit**: Restricts the total number of model calls across an entire conversation thread\n * - **Run-level limit**: Restricts the number of model calls within a single agent run/invocation\n *\n * ## How It Works\n *\n * The middleware intercepts model requests before they are sent and checks the current call counts\n * against the configured limits. If either limit is exceeded, it throws a `ModelCallLimitMiddlewareError`\n * to stop execution and prevent further API calls.\n *\n * ## Use Cases\n *\n * - **Cost Control**: Prevent runaway costs from excessive model calls in production\n * - **Testing**: Ensure agents don't make too many calls during development/testing\n * - **Safety**: Limit potential infinite loops or recursive agent behaviors\n * - **Rate Limiting**: Enforce organizational policies on model usage per conversation\n *\n * @param middlewareOptions - Configuration options for the call limits\n * @param middlewareOptions.threadLimit - Maximum number of model calls allowed per thread (optional)\n * @param middlewareOptions.runLimit - Maximum number of model calls allowed per run (optional)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {ModelCallLimitMiddlewareError} When either the thread or run limit is exceeded\n *\n * @example\n * ```typescript\n * import { createAgent, modelCallLimitMiddleware } from \"langchain\";\n *\n * // Limit to 10 calls per thread and 3 calls per run\n * const agent = createAgent({\n * model: \"openai:gpt-4o-mini\",\n * tools: [myTool],\n * middleware: [\n * modelCallLimitMiddleware({\n * threadLimit: 10,\n * runLimit: 3\n * })\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Limits can also be configured at runtime via context\n * const result = await agent.invoke(\n * { messages: [\"Hello\"] },\n * {\n * configurable: {\n * threadLimit: 5 // Override the default limit for this run\n * }\n * }\n * );\n * ```\n */\nexport function modelCallLimitMiddleware(\n middlewareOptions?: ModelCallLimitMiddlewareConfig\n) {\n return createMiddleware({\n name: \"ModelCallLimitMiddleware\",\n contextSchema,\n stateSchema,\n beforeModel: {\n canJumpTo: [\"end\"],\n hook: (state, runtime) => {\n let exitBehavior =\n runtime.context.exitBehavior ??\n middlewareOptions?.exitBehavior ??\n DEFAULT_EXIT_BEHAVIOR;\n\n // @ts-expect-error - throw is deprecated\n if (exitBehavior === \"throw\") {\n console.warn(\n \"The 'throw' exit behavior is deprecated. Please use 'error' instead.\"\n );\n exitBehavior = \"error\";\n }\n\n const threadLimit =\n runtime.context.threadLimit ?? middlewareOptions?.threadLimit;\n const runLimit =\n runtime.context.runLimit ?? middlewareOptions?.runLimit;\n\n const threadCount = state.threadModelCallCount;\n const runCount = state.runModelCallCount;\n if (typeof threadLimit === \"number\" && threadLimit <= threadCount) {\n const error = new ModelCallLimitMiddlewareError({\n threadLimit,\n threadCount,\n });\n if (exitBehavior === \"end\") {\n return {\n jumpTo: \"end\",\n messages: [new AIMessage(error.message)],\n };\n }\n\n throw error;\n }\n if (typeof runLimit === \"number\" && runLimit <= runCount) {\n const error = new ModelCallLimitMiddlewareError({\n runLimit,\n runCount,\n });\n if (exitBehavior === \"end\") {\n return {\n jumpTo: \"end\",\n messages: [new AIMessage(error.message)],\n };\n }\n\n throw error;\n }\n\n return state;\n },\n },\n afterModel: (state) => ({\n runModelCallCount: state.runModelCallCount + 1,\n threadModelCallCount: state.threadModelCallCount + 1,\n }),\n afterAgent: () => ({\n runModelCallCount: 0,\n }),\n });\n}\n"],"mappings":";;;;;AAMA,MAAM,wBAAwB;AAE9B,MAAM,gBAAgB,EAAE,OAAO;CAI7B,aAAa,EAAE,QAAQ,CAAC,UAAU;CAIlC,UAAU,EAAE,QAAQ,CAAC,UAAU;CAO/B,cAAc,EAAE,KAAK,CAAC,SAAS,KAAM,EAAC,CAAC,UAAU;AAClD,EAAC;;;;AAQF,MAAM,cAAc,EAAE,OAAO;CAC3B,sBAAsB,EAAE,QAAQ,CAAC,QAAQ,EAAE;CAC3C,mBAAmB,EAAE,QAAQ,CAAC,QAAQ,EAAE;AACzC,EAAC;;;;;;;;;AAUF,IAAM,gCAAN,cAA4C,MAAM;CAChD,YAAY,EACV,aACA,UACA,aACA,UAMD,EAAE;EACD,MAAMA,eAAyB,C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AAO;GACR;EACF;EACD,YAAY,CAAC,WAAW;GACtB,mBAAmB,MAAM,oBAAoB;GAC7C,sBAAsB,MAAM,uBAAuB;EACpD;EACD,YAAY,OAAO,EACjB,mBAAmB,EACpB;CACF,EAAC;AACH"}
1
+ {"version":3,"file":"modelCallLimit.js","names":[],"sources":["../../../src/agents/middleware/modelCallLimit.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { AIMessage } from \"@langchain/core/messages\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\n\nimport { createMiddleware } from \"../middleware.js\";\n\nconst DEFAULT_EXIT_BEHAVIOR = \"end\";\n\nconst contextSchema = z.object({\n /**\n * The maximum number of model calls allowed per thread.\n */\n threadLimit: z.number().optional(),\n /**\n * The maximum number of model calls allowed per run.\n */\n runLimit: z.number().optional(),\n /**\n * The behavior to take when the limit is exceeded.\n * - \"error\" will throw an error and stop the agent.\n * - \"end\" will end the agent.\n * @default \"end\"\n */\n exitBehavior: z.enum([\"error\", \"end\"]).optional(),\n});\nexport type ModelCallLimitMiddlewareConfig = Partial<\n InferInteropZodInput<typeof contextSchema>\n>;\n\n/**\n * Middleware state schema to track the number of model calls made at the thread and run level.\n */\nconst stateSchema = z.object({\n threadModelCallCount: z.number().default(0),\n runModelCallCount: z.number().default(0),\n});\n\n/**\n * Error thrown when the model call limit is exceeded.\n *\n * @param threadLimit - The maximum number of model calls allowed per thread.\n * @param runLimit - The maximum number of model calls allowed per run.\n * @param threadCount - The number of model calls made at the thread level.\n * @param runCount - The number of model calls made at the run level.\n */\nclass ModelCallLimitMiddlewareError extends Error {\n constructor({\n threadLimit,\n runLimit,\n threadCount,\n runCount,\n }: {\n threadLimit?: number;\n runLimit?: number;\n threadCount?: number;\n runCount?: number;\n }) {\n const exceededHint: string[] = [];\n if (typeof threadLimit === \"number\" && typeof threadCount === \"number\") {\n exceededHint.push(\n `thread level call limit reached with ${threadCount} model calls`\n );\n }\n if (typeof runLimit === \"number\" && typeof runCount === \"number\") {\n exceededHint.push(\n `run level call limit reached with ${runCount} model calls`\n );\n }\n super(\n `Model call limits exceeded${\n exceededHint.length > 0 ? `: ${exceededHint.join(\", \")}` : \"\"\n }`\n );\n this.name = \"ModelCallLimitMiddlewareError\";\n }\n}\n\n/**\n * Creates a middleware to limit the number of model calls at both thread and run levels.\n *\n * This middleware helps prevent excessive model API calls by enforcing limits on how many\n * times the model can be invoked. It supports two types of limits:\n *\n * - **Thread-level limit**: Restricts the total number of model calls across an entire conversation thread\n * - **Run-level limit**: Restricts the number of model calls within a single agent run/invocation\n *\n * ## How It Works\n *\n * The middleware intercepts model requests before they are sent and checks the current call counts\n * against the configured limits. If either limit is exceeded, it throws a `ModelCallLimitMiddlewareError`\n * to stop execution and prevent further API calls.\n *\n * ## Use Cases\n *\n * - **Cost Control**: Prevent runaway costs from excessive model calls in production\n * - **Testing**: Ensure agents don't make too many calls during development/testing\n * - **Safety**: Limit potential infinite loops or recursive agent behaviors\n * - **Rate Limiting**: Enforce organizational policies on model usage per conversation\n *\n * @param middlewareOptions - Configuration options for the call limits\n * @param middlewareOptions.threadLimit - Maximum number of model calls allowed per thread (optional)\n * @param middlewareOptions.runLimit - Maximum number of model calls allowed per run (optional)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {ModelCallLimitMiddlewareError} When either the thread or run limit is exceeded\n *\n * @example\n * ```typescript\n * import { createAgent, modelCallLimitMiddleware } from \"langchain\";\n *\n * // Limit to 10 calls per thread and 3 calls per run\n * const agent = createAgent({\n * model: \"openai:gpt-4o-mini\",\n * tools: [myTool],\n * middleware: [\n * modelCallLimitMiddleware({\n * threadLimit: 10,\n * runLimit: 3\n * })\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Limits can also be configured at runtime via context\n * const result = await agent.invoke(\n * { messages: [\"Hello\"] },\n * {\n * configurable: {\n * threadLimit: 5 // Override the default limit for this run\n * }\n * }\n * );\n * ```\n */\nexport function modelCallLimitMiddleware(\n middlewareOptions?: ModelCallLimitMiddlewareConfig\n) {\n return createMiddleware({\n name: \"ModelCallLimitMiddleware\",\n contextSchema,\n stateSchema,\n beforeModel: {\n canJumpTo: [\"end\"],\n hook: (state, runtime) => {\n let exitBehavior =\n runtime.context.exitBehavior ??\n middlewareOptions?.exitBehavior ??\n DEFAULT_EXIT_BEHAVIOR;\n\n // @ts-expect-error - throw is deprecated\n if (exitBehavior === \"throw\") {\n console.warn(\n \"The 'throw' exit behavior is deprecated. Please use 'error' instead.\"\n );\n exitBehavior = \"error\";\n }\n\n const threadLimit =\n runtime.context.threadLimit ?? middlewareOptions?.threadLimit;\n const runLimit =\n runtime.context.runLimit ?? middlewareOptions?.runLimit;\n\n const threadCount = state.threadModelCallCount;\n const runCount = state.runModelCallCount;\n if (typeof threadLimit === \"number\" && threadLimit <= threadCount) {\n const error = new ModelCallLimitMiddlewareError({\n threadLimit,\n threadCount,\n });\n if (exitBehavior === \"end\") {\n return {\n jumpTo: \"end\",\n messages: [new AIMessage(error.message)],\n };\n }\n\n throw error;\n }\n if (typeof runLimit === \"number\" && runLimit <= runCount) {\n const error = new ModelCallLimitMiddlewareError({\n runLimit,\n runCount,\n });\n if (exitBehavior === \"end\") {\n return {\n jumpTo: \"end\",\n messages: [new AIMessage(error.message)],\n };\n }\n\n throw error;\n }\n\n return state;\n },\n },\n afterModel: (state) => ({\n runModelCallCount: state.runModelCallCount + 1,\n threadModelCallCount: state.threadModelCallCount + 1,\n }),\n afterAgent: () => ({\n runModelCallCount: 0,\n }),\n });\n}\n"],"mappings":";;;;;AAMA,MAAM,wBAAwB;AAE9B,MAAM,gBAAgB,EAAE,OAAO;CAI7B,aAAa,EAAE,QAAQ,CAAC,UAAU;CAIlC,UAAU,EAAE,QAAQ,CAAC,UAAU;CAO/B,cAAc,EAAE,KAAK,CAAC,SAAS,MAAM,CAAC,CAAC,UAAU;CAClD,CAAC;;;;AAQF,MAAM,cAAc,EAAE,OAAO;CAC3B,sBAAsB,EAAE,QAAQ,CAAC,QAAQ,EA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,QAAQ;MACR,UAAU,CAAC,IAAI,UAAU,MAAM,QAAQ,CAAC;MACzC;AAGH,WAAM;;AAGR,WAAO;;GAEV;EACD,aAAa,WAAW;GACtB,mBAAmB,MAAM,oBAAoB;GAC7C,sBAAsB,MAAM,uBAAuB;GACpD;EACD,mBAAmB,EACjB,mBAAmB,GACpB;EACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"modelFallback.cjs","names":["createMiddleware","initChatModel"],"sources":["../../../src/agents/middleware/modelFallback.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport type { AgentMiddleware } from \"./types.js\";\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Middleware that provides automatic model fallback on errors.\n *\n * This middleware attempts to retry failed model calls with alternative models\n * in sequence. When a model call fails, it tries the next model in the fallback\n * list until either a call succeeds or all models have been exhausted.\n *\n * @example\n * ```ts\n * import { createAgent, modelFallbackMiddleware } from \"langchain\";\n *\n * // Create middleware with fallback models (not including primary)\n * const fallback = modelFallbackMiddleware(\n * \"openai:gpt-4o-mini\", // First fallback\n * \"anthropic:claude-sonnet-4-5-20250929\", // Second fallback\n * );\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\", // Primary model\n * middleware: [fallback],\n * tools: [],\n * });\n *\n * // If gpt-4o fails, automatically tries gpt-4o-mini, then claude\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Hello\" }]\n * });\n * ```\n *\n * @param fallbackModels - The fallback models to try, in order.\n * @returns A middleware instance that handles model failures with fallbacks\n */\nexport function modelFallbackMiddleware(\n /**\n * The fallback models to try, in order.\n */\n ...fallbackModels: (string | LanguageModelLike)[]\n): AgentMiddleware {\n return createMiddleware({\n name: \"modelFallbackMiddleware\",\n wrapModelCall: async (request, handler) => {\n /**\n * Try the primary model first\n */\n try {\n return await handler(request);\n } catch (error) {\n /**\n * If primary model fails, try fallback models in sequence\n */\n for (let i = 0; i < fallbackModels.length; i++) {\n try {\n const fallbackModel = fallbackModels[i];\n const model =\n typeof fallbackModel === \"string\"\n ? await initChatModel(fallbackModel)\n : fallbackModel;\n\n return await handler({\n ...request,\n model,\n });\n } catch (fallbackError) {\n /**\n * If this is the last fallback, throw the error\n */\n if (i === fallbackModels.length - 1) {\n throw fallbackError;\n }\n // Otherwise, continue to next fallback\n }\n }\n /**\n * If no fallbacks were provided, re-throw the original error\n */\n throw error;\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,wBAId,GAAG,gBACc;AACjB,QAAOA,oCAAiB;EACtB,MAAM;EACN,eAAe,OAAO,SAAS,YAAY;;;;AAIzC,OAAI;AACF,WAAO,MAAM,QAAQ,QAAQ;GAC9B,SAAQ,OAAO;;;;AAId,SAAK,IAAI,IAAI,GAAG,IAAI,eAAe,QAAQ,IACzC,KAAI;KACF,MAAM,gBAAgB,eAAe;KACrC,MAAM,QACJ,OAAO,kBAAkB,WACrB,MAAMC,4CAAc,cAAc,GAClC;AAEN,YAAO,MAAM,QAAQ;MACnB,GAAG;MACH;KACD,EAAC;IACH,SAAQ,eAAe;;;;AAItB,SAAI,MAAM,eAAe,SAAS,EAChC,OAAM;IAGT;;;;AAKH,UAAM;GACP;EACF;CACF,EAAC;AACH"}
1
+ {"version":3,"file":"modelFallback.cjs","names":["createMiddleware","initChatModel"],"sources":["../../../src/agents/middleware/modelFallback.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport type { AgentMiddleware } from \"./types.js\";\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Middleware that provides automatic model fallback on errors.\n *\n * This middleware attempts to retry failed model calls with alternative models\n * in sequence. When a model call fails, it tries the next model in the fallback\n * list until either a call succeeds or all models have been exhausted.\n *\n * @example\n * ```ts\n * import { createAgent, modelFallbackMiddleware } from \"langchain\";\n *\n * // Create middleware with fallback models (not including primary)\n * const fallback = modelFallbackMiddleware(\n * \"openai:gpt-4o-mini\", // First fallback\n * \"anthropic:claude-sonnet-4-5-20250929\", // Second fallback\n * );\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\", // Primary model\n * middleware: [fallback],\n * tools: [],\n * });\n *\n * // If gpt-4o fails, automatically tries gpt-4o-mini, then claude\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Hello\" }]\n * });\n * ```\n *\n * @param fallbackModels - The fallback models to try, in order.\n * @returns A middleware instance that handles model failures with fallbacks\n */\nexport function modelFallbackMiddleware(\n /**\n * The fallback models to try, in order.\n */\n ...fallbackModels: (string | LanguageModelLike)[]\n): AgentMiddleware {\n return createMiddleware({\n name: \"modelFallbackMiddleware\",\n wrapModelCall: async (request, handler) => {\n /**\n * Try the primary model first\n */\n try {\n return await handler(request);\n } catch (error) {\n /**\n * If primary model fails, try fallback models in sequence\n */\n for (let i = 0; i < fallbackModels.length; i++) {\n try {\n const fallbackModel = fallbackModels[i];\n const model =\n typeof fallbackModel === \"string\"\n ? await initChatModel(fallbackModel)\n : fallbackModel;\n\n return await handler({\n ...request,\n model,\n });\n } catch (fallbackError) {\n /**\n * If this is the last fallback, throw the error\n */\n if (i === fallbackModels.length - 1) {\n throw fallbackError;\n }\n // Otherwise, continue to next fallback\n }\n }\n /**\n * If no fallbacks were provided, re-throw the original error\n */\n throw error;\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,wBAId,GAAG,gBACc;AACjB,QAAOA,oCAAiB;EACtB,MAAM;EACN,eAAe,OAAO,SAAS,YAAY;;;;AAIzC,OAAI;AACF,WAAO,MAAM,QAAQ,QAAQ;YACtB,OAAO;;;;AAId,SAAK,IAAI,IAAI,GAAG,IAAI,eAAe,QAAQ,IACzC,KAAI;KACF,MAAM,gBAAgB,eAAe;KACrC,MAAM,QACJ,OAAO,kBAAkB,WACrB,MAAMC,4CAAc,cAAc,GAClC;AAEN,YAAO,MAAM,QAAQ;MACnB,GAAG;MACH;MACD,CAAC;aACK,eAAe;;;;AAItB,SAAI,MAAM,eAAe,SAAS,EAChC,OAAM;;;;;AAQZ,UAAM;;;EAGX,CAAC"}
@@ -2,7 +2,6 @@ import { AgentMiddleware } from "./types.cjs";
2
2
  import { LanguageModelLike } from "@langchain/core/language_models/base";
3
3
 
4
4
  //#region src/agents/middleware/modelFallback.d.ts
5
-
6
5
  /**
7
6
  * Middleware that provides automatic model fallback on errors.
8
7
  *
@@ -1 +1 @@
1
- {"version":3,"file":"modelFallback.d.cts","names":["LanguageModelLike","AgentMiddleware","modelFallbackMiddleware"],"sources":["../../../src/agents/middleware/modelFallback.d.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { AgentMiddleware } from \"./types.js\";\n/**\n * Middleware that provides automatic model fallback on errors.\n *\n * This middleware attempts to retry failed model calls with alternative models\n * in sequence. When a model call fails, it tries the next model in the fallback\n * list until either a call succeeds or all models have been exhausted.\n *\n * @example\n * ```ts\n * import { createAgent, modelFallbackMiddleware } from \"langchain\";\n *\n * // Create middleware with fallback models (not including primary)\n * const fallback = modelFallbackMiddleware(\n * \"openai:gpt-4o-mini\", // First fallback\n * \"anthropic:claude-sonnet-4-5-20250929\", // Second fallback\n * );\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\", // Primary model\n * middleware: [fallback],\n * tools: [],\n * });\n *\n * // If gpt-4o fails, automatically tries gpt-4o-mini, then claude\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Hello\" }]\n * });\n * ```\n *\n * @param fallbackModels - The fallback models to try, in order.\n * @returns A middleware instance that handles model failures with fallbacks\n */\nexport declare function modelFallbackMiddleware(\n/**\n * The fallback models to try, in order.\n */\n...fallbackModels: (string | LanguageModelLike)[]): AgentMiddleware;\n//# sourceMappingURL=modelFallback.d.ts.map"],"mappings":";;;;;;;AAkCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAwBE,uBAAAA;;;;6BAIKF,uBAAuBC"}
1
+ {"version":3,"file":"modelFallback.d.cts","names":[],"sources":["../../../src/agents/middleware/modelFallback.ts"],"mappings":";;;;;;AAqCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,uBAAA;;;;GAIX,cAAA,YAA0B,iBAAA,MAC5B,eAAA"}
@@ -2,7 +2,6 @@ import { AgentMiddleware } from "./types.js";
2
2
  import { LanguageModelLike } from "@langchain/core/language_models/base";
3
3
 
4
4
  //#region src/agents/middleware/modelFallback.d.ts
5
-
6
5
  /**
7
6
  * Middleware that provides automatic model fallback on errors.
8
7
  *
@@ -1 +1 @@
1
- {"version":3,"file":"modelFallback.d.ts","names":["LanguageModelLike","AgentMiddleware","modelFallbackMiddleware"],"sources":["../../../src/agents/middleware/modelFallback.d.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { AgentMiddleware } from \"./types.js\";\n/**\n * Middleware that provides automatic model fallback on errors.\n *\n * This middleware attempts to retry failed model calls with alternative models\n * in sequence. When a model call fails, it tries the next model in the fallback\n * list until either a call succeeds or all models have been exhausted.\n *\n * @example\n * ```ts\n * import { createAgent, modelFallbackMiddleware } from \"langchain\";\n *\n * // Create middleware with fallback models (not including primary)\n * const fallback = modelFallbackMiddleware(\n * \"openai:gpt-4o-mini\", // First fallback\n * \"anthropic:claude-sonnet-4-5-20250929\", // Second fallback\n * );\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\", // Primary model\n * middleware: [fallback],\n * tools: [],\n * });\n *\n * // If gpt-4o fails, automatically tries gpt-4o-mini, then claude\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Hello\" }]\n * });\n * ```\n *\n * @param fallbackModels - The fallback models to try, in order.\n * @returns A middleware instance that handles model failures with fallbacks\n */\nexport declare function modelFallbackMiddleware(\n/**\n * The fallback models to try, in order.\n */\n...fallbackModels: (string | LanguageModelLike)[]): AgentMiddleware;\n//# sourceMappingURL=modelFallback.d.ts.map"],"mappings":";;;;;;;AAkCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAwBE,uBAAAA;;;;6BAIKF,uBAAuBC"}
1
+ {"version":3,"file":"modelFallback.d.ts","names":[],"sources":["../../../src/agents/middleware/modelFallback.ts"],"mappings":";;;;;;AAqCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,uBAAA;;;;GAIX,cAAA,YAA0B,iBAAA,MAC5B,eAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"modelFallback.js","names":[],"sources":["../../../src/agents/middleware/modelFallback.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport type { AgentMiddleware } from \"./types.js\";\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Middleware that provides automatic model fallback on errors.\n *\n * This middleware attempts to retry failed model calls with alternative models\n * in sequence. When a model call fails, it tries the next model in the fallback\n * list until either a call succeeds or all models have been exhausted.\n *\n * @example\n * ```ts\n * import { createAgent, modelFallbackMiddleware } from \"langchain\";\n *\n * // Create middleware with fallback models (not including primary)\n * const fallback = modelFallbackMiddleware(\n * \"openai:gpt-4o-mini\", // First fallback\n * \"anthropic:claude-sonnet-4-5-20250929\", // Second fallback\n * );\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\", // Primary model\n * middleware: [fallback],\n * tools: [],\n * });\n *\n * // If gpt-4o fails, automatically tries gpt-4o-mini, then claude\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Hello\" }]\n * });\n * ```\n *\n * @param fallbackModels - The fallback models to try, in order.\n * @returns A middleware instance that handles model failures with fallbacks\n */\nexport function modelFallbackMiddleware(\n /**\n * The fallback models to try, in order.\n */\n ...fallbackModels: (string | LanguageModelLike)[]\n): AgentMiddleware {\n return createMiddleware({\n name: \"modelFallbackMiddleware\",\n wrapModelCall: async (request, handler) => {\n /**\n * Try the primary model first\n */\n try {\n return await handler(request);\n } catch (error) {\n /**\n * If primary model fails, try fallback models in sequence\n */\n for (let i = 0; i < fallbackModels.length; i++) {\n try {\n const fallbackModel = fallbackModels[i];\n const model =\n typeof fallbackModel === \"string\"\n ? await initChatModel(fallbackModel)\n : fallbackModel;\n\n return await handler({\n ...request,\n model,\n });\n } catch (fallbackError) {\n /**\n * If this is the last fallback, throw the error\n */\n if (i === fallbackModels.length - 1) {\n throw fallbackError;\n }\n // Otherwise, continue to next fallback\n }\n }\n /**\n * If no fallbacks were provided, re-throw the original error\n */\n throw error;\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,wBAId,GAAG,gBACc;AACjB,QAAO,iBAAiB;EACtB,MAAM;EACN,eAAe,OAAO,SAAS,YAAY;;;;AAIzC,OAAI;AACF,WAAO,MAAM,QAAQ,QAAQ;GAC9B,SAAQ,OAAO;;;;AAId,SAAK,IAAI,IAAI,GAAG,IAAI,eAAe,QAAQ,IACzC,KAAI;KACF,MAAM,gBAAgB,eAAe;KACrC,MAAM,QACJ,OAAO,kBAAkB,WACrB,MAAM,cAAc,cAAc,GAClC;AAEN,YAAO,MAAM,QAAQ;MACnB,GAAG;MACH;KACD,EAAC;IACH,SAAQ,eAAe;;;;AAItB,SAAI,MAAM,eAAe,SAAS,EAChC,OAAM;IAGT;;;;AAKH,UAAM;GACP;EACF;CACF,EAAC;AACH"}
1
+ {"version":3,"file":"modelFallback.js","names":[],"sources":["../../../src/agents/middleware/modelFallback.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport type { AgentMiddleware } from \"./types.js\";\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Middleware that provides automatic model fallback on errors.\n *\n * This middleware attempts to retry failed model calls with alternative models\n * in sequence. When a model call fails, it tries the next model in the fallback\n * list until either a call succeeds or all models have been exhausted.\n *\n * @example\n * ```ts\n * import { createAgent, modelFallbackMiddleware } from \"langchain\";\n *\n * // Create middleware with fallback models (not including primary)\n * const fallback = modelFallbackMiddleware(\n * \"openai:gpt-4o-mini\", // First fallback\n * \"anthropic:claude-sonnet-4-5-20250929\", // Second fallback\n * );\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\", // Primary model\n * middleware: [fallback],\n * tools: [],\n * });\n *\n * // If gpt-4o fails, automatically tries gpt-4o-mini, then claude\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Hello\" }]\n * });\n * ```\n *\n * @param fallbackModels - The fallback models to try, in order.\n * @returns A middleware instance that handles model failures with fallbacks\n */\nexport function modelFallbackMiddleware(\n /**\n * The fallback models to try, in order.\n */\n ...fallbackModels: (string | LanguageModelLike)[]\n): AgentMiddleware {\n return createMiddleware({\n name: \"modelFallbackMiddleware\",\n wrapModelCall: async (request, handler) => {\n /**\n * Try the primary model first\n */\n try {\n return await handler(request);\n } catch (error) {\n /**\n * If primary model fails, try fallback models in sequence\n */\n for (let i = 0; i < fallbackModels.length; i++) {\n try {\n const fallbackModel = fallbackModels[i];\n const model =\n typeof fallbackModel === \"string\"\n ? await initChatModel(fallbackModel)\n : fallbackModel;\n\n return await handler({\n ...request,\n model,\n });\n } catch (fallbackError) {\n /**\n * If this is the last fallback, throw the error\n */\n if (i === fallbackModels.length - 1) {\n throw fallbackError;\n }\n // Otherwise, continue to next fallback\n }\n }\n /**\n * If no fallbacks were provided, re-throw the original error\n */\n throw error;\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,wBAId,GAAG,gBACc;AACjB,QAAO,iBAAiB;EACtB,MAAM;EACN,eAAe,OAAO,SAAS,YAAY;;;;AAIzC,OAAI;AACF,WAAO,MAAM,QAAQ,QAAQ;YACtB,OAAO;;;;AAId,SAAK,IAAI,IAAI,GAAG,IAAI,eAAe,QAAQ,IACzC,KAAI;KACF,MAAM,gBAAgB,eAAe;KACrC,MAAM,QACJ,OAAO,kBAAkB,WACrB,MAAM,cAAc,cAAc,GAClC;AAEN,YAAO,MAAM,QAAQ;MACnB,GAAG;MACH;MACD,CAAC;aACK,eAAe;;;;AAItB,SAAI,MAAM,eAAe,SAAS,EAChC,OAAM;;;;;AAQZ,UAAM;;;EAGX,CAAC"}
@@ -1,13 +1,16 @@
1
- const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
1
+ const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
2
2
  const require_utils = require('./utils.cjs');
3
3
  const require_middleware = require('../middleware.cjs');
4
4
  const require_constants = require('./constants.cjs');
5
5
  const require_error = require('./error.cjs');
6
- const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
7
- const zod_v3 = require_rolldown_runtime.__toESM(require("zod/v3"));
6
+ let _langchain_core_messages = require("@langchain/core/messages");
7
+ let zod_v3 = require("zod/v3");
8
8
 
9
9
  //#region src/agents/middleware/modelRetry.ts
10
10
  /**
11
+ * Model retry middleware for agents.
12
+ */
13
+ /**
11
14
  * Configuration options for the Model Retry Middleware.
12
15
  */
13
16
  const ModelRetryMiddlewareOptionsSchema = zod_v3.z.object({ onFailure: zod_v3.z.union([
@@ -109,9 +112,9 @@ function modelRetryMiddleware(config = {}) {
109
112
  /**
110
113
  * Check if the exception should trigger a retry.
111
114
  */
112
- const shouldRetryException = (error$1) => {
113
- if (typeof retryOn === "function") return retryOn(error$1);
114
- return retryOn.some((ErrorConstructor) => error$1.constructor === ErrorConstructor);
115
+ const shouldRetryException = (error) => {
116
+ if (typeof retryOn === "function") return retryOn(error);
117
+ return retryOn.some((ErrorConstructor) => error.constructor === ErrorConstructor);
115
118
  };
116
119
  const delayConfig = {
117
120
  backoffFactor,
@@ -122,20 +125,19 @@ function modelRetryMiddleware(config = {}) {
122
125
  /**
123
126
  * Format the failure message when retries are exhausted.
124
127
  */
125
- const formatFailureMessage = (error$1, attemptsMade) => {
126
- const errorType = error$1.constructor.name;
127
- const attemptWord = attemptsMade === 1 ? "attempt" : "attempts";
128
- return `Model call failed after ${attemptsMade} ${attemptWord} with ${errorType}: ${error$1.message}`;
128
+ const formatFailureMessage = (error, attemptsMade) => {
129
+ const errorType = error.constructor.name;
130
+ return `Model call failed after ${attemptsMade} ${attemptsMade === 1 ? "attempt" : "attempts"} with ${errorType}: ${error.message}`;
129
131
  };
130
132
  /**
131
133
  * Handle failure when all retries are exhausted.
132
134
  */
133
- const handleFailure = (error$1, attemptsMade) => {
134
- if (onFailure === "error") throw error$1;
135
+ const handleFailure = (error, attemptsMade) => {
136
+ if (onFailure === "error") throw error;
135
137
  let content;
136
- if (typeof onFailure === "function") content = onFailure(error$1);
137
- else content = formatFailureMessage(error$1, attemptsMade);
138
- return new __langchain_core_messages.AIMessage({ content });
138
+ if (typeof onFailure === "function") content = onFailure(error);
139
+ else content = formatFailureMessage(error, attemptsMade);
140
+ return new _langchain_core_messages.AIMessage({ content });
139
141
  };
140
142
  return require_middleware.createMiddleware({
141
143
  name: "modelRetryMiddleware",
@@ -143,9 +145,9 @@ function modelRetryMiddleware(config = {}) {
143
145
  wrapModelCall: async (request, handler) => {
144
146
  for (let attempt = 0; attempt <= maxRetries; attempt++) try {
145
147
  return await handler(request);
146
- } catch (error$1) {
148
+ } catch (error) {
147
149
  const attemptsMade = attempt + 1;
148
- const err = error$1 && typeof error$1 === "object" && "message" in error$1 ? error$1 : new Error(String(error$1));
150
+ const err = error && typeof error === "object" && "message" in error ? error : new Error(String(error));
149
151
  if (!shouldRetryException(err)) return handleFailure(err, attemptsMade);
150
152
  if (attempt < maxRetries) {
151
153
  const delay = require_utils.calculateRetryDelay(delayConfig, attempt);
@@ -1 +1 @@
1
- {"version":3,"file":"modelRetry.cjs","names":["z","RetrySchema","config: ModelRetryMiddlewareConfig","InvalidRetryConfigError","error: Error","error","attemptsMade: number","content: string","AIMessage","createMiddleware","calculateRetryDelay","sleep"],"sources":["../../../src/agents/middleware/modelRetry.ts"],"sourcesContent":["/**\n * Model retry middleware for agents.\n */\nimport { z } from \"zod/v3\";\nimport { AIMessage } from \"@langchain/core/messages\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport type { AgentMiddleware } from \"./types.js\";\nimport { sleep, calculateRetryDelay } from \"./utils.js\";\nimport { RetrySchema } from \"./constants.js\";\nimport { InvalidRetryConfigError } from \"./error.js\";\n\n/**\n * Configuration options for the Model Retry Middleware.\n */\nexport const ModelRetryMiddlewareOptionsSchema = z\n .object({\n /**\n * Behavior when all retries are exhausted. Options:\n * - `\"continue\"` (default): Return an AIMessage with error details, allowing\n * the agent to potentially handle the failure gracefully.\n * - `\"error\"`: Re-raise the exception, stopping agent execution.\n * - Custom function: Function that takes the exception and returns a string\n * for the AIMessage content, allowing custom error formatting.\n */\n onFailure: z\n .union([\n z.literal(\"error\"),\n z.literal(\"continue\"),\n z.function().args(z.instanceof(Error)).returns(z.string()),\n ])\n .default(\"continue\"),\n })\n .merge(RetrySchema);\n\nexport type ModelRetryMiddlewareConfig = z.input<\n typeof ModelRetryMiddlewareOptionsSchema\n>;\n\n/**\n * Middleware that automatically retries failed model calls with configurable backoff.\n *\n * Supports retrying on specific exceptions and exponential backoff.\n *\n * @example Basic usage with default settings (2 retries, exponential backoff)\n * ```ts\n * import { createAgent, modelRetryMiddleware } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [searchTool],\n * middleware: [modelRetryMiddleware()],\n * });\n * ```\n *\n * @example Retry specific exceptions only\n * ```ts\n * import { modelRetryMiddleware } from \"langchain\";\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * retryOn: [TimeoutError, NetworkError],\n * backoffFactor: 1.5,\n * });\n * ```\n *\n * @example Custom exception filtering\n * ```ts\n * function shouldRetry(error: Error): boolean {\n * // Only retry on rate limit errors\n * if (error.name === \"RateLimitError\") {\n * return true;\n * }\n * // Or check for specific HTTP status codes\n * if (error.name === \"HTTPError\" && \"statusCode\" in error) {\n * const statusCode = (error as any).statusCode;\n * return statusCode === 429 || statusCode === 503;\n * }\n * return false;\n * }\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 3,\n * retryOn: shouldRetry,\n * });\n * ```\n *\n * @example Return error message instead of raising\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * onFailure: \"continue\", // Return AIMessage with error instead of throwing\n * });\n * ```\n *\n * @example Custom error message formatting\n * ```ts\n * const formatError = (error: Error) =>\n * `Model call failed: ${error.message}. Please try again later.`;\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * onFailure: formatError,\n * });\n * ```\n *\n * @example Constant backoff (no exponential growth)\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 5,\n * backoffFactor: 0.0, // No exponential growth\n * initialDelayMs: 2000, // Always wait 2 seconds\n * });\n * ```\n *\n * @example Raise exception on failure\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 2,\n * onFailure: \"error\", // Re-raise exception instead of returning message\n * });\n * ```\n *\n * @param config - Configuration options for the retry middleware\n * @returns A middleware instance that handles model failures with retries\n */\nexport function modelRetryMiddleware(\n config: ModelRetryMiddlewareConfig = {}\n): AgentMiddleware {\n const { success, error, data } =\n ModelRetryMiddlewareOptionsSchema.safeParse(config);\n if (!success) {\n throw new InvalidRetryConfigError(error);\n }\n const {\n maxRetries,\n retryOn,\n onFailure,\n backoffFactor,\n initialDelayMs,\n maxDelayMs,\n jitter,\n } = data;\n\n /**\n * Check if the exception should trigger a retry.\n */\n const shouldRetryException = (error: Error): boolean => {\n if (typeof retryOn === \"function\") {\n return retryOn(error);\n }\n // retryOn is an array of error constructors\n return retryOn.some(\n (ErrorConstructor) => error.constructor === ErrorConstructor\n );\n };\n\n // Use the exported calculateRetryDelay function with our config\n const delayConfig = { backoffFactor, initialDelayMs, maxDelayMs, jitter };\n\n /**\n * Format the failure message when retries are exhausted.\n */\n const formatFailureMessage = (error: Error, attemptsMade: number): string => {\n const errorType = error.constructor.name;\n const attemptWord = attemptsMade === 1 ? \"attempt\" : \"attempts\";\n return `Model call failed after ${attemptsMade} ${attemptWord} with ${errorType}: ${error.message}`;\n };\n\n /**\n * Handle failure when all retries are exhausted.\n */\n const handleFailure = (error: Error, attemptsMade: number): AIMessage => {\n if (onFailure === \"error\") {\n throw error;\n }\n\n let content: string;\n if (typeof onFailure === \"function\") {\n content = onFailure(error);\n } else {\n content = formatFailureMessage(error, attemptsMade);\n }\n\n return new AIMessage({\n content,\n });\n };\n\n return createMiddleware({\n name: \"modelRetryMiddleware\",\n contextSchema: ModelRetryMiddlewareOptionsSchema,\n wrapModelCall: async (request, handler) => {\n // Initial attempt + retries\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await handler(request);\n } catch (error) {\n const attemptsMade = attempt + 1; // attempt is 0-indexed\n\n // Ensure error is an Error instance\n const err =\n error && typeof error === \"object\" && \"message\" in error\n ? (error as Error)\n : new Error(String(error));\n\n // Check if we should retry this exception\n if (!shouldRetryException(err)) {\n // Exception is not retryable, handle failure immediately\n return handleFailure(err, attemptsMade);\n }\n\n // Check if we have more retries left\n if (attempt < maxRetries) {\n // Calculate and apply backoff delay\n const delay = calculateRetryDelay(delayConfig, attempt);\n if (delay > 0) {\n await sleep(delay);\n }\n // Continue to next retry\n } else {\n // No more retries, handle failure\n return handleFailure(err, attemptsMade);\n }\n }\n }\n\n // Unreachable: loop always returns via handler success or handleFailure\n throw new Error(\"Unexpected: retry loop completed without returning\");\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;AAeA,MAAa,oCAAoCA,SAC9C,OAAO,EASN,WAAWA,SACR,MAAM;CACLA,SAAE,QAAQ,QAAQ;CAClBA,SAAE,QAAQ,WAAW;CACrBA,SAAE,UAAU,CAAC,KAAKA,SAAE,WAAW,MAAM,CAAC,CAAC,QAAQA,SAAE,QAAQ,CAAC;AAC3D,EAAC,CACD,QAAQ,WAAW,CACvB,EAAC,CACD,MAAMC,8B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,UACD,IAAI,MAAM,OAAOA,QAAM;AAG7B,QAAI,CAAC,qBAAqB,IAAI,CAE5B,QAAO,cAAc,KAAK,aAAa;AAIzC,QAAI,UAAU,YAAY;KAExB,MAAM,QAAQK,kCAAoB,aAAa,QAAQ;AACvD,SAAI,QAAQ,GACV,MAAMC,oBAAM,MAAM;IAGrB,MAEC,QAAO,cAAc,KAAK,aAAa;GAE1C;AAIH,SAAM,IAAI,MAAM;EACjB;CACF,EAAC;AACH"}
1
+ {"version":3,"file":"modelRetry.cjs","names":["z","RetrySchema","InvalidRetryConfigError","AIMessage","createMiddleware","calculateRetryDelay","sleep"],"sources":["../../../src/agents/middleware/modelRetry.ts"],"sourcesContent":["/**\n * Model retry middleware for agents.\n */\nimport { z } from \"zod/v3\";\nimport { AIMessage } from \"@langchain/core/messages\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport type { AgentMiddleware } from \"./types.js\";\nimport { sleep, calculateRetryDelay } from \"./utils.js\";\nimport { RetrySchema } from \"./constants.js\";\nimport { InvalidRetryConfigError } from \"./error.js\";\n\n/**\n * Configuration options for the Model Retry Middleware.\n */\nexport const ModelRetryMiddlewareOptionsSchema = z\n .object({\n /**\n * Behavior when all retries are exhausted. Options:\n * - `\"continue\"` (default): Return an AIMessage with error details, allowing\n * the agent to potentially handle the failure gracefully.\n * - `\"error\"`: Re-raise the exception, stopping agent execution.\n * - Custom function: Function that takes the exception and returns a string\n * for the AIMessage content, allowing custom error formatting.\n */\n onFailure: z\n .union([\n z.literal(\"error\"),\n z.literal(\"continue\"),\n z.function().args(z.instanceof(Error)).returns(z.string()),\n ])\n .default(\"continue\"),\n })\n .merge(RetrySchema);\n\nexport type ModelRetryMiddlewareConfig = z.input<\n typeof ModelRetryMiddlewareOptionsSchema\n>;\n\n/**\n * Middleware that automatically retries failed model calls with configurable backoff.\n *\n * Supports retrying on specific exceptions and exponential backoff.\n *\n * @example Basic usage with default settings (2 retries, exponential backoff)\n * ```ts\n * import { createAgent, modelRetryMiddleware } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [searchTool],\n * middleware: [modelRetryMiddleware()],\n * });\n * ```\n *\n * @example Retry specific exceptions only\n * ```ts\n * import { modelRetryMiddleware } from \"langchain\";\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * retryOn: [TimeoutError, NetworkError],\n * backoffFactor: 1.5,\n * });\n * ```\n *\n * @example Custom exception filtering\n * ```ts\n * function shouldRetry(error: Error): boolean {\n * // Only retry on rate limit errors\n * if (error.name === \"RateLimitError\") {\n * return true;\n * }\n * // Or check for specific HTTP status codes\n * if (error.name === \"HTTPError\" && \"statusCode\" in error) {\n * const statusCode = (error as any).statusCode;\n * return statusCode === 429 || statusCode === 503;\n * }\n * return false;\n * }\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 3,\n * retryOn: shouldRetry,\n * });\n * ```\n *\n * @example Return error message instead of raising\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * onFailure: \"continue\", // Return AIMessage with error instead of throwing\n * });\n * ```\n *\n * @example Custom error message formatting\n * ```ts\n * const formatError = (error: Error) =>\n * `Model call failed: ${error.message}. Please try again later.`;\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * onFailure: formatError,\n * });\n * ```\n *\n * @example Constant backoff (no exponential growth)\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 5,\n * backoffFactor: 0.0, // No exponential growth\n * initialDelayMs: 2000, // Always wait 2 seconds\n * });\n * ```\n *\n * @example Raise exception on failure\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 2,\n * onFailure: \"error\", // Re-raise exception instead of returning message\n * });\n * ```\n *\n * @param config - Configuration options for the retry middleware\n * @returns A middleware instance that handles model failures with retries\n */\nexport function modelRetryMiddleware(\n config: ModelRetryMiddlewareConfig = {}\n): AgentMiddleware {\n const { success, error, data } =\n ModelRetryMiddlewareOptionsSchema.safeParse(config);\n if (!success) {\n throw new InvalidRetryConfigError(error);\n }\n const {\n maxRetries,\n retryOn,\n onFailure,\n backoffFactor,\n initialDelayMs,\n maxDelayMs,\n jitter,\n } = data;\n\n /**\n * Check if the exception should trigger a retry.\n */\n const shouldRetryException = (error: Error): boolean => {\n if (typeof retryOn === \"function\") {\n return retryOn(error);\n }\n // retryOn is an array of error constructors\n return retryOn.some(\n (ErrorConstructor) => error.constructor === ErrorConstructor\n );\n };\n\n // Use the exported calculateRetryDelay function with our config\n const delayConfig = { backoffFactor, initialDelayMs, maxDelayMs, jitter };\n\n /**\n * Format the failure message when retries are exhausted.\n */\n const formatFailureMessage = (error: Error, attemptsMade: number): string => {\n const errorType = error.constructor.name;\n const attemptWord = attemptsMade === 1 ? \"attempt\" : \"attempts\";\n return `Model call failed after ${attemptsMade} ${attemptWord} with ${errorType}: ${error.message}`;\n };\n\n /**\n * Handle failure when all retries are exhausted.\n */\n const handleFailure = (error: Error, attemptsMade: number): AIMessage => {\n if (onFailure === \"error\") {\n throw error;\n }\n\n let content: string;\n if (typeof onFailure === \"function\") {\n content = onFailure(error);\n } else {\n content = formatFailureMessage(error, attemptsMade);\n }\n\n return new AIMessage({\n content,\n });\n };\n\n return createMiddleware({\n name: \"modelRetryMiddleware\",\n contextSchema: ModelRetryMiddlewareOptionsSchema,\n wrapModelCall: async (request, handler) => {\n // Initial attempt + retries\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await handler(request);\n } catch (error) {\n const attemptsMade = attempt + 1; // attempt is 0-indexed\n\n // Ensure error is an Error instance\n const err =\n error && typeof error === \"object\" && \"message\" in error\n ? (error as Error)\n : new Error(String(error));\n\n // Check if we should retry this exception\n if (!shouldRetryException(err)) {\n // Exception is not retryable, handle failure immediately\n return handleFailure(err, attemptsMade);\n }\n\n // Check if we have more retries left\n if (attempt < maxRetries) {\n // Calculate and apply backoff delay\n const delay = calculateRetryDelay(delayConfig, attempt);\n if (delay > 0) {\n await sleep(delay);\n }\n // Continue to next retry\n } else {\n // No more retries, handle failure\n return handleFailure(err, attemptsMade);\n }\n }\n }\n\n // Unreachable: loop always returns via handler success or handleFailure\n throw new Error(\"Unexpected: retry loop completed without returning\");\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAeA,MAAa,oCAAoCA,SAC9C,OAAO,EASN,WAAWA,SACR,MAAM;CACLA,SAAE,QAAQ,QAAQ;CAClBA,SAAE,QAAQ,WAAW;CACrBA,SAAE,UAAU,CAAC,KAAKA,SAAE,WAAW,MAAM,CAAC,CAAC,QAAQA,SAAE,QAAQ,CAAC;CAC3D,CAAC,CACD,QAAQ,WAAW,EACvB,CAAC,CACD,MAAMC,8BAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6FrB,SAAgB,qBACd,SAAqC,EAAE,EACtB;CACjB,MAAM,EAAE,SAAS,OAAO,SACtB,kCAAkC,UAAU,OAAO;AACrD,KAAI,CAAC,QACH,OAAM,IAAIC,sCAAwB,MAAM;CAE1C,MAAM,EACJ,YACA,SACA,WACA,eACA,gBACA,YACA,WACE;;;;CAKJ,MAAM,wBAAwB,UAA0B;AACtD,MAAI,OAAO,YAAY,WACrB,QAAO,QAAQ,MAAM;AAGvB,SAAO,QAAQ,MACZ,qBAAqB,MAAM,gBAAgB,iBAC7C;;CAIH,MAAM,cAAc;EAAE;EAAe;EAAgB;EAAY;EAAQ;;;;CAKzE,MAAM,wBAAwB,OAAc,iBAAiC;EAC3E,MAAM,YAAY,MAAM,YAAY;AAEpC,SAAO,2BAA2B,aAAa,GAD3B,iBAAiB,IAAI,YAAY,WACS,QAAQ,UAAU,IAAI,MAAM;;;;;CAM5F,MAAM,iBAAiB,OAAc,iBAAoC;AACvE,MAAI,cAAc,QAChB,OAAM;EAGR,IAAI;AACJ,MAAI,OAAO,cAAc,WACvB,WAAU,UAAU,MAAM;MAE1B,WAAU,qBAAqB,OAAO,aAAa;AAGrD,SAAO,IAAIC,mCAAU,EACnB,SACD,CAAC;;AAGJ,QAAOC,oCAAiB;EACtB,MAAM;EACN,eAAe;EACf,eAAe,OAAO,SAAS,YAAY;AAEzC,QAAK,IAAI,UAAU,GAAG,WAAW,YAAY,UAC3C,KAAI;AACF,WAAO,MAAM,QAAQ,QAAQ;YACtB,OAAO;IACd,MAAM,eAAe,UAAU;IAG/B,MAAM,MACJ,SAAS,OAAO,UAAU,YAAY,aAAa,QAC9C,QACD,IAAI,MAAM,OAAO,MAAM,CAAC;AAG9B,QAAI,CAAC,qBAAqB,IAAI,CAE5B,QAAO,cAAc,KAAK,aAAa;AAIzC,QAAI,UAAU,YAAY;KAExB,MAAM,QAAQC,kCAAoB,aAAa,QAAQ;AACvD,SAAI,QAAQ,EACV,OAAMC,oBAAM,MAAM;UAKpB,QAAO,cAAc,KAAK,aAAa;;AAM7C,SAAM,IAAI,MAAM,qDAAqD;;EAExE,CAAC"}
@@ -2,7 +2,6 @@ import { AgentMiddleware } from "./types.cjs";
2
2
  import { z } from "zod/v3";
3
3
 
4
4
  //#region src/agents/middleware/modelRetry.d.ts
5
-
6
5
  /**
7
6
  * Configuration options for the Model Retry Middleware.
8
7
  */