langchain 1.0.5 → 1.1.0

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 (216) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +1 -1
  3. package/chat_models/universal.cjs +1 -0
  4. package/chat_models/universal.d.cts +1 -0
  5. package/chat_models/universal.d.ts +1 -0
  6. package/chat_models/universal.js +1 -0
  7. package/dist/agents/ReactAgent.cjs +43 -39
  8. package/dist/agents/ReactAgent.cjs.map +1 -1
  9. package/dist/agents/ReactAgent.js +46 -42
  10. package/dist/agents/ReactAgent.js.map +1 -1
  11. package/dist/agents/index.d.cts +0 -2
  12. package/dist/agents/index.d.ts +0 -2
  13. package/dist/agents/middleware/constants.cjs +16 -0
  14. package/dist/agents/middleware/constants.cjs.map +1 -0
  15. package/dist/agents/middleware/constants.js +15 -0
  16. package/dist/agents/middleware/constants.js.map +1 -0
  17. package/dist/agents/middleware/contextEditing.cjs.map +1 -1
  18. package/dist/agents/middleware/contextEditing.d.cts +23 -7
  19. package/dist/agents/middleware/contextEditing.d.ts +23 -7
  20. package/dist/agents/middleware/contextEditing.js.map +1 -1
  21. package/dist/agents/middleware/dynamicSystemPrompt.cjs +5 -2
  22. package/dist/agents/middleware/dynamicSystemPrompt.cjs.map +1 -1
  23. package/dist/agents/middleware/dynamicSystemPrompt.d.cts +2 -1
  24. package/dist/agents/middleware/dynamicSystemPrompt.d.ts +2 -1
  25. package/dist/agents/middleware/dynamicSystemPrompt.js +4 -2
  26. package/dist/agents/middleware/dynamicSystemPrompt.js.map +1 -1
  27. package/dist/agents/middleware/error.cjs +20 -0
  28. package/dist/agents/middleware/error.cjs.map +1 -0
  29. package/dist/agents/middleware/error.js +19 -0
  30. package/dist/agents/middleware/error.js.map +1 -0
  31. package/dist/agents/middleware/index.cjs +4 -2
  32. package/dist/agents/middleware/index.d.ts +18 -0
  33. package/dist/agents/middleware/index.js +4 -2
  34. package/dist/agents/middleware/modelRetry.cjs +162 -0
  35. package/dist/agents/middleware/modelRetry.cjs.map +1 -0
  36. package/dist/agents/middleware/modelRetry.d.cts +134 -0
  37. package/dist/agents/middleware/modelRetry.d.ts +134 -0
  38. package/dist/agents/middleware/modelRetry.js +161 -0
  39. package/dist/agents/middleware/modelRetry.js.map +1 -0
  40. package/dist/agents/middleware/{promptCaching.cjs → provider/anthropic/promptCaching.cjs} +3 -3
  41. package/dist/agents/middleware/provider/anthropic/promptCaching.cjs.map +1 -0
  42. package/dist/agents/middleware/{promptCaching.d.cts → provider/anthropic/promptCaching.d.cts} +2 -2
  43. package/dist/agents/middleware/{promptCaching.d.ts → provider/anthropic/promptCaching.d.ts} +2 -2
  44. package/dist/agents/middleware/{promptCaching.js → provider/anthropic/promptCaching.js} +2 -2
  45. package/dist/agents/middleware/provider/anthropic/promptCaching.js.map +1 -0
  46. package/dist/agents/middleware/provider/openai/moderation.cjs +299 -0
  47. package/dist/agents/middleware/provider/openai/moderation.cjs.map +1 -0
  48. package/dist/agents/middleware/provider/openai/moderation.d.cts +133 -0
  49. package/dist/agents/middleware/provider/openai/moderation.d.ts +133 -0
  50. package/dist/agents/middleware/provider/openai/moderation.js +298 -0
  51. package/dist/agents/middleware/provider/openai/moderation.js.map +1 -0
  52. package/dist/agents/middleware/summarization.d.cts +0 -4
  53. package/dist/agents/middleware/summarization.d.ts +0 -4
  54. package/dist/agents/middleware/todoListMiddleware.cjs +1 -1
  55. package/dist/agents/middleware/todoListMiddleware.cjs.map +1 -1
  56. package/dist/agents/middleware/todoListMiddleware.js +1 -1
  57. package/dist/agents/middleware/todoListMiddleware.js.map +1 -1
  58. package/dist/agents/middleware/toolRetry.cjs +32 -44
  59. package/dist/agents/middleware/toolRetry.cjs.map +1 -1
  60. package/dist/agents/middleware/toolRetry.d.cts +16 -36
  61. package/dist/agents/middleware/toolRetry.d.ts +16 -36
  62. package/dist/agents/middleware/toolRetry.js +32 -44
  63. package/dist/agents/middleware/toolRetry.js.map +1 -1
  64. package/dist/agents/middleware/types.d.cts +9 -10
  65. package/dist/agents/middleware/types.d.ts +9 -10
  66. package/dist/agents/middleware/utils.cjs +23 -0
  67. package/dist/agents/middleware/utils.cjs.map +1 -1
  68. package/dist/agents/middleware/utils.d.ts +2 -0
  69. package/dist/agents/middleware/utils.js +23 -1
  70. package/dist/agents/middleware/utils.js.map +1 -1
  71. package/dist/agents/nodes/AgentNode.cjs +72 -28
  72. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  73. package/dist/agents/nodes/AgentNode.js +74 -31
  74. package/dist/agents/nodes/AgentNode.js.map +1 -1
  75. package/dist/agents/nodes/ToolNode.cjs +5 -0
  76. package/dist/agents/nodes/ToolNode.cjs.map +1 -1
  77. package/dist/agents/nodes/ToolNode.js +5 -1
  78. package/dist/agents/nodes/ToolNode.js.map +1 -1
  79. package/dist/agents/nodes/types.d.cts +39 -3
  80. package/dist/agents/nodes/types.d.ts +39 -3
  81. package/dist/agents/responses.cjs.map +1 -1
  82. package/dist/agents/responses.d.cts +2 -19
  83. package/dist/agents/responses.d.ts +2 -19
  84. package/dist/agents/responses.js.map +1 -1
  85. package/dist/agents/runtime.d.ts +1 -0
  86. package/dist/agents/tests/utils.cjs +10 -1
  87. package/dist/agents/tests/utils.cjs.map +1 -1
  88. package/dist/agents/tests/utils.js +10 -1
  89. package/dist/agents/tests/utils.js.map +1 -1
  90. package/dist/agents/types.d.cts +68 -2
  91. package/dist/agents/types.d.ts +68 -2
  92. package/dist/agents/utils.cjs +15 -12
  93. package/dist/agents/utils.cjs.map +1 -1
  94. package/dist/agents/utils.js +16 -13
  95. package/dist/agents/utils.js.map +1 -1
  96. package/dist/chat_models/universal.cjs +50 -16
  97. package/dist/chat_models/universal.cjs.map +1 -1
  98. package/dist/chat_models/universal.d.cts +19 -1
  99. package/dist/chat_models/universal.d.ts +19 -1
  100. package/dist/chat_models/universal.js +50 -16
  101. package/dist/chat_models/universal.js.map +1 -1
  102. package/dist/index.cjs +8 -2
  103. package/dist/index.d.cts +5 -3
  104. package/dist/index.d.ts +6 -3
  105. package/dist/index.js +7 -3
  106. package/dist/load/import_constants.cjs +2 -1
  107. package/dist/load/import_constants.cjs.map +1 -1
  108. package/dist/load/import_constants.js +2 -1
  109. package/dist/load/import_constants.js.map +1 -1
  110. package/dist/load/import_map.cjs +2 -19
  111. package/dist/load/import_map.cjs.map +1 -1
  112. package/dist/load/import_map.js +2 -19
  113. package/dist/load/import_map.js.map +1 -1
  114. package/hub/node.cjs +1 -0
  115. package/hub/node.d.cts +1 -0
  116. package/hub/node.d.ts +1 -0
  117. package/hub/node.js +1 -0
  118. package/hub.cjs +1 -0
  119. package/hub.d.cts +1 -0
  120. package/hub.d.ts +1 -0
  121. package/hub.js +1 -0
  122. package/load/serializable.cjs +1 -0
  123. package/load/serializable.d.cts +1 -0
  124. package/load/serializable.d.ts +1 -0
  125. package/load/serializable.js +1 -0
  126. package/load.cjs +1 -0
  127. package/load.d.cts +1 -0
  128. package/load.d.ts +1 -0
  129. package/load.js +1 -0
  130. package/package.json +65 -52
  131. package/storage/encoder_backed.cjs +1 -0
  132. package/storage/encoder_backed.d.cts +1 -0
  133. package/storage/encoder_backed.d.ts +1 -0
  134. package/storage/encoder_backed.js +1 -0
  135. package/storage/file_system.cjs +1 -0
  136. package/storage/file_system.d.cts +1 -0
  137. package/storage/file_system.d.ts +1 -0
  138. package/storage/file_system.js +1 -0
  139. package/storage/in_memory.cjs +1 -0
  140. package/storage/in_memory.d.cts +1 -0
  141. package/storage/in_memory.d.ts +1 -0
  142. package/storage/in_memory.js +1 -0
  143. package/dist/agents/ReactAgent.d.cts.map +0 -1
  144. package/dist/agents/ReactAgent.d.ts.map +0 -1
  145. package/dist/agents/constants.cjs +0 -7
  146. package/dist/agents/constants.cjs.map +0 -1
  147. package/dist/agents/constants.d.cts.map +0 -1
  148. package/dist/agents/constants.d.ts.map +0 -1
  149. package/dist/agents/constants.js +0 -6
  150. package/dist/agents/constants.js.map +0 -1
  151. package/dist/agents/errors.d.cts.map +0 -1
  152. package/dist/agents/errors.d.ts.map +0 -1
  153. package/dist/agents/index.d.cts.map +0 -1
  154. package/dist/agents/index.d.ts.map +0 -1
  155. package/dist/agents/middleware/contextEditing.d.cts.map +0 -1
  156. package/dist/agents/middleware/contextEditing.d.ts.map +0 -1
  157. package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +0 -1
  158. package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +0 -1
  159. package/dist/agents/middleware/hitl.d.cts.map +0 -1
  160. package/dist/agents/middleware/hitl.d.ts.map +0 -1
  161. package/dist/agents/middleware/llmToolSelector.d.cts.map +0 -1
  162. package/dist/agents/middleware/llmToolSelector.d.ts.map +0 -1
  163. package/dist/agents/middleware/modelCallLimit.d.cts.map +0 -1
  164. package/dist/agents/middleware/modelCallLimit.d.ts.map +0 -1
  165. package/dist/agents/middleware/modelFallback.d.cts.map +0 -1
  166. package/dist/agents/middleware/modelFallback.d.ts.map +0 -1
  167. package/dist/agents/middleware/pii.d.cts.map +0 -1
  168. package/dist/agents/middleware/pii.d.ts.map +0 -1
  169. package/dist/agents/middleware/piiRedaction.d.cts.map +0 -1
  170. package/dist/agents/middleware/piiRedaction.d.ts.map +0 -1
  171. package/dist/agents/middleware/promptCaching.cjs.map +0 -1
  172. package/dist/agents/middleware/promptCaching.d.cts.map +0 -1
  173. package/dist/agents/middleware/promptCaching.d.ts.map +0 -1
  174. package/dist/agents/middleware/promptCaching.js.map +0 -1
  175. package/dist/agents/middleware/summarization.d.cts.map +0 -1
  176. package/dist/agents/middleware/summarization.d.ts.map +0 -1
  177. package/dist/agents/middleware/todoListMiddleware.d.cts.map +0 -1
  178. package/dist/agents/middleware/todoListMiddleware.d.ts.map +0 -1
  179. package/dist/agents/middleware/toolCallLimit.d.cts.map +0 -1
  180. package/dist/agents/middleware/toolCallLimit.d.ts.map +0 -1
  181. package/dist/agents/middleware/toolEmulator.d.cts.map +0 -1
  182. package/dist/agents/middleware/toolEmulator.d.ts.map +0 -1
  183. package/dist/agents/middleware/toolRetry.d.cts.map +0 -1
  184. package/dist/agents/middleware/toolRetry.d.ts.map +0 -1
  185. package/dist/agents/middleware/types.d.cts.map +0 -1
  186. package/dist/agents/middleware/types.d.ts.map +0 -1
  187. package/dist/agents/middleware/utils.d.cts.map +0 -1
  188. package/dist/agents/middleware/utils.d.ts.map +0 -1
  189. package/dist/agents/middleware.d.cts.map +0 -1
  190. package/dist/agents/middleware.d.ts.map +0 -1
  191. package/dist/agents/nodes/types.d.cts.map +0 -1
  192. package/dist/agents/nodes/types.d.ts.map +0 -1
  193. package/dist/agents/responses.d.cts.map +0 -1
  194. package/dist/agents/responses.d.ts.map +0 -1
  195. package/dist/agents/runtime.d.cts.map +0 -1
  196. package/dist/agents/runtime.d.ts.map +0 -1
  197. package/dist/agents/tests/utils.d.cts.map +0 -1
  198. package/dist/agents/tests/utils.d.ts.map +0 -1
  199. package/dist/agents/types.d.cts.map +0 -1
  200. package/dist/agents/types.d.ts.map +0 -1
  201. package/dist/chat_models/universal.d.cts.map +0 -1
  202. package/dist/chat_models/universal.d.ts.map +0 -1
  203. package/dist/hub/base.d.cts.map +0 -1
  204. package/dist/hub/base.d.ts.map +0 -1
  205. package/dist/hub/index.d.cts.map +0 -1
  206. package/dist/hub/index.d.ts.map +0 -1
  207. package/dist/hub/node.d.cts.map +0 -1
  208. package/dist/hub/node.d.ts.map +0 -1
  209. package/dist/load/import_type.d.cts.map +0 -1
  210. package/dist/load/import_type.d.ts.map +0 -1
  211. package/dist/load/index.d.cts.map +0 -1
  212. package/dist/load/index.d.ts.map +0 -1
  213. package/dist/storage/encoder_backed.d.cts.map +0 -1
  214. package/dist/storage/encoder_backed.d.ts.map +0 -1
  215. package/dist/storage/file_system.d.cts.map +0 -1
  216. package/dist/storage/file_system.d.ts.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","names":["InteropZodObject","InteropZodType","ResponseFormatUndefined","CreateAgentParams","AgentMiddleware","AnyAnnotationRoot","ExtractZodArrayTypes","ToolStrategy","TypedToolStrategy","ProviderStrategy","ResponseFormat","JsonSchemaFormat","ReactAgent","createAgent","Record","T","StateSchema","ContextSchema","TMiddleware","Omit","StructuredResponseFormat","JumpToTarget","Runtime","toolStrategy","providerStrategy","createMiddleware","ToolCallRequest","ToolCallHandler","WrapToolCallHook","FakeToolCallingModel"],"sources":["../../src/agents/index.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { ResponseFormatUndefined } from \"./responses.js\";\nimport type { CreateAgentParams } from \"./types.js\";\nimport type { AgentMiddleware, AnyAnnotationRoot } from \"./middleware/types.js\";\nimport type { ExtractZodArrayTypes } from \"./types.js\";\nimport type { ToolStrategy, TypedToolStrategy, ProviderStrategy, ResponseFormat, JsonSchemaFormat } from \"./responses.js\";\nimport { ReactAgent } from \"./ReactAgent.js\";\n/**\n * Creates a production-ready ReAct (Reasoning + Acting) agent that combines language models with tools\n * and middleware to create systems that can reason about tasks, decide which tools to use, and iteratively\n * work towards solutions.\n *\n * The agent follows the ReAct pattern, interleaving reasoning steps with tool calls to iteratively\n * work towards solutions. It can handle multiple tool calls in sequence or parallel, maintain state\n * across interactions, and provide auditable decision processes.\n *\n * ## Core Components\n *\n * ### Model\n * The reasoning engine can be specified as:\n * - **String identifier**: `\"openai:gpt-4o\"` for simple setup\n * - **Model instance**: Configured model object for full control\n * - **Dynamic function**: Select models at runtime based on state\n *\n * ### Tools\n * Tools give agents the ability to take actions:\n * - Pass an array of tools created with the `tool` function\n * - Or provide a configured `ToolNode` for custom error handling\n *\n * ### Prompt\n * Shape how your agent approaches tasks:\n * - String for simple instructions\n * - SystemMessage for structured prompts\n * - Function for dynamic prompts based on state\n *\n * ### Middleware\n * Middleware allows you to extend the agent's behavior:\n * - Add pre/post-model processing for context injection or validation\n * - Add dynamic control flows, e.g. terminate invocation or retries\n * - Add human-in-the-loop capabilities\n * - Add tool calls to the agent\n * - Add tool results to the agent\n *\n * ## Advanced Features\n *\n * - **Structured Output**: Use `responseFormat` with a Zod schema to get typed responses\n * - **Memory**: Extend the state schema to remember information across interactions\n * - **Streaming**: Get real-time updates as the agent processes\n *\n * @param options - Configuration options for the agent\n * @param options.llm - The language model as an instance of a chat model\n * @param options.model - The language model as a string identifier, see more in {@link https://docs.langchain.com/oss/javascript/langchain/models#basic-usage | Models}.\n * @param options.tools - Array of tools or configured ToolNode\n * @param options.prompt - System instructions (string, SystemMessage, or function)\n * @param options.responseFormat - Zod schema for structured output\n * @param options.stateSchema - Custom state schema for memory\n * @param options.middleware - Array of middleware for extending agent behavior, see more in {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}.\n *\n * @returns A ReactAgent instance with `invoke` and `stream` methods\n *\n * @example Basic agent with tools\n * ```ts\n * import { createAgent, tool } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const search = tool(\n * ({ query }) => `Results for: ${query}`,\n * {\n * name: \"search\",\n * description: \"Search for information\",\n * schema: z.object({\n * query: z.string().describe(\"The search query\"),\n * })\n * }\n * );\n *\n * const agent = createAgent({\n * llm: \"openai:gpt-4o\",\n * tools: [search],\n * });\n *\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Search for ReAct agents\" }],\n * });\n * ```\n *\n * @example Structured output\n * ```ts\n * import { createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const ContactInfo = z.object({\n * name: z.string(),\n * email: z.string(),\n * phone: z.string(),\n * });\n *\n * const agent = createAgent({\n * llm: \"openai:gpt-4o\",\n * tools: [],\n * responseFormat: ContactInfo,\n * });\n *\n * const result = await agent.invoke({\n * messages: [{\n * role: \"user\",\n * content: \"Extract: John Doe, john@example.com, (555) 123-4567\"\n * }],\n * });\n *\n * console.log(result.structuredResponse);\n * // { name: 'John Doe', email: 'john@example.com', phone: '(555) 123-4567' }\n * ```\n *\n * @example Streaming responses\n * ```ts\n * const stream = await agent.stream(\n * { messages: [{ role: \"user\", content: \"What's the weather?\" }] },\n * { streamMode: \"values\" }\n * );\n *\n * for await (const chunk of stream) {\n * // ...\n * }\n * ```\n */\n// Overload 1: With responseFormat as single InteropZodType\nexport declare function createAgent<T extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<T, StateSchema, ContextSchema, InteropZodType<T>> & {\n responseFormat: InteropZodType<T>;\n middleware?: TMiddleware;\n}): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)\nexport declare function createAgent<T extends readonly InteropZodType<any>[], StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<ExtractZodArrayTypes<T> extends Record<string, any> ? ExtractZodArrayTypes<T> : Record<string, any>, StateSchema, ContextSchema, T> & {\n responseFormat: T;\n middleware?: TMiddleware;\n}): ReactAgent<ExtractZodArrayTypes<T> extends Record<string, any> ? ExtractZodArrayTypes<T> : Record<string, any>, StateSchema, ContextSchema, TMiddleware>;\n// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)\nexport declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<Record<string, unknown>, StateSchema, ContextSchema, JsonSchemaFormat> & {\n responseFormat: JsonSchemaFormat;\n middleware?: TMiddleware;\n}): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)\nexport declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<Record<string, unknown>, StateSchema, ContextSchema, JsonSchemaFormat[]> & {\n responseFormat: JsonSchemaFormat[];\n middleware?: TMiddleware;\n}): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]\nexport declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<Record<string, unknown>, StateSchema, ContextSchema, JsonSchemaFormat | JsonSchemaFormat[]> & {\n responseFormat: JsonSchemaFormat | JsonSchemaFormat[];\n middleware?: TMiddleware;\n}): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)\nexport declare function createAgent<T extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<T, StateSchema, ContextSchema, TypedToolStrategy<T>> & {\n responseFormat: TypedToolStrategy<T>;\n middleware?: TMiddleware;\n}): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n// Overload 6: With responseFormat as single ToolStrategy instance\nexport declare function createAgent<T extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<T, StateSchema, ContextSchema, ToolStrategy<T>> & {\n responseFormat: ToolStrategy<T>;\n middleware?: TMiddleware;\n}): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n// Overload 7: With responseFormat as ProviderStrategy\nexport declare function createAgent<T extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<T, StateSchema, ContextSchema, ProviderStrategy<T>> & {\n responseFormat: ProviderStrategy<T>;\n middleware?: TMiddleware;\n}): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n// Overload 8: Without responseFormat property at all - with proper middleware state typing\nexport declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: Omit<CreateAgentParams<ResponseFormatUndefined, StateSchema, ContextSchema, never>, \"responseFormat\"> & {\n middleware?: TMiddleware;\n}): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;\n// Overload 9: With responseFormat explicitly undefined\nexport declare function createAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: Omit<CreateAgentParams<ResponseFormatUndefined, StateSchema, ContextSchema, never>, \"responseFormat\"> & {\n responseFormat?: undefined;\n middleware?: TMiddleware;\n}): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;\n// Overload 10: For other ResponseFormat values (failsafe)\nexport declare function createAgent<StructuredResponseFormat extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]>(params: CreateAgentParams<StructuredResponseFormat, StateSchema, ContextSchema, ResponseFormat> & {\n responseFormat: ResponseFormat;\n middleware?: TMiddleware;\n}): ReactAgent<StructuredResponseFormat, StateSchema, ContextSchema, TMiddleware>;\n// Re-export types and utilities\nexport * from \"./types.js\";\nexport * from \"./errors.js\";\nexport type { JumpToTarget } from \"./constants.js\";\nexport type { Runtime } from \"./runtime.js\";\nexport { toolStrategy, providerStrategy, ToolStrategy, ProviderStrategy, type ResponseFormat, type ResponseFormatUndefined, } from \"./responses.js\";\nexport { createMiddleware } from \"./middleware.js\";\nexport type { ToolCallRequest, ToolCallHandler, WrapToolCallHook, } from \"./middleware/types.js\";\nexport { FakeToolCallingModel } from \"./tests/utils.js\";\nexport type { ReactAgent } from \"./ReactAgent.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;AAgIA;;;;;;;;;;;;;;;;;;;;;;;;;AAGc;AAEd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGc;AAEd;;;;;;;;;;;;;;;;;;;;;AAGc;AAEd;;;;;;;;;;;;;;;;;;;;;AAGc;AAEd;;;;;;;;;;;;;AAA2XW,iBApBnWE,WAoBmWF,CAAAA,UApB7UG,MAoB6UH,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,GApBvTG,MAoBuTH,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,EAAAA,oBApB9QN,iBAoB8QM,GApB1PX,gBAoB0PW,GAAAA,SAAAA,GAAAA,SAAAA,EAAAA,sBApB1LN,iBAoB0LM,GApBtKX,gBAoBsKW,GApBnJN,iBAoBmJM,EAAAA,0BAAAA,SApB7FP,eAoB6FO,EAAAA,GAAAA,SApBhEP,eAoBgEO,EAAAA,CAAAA,CAAAA,MAAAA,EApBrCR,iBAoBqCQ,CApBnBI,CAoBmBJ,EApBhBK,WAoBgBL,E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CAAA,EAiBzSQ,UAjBuTR,CAiB5SF,uBAjB4SE,EAiBnRY,WAjBmRZ,EAiBtQa,aAjBsQb,EAiBvPc,WAjBuPd,CAAAA;;AAAgDY,iBAmBnVH,WAnBmVG,CAAAA,iCAmBtSF,MAnBsSE,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,GAmBhRF,MAnBgRE,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,EAAAA,oBAmBvOX,iBAnBuOW,GAmBnNhB,gBAnBmNgB,GAAAA,SAAAA,GAAAA,SAAAA,EAAAA,sBAmBnJX,iBAnBmJW,GAmB/HhB,gBAnB+HgB,GAmB5GX,iBAnB4GW,EAAAA,0BAAAA,SAmBtDZ,eAnBsDY,EAAAA,GAAAA,SAmBzBZ,eAnByBY,EAAAA,CAAAA,CAAAA,MAAAA,EAmBEb,iBAnBFa,CAmBoBI,wBAnBpBJ,EAmB8CA,WAnB9CA,EAmB2DC,aAnB3DD,EAmB0EN,cAnB1EM,CAAAA,GAAAA;EAAW,cAAEC,EAoBpWP,cApBoWO;EAAa,UAAeF,CAAAA,EAqBnYG,WArBmYH;CAAC,CAAA,EAsBjZH,UAtBmYL,CAsBxXa,wBAtBwXb,EAsB9VS,WAtB8VT,EAsBjVU,aAtBiVV,EAsBlUW,WAtBkUX,CAAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"contextEditing.d.cts","names":["BaseMessage","BaseLanguageModel","ContextSize","KeepSize","TokenCounter","ContextEdit","Promise","ClearToolUsesEditConfig","ClearToolUsesEdit","Set","ContextEditingMiddlewareConfig","contextEditingMiddleware","__types_js11","AgentMiddleware"],"sources":["../../../src/agents/middleware/contextEditing.d.ts"],"sourcesContent":["/**\n * Context editing middleware.\n *\n * This middleware mirrors Anthropic's context editing capabilities by clearing\n * older tool results once the conversation grows beyond a configurable token\n * threshold. The implementation is intentionally model-agnostic so it can be used\n * with any LangChain chat model.\n */\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport { type ContextSize, type KeepSize, type TokenCounter } from \"./summarization.js\";\n/**\n * Protocol describing a context editing strategy.\n *\n * Implement this interface to create custom strategies for managing\n * conversation context size. The `apply` method should modify the\n * messages array in-place and return the updated token count.\n *\n * @example\n * ```ts\n * import { SystemMessage } from \"langchain\";\n *\n * class RemoveOldSystemMessages implements ContextEdit {\n * async apply({ tokens, messages, countTokens }) {\n * // Remove old system messages if over limit\n * if (tokens > 50000) {\n * messages = messages.filter(SystemMessage.isInstance);\n * return await countTokens(messages);\n * }\n * return tokens;\n * }\n * }\n * ```\n */\nexport interface ContextEdit {\n /**\n * Apply an edit to the message list, returning the new token count.\n *\n * This method should:\n * 1. Check if editing is needed based on `tokens` parameter\n * 2. Modify the `messages` array in-place (if needed)\n * 3. Return the new token count after modifications\n *\n * @param params - Parameters for the editing operation\n * @returns The updated token count after applying edits\n */\n apply(params: {\n /**\n * Array of messages to potentially edit (modify in-place)\n */\n messages: BaseMessage[];\n /**\n * Function to count tokens in a message array\n */\n countTokens: TokenCounter;\n /**\n * Optional model instance for model profile information\n */\n model?: BaseLanguageModel;\n }): void | Promise<void>;\n}\n/**\n * Configuration for clearing tool outputs when token limits are exceeded.\n */\nexport interface ClearToolUsesEditConfig {\n /**\n * Trigger conditions for context editing.\n * Can be a single condition object (all properties must be met) or an array of conditions (any condition must be met).\n *\n * @example\n * ```ts\n * // Single condition: trigger if tokens >= 100000 AND messages >= 50\n * trigger: { tokens: 100000, messages: 50 }\n *\n * // Multiple conditions: trigger if (tokens >= 100000 AND messages >= 50) OR (tokens >= 50000 AND messages >= 100)\n * trigger: [\n * { tokens: 100000, messages: 50 },\n * { tokens: 50000, messages: 100 }\n * ]\n *\n * // Fractional trigger: trigger at 80% of model's max input tokens\n * trigger: { fraction: 0.8 }\n * ```\n */\n trigger?: ContextSize | ContextSize[];\n /**\n * Context retention policy applied after editing.\n * Specify how many tool results to preserve using messages, tokens, or fraction.\n *\n * @example\n * ```ts\n * // Keep 3 most recent tool results\n * keep: { messages: 3 }\n *\n * // Keep tool results that fit within 1000 tokens\n * keep: { tokens: 1000 }\n *\n * // Keep tool results that fit within 30% of model's max input tokens\n * keep: { fraction: 0.3 }\n * ```\n */\n keep?: KeepSize;\n /**\n * Whether to clear the originating tool call parameters on the AI message.\n * @default false\n */\n clearToolInputs?: boolean;\n /**\n * List of tool names to exclude from clearing.\n * @default []\n */\n excludeTools?: string[];\n /**\n * Placeholder text inserted for cleared tool outputs.\n * @default \"[cleared]\"\n */\n placeholder?: string;\n /**\n * @deprecated Use `trigger: { tokens: value }` instead.\n */\n triggerTokens?: number;\n /**\n * @deprecated Use `keep: { messages: value }` instead.\n */\n keepMessages?: number;\n /**\n * @deprecated This property is deprecated and will be removed in a future version.\n * Use `keep: { tokens: value }` or `keep: { messages: value }` instead to control retention.\n */\n clearAtLeast?: number;\n}\n/**\n * Strategy for clearing tool outputs when token limits are exceeded.\n *\n * This strategy mirrors Anthropic's `clear_tool_uses_20250919` behavior by\n * replacing older tool results with a placeholder text when the conversation\n * grows too large. It preserves the most recent tool results and can exclude\n * specific tools from being cleared.\n *\n * @example\n * ```ts\n * import { ClearToolUsesEdit } from \"langchain\";\n *\n * const edit = new ClearToolUsesEdit({\n * trigger: { tokens: 100000 }, // Start clearing at 100K tokens\n * keep: { messages: 3 }, // Keep 3 most recent tool results\n * excludeTools: [\"important\"], // Never clear \"important\" tool\n * clearToolInputs: false, // Keep tool call arguments\n * placeholder: \"[cleared]\", // Replacement text\n * });\n *\n * // Multiple trigger conditions\n * const edit2 = new ClearToolUsesEdit({\n * trigger: [\n * { tokens: 100000, messages: 50 },\n * { tokens: 50000, messages: 100 }\n * ],\n * keep: { messages: 3 },\n * });\n *\n * // Fractional trigger with model profile\n * const edit3 = new ClearToolUsesEdit({\n * trigger: { fraction: 0.8 }, // Trigger at 80% of model's max tokens\n * keep: { fraction: 0.3 }, // Keep 30% of model's max tokens\n * });\n * ```\n */\nexport declare class ClearToolUsesEdit implements ContextEdit {\n #private;\n trigger: ContextSize | ContextSize[];\n keep: KeepSize;\n clearToolInputs: boolean;\n excludeTools: Set<string>;\n placeholder: string;\n model: BaseLanguageModel;\n clearAtLeast: number;\n constructor(config?: ClearToolUsesEditConfig);\n apply(params: {\n messages: BaseMessage[];\n model: BaseLanguageModel;\n countTokens: TokenCounter;\n }): Promise<void>;\n}\n/**\n * Configuration for the Context Editing Middleware.\n */\nexport interface ContextEditingMiddlewareConfig {\n /**\n * Sequence of edit strategies to apply. Defaults to a single\n * ClearToolUsesEdit mirroring Anthropic defaults.\n */\n edits?: ContextEdit[];\n /**\n * Whether to use approximate token counting (faster, less accurate)\n * or exact counting implemented by the chat model (potentially slower, more accurate).\n * Currently only OpenAI models support exact counting.\n * @default \"approx\"\n */\n tokenCountMethod?: \"approx\" | \"model\";\n}\n/**\n * Middleware that automatically prunes tool results to manage context size.\n *\n * This middleware applies a sequence of edits when the total input token count\n * exceeds configured thresholds. By default, it uses the `ClearToolUsesEdit` strategy\n * which mirrors Anthropic's `clear_tool_uses_20250919` behaviour by clearing older\n * tool results once the conversation exceeds 100,000 tokens.\n *\n * ## Basic Usage\n *\n * Use the middleware with default settings to automatically manage context:\n *\n * @example Basic usage with defaults\n * ```ts\n * import { contextEditingMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-sonnet-4-5\",\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware(),\n * ],\n * });\n * ```\n *\n * The default configuration:\n * - Triggers when context exceeds **100,000 tokens**\n * - Keeps the **3 most recent** tool results\n * - Uses **approximate token counting** (fast)\n * - Does not clear tool call arguments\n *\n * ## Custom Configuration\n *\n * Customize the clearing behavior with `ClearToolUsesEdit`:\n *\n * @example Custom ClearToolUsesEdit configuration\n * ```ts\n * import { contextEditingMiddleware, ClearToolUsesEdit } from \"langchain\";\n *\n * // Single condition: trigger if tokens >= 50000 AND messages >= 20\n * const agent1 = createAgent({\n * model: \"anthropic:claude-sonnet-4-5\",\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware({\n * edits: [\n * new ClearToolUsesEdit({\n * trigger: { tokens: 50000, messages: 20 },\n * keep: { messages: 5 },\n * excludeTools: [\"search\"],\n * clearToolInputs: true,\n * }),\n * ],\n * tokenCountMethod: \"approx\",\n * }),\n * ],\n * });\n *\n * // Multiple conditions: trigger if (tokens >= 50000 AND messages >= 20) OR (tokens >= 30000 AND messages >= 50)\n * const agent2 = createAgent({\n * model: \"anthropic:claude-sonnet-4-5\",\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware({\n * edits: [\n * new ClearToolUsesEdit({\n * trigger: [\n * { tokens: 50000, messages: 20 },\n * { tokens: 30000, messages: 50 },\n * ],\n * keep: { messages: 5 },\n * }),\n * ],\n * }),\n * ],\n * });\n *\n * // Fractional trigger with model profile\n * const agent3 = createAgent({\n * model: chatModel,\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware({\n * edits: [\n * new ClearToolUsesEdit({\n * trigger: { fraction: 0.8 }, // Trigger at 80% of model's max tokens\n * keep: { fraction: 0.3 }, // Keep 30% of model's max tokens\n * model: chatModel,\n * }),\n * ],\n * }),\n * ],\n * });\n * ```\n *\n * ## Custom Editing Strategies\n *\n * Implement your own context editing strategy by creating a class that\n * implements the `ContextEdit` interface:\n *\n * @example Custom editing strategy\n * ```ts\n * import { contextEditingMiddleware, type ContextEdit, type TokenCounter } from \"langchain\";\n * import type { BaseMessage } from \"@langchain/core/messages\";\n *\n * class CustomEdit implements ContextEdit {\n * async apply(params: {\n * tokens: number;\n * messages: BaseMessage[];\n * countTokens: TokenCounter;\n * }): Promise<number> {\n * // Implement your custom editing logic here\n * // and apply it to the messages array, then\n * // return the new token count after edits\n * return countTokens(messages);\n * }\n * }\n * ```\n *\n * @param config - Configuration options for the middleware\n * @returns A middleware instance that can be used with `createAgent`\n */\nexport declare function contextEditingMiddleware(config?: ContextEditingMiddlewareConfig): import(\"./types.js\").AgentMiddleware<undefined, undefined, any>;\n"],"mappings":";;;;;;;;AA2DsB;AAKtB;;;;;AAqCmB;AAkEnB;;;;;;;;;;;;;AAA6D;AAmB7D;AAyIwBW,UAjSPN,WAAAA,CAiSOM;EAAwB;;;AAA+E;;;;;;;;;;;;cAjR7GX;;;;iBAIGI;;;;YAILH;aACDK;;;;;UAKEC,uBAAAA;;;;;;;;;;;;;;;;;;;;YAoBHL,cAAcA;;;;;;;;;;;;;;;;;SAiBjBC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAkEUK,iBAAAA,YAA6BH;;WAErCH,cAAcA;QACjBC;;gBAEQM;;SAEPR;;uBAEcM;;cAEPP;WACHC;iBACMG;MACbE;;;;;UAKSI,8BAAAA;;;;;UAKLL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAoIYM,wBAAAA,UAAkCD,iCAA8B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"contextEditing.d.ts","names":["BaseMessage","BaseLanguageModel","ContextSize","KeepSize","TokenCounter","ContextEdit","Promise","ClearToolUsesEditConfig","ClearToolUsesEdit","Set","ContextEditingMiddlewareConfig","contextEditingMiddleware","__types_js0","AgentMiddleware"],"sources":["../../../src/agents/middleware/contextEditing.d.ts"],"sourcesContent":["/**\n * Context editing middleware.\n *\n * This middleware mirrors Anthropic's context editing capabilities by clearing\n * older tool results once the conversation grows beyond a configurable token\n * threshold. The implementation is intentionally model-agnostic so it can be used\n * with any LangChain chat model.\n */\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport { type ContextSize, type KeepSize, type TokenCounter } from \"./summarization.js\";\n/**\n * Protocol describing a context editing strategy.\n *\n * Implement this interface to create custom strategies for managing\n * conversation context size. The `apply` method should modify the\n * messages array in-place and return the updated token count.\n *\n * @example\n * ```ts\n * import { SystemMessage } from \"langchain\";\n *\n * class RemoveOldSystemMessages implements ContextEdit {\n * async apply({ tokens, messages, countTokens }) {\n * // Remove old system messages if over limit\n * if (tokens > 50000) {\n * messages = messages.filter(SystemMessage.isInstance);\n * return await countTokens(messages);\n * }\n * return tokens;\n * }\n * }\n * ```\n */\nexport interface ContextEdit {\n /**\n * Apply an edit to the message list, returning the new token count.\n *\n * This method should:\n * 1. Check if editing is needed based on `tokens` parameter\n * 2. Modify the `messages` array in-place (if needed)\n * 3. Return the new token count after modifications\n *\n * @param params - Parameters for the editing operation\n * @returns The updated token count after applying edits\n */\n apply(params: {\n /**\n * Array of messages to potentially edit (modify in-place)\n */\n messages: BaseMessage[];\n /**\n * Function to count tokens in a message array\n */\n countTokens: TokenCounter;\n /**\n * Optional model instance for model profile information\n */\n model?: BaseLanguageModel;\n }): void | Promise<void>;\n}\n/**\n * Configuration for clearing tool outputs when token limits are exceeded.\n */\nexport interface ClearToolUsesEditConfig {\n /**\n * Trigger conditions for context editing.\n * Can be a single condition object (all properties must be met) or an array of conditions (any condition must be met).\n *\n * @example\n * ```ts\n * // Single condition: trigger if tokens >= 100000 AND messages >= 50\n * trigger: { tokens: 100000, messages: 50 }\n *\n * // Multiple conditions: trigger if (tokens >= 100000 AND messages >= 50) OR (tokens >= 50000 AND messages >= 100)\n * trigger: [\n * { tokens: 100000, messages: 50 },\n * { tokens: 50000, messages: 100 }\n * ]\n *\n * // Fractional trigger: trigger at 80% of model's max input tokens\n * trigger: { fraction: 0.8 }\n * ```\n */\n trigger?: ContextSize | ContextSize[];\n /**\n * Context retention policy applied after editing.\n * Specify how many tool results to preserve using messages, tokens, or fraction.\n *\n * @example\n * ```ts\n * // Keep 3 most recent tool results\n * keep: { messages: 3 }\n *\n * // Keep tool results that fit within 1000 tokens\n * keep: { tokens: 1000 }\n *\n * // Keep tool results that fit within 30% of model's max input tokens\n * keep: { fraction: 0.3 }\n * ```\n */\n keep?: KeepSize;\n /**\n * Whether to clear the originating tool call parameters on the AI message.\n * @default false\n */\n clearToolInputs?: boolean;\n /**\n * List of tool names to exclude from clearing.\n * @default []\n */\n excludeTools?: string[];\n /**\n * Placeholder text inserted for cleared tool outputs.\n * @default \"[cleared]\"\n */\n placeholder?: string;\n /**\n * @deprecated Use `trigger: { tokens: value }` instead.\n */\n triggerTokens?: number;\n /**\n * @deprecated Use `keep: { messages: value }` instead.\n */\n keepMessages?: number;\n /**\n * @deprecated This property is deprecated and will be removed in a future version.\n * Use `keep: { tokens: value }` or `keep: { messages: value }` instead to control retention.\n */\n clearAtLeast?: number;\n}\n/**\n * Strategy for clearing tool outputs when token limits are exceeded.\n *\n * This strategy mirrors Anthropic's `clear_tool_uses_20250919` behavior by\n * replacing older tool results with a placeholder text when the conversation\n * grows too large. It preserves the most recent tool results and can exclude\n * specific tools from being cleared.\n *\n * @example\n * ```ts\n * import { ClearToolUsesEdit } from \"langchain\";\n *\n * const edit = new ClearToolUsesEdit({\n * trigger: { tokens: 100000 }, // Start clearing at 100K tokens\n * keep: { messages: 3 }, // Keep 3 most recent tool results\n * excludeTools: [\"important\"], // Never clear \"important\" tool\n * clearToolInputs: false, // Keep tool call arguments\n * placeholder: \"[cleared]\", // Replacement text\n * });\n *\n * // Multiple trigger conditions\n * const edit2 = new ClearToolUsesEdit({\n * trigger: [\n * { tokens: 100000, messages: 50 },\n * { tokens: 50000, messages: 100 }\n * ],\n * keep: { messages: 3 },\n * });\n *\n * // Fractional trigger with model profile\n * const edit3 = new ClearToolUsesEdit({\n * trigger: { fraction: 0.8 }, // Trigger at 80% of model's max tokens\n * keep: { fraction: 0.3 }, // Keep 30% of model's max tokens\n * });\n * ```\n */\nexport declare class ClearToolUsesEdit implements ContextEdit {\n #private;\n trigger: ContextSize | ContextSize[];\n keep: KeepSize;\n clearToolInputs: boolean;\n excludeTools: Set<string>;\n placeholder: string;\n model: BaseLanguageModel;\n clearAtLeast: number;\n constructor(config?: ClearToolUsesEditConfig);\n apply(params: {\n messages: BaseMessage[];\n model: BaseLanguageModel;\n countTokens: TokenCounter;\n }): Promise<void>;\n}\n/**\n * Configuration for the Context Editing Middleware.\n */\nexport interface ContextEditingMiddlewareConfig {\n /**\n * Sequence of edit strategies to apply. Defaults to a single\n * ClearToolUsesEdit mirroring Anthropic defaults.\n */\n edits?: ContextEdit[];\n /**\n * Whether to use approximate token counting (faster, less accurate)\n * or exact counting implemented by the chat model (potentially slower, more accurate).\n * Currently only OpenAI models support exact counting.\n * @default \"approx\"\n */\n tokenCountMethod?: \"approx\" | \"model\";\n}\n/**\n * Middleware that automatically prunes tool results to manage context size.\n *\n * This middleware applies a sequence of edits when the total input token count\n * exceeds configured thresholds. By default, it uses the `ClearToolUsesEdit` strategy\n * which mirrors Anthropic's `clear_tool_uses_20250919` behaviour by clearing older\n * tool results once the conversation exceeds 100,000 tokens.\n *\n * ## Basic Usage\n *\n * Use the middleware with default settings to automatically manage context:\n *\n * @example Basic usage with defaults\n * ```ts\n * import { contextEditingMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-sonnet-4-5\",\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware(),\n * ],\n * });\n * ```\n *\n * The default configuration:\n * - Triggers when context exceeds **100,000 tokens**\n * - Keeps the **3 most recent** tool results\n * - Uses **approximate token counting** (fast)\n * - Does not clear tool call arguments\n *\n * ## Custom Configuration\n *\n * Customize the clearing behavior with `ClearToolUsesEdit`:\n *\n * @example Custom ClearToolUsesEdit configuration\n * ```ts\n * import { contextEditingMiddleware, ClearToolUsesEdit } from \"langchain\";\n *\n * // Single condition: trigger if tokens >= 50000 AND messages >= 20\n * const agent1 = createAgent({\n * model: \"anthropic:claude-sonnet-4-5\",\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware({\n * edits: [\n * new ClearToolUsesEdit({\n * trigger: { tokens: 50000, messages: 20 },\n * keep: { messages: 5 },\n * excludeTools: [\"search\"],\n * clearToolInputs: true,\n * }),\n * ],\n * tokenCountMethod: \"approx\",\n * }),\n * ],\n * });\n *\n * // Multiple conditions: trigger if (tokens >= 50000 AND messages >= 20) OR (tokens >= 30000 AND messages >= 50)\n * const agent2 = createAgent({\n * model: \"anthropic:claude-sonnet-4-5\",\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware({\n * edits: [\n * new ClearToolUsesEdit({\n * trigger: [\n * { tokens: 50000, messages: 20 },\n * { tokens: 30000, messages: 50 },\n * ],\n * keep: { messages: 5 },\n * }),\n * ],\n * }),\n * ],\n * });\n *\n * // Fractional trigger with model profile\n * const agent3 = createAgent({\n * model: chatModel,\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware({\n * edits: [\n * new ClearToolUsesEdit({\n * trigger: { fraction: 0.8 }, // Trigger at 80% of model's max tokens\n * keep: { fraction: 0.3 }, // Keep 30% of model's max tokens\n * model: chatModel,\n * }),\n * ],\n * }),\n * ],\n * });\n * ```\n *\n * ## Custom Editing Strategies\n *\n * Implement your own context editing strategy by creating a class that\n * implements the `ContextEdit` interface:\n *\n * @example Custom editing strategy\n * ```ts\n * import { contextEditingMiddleware, type ContextEdit, type TokenCounter } from \"langchain\";\n * import type { BaseMessage } from \"@langchain/core/messages\";\n *\n * class CustomEdit implements ContextEdit {\n * async apply(params: {\n * tokens: number;\n * messages: BaseMessage[];\n * countTokens: TokenCounter;\n * }): Promise<number> {\n * // Implement your custom editing logic here\n * // and apply it to the messages array, then\n * // return the new token count after edits\n * return countTokens(messages);\n * }\n * }\n * ```\n *\n * @param config - Configuration options for the middleware\n * @returns A middleware instance that can be used with `createAgent`\n */\nexport declare function contextEditingMiddleware(config?: ContextEditingMiddlewareConfig): import(\"./types.js\").AgentMiddleware<undefined, undefined, any>;\n"],"mappings":";;;;;;;;AA2DsB;AAKtB;;;;;AAqCmB;AAkEnB;;;;;;;;;;;;;AAA6D;AAmB7D;AAyIwBW,UAjSPN,WAAAA,CAiSOM;EAAwB;;;AAA+E;;;;;;;;;;;;cAjR7GX;;;;iBAIGI;;;;YAILH;aACDK;;;;;UAKEC,uBAAAA;;;;;;;;;;;;;;;;;;;;YAoBHL,cAAcA;;;;;;;;;;;;;;;;;SAiBjBC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAkEUK,iBAAAA,YAA6BH;;WAErCH,cAAcA;QACjBC;;gBAEQM;;SAEPR;;uBAEcM;;cAEPP;WACHC;iBACMG;MACbE;;;;;UAKSI,8BAAAA;;;;;UAKLL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAoIYM,wBAAAA,UAAkCD,iCAA8B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"dynamicSystemPrompt.d.cts","names":["Runtime","AgentBuiltInState","DynamicSystemPromptMiddlewareConfig","TContextSchema","Promise","dynamicSystemPromptMiddleware","__types_js10","AgentMiddleware"],"sources":["../../../src/agents/middleware/dynamicSystemPrompt.d.ts"],"sourcesContent":["import type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nexport type DynamicSystemPromptMiddlewareConfig<TContextSchema> = (state: AgentBuiltInState, runtime: Runtime<TContextSchema>) => string | Promise<string>;\n/**\n * Dynamic System Prompt Middleware\n *\n * Allows setting the system prompt dynamically right before each model invocation.\n * Useful when the prompt depends on the current agent state or per-invocation context.\n *\n * @typeParam TContextSchema - The shape of the runtime context available at invocation time.\n * If your agent defines a `contextSchema`, pass the inferred type here to get full type-safety\n * for `runtime.context`.\n *\n * @param fn - Function that receives the current agent `state` and `runtime`, and\n * returns the system prompt for the next model call as a string.\n *\n * @returns A middleware instance that sets `systemPrompt` for the next model call.\n *\n * @example Basic usage with typed context\n * ```ts\n * import { z } from \"zod\";\n * import { dynamicSystemPrompt } from \"langchain\";\n * import { createAgent, SystemMessage } from \"langchain\";\n *\n * const contextSchema = z.object({ region: z.string().optional() });\n *\n * const middleware = dynamicSystemPrompt<z.infer<typeof contextSchema>>(\n * (_state, runtime) => `You are a helpful assistant. Region: ${runtime.context.region ?? \"n/a\"}`\n * );\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * contextSchema,\n * middleware: [middleware],\n * });\n *\n * await agent.invoke({ messages }, { context: { region: \"EU\" } });\n * ```\n *\n * @public\n */\nexport declare function dynamicSystemPromptMiddleware<TContextSchema = unknown>(fn: DynamicSystemPromptMiddlewareConfig<TContextSchema>): import(\"./types.js\").AgentMiddleware<undefined, undefined, any>;\n"],"mappings":";;;;KACYE,8DAA8DD,4BAA4BD,QAAQG,6BAA6BC;;;AAA3I;;;;;;AAAkJ;AAuClJ;;;;;AAA8K;;;;;;;;;;;;;;;;;;;;;;;;iBAAtJC,4DAA4DH,oCAAoCC,kBAAD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"dynamicSystemPrompt.d.ts","names":["Runtime","AgentBuiltInState","DynamicSystemPromptMiddlewareConfig","TContextSchema","Promise","dynamicSystemPromptMiddleware","__types_js6","AgentMiddleware"],"sources":["../../../src/agents/middleware/dynamicSystemPrompt.d.ts"],"sourcesContent":["import type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nexport type DynamicSystemPromptMiddlewareConfig<TContextSchema> = (state: AgentBuiltInState, runtime: Runtime<TContextSchema>) => string | Promise<string>;\n/**\n * Dynamic System Prompt Middleware\n *\n * Allows setting the system prompt dynamically right before each model invocation.\n * Useful when the prompt depends on the current agent state or per-invocation context.\n *\n * @typeParam TContextSchema - The shape of the runtime context available at invocation time.\n * If your agent defines a `contextSchema`, pass the inferred type here to get full type-safety\n * for `runtime.context`.\n *\n * @param fn - Function that receives the current agent `state` and `runtime`, and\n * returns the system prompt for the next model call as a string.\n *\n * @returns A middleware instance that sets `systemPrompt` for the next model call.\n *\n * @example Basic usage with typed context\n * ```ts\n * import { z } from \"zod\";\n * import { dynamicSystemPrompt } from \"langchain\";\n * import { createAgent, SystemMessage } from \"langchain\";\n *\n * const contextSchema = z.object({ region: z.string().optional() });\n *\n * const middleware = dynamicSystemPrompt<z.infer<typeof contextSchema>>(\n * (_state, runtime) => `You are a helpful assistant. Region: ${runtime.context.region ?? \"n/a\"}`\n * );\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * contextSchema,\n * middleware: [middleware],\n * });\n *\n * await agent.invoke({ messages }, { context: { region: \"EU\" } });\n * ```\n *\n * @public\n */\nexport declare function dynamicSystemPromptMiddleware<TContextSchema = unknown>(fn: DynamicSystemPromptMiddlewareConfig<TContextSchema>): import(\"./types.js\").AgentMiddleware<undefined, undefined, any>;\n"],"mappings":";;;;KACYE,8DAA8DD,4BAA4BD,QAAQG,6BAA6BC;;;AAA3I;;;;;;AAAkJ;AAuClJ;;;;;AAA8K;;;;;;;;;;;;;;;;;;;;;;;;iBAAtJC,4DAA4DH,oCAAoCC,kBAAD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"hitl.d.cts","names":["z","ToolCall","InferInteropZodInput","AgentBuiltInState","Runtime","DescriptionFunctionSchema","Record","ZodTypeDef","ZodType","ZodUnknown","ZodTuple","ZodString","ZodPromise","ZodUnion","ZodFunction","DescriptionFactory","infer","DecisionType","ZodEnum","InterruptOnConfigSchema","ZodArray","ZodOptional","ZodAny","ZodRecord","ZodTypeAny","Promise","ZodObject","InterruptOnConfig","input","Action","ActionRequest","ReviewConfig","HITLRequest","ApproveDecision","EditDecision","RejectDecision","Decision","HITLResponse","contextSchema","ZodBoolean","ZodDefault","HumanInTheLoopMiddlewareConfig","humanInTheLoopMiddleware","NonNullable","__types_js8","AgentMiddleware"],"sources":["../../../src/agents/middleware/hitl.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { z } from \"zod/v3\";\nimport { ToolCall } from \"@langchain/core/messages\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\ndeclare const DescriptionFunctionSchema: z.ZodFunction<z.ZodTuple<[z.ZodType<ToolCall<string, Record<string, any>>, z.ZodTypeDef, ToolCall<string, Record<string, any>>>, z.ZodType<AgentBuiltInState, z.ZodTypeDef, AgentBuiltInState>, z.ZodType<Runtime<unknown>, z.ZodTypeDef, Runtime<unknown>>], z.ZodUnknown>, z.ZodUnion<[z.ZodString, z.ZodPromise<z.ZodString>]>>;\n/**\n * Function type that dynamically generates a description for a tool call approval request.\n *\n * @param toolCall - The tool call being reviewed\n * @param state - The current agent state\n * @param runtime - The agent runtime context\n * @returns A string description or Promise that resolves to a string description\n *\n * @example\n * ```typescript\n * import { type DescriptionFactory, type ToolCall } from \"langchain\";\n *\n * const descriptionFactory: DescriptionFactory = (toolCall, state, runtime) => {\n * return `Please review: ${toolCall.name}(${JSON.stringify(toolCall.args)})`;\n * };\n * ```\n */\nexport type DescriptionFactory = z.infer<typeof DescriptionFunctionSchema>;\ndeclare const DecisionType: z.ZodEnum<[\"approve\", \"edit\", \"reject\"]>;\nexport type DecisionType = z.infer<typeof DecisionType>;\ndeclare const InterruptOnConfigSchema: z.ZodObject<{\n /**\n * The decisions that are allowed for this action.\n */\n allowedDecisions: z.ZodArray<z.ZodEnum<[\"approve\", \"edit\", \"reject\"]>, \"many\">;\n /**\n * The description attached to the request for human input.\n * Can be either:\n * - A static string describing the approval request\n * - A callable that dynamically generates the description based on agent state,\n * runtime, and tool call information\n *\n * @example\n * Static string description\n * ```typescript\n * import type { InterruptOnConfig } from \"langchain\";\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: \"Please review this tool execution\"\n * };\n * ```\n *\n * @example\n * Dynamic callable description\n * ```typescript\n * import type {\n * AgentBuiltInState,\n * Runtime,\n * DescriptionFactory,\n * ToolCall,\n * InterruptOnConfig\n * } from \"langchain\";\n *\n * const formatToolDescription: DescriptionFactory = (\n * toolCall: ToolCall,\n * state: AgentBuiltInState,\n * runtime: Runtime<unknown>\n * ) => {\n * return `Tool: ${toolCall.name}\\nArguments:\\n${JSON.stringify(toolCall.args, null, 2)}`;\n * };\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"edit\"],\n * description: formatToolDescription\n * };\n * ```\n */\n description: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodFunction<z.ZodTuple<[z.ZodType<ToolCall<string, Record<string, any>>, z.ZodTypeDef, ToolCall<string, Record<string, any>>>, z.ZodType<AgentBuiltInState, z.ZodTypeDef, AgentBuiltInState>, z.ZodType<Runtime<unknown>, z.ZodTypeDef, Runtime<unknown>>], z.ZodUnknown>, z.ZodUnion<[z.ZodString, z.ZodPromise<z.ZodString>]>>]>>;\n /**\n * JSON schema for the arguments associated with the action, if edits are allowed.\n */\n argsSchema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;\n}, \"strip\", z.ZodTypeAny, {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n}, {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n}>;\nexport type InterruptOnConfig = z.input<typeof InterruptOnConfigSchema>;\n/**\n * Represents an action with a name and arguments.\n */\nexport interface Action {\n /**\n * The type or name of action being requested (e.g., \"add_numbers\").\n */\n name: string;\n /**\n * Key-value pairs of arguments needed for the action (e.g., {\"a\": 1, \"b\": 2}).\n */\n args: Record<string, any>;\n}\n/**\n * Represents an action request with a name, arguments, and description.\n */\nexport interface ActionRequest {\n /**\n * The name of the action being requested.\n */\n name: string;\n /**\n * Key-value pairs of arguments needed for the action (e.g., {\"a\": 1, \"b\": 2}).\n */\n args: Record<string, any>;\n /**\n * The description of the action to be reviewed.\n */\n description?: string;\n}\n/**\n * Policy for reviewing a HITL request.\n */\nexport interface ReviewConfig {\n /**\n * Name of the action associated with this review configuration.\n */\n actionName: string;\n /**\n * The decisions that are allowed for this request.\n */\n allowedDecisions: DecisionType[];\n /**\n * JSON schema for the arguments associated with the action, if edits are allowed.\n */\n argsSchema?: Record<string, any>;\n}\n/**\n * Request for human feedback on a sequence of actions requested by a model.\n *\n * @example\n * ```ts\n * const hitlRequest: HITLRequest = {\n * actionRequests: [\n * { name: \"send_email\", args: { to: \"user@example.com\", subject: \"Hello\" } }\n * ],\n * reviewConfigs: [\n * {\n * actionName: \"send_email\",\n * allowedDecisions: [\"approve\", \"edit\", \"reject\"],\n * description: \"Please review the email before sending\"\n * }\n * ]\n * };\n * const response = interrupt(hitlRequest);\n * ```\n */\nexport interface HITLRequest {\n /**\n * A list of agent actions for human review.\n */\n actionRequests: ActionRequest[];\n /**\n * Review configuration for all possible actions.\n */\n reviewConfigs: ReviewConfig[];\n}\n/**\n * Response when a human approves the action.\n */\nexport interface ApproveDecision {\n type: \"approve\";\n}\n/**\n * Response when a human edits the action.\n */\nexport interface EditDecision {\n type: \"edit\";\n /**\n * Edited action for the agent to perform.\n * Ex: for a tool call, a human reviewer can edit the tool name and args.\n */\n editedAction: Action;\n}\n/**\n * Response when a human rejects the action.\n */\nexport interface RejectDecision {\n type: \"reject\";\n /**\n * The message sent to the model explaining why the action was rejected.\n */\n message?: string;\n}\n/**\n * Union of all possible decision types.\n */\nexport type Decision = ApproveDecision | EditDecision | RejectDecision;\n/**\n * Response payload for a HITLRequest.\n */\nexport interface HITLResponse {\n /**\n * The decisions made by the human.\n */\n decisions: Decision[];\n}\ndeclare const contextSchema: z.ZodObject<{\n /**\n * Mapping of tool name to allowed reviewer responses.\n * If a tool doesn't have an entry, it's auto-approved by default.\n *\n * - `true` -> pause for approval and allow approve/edit/reject decisions\n * - `false` -> auto-approve (no human review)\n * - `InterruptOnConfig` -> explicitly specify which decisions are allowed for this tool\n */\n interruptOn: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodBoolean, z.ZodObject<{\n /**\n * The decisions that are allowed for this action.\n */\n allowedDecisions: z.ZodArray<z.ZodEnum<[\"approve\", \"edit\", \"reject\"]>, \"many\">;\n /**\n * The description attached to the request for human input.\n * Can be either:\n * - A static string describing the approval request\n * - A callable that dynamically generates the description based on agent state,\n * runtime, and tool call information\n *\n * @example\n * Static string description\n * ```typescript\n * import type { InterruptOnConfig } from \"langchain\";\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: \"Please review this tool execution\"\n * };\n * ```\n *\n * @example\n * Dynamic callable description\n * ```typescript\n * import type {\n * AgentBuiltInState,\n * Runtime,\n * DescriptionFactory,\n * ToolCall,\n * InterruptOnConfig\n * } from \"langchain\";\n *\n * const formatToolDescription: DescriptionFactory = (\n * toolCall: ToolCall,\n * state: AgentBuiltInState,\n * runtime: Runtime<unknown>\n * ) => {\n * return `Tool: ${toolCall.name}\\nArguments:\\n${JSON.stringify(toolCall.args, null, 2)}`;\n * };\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"edit\"],\n * description: formatToolDescription\n * };\n * ```\n */\n description: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodFunction<z.ZodTuple<[z.ZodType<ToolCall<string, Record<string, any>>, z.ZodTypeDef, ToolCall<string, Record<string, any>>>, z.ZodType<AgentBuiltInState, z.ZodTypeDef, AgentBuiltInState>, z.ZodType<Runtime<unknown>, z.ZodTypeDef, Runtime<unknown>>], z.ZodUnknown>, z.ZodUnion<[z.ZodString, z.ZodPromise<z.ZodString>]>>]>>;\n /**\n * JSON schema for the arguments associated with the action, if edits are allowed.\n */\n argsSchema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;\n }, \"strip\", z.ZodTypeAny, {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n }, {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n }>]>>>;\n /**\n * Prefix used when constructing human-facing approval messages.\n * Provides context about the tool call being reviewed; does not change the underlying action.\n *\n * Note: This prefix is only applied for tools that do not provide a custom\n * `description` via their {@link InterruptOnConfig}. If a tool specifies a custom\n * `description`, that per-tool text is used and this prefix is ignored.\n */\n descriptionPrefix: z.ZodDefault<z.ZodString>;\n}, \"strip\", z.ZodTypeAny, {\n interruptOn?: Record<string, boolean | {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n }> | undefined;\n descriptionPrefix: string;\n}, {\n interruptOn?: Record<string, boolean | {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n }> | undefined;\n descriptionPrefix?: string | undefined;\n}>;\nexport type HumanInTheLoopMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;\n/**\n * Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.\n *\n * This middleware intercepts tool calls made by an AI agent and provides human oversight\n * capabilities before execution. It enables selective approval workflows where certain tools\n * require human intervention while others can execute automatically.\n *\n * A invocation result that has been interrupted by the middleware will have a `__interrupt__`\n * property that contains the interrupt request.\n *\n * ```ts\n * import { type HITLRequest, type HITLResponse } from \"langchain\";\n * import { type Interrupt } from \"langchain\";\n *\n * const result = await agent.invoke(request);\n * const interruptRequest = result.__interrupt__?.[0] as Interrupt<HITLRequest>;\n *\n * // Examine the action requests and review configs\n * const actionRequests = interruptRequest.value.actionRequests;\n * const reviewConfigs = interruptRequest.value.reviewConfigs;\n *\n * // Create decisions for each action\n * const resume: HITLResponse = {\n * decisions: actionRequests.map((action, i) => {\n * if (action.name === \"calculator\") {\n * return { type: \"approve\" };\n * } else if (action.name === \"write_file\") {\n * return {\n * type: \"edit\",\n * editedAction: { name: \"write_file\", args: { filename: \"safe.txt\", content: \"Safe content\" } }\n * };\n * }\n * return { type: \"reject\", message: \"Action not allowed\" };\n * })\n * };\n *\n * // Resume with decisions\n * await agent.invoke(new Command({ resume }), config);\n * ```\n *\n * ## Features\n *\n * - **Selective Tool Approval**: Configure which tools require human approval\n * - **Multiple Decision Types**: Approve, edit, or reject tool calls\n * - **Asynchronous Workflow**: Uses LangGraph's interrupt mechanism for non-blocking approval\n * - **Custom Approval Messages**: Provide context-specific descriptions for approval requests\n *\n * ## Decision Types\n *\n * When a tool requires approval, the human operator can respond with:\n * - `approve`: Execute the tool with original arguments\n * - `edit`: Modify the tool name and/or arguments before execution\n * - `reject`: Provide a manual response instead of executing the tool\n *\n * @param options - Configuration options for the middleware\n * @param options.interruptOn - Per-tool configuration mapping tool names to their settings\n * @param options.interruptOn[toolName].allowedDecisions - Array of decision types allowed for this tool (e.g., [\"approve\", \"edit\", \"reject\"])\n * @param options.interruptOn[toolName].description - Custom approval message for the tool. Can be either a static string or a callable that dynamically generates the description based on agent state, runtime, and tool call information\n * @param options.interruptOn[toolName].argsSchema - JSON schema for the arguments associated with the action, if edits are allowed\n * @param options.descriptionPrefix - Default prefix for approval messages (default: \"Tool execution requires approval\"). Only used for tools that do not define a custom `description` in their InterruptOnConfig.\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @example\n * Basic usage with selective tool approval\n * ```typescript\n * import { humanInTheLoopMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * interruptOn: {\n * // Interrupt write_file tool and allow edits or approvals\n * \"write_file\": {\n * allowedDecisions: [\"approve\", \"edit\"],\n * description: \"⚠️ File write operation requires approval\"\n * },\n * // Auto-approve read_file tool\n * \"read_file\": false\n * }\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * tools: [writeFileTool, readFileTool],\n * middleware: [hitlMiddleware]\n * });\n * ```\n *\n * @example\n * Handling approval requests\n * ```typescript\n * import { type HITLRequest, type HITLResponse, type Interrupt } from \"langchain\";\n * import { Command } from \"@langchain/langgraph\";\n *\n * // Initial agent invocation\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Write 'Hello' to output.txt\")]\n * }, config);\n *\n * // Check if agent is paused for approval\n * if (result.__interrupt__) {\n * const interruptRequest = result.__interrupt__?.[0] as Interrupt<HITLRequest>;\n *\n * // Show tool call details to user\n * console.log(\"Actions:\", interruptRequest.value.actionRequests);\n * console.log(\"Review configs:\", interruptRequest.value.reviewConfigs);\n *\n * // Resume with approval\n * const resume: HITLResponse = {\n * decisions: [{ type: \"approve\" }]\n * };\n * await agent.invoke(\n * new Command({ resume }),\n * config\n * );\n * }\n * ```\n *\n * @example\n * Different decision types\n * ```typescript\n * import { type HITLResponse } from \"langchain\";\n *\n * // Approve the tool call as-is\n * const resume: HITLResponse = {\n * decisions: [{ type: \"approve\" }]\n * };\n *\n * // Edit the tool arguments\n * const resume: HITLResponse = {\n * decisions: [{\n * type: \"edit\",\n * editedAction: { name: \"write_file\", args: { filename: \"safe.txt\", content: \"Modified\" } }\n * }]\n * };\n *\n * // Reject with feedback\n * const resume: HITLResponse = {\n * decisions: [{\n * type: \"reject\",\n * message: \"File operation not allowed in demo mode\"\n * }]\n * };\n * ```\n *\n * @example\n * Production use case with database operations\n * ```typescript\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * interruptOn: {\n * \"execute_sql\": {\n * allowedDecisions: [\"approve\", \"edit\", \"reject\"],\n * description: \"🚨 SQL query requires DBA approval\\nPlease review for safety and performance\"\n * },\n * \"read_schema\": false, // Reading metadata is safe\n * \"delete_records\": {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: \"⛔ DESTRUCTIVE OPERATION - Requires manager approval\"\n * }\n * },\n * descriptionPrefix: \"Database operation pending approval\"\n * });\n * ```\n *\n * @example\n * Using dynamic callable descriptions\n * ```typescript\n * import { type DescriptionFactory, type ToolCall } from \"langchain\";\n * import type { AgentBuiltInState, Runtime } from \"langchain/agents\";\n *\n * // Define a dynamic description factory\n * const formatToolDescription: DescriptionFactory = (\n * toolCall: ToolCall,\n * state: AgentBuiltInState,\n * runtime: Runtime<unknown>\n * ) => {\n * return `Tool: ${toolCall.name}\\nArguments:\\n${JSON.stringify(toolCall.args, null, 2)}`;\n * };\n *\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * interruptOn: {\n * \"write_file\": {\n * allowedDecisions: [\"approve\", \"edit\"],\n * // Use dynamic description that can access tool call, state, and runtime\n * description: formatToolDescription\n * },\n * // Or use an inline function\n * \"send_email\": {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: (toolCall, state, runtime) => {\n * const { to, subject } = toolCall.args;\n * return `Email to ${to}\\nSubject: ${subject}\\n\\nRequires approval before sending`;\n * }\n * }\n * }\n * });\n * ```\n *\n * @remarks\n * - Tool calls are processed in the order they appear in the AI message\n * - Auto-approved tools execute immediately without interruption\n * - Multiple tools requiring approval are bundled into a single interrupt request\n * - The middleware operates in the `afterModel` phase, intercepting before tool execution\n * - Requires a checkpointer to maintain state across interruptions\n *\n * @see {@link createAgent} for agent creation\n * @see {@link Command} for resuming interrupted execution\n * @public\n */\nexport declare function humanInTheLoopMiddleware(options: NonNullable<HumanInTheLoopMiddlewareConfig>): import(\"./types.js\").AgentMiddleware<undefined, z.ZodObject<{\n /**\n * Mapping of tool name to allowed reviewer responses.\n * If a tool doesn't have an entry, it's auto-approved by default.\n *\n * - `true` -> pause for approval and allow approve/edit/reject decisions\n * - `false` -> auto-approve (no human review)\n * - `InterruptOnConfig` -> explicitly specify which decisions are allowed for this tool\n */\n interruptOn: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodBoolean, z.ZodObject<{\n /**\n * The decisions that are allowed for this action.\n */\n allowedDecisions: z.ZodArray<z.ZodEnum<[\"approve\", \"edit\", \"reject\"]>, \"many\">;\n /**\n * The description attached to the request for human input.\n * Can be either:\n * - A static string describing the approval request\n * - A callable that dynamically generates the description based on agent state,\n * runtime, and tool call information\n *\n * @example\n * Static string description\n * ```typescript\n * import type { InterruptOnConfig } from \"langchain\";\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: \"Please review this tool execution\"\n * };\n * ```\n *\n * @example\n * Dynamic callable description\n * ```typescript\n * import type {\n * AgentBuiltInState,\n * Runtime,\n * DescriptionFactory,\n * ToolCall,\n * InterruptOnConfig\n * } from \"langchain\";\n *\n * const formatToolDescription: DescriptionFactory = (\n * toolCall: ToolCall,\n * state: AgentBuiltInState,\n * runtime: Runtime<unknown>\n * ) => {\n * return `Tool: ${toolCall.name}\\nArguments:\\n${JSON.stringify(toolCall.args, null, 2)}`;\n * };\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"edit\"],\n * description: formatToolDescription\n * };\n * ```\n */\n description: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodFunction<z.ZodTuple<[z.ZodType<ToolCall<string, Record<string, any>>, z.ZodTypeDef, ToolCall<string, Record<string, any>>>, z.ZodType<AgentBuiltInState, z.ZodTypeDef, AgentBuiltInState>, z.ZodType<Runtime<unknown>, z.ZodTypeDef, Runtime<unknown>>], z.ZodUnknown>, z.ZodUnion<[z.ZodString, z.ZodPromise<z.ZodString>]>>]>>;\n /**\n * JSON schema for the arguments associated with the action, if edits are allowed.\n */\n argsSchema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;\n }, \"strip\", z.ZodTypeAny, {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n }, {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n }>]>>>;\n /**\n * Prefix used when constructing human-facing approval messages.\n * Provides context about the tool call being reviewed; does not change the underlying action.\n *\n * Note: This prefix is only applied for tools that do not provide a custom\n * `description` via their {@link InterruptOnConfig}. If a tool specifies a custom\n * `description`, that per-tool text is used and this prefix is ignored.\n */\n descriptionPrefix: z.ZodDefault<z.ZodString>;\n}, \"strip\", z.ZodTypeAny, {\n interruptOn?: Record<string, boolean | {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n }> | undefined;\n descriptionPrefix: string;\n}, {\n interruptOn?: Record<string, boolean | {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?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AYd,CAAAA,CAAEU,UAAUV,CAAAA,CAAEQ,QAAQP,iBAAiBK,sBAAsBN,CAAAA,CAAEO,YAAYN,iBAAiBK,uBAAuBN,CAAAA,CAAEQ,QAAQL,mBAAmBH,CAAAA,CAAEO,YAAYJ,oBAAoBH,CAAAA,CAAEQ,QAAQJ,kBAAkBJ,CAAAA,CAAEO,YAAYH,oBAAoBJ,CAAAA,CAAES,aAAaT,CAAAA,CAAEa,UAAUb,CAAAA,CAAEW,WAAWX,CAAAA,CAAEY,WAAWZ,CAAAA,CAAEW;;;;gBAI7VX,CAAAA,CAAEqB,YAAYrB,CAAAA,CAAEuB,UAAUvB,CAAAA,CAAEW,WAAWX,CAAAA,CAAEsB;cAC7CtB,CAAAA,CAAEwB;;qCAEuBvB,iBAAiBK,8BAA8BH,2BAA2BC,kDAAkDqB;iBAChJnB;;;qCAGoBL,iBAAiBK,8BAA8BH,2BAA2BC,kDAAkDqB;iBAChJnB;;;;;;;;;;qBAUEN,CAAAA,CAAEwC,WAAWxC,CAAAA,CAAEW;YAC1BX,CAAAA,CAAEwB;gBACIlB;;qCAEuBL,iBAAiBK,8BAA8BH,2BAA2BC,kDAAkDqB;iBAChJnB;;;;gBAIHA;;qCAEuBL,iBAAiBK,8BAA8BH,2BAA2BC,kDAAkDqB;iBAChJnB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"hitl.d.ts","names":["z","ToolCall","InferInteropZodInput","AgentBuiltInState","Runtime","DescriptionFunctionSchema","Record","ZodTypeDef","ZodType","ZodUnknown","ZodTuple","ZodString","ZodPromise","ZodUnion","ZodFunction","DescriptionFactory","infer","DecisionType","ZodEnum","InterruptOnConfigSchema","ZodArray","ZodOptional","ZodAny","ZodRecord","ZodTypeAny","Promise","ZodObject","InterruptOnConfig","input","Action","ActionRequest","ReviewConfig","HITLRequest","ApproveDecision","EditDecision","RejectDecision","Decision","HITLResponse","contextSchema","ZodBoolean","ZodDefault","HumanInTheLoopMiddlewareConfig","humanInTheLoopMiddleware","NonNullable","__types_js1","AgentMiddleware"],"sources":["../../../src/agents/middleware/hitl.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { z } from \"zod/v3\";\nimport { ToolCall } from \"@langchain/core/messages\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\ndeclare const DescriptionFunctionSchema: z.ZodFunction<z.ZodTuple<[z.ZodType<ToolCall<string, Record<string, any>>, z.ZodTypeDef, ToolCall<string, Record<string, any>>>, z.ZodType<AgentBuiltInState, z.ZodTypeDef, AgentBuiltInState>, z.ZodType<Runtime<unknown>, z.ZodTypeDef, Runtime<unknown>>], z.ZodUnknown>, z.ZodUnion<[z.ZodString, z.ZodPromise<z.ZodString>]>>;\n/**\n * Function type that dynamically generates a description for a tool call approval request.\n *\n * @param toolCall - The tool call being reviewed\n * @param state - The current agent state\n * @param runtime - The agent runtime context\n * @returns A string description or Promise that resolves to a string description\n *\n * @example\n * ```typescript\n * import { type DescriptionFactory, type ToolCall } from \"langchain\";\n *\n * const descriptionFactory: DescriptionFactory = (toolCall, state, runtime) => {\n * return `Please review: ${toolCall.name}(${JSON.stringify(toolCall.args)})`;\n * };\n * ```\n */\nexport type DescriptionFactory = z.infer<typeof DescriptionFunctionSchema>;\ndeclare const DecisionType: z.ZodEnum<[\"approve\", \"edit\", \"reject\"]>;\nexport type DecisionType = z.infer<typeof DecisionType>;\ndeclare const InterruptOnConfigSchema: z.ZodObject<{\n /**\n * The decisions that are allowed for this action.\n */\n allowedDecisions: z.ZodArray<z.ZodEnum<[\"approve\", \"edit\", \"reject\"]>, \"many\">;\n /**\n * The description attached to the request for human input.\n * Can be either:\n * - A static string describing the approval request\n * - A callable that dynamically generates the description based on agent state,\n * runtime, and tool call information\n *\n * @example\n * Static string description\n * ```typescript\n * import type { InterruptOnConfig } from \"langchain\";\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: \"Please review this tool execution\"\n * };\n * ```\n *\n * @example\n * Dynamic callable description\n * ```typescript\n * import type {\n * AgentBuiltInState,\n * Runtime,\n * DescriptionFactory,\n * ToolCall,\n * InterruptOnConfig\n * } from \"langchain\";\n *\n * const formatToolDescription: DescriptionFactory = (\n * toolCall: ToolCall,\n * state: AgentBuiltInState,\n * runtime: Runtime<unknown>\n * ) => {\n * return `Tool: ${toolCall.name}\\nArguments:\\n${JSON.stringify(toolCall.args, null, 2)}`;\n * };\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"edit\"],\n * description: formatToolDescription\n * };\n * ```\n */\n description: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodFunction<z.ZodTuple<[z.ZodType<ToolCall<string, Record<string, any>>, z.ZodTypeDef, ToolCall<string, Record<string, any>>>, z.ZodType<AgentBuiltInState, z.ZodTypeDef, AgentBuiltInState>, z.ZodType<Runtime<unknown>, z.ZodTypeDef, Runtime<unknown>>], z.ZodUnknown>, z.ZodUnion<[z.ZodString, z.ZodPromise<z.ZodString>]>>]>>;\n /**\n * JSON schema for the arguments associated with the action, if edits are allowed.\n */\n argsSchema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;\n}, \"strip\", z.ZodTypeAny, {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n}, {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n}>;\nexport type InterruptOnConfig = z.input<typeof InterruptOnConfigSchema>;\n/**\n * Represents an action with a name and arguments.\n */\nexport interface Action {\n /**\n * The type or name of action being requested (e.g., \"add_numbers\").\n */\n name: string;\n /**\n * Key-value pairs of arguments needed for the action (e.g., {\"a\": 1, \"b\": 2}).\n */\n args: Record<string, any>;\n}\n/**\n * Represents an action request with a name, arguments, and description.\n */\nexport interface ActionRequest {\n /**\n * The name of the action being requested.\n */\n name: string;\n /**\n * Key-value pairs of arguments needed for the action (e.g., {\"a\": 1, \"b\": 2}).\n */\n args: Record<string, any>;\n /**\n * The description of the action to be reviewed.\n */\n description?: string;\n}\n/**\n * Policy for reviewing a HITL request.\n */\nexport interface ReviewConfig {\n /**\n * Name of the action associated with this review configuration.\n */\n actionName: string;\n /**\n * The decisions that are allowed for this request.\n */\n allowedDecisions: DecisionType[];\n /**\n * JSON schema for the arguments associated with the action, if edits are allowed.\n */\n argsSchema?: Record<string, any>;\n}\n/**\n * Request for human feedback on a sequence of actions requested by a model.\n *\n * @example\n * ```ts\n * const hitlRequest: HITLRequest = {\n * actionRequests: [\n * { name: \"send_email\", args: { to: \"user@example.com\", subject: \"Hello\" } }\n * ],\n * reviewConfigs: [\n * {\n * actionName: \"send_email\",\n * allowedDecisions: [\"approve\", \"edit\", \"reject\"],\n * description: \"Please review the email before sending\"\n * }\n * ]\n * };\n * const response = interrupt(hitlRequest);\n * ```\n */\nexport interface HITLRequest {\n /**\n * A list of agent actions for human review.\n */\n actionRequests: ActionRequest[];\n /**\n * Review configuration for all possible actions.\n */\n reviewConfigs: ReviewConfig[];\n}\n/**\n * Response when a human approves the action.\n */\nexport interface ApproveDecision {\n type: \"approve\";\n}\n/**\n * Response when a human edits the action.\n */\nexport interface EditDecision {\n type: \"edit\";\n /**\n * Edited action for the agent to perform.\n * Ex: for a tool call, a human reviewer can edit the tool name and args.\n */\n editedAction: Action;\n}\n/**\n * Response when a human rejects the action.\n */\nexport interface RejectDecision {\n type: \"reject\";\n /**\n * The message sent to the model explaining why the action was rejected.\n */\n message?: string;\n}\n/**\n * Union of all possible decision types.\n */\nexport type Decision = ApproveDecision | EditDecision | RejectDecision;\n/**\n * Response payload for a HITLRequest.\n */\nexport interface HITLResponse {\n /**\n * The decisions made by the human.\n */\n decisions: Decision[];\n}\ndeclare const contextSchema: z.ZodObject<{\n /**\n * Mapping of tool name to allowed reviewer responses.\n * If a tool doesn't have an entry, it's auto-approved by default.\n *\n * - `true` -> pause for approval and allow approve/edit/reject decisions\n * - `false` -> auto-approve (no human review)\n * - `InterruptOnConfig` -> explicitly specify which decisions are allowed for this tool\n */\n interruptOn: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodBoolean, z.ZodObject<{\n /**\n * The decisions that are allowed for this action.\n */\n allowedDecisions: z.ZodArray<z.ZodEnum<[\"approve\", \"edit\", \"reject\"]>, \"many\">;\n /**\n * The description attached to the request for human input.\n * Can be either:\n * - A static string describing the approval request\n * - A callable that dynamically generates the description based on agent state,\n * runtime, and tool call information\n *\n * @example\n * Static string description\n * ```typescript\n * import type { InterruptOnConfig } from \"langchain\";\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: \"Please review this tool execution\"\n * };\n * ```\n *\n * @example\n * Dynamic callable description\n * ```typescript\n * import type {\n * AgentBuiltInState,\n * Runtime,\n * DescriptionFactory,\n * ToolCall,\n * InterruptOnConfig\n * } from \"langchain\";\n *\n * const formatToolDescription: DescriptionFactory = (\n * toolCall: ToolCall,\n * state: AgentBuiltInState,\n * runtime: Runtime<unknown>\n * ) => {\n * return `Tool: ${toolCall.name}\\nArguments:\\n${JSON.stringify(toolCall.args, null, 2)}`;\n * };\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"edit\"],\n * description: formatToolDescription\n * };\n * ```\n */\n description: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodFunction<z.ZodTuple<[z.ZodType<ToolCall<string, Record<string, any>>, z.ZodTypeDef, ToolCall<string, Record<string, any>>>, z.ZodType<AgentBuiltInState, z.ZodTypeDef, AgentBuiltInState>, z.ZodType<Runtime<unknown>, z.ZodTypeDef, Runtime<unknown>>], z.ZodUnknown>, z.ZodUnion<[z.ZodString, z.ZodPromise<z.ZodString>]>>]>>;\n /**\n * JSON schema for the arguments associated with the action, if edits are allowed.\n */\n argsSchema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;\n }, \"strip\", z.ZodTypeAny, {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n }, {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n }>]>>>;\n /**\n * Prefix used when constructing human-facing approval messages.\n * Provides context about the tool call being reviewed; does not change the underlying action.\n *\n * Note: This prefix is only applied for tools that do not provide a custom\n * `description` via their {@link InterruptOnConfig}. If a tool specifies a custom\n * `description`, that per-tool text is used and this prefix is ignored.\n */\n descriptionPrefix: z.ZodDefault<z.ZodString>;\n}, \"strip\", z.ZodTypeAny, {\n interruptOn?: Record<string, boolean | {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n }> | undefined;\n descriptionPrefix: string;\n}, {\n interruptOn?: Record<string, boolean | {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n }> | undefined;\n descriptionPrefix?: string | undefined;\n}>;\nexport type HumanInTheLoopMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;\n/**\n * Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.\n *\n * This middleware intercepts tool calls made by an AI agent and provides human oversight\n * capabilities before execution. It enables selective approval workflows where certain tools\n * require human intervention while others can execute automatically.\n *\n * A invocation result that has been interrupted by the middleware will have a `__interrupt__`\n * property that contains the interrupt request.\n *\n * ```ts\n * import { type HITLRequest, type HITLResponse } from \"langchain\";\n * import { type Interrupt } from \"langchain\";\n *\n * const result = await agent.invoke(request);\n * const interruptRequest = result.__interrupt__?.[0] as Interrupt<HITLRequest>;\n *\n * // Examine the action requests and review configs\n * const actionRequests = interruptRequest.value.actionRequests;\n * const reviewConfigs = interruptRequest.value.reviewConfigs;\n *\n * // Create decisions for each action\n * const resume: HITLResponse = {\n * decisions: actionRequests.map((action, i) => {\n * if (action.name === \"calculator\") {\n * return { type: \"approve\" };\n * } else if (action.name === \"write_file\") {\n * return {\n * type: \"edit\",\n * editedAction: { name: \"write_file\", args: { filename: \"safe.txt\", content: \"Safe content\" } }\n * };\n * }\n * return { type: \"reject\", message: \"Action not allowed\" };\n * })\n * };\n *\n * // Resume with decisions\n * await agent.invoke(new Command({ resume }), config);\n * ```\n *\n * ## Features\n *\n * - **Selective Tool Approval**: Configure which tools require human approval\n * - **Multiple Decision Types**: Approve, edit, or reject tool calls\n * - **Asynchronous Workflow**: Uses LangGraph's interrupt mechanism for non-blocking approval\n * - **Custom Approval Messages**: Provide context-specific descriptions for approval requests\n *\n * ## Decision Types\n *\n * When a tool requires approval, the human operator can respond with:\n * - `approve`: Execute the tool with original arguments\n * - `edit`: Modify the tool name and/or arguments before execution\n * - `reject`: Provide a manual response instead of executing the tool\n *\n * @param options - Configuration options for the middleware\n * @param options.interruptOn - Per-tool configuration mapping tool names to their settings\n * @param options.interruptOn[toolName].allowedDecisions - Array of decision types allowed for this tool (e.g., [\"approve\", \"edit\", \"reject\"])\n * @param options.interruptOn[toolName].description - Custom approval message for the tool. Can be either a static string or a callable that dynamically generates the description based on agent state, runtime, and tool call information\n * @param options.interruptOn[toolName].argsSchema - JSON schema for the arguments associated with the action, if edits are allowed\n * @param options.descriptionPrefix - Default prefix for approval messages (default: \"Tool execution requires approval\"). Only used for tools that do not define a custom `description` in their InterruptOnConfig.\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @example\n * Basic usage with selective tool approval\n * ```typescript\n * import { humanInTheLoopMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * interruptOn: {\n * // Interrupt write_file tool and allow edits or approvals\n * \"write_file\": {\n * allowedDecisions: [\"approve\", \"edit\"],\n * description: \"⚠️ File write operation requires approval\"\n * },\n * // Auto-approve read_file tool\n * \"read_file\": false\n * }\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * tools: [writeFileTool, readFileTool],\n * middleware: [hitlMiddleware]\n * });\n * ```\n *\n * @example\n * Handling approval requests\n * ```typescript\n * import { type HITLRequest, type HITLResponse, type Interrupt } from \"langchain\";\n * import { Command } from \"@langchain/langgraph\";\n *\n * // Initial agent invocation\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Write 'Hello' to output.txt\")]\n * }, config);\n *\n * // Check if agent is paused for approval\n * if (result.__interrupt__) {\n * const interruptRequest = result.__interrupt__?.[0] as Interrupt<HITLRequest>;\n *\n * // Show tool call details to user\n * console.log(\"Actions:\", interruptRequest.value.actionRequests);\n * console.log(\"Review configs:\", interruptRequest.value.reviewConfigs);\n *\n * // Resume with approval\n * const resume: HITLResponse = {\n * decisions: [{ type: \"approve\" }]\n * };\n * await agent.invoke(\n * new Command({ resume }),\n * config\n * );\n * }\n * ```\n *\n * @example\n * Different decision types\n * ```typescript\n * import { type HITLResponse } from \"langchain\";\n *\n * // Approve the tool call as-is\n * const resume: HITLResponse = {\n * decisions: [{ type: \"approve\" }]\n * };\n *\n * // Edit the tool arguments\n * const resume: HITLResponse = {\n * decisions: [{\n * type: \"edit\",\n * editedAction: { name: \"write_file\", args: { filename: \"safe.txt\", content: \"Modified\" } }\n * }]\n * };\n *\n * // Reject with feedback\n * const resume: HITLResponse = {\n * decisions: [{\n * type: \"reject\",\n * message: \"File operation not allowed in demo mode\"\n * }]\n * };\n * ```\n *\n * @example\n * Production use case with database operations\n * ```typescript\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * interruptOn: {\n * \"execute_sql\": {\n * allowedDecisions: [\"approve\", \"edit\", \"reject\"],\n * description: \"🚨 SQL query requires DBA approval\\nPlease review for safety and performance\"\n * },\n * \"read_schema\": false, // Reading metadata is safe\n * \"delete_records\": {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: \"⛔ DESTRUCTIVE OPERATION - Requires manager approval\"\n * }\n * },\n * descriptionPrefix: \"Database operation pending approval\"\n * });\n * ```\n *\n * @example\n * Using dynamic callable descriptions\n * ```typescript\n * import { type DescriptionFactory, type ToolCall } from \"langchain\";\n * import type { AgentBuiltInState, Runtime } from \"langchain/agents\";\n *\n * // Define a dynamic description factory\n * const formatToolDescription: DescriptionFactory = (\n * toolCall: ToolCall,\n * state: AgentBuiltInState,\n * runtime: Runtime<unknown>\n * ) => {\n * return `Tool: ${toolCall.name}\\nArguments:\\n${JSON.stringify(toolCall.args, null, 2)}`;\n * };\n *\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * interruptOn: {\n * \"write_file\": {\n * allowedDecisions: [\"approve\", \"edit\"],\n * // Use dynamic description that can access tool call, state, and runtime\n * description: formatToolDescription\n * },\n * // Or use an inline function\n * \"send_email\": {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: (toolCall, state, runtime) => {\n * const { to, subject } = toolCall.args;\n * return `Email to ${to}\\nSubject: ${subject}\\n\\nRequires approval before sending`;\n * }\n * }\n * }\n * });\n * ```\n *\n * @remarks\n * - Tool calls are processed in the order they appear in the AI message\n * - Auto-approved tools execute immediately without interruption\n * - Multiple tools requiring approval are bundled into a single interrupt request\n * - The middleware operates in the `afterModel` phase, intercepting before tool execution\n * - Requires a checkpointer to maintain state across interruptions\n *\n * @see {@link createAgent} for agent creation\n * @see {@link Command} for resuming interrupted execution\n * @public\n */\nexport declare function humanInTheLoopMiddleware(options: NonNullable<HumanInTheLoopMiddlewareConfig>): import(\"./types.js\").AgentMiddleware<undefined, z.ZodObject<{\n /**\n * Mapping of tool name to allowed reviewer responses.\n * If a tool doesn't have an entry, it's auto-approved by default.\n *\n * - `true` -> pause for approval and allow approve/edit/reject decisions\n * - `false` -> auto-approve (no human review)\n * - `InterruptOnConfig` -> explicitly specify which decisions are allowed for this tool\n */\n interruptOn: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodBoolean, z.ZodObject<{\n /**\n * The decisions that are allowed for this action.\n */\n allowedDecisions: z.ZodArray<z.ZodEnum<[\"approve\", \"edit\", \"reject\"]>, \"many\">;\n /**\n * The description attached to the request for human input.\n * Can be either:\n * - A static string describing the approval request\n * - A callable that dynamically generates the description based on agent state,\n * runtime, and tool call information\n *\n * @example\n * Static string description\n * ```typescript\n * import type { InterruptOnConfig } from \"langchain\";\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"reject\"],\n * description: \"Please review this tool execution\"\n * };\n * ```\n *\n * @example\n * Dynamic callable description\n * ```typescript\n * import type {\n * AgentBuiltInState,\n * Runtime,\n * DescriptionFactory,\n * ToolCall,\n * InterruptOnConfig\n * } from \"langchain\";\n *\n * const formatToolDescription: DescriptionFactory = (\n * toolCall: ToolCall,\n * state: AgentBuiltInState,\n * runtime: Runtime<unknown>\n * ) => {\n * return `Tool: ${toolCall.name}\\nArguments:\\n${JSON.stringify(toolCall.args, null, 2)}`;\n * };\n *\n * const config: InterruptOnConfig = {\n * allowedDecisions: [\"approve\", \"edit\"],\n * description: formatToolDescription\n * };\n * ```\n */\n description: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodFunction<z.ZodTuple<[z.ZodType<ToolCall<string, Record<string, any>>, z.ZodTypeDef, ToolCall<string, Record<string, any>>>, z.ZodType<AgentBuiltInState, z.ZodTypeDef, AgentBuiltInState>, z.ZodType<Runtime<unknown>, z.ZodTypeDef, Runtime<unknown>>], z.ZodUnknown>, z.ZodUnion<[z.ZodString, z.ZodPromise<z.ZodString>]>>]>>;\n /**\n * JSON schema for the arguments associated with the action, if edits are allowed.\n */\n argsSchema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;\n }, \"strip\", z.ZodTypeAny, {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n }, {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n }>]>>>;\n /**\n * Prefix used when constructing human-facing approval messages.\n * Provides context about the tool call being reviewed; does not change the underlying action.\n *\n * Note: This prefix is only applied for tools that do not provide a custom\n * `description` via their {@link InterruptOnConfig}. If a tool specifies a custom\n * `description`, that per-tool text is used and this prefix is ignored.\n */\n descriptionPrefix: z.ZodDefault<z.ZodString>;\n}, \"strip\", z.ZodTypeAny, {\n interruptOn?: Record<string, boolean | {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n }> | undefined;\n descriptionPrefix: string;\n}, {\n interruptOn?: Record<string, boolean | {\n allowedDecisions: (\"approve\" | \"edit\" | \"reject\")[];\n description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;\n argsSchema?: Record<string, any> | undefined;\n }> | undefined;\n descriptionPrefix?: string | undefined;\n}>, any>;\nexport {};\n"],"mappings":";;;;;;;cAKcK,2BAA2BL,CAAAA,CAAEc,YAAYd,CAAAA,CAAEU,UAAUV,CAAAA,CAAEQ,QAAQP,iBAAiBK,sBAAsBN,CAAAA,CAAEO,YAAYN,iBAAiBK,uBAAuBN,CAAAA,CAAEQ,QAAQL,mBAAmBH,CAAAA,CAAEO,YAAYJ,oBAAoBH,CAAAA,CAAEQ,QAAQJ,kBAAkBJ,CAAAA,CAAEO,YAAYH,oBAAoBJ,CAAAA,CAAES,aAAaT,CAAAA,CAAEa,UAAUb,CAAAA,CAAEW,WAAWX,CAAAA,CAAEY,WAAWZ,CAAAA,CAAEW;;AAD9R;;;;;;;;;;;;;;;;AACuOX,KAkB3Re,kBAAAA,GAAqBf,CAAAA,CAAEgB,KAlBsQP,CAAAA,OAkBzPJ,yBAlByPI,CAAAA;cAmB3RQ,YAnB2CP,EAmB7BV,CAAAA,CAAEkB,OAnB2BR,CAAAA,CAAAA,SAAAA,EAAAA,MAAAA,EAAAA,QAAAA,CAAAA,CAAAA;AAAyQV,KAoBtTiB,YAAAA,GAAejB,CAAAA,CAAEgB,KApBuSL,CAAAA,OAoB1RM,YApB0RN,CAAAA;cAqBtTQ,uBArBgVR,EAqBvTX,CAAAA,CAAE0B,SArBqTf,CAAAA;EAAS;;;EAAjT,gBAAA,EAyBhCX,CAAAA,CAAEoB,QAzB8B,CAyBrBpB,CAAAA,CAAEkB,OAzBmB,CAAA,CAAA,SAAA,EAAA,MAAA,EAAA,QAAA,CAAA,CAAA,EAAA,MAAA,CAAA;EAkB1CH;;;;AAA4B;AAAmC;AAE3E;;;;AAAkC;AAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAqD3B,WACfS,EALGxB,CAAAA,CAAEqB,WAKLG,CALiBxB,CAAAA,CAAEa,QAKnBW,CAAAA,C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b,CAAAA,CAAEW,WAAWX,CAAAA,CAAEc,YAAYd,CAAAA,CAAEU,UAAUV,CAAAA,CAAEQ,QAAQP,iBAAiBK,sBAAsBN,CAAAA,CAAEO,YAAYN,iBAAiBK,uBAAuBN,CAAAA,CAAEQ,QAAQL,mBAAmBH,CAAAA,CAAEO,YAAYJ,oBAAoBH,CAAAA,CAAEQ,QAAQJ,kBAAkBJ,CAAAA,CAAEO,YAAYH,oBAAoBJ,CAAAA,CAAES,aAAaT,CAAAA,CAAEa,UAAUb,CAAAA,CAAEW,WAAWX,CAAAA,CAAEY,WAAWZ,CAAAA,CAAEW;;;;gBAI7VX,CAAAA,CAAEqB,YAAYrB,CAAAA,CAAEuB,UAAUvB,CAAAA,CAAEW,WAAWX,CAAAA,CAAEsB;cAC7CtB,CAAAA,CAAEwB;;qCAEuBvB,iBAAiBK,8BAA8BH,2BAA2BC,kDAAkDqB;iBAChJnB;;;qCAGoBL,iBAAiBK,8BAA8BH,2BAA2BC,kDAAkDqB;iBAChJnB;;;;;;;;;;qBAUEN,CAAAA,CAAEwC,WAAWxC,CAAAA,CAAEW;YAC1BX,CAAAA,CAAEwB;gBACIlB;;qCAEuBL,iBAAiBK,8BAA8BH,2BAA2BC,kDAAkDqB;iBAChJnB;;;;gBAIHA;;qCAEuBL,iBAAiBK,8BAA8BH,2BAA2BC,kDAAkDqB;iBAChJnB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"llmToolSelector.d.cts","names":["z","BaseLanguageModel","InferInteropZodInput","createMiddleware","LLMToolSelectorOptionsSchema","ZodString","_langchain_core_language_models_base7","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"],"mappings":";;;;;;;;;;AAOqBI,cAAAA,4BA6BnB,EA7BiDJ,CAAAA,CAAEe,SA6BnD,CAAA;EAAA;;;EAzBgK,KAAtGd,EAAjDD,CAAAA,CAAEW,WAA+CV,CAAnCD,CAAAA,CAAEU,QAAiCT,CAAAA,CAAvBD,CAAAA,CAAEK,SAAqBJ,EAAVD,CAAAA,CAAES,OAAQR,CAAAA,iBAAAA,CAAAA,OAAAA,EAAZK,qCAAAA,CAAsFC,4BAAAA,CAA1EN,EAAyGD,CAAAA,CAAEQ,UAA3GP,EAAuHA,iBAAvHA,CAAAA,OAAAA,EAAqHK,qCAAAA,CAA4EC,4BAAAA,CAAjMN,CAAAA,CAAAA,CAAAA,CAAAA;EAAiB;;;EAAuH,YAAhJQ,EAIlCT,CAAAA,CAAEW,WAJgCF,CAIpBT,CAAAA,CAAEK,SAJkBI,CAAAA;EAAO;;;;EAI5B,QAKDG,EAAhBZ,CAAAA,CAAEW,WAAcC,CAAFZ,CAAAA,CAAEY,SAAAA,CAAAA;EAAS;;;;EAKP,aAClBE,EADKd,CAAAA,CAAEW,WACPG,CADmBd,CAAAA,CAAEa,QACrBC,CAD8Bd,CAAAA,CAAEK,SAChCS,EAAAA,MAAAA,CAAAA,CAAAA;CAAU,EAAA,OAAAR,EAAZN,CAAAA,CAAEc,UAAUR,EAAAA;EACmG,KAAtGL,CAAAA,EAAAA,MAAAA,GAAAA,iBAAAA,CAAAA,OAAAA,EADGK,qCAAAA,CACuEC,4BAAAA,CAA1EN,GAAAA,SAAAA;EAAiB,YAAAK,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAKqF,QAAtGL,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAiB,aAzBec,CAAAA,EAAAA,MAAAA,EAAAA,GAAAA,SAAAA;AAAS,CAAA,EAAA;EA8BlDC,KAAAA,CAAAA,EAAAA,MAAAA,GALSf,iBAKY,CAAA,OAAA,EAVKK,qCAAAA,CAKyDC,4BAAAA,CAK9D,GAAA,SAAA;EAAA,YAAA,CAAA,EAAA,MAAA,GAAA,SAAA;EAAA,QAA+BH,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAA4B,aAAxDF,CAAAA,EAAAA,MAAAA,EAAAA,GAAAA,SAAAA;AAAoB,CAAA,CAAA;AAuChCe,KAvCZD,qBAAAA,GAAwBd,oBAuCa,CAAA,OAvCeE,4BAuCf,CAAA;;;;;AAA4C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAArEa,yBAAAA,UAAmCD,wBAAwBE,kBAAkBf"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"llmToolSelector.d.ts","names":["z","BaseLanguageModel","InferInteropZodInput","createMiddleware","LLMToolSelectorOptionsSchema","ZodString","_langchain_core_language_models_base7","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"],"mappings":";;;;;;;;;;AAOqBI,cAAAA,4BA6BnB,EA7BiDJ,CAAAA,CAAEe,SA6BnD,CAAA;EAAA;;;EAzBgK,KAAtGd,EAAjDD,CAAAA,CAAEW,WAA+CV,CAAnCD,CAAAA,CAAEU,QAAiCT,CAAAA,CAAvBD,CAAAA,CAAEK,SAAqBJ,EAAVD,CAAAA,CAAES,OAAQR,CAAAA,iBAAAA,CAAAA,OAAAA,EAAZK,qCAAAA,CAAsFC,4BAAAA,CAA1EN,EAAyGD,CAAAA,CAAEQ,UAA3GP,EAAuHA,iBAAvHA,CAAAA,OAAAA,EAAqHK,qCAAAA,CAA4EC,4BAAAA,CAAjMN,CAAAA,CAAAA,CAAAA,CAAAA;EAAiB;;;EAAuH,YAAhJQ,EAIlCT,CAAAA,CAAEW,WAJgCF,CAIpBT,CAAAA,CAAEK,SAJkBI,CAAAA;EAAO;;;;EAI5B,QAKDG,EAAhBZ,CAAAA,CAAEW,WAAcC,CAAFZ,CAAAA,CAAEY,SAAAA,CAAAA;EAAS;;;;EAKP,aAClBE,EADKd,CAAAA,CAAEW,WACPG,CADmBd,CAAAA,CAAEa,QACrBC,CAD8Bd,CAAAA,CAAEK,SAChCS,EAAAA,MAAAA,CAAAA,CAAAA;CAAU,EAAA,OAAAR,EAAZN,CAAAA,CAAEc,UAAUR,EAAAA;EACmG,KAAtGL,CAAAA,EAAAA,MAAAA,GAAAA,iBAAAA,CAAAA,OAAAA,EADGK,qCAAAA,CACuEC,4BAAAA,CAA1EN,GAAAA,SAAAA;EAAiB,YAAAK,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAKqF,QAAtGL,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAiB,aAzBec,CAAAA,EAAAA,MAAAA,EAAAA,GAAAA,SAAAA;AAAS,CAAA,EAAA;EA8BlDC,KAAAA,CAAAA,EAAAA,MAAAA,GALSf,iBAKY,CAAA,OAAA,EAVKK,qCAAAA,CAKyDC,4BAAAA,CAK9D,GAAA,SAAA;EAAA,YAAA,CAAA,EAAA,MAAA,GAAA,SAAA;EAAA,QAA+BH,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAA4B,aAAxDF,CAAAA,EAAAA,MAAAA,EAAAA,GAAAA,SAAAA;AAAoB,CAAA,CAAA;AAuChCe,KAvCZD,qBAAAA,GAAwBd,oBAuCa,CAAA,OAvCeE,4BAuCf,CAAA;;;;;AAA4C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAArEa,yBAAAA,UAAmCD,wBAAwBE,kBAAkBf"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"modelCallLimit.d.cts","names":["z","InferInteropZodInput","contextSchema","ZodNumber","ZodOptional","ZodEnum","ZodTypeAny","ZodObject","ModelCallLimitMiddlewareConfig","Partial","modelCallLimitMiddleware","ZodDefault","__types_js14","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}>, any>;\nexport {};\n"],"mappings":";;;;;cAEcE,eAAeF,CAAAA,CAAEO;;;AADoC;EAyBjE,WAAA,EApBeP,CAAAA,CAAEI,WAoBjB,CApB6BJ,CAAAA,CAAEG,SAoB/B,CAAA;EAAA;;;EAhBqC,QAAvBC,EAAFJ,CAAAA,CAAEI,WAAAA,CAAYJ,CAAAA,CAAEG,SAAdC,CAAAA;EAAW;;;;AARa;AAyBxC;EAA0C,YAAA,EAVxBJ,CAAAA,CAAEI,WAUsB,CAVVJ,CAAAA,CAAEK,OAUQ,CAAA,CAAA,OAAA,EAAA,KAAA,CAAA,CAAA,CAAA;CAAA,EAAA,OAAuCH,EATrEF,CAAAA,CAAEM,UASmEJ,EAAAA;EAAa,WAAzCD,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAoB,QAA5BQ,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAO,YAAA,CAAA,EAAA,KAAA,GAAA,OAAA,GAAA,SAAA;AA6DpD,CAAA,EAAA;EAAgD,WAAA,CAAA,EAAA,MAAA,GAAA,SAAA;EAAA,QAAqBD,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAA8B,YAC1DL,CAAAA,EAAAA,KAAAA,GAAAA,OAAAA,GAAAA,SAAAA;CAAS,CAAA;AACdH,KA/DxBQ,8BAAAA,GAAiCC,OA+DPN,CA/DeF,oBA+DfE,CAAAA,OA/D2CD,aA+D3CC,CAAAA,CAAAA;;;;;;;;;;;;;AAFoG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAlHO,wBAAAA,qBAA6CF,iCAStD,gBAT4HR,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"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"modelCallLimit.d.ts","names":["z","InferInteropZodInput","contextSchema","ZodNumber","ZodOptional","ZodEnum","ZodTypeAny","ZodObject","ModelCallLimitMiddlewareConfig","Partial","modelCallLimitMiddleware","ZodDefault","__types_js5","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}>, any>;\nexport {};\n"],"mappings":";;;;;cAEcE,eAAeF,CAAAA,CAAEO;;;AADoC;EAyBjE,WAAA,EApBeP,CAAAA,CAAEI,WAoBjB,CApB6BJ,CAAAA,CAAEG,SAoB/B,CAAA;EAAA;;;EAhBqC,QAAvBC,EAAFJ,CAAAA,CAAEI,WAAAA,CAAYJ,CAAAA,CAAEG,SAAdC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"],"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"],"mappings":";;;;;;;AAkCA;;;;AAImE;;;;;;;;;;;;;;;;;;;;;;;;;;iBAJ3CE,uBAAAA;;;;6BAIKF,uBAAuBC"}
@@ -1 +0,0 @@
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"],"mappings":";;;;;;;AAkCA;;;;AAImE;;;;;;;;;;;;;;;;;;;;;;;;;;iBAJ3CE,uBAAAA;;;;6BAIKF,uBAAuBC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"pii.d.cts","names":["z","InferInteropZodInput","createMiddleware","PIIMatch","PIIDetectionError","Error","PIIStrategy","BuiltInPIIType","PIIDetector","Detector","RegExp","RedactionRuleConfig","ResolvedRedactionRule","detectEmail","detectCreditCard","detectIP","detectMacAddress","detectUrl","resolveRedactionRule","applyStrategy","contextSchema","ZodBoolean","ZodOptional","ZodTypeAny","ZodObject","PIIMiddlewareConfig","piiMiddleware","ReturnType"],"sources":["../../../src/agents/middleware/pii.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport { createMiddleware } from \"../middleware.js\";\n/**\n * Represents a detected PII match in content\n */\nexport interface PIIMatch {\n /**\n * The matched text\n */\n text: string;\n /**\n * The start index of the match\n */\n start: number;\n /**\n * The end index of the match\n */\n end: number;\n}\n/**\n * Error thrown when PII is detected and strategy is 'block'\n */\nexport declare class PIIDetectionError extends Error {\n readonly piiType: string;\n readonly matches: PIIMatch[];\n constructor(piiType: string, matches: PIIMatch[]);\n}\n/**\n * Strategy for handling detected PII\n */\nexport type PIIStrategy = \"block\" | \"redact\" | \"mask\" | \"hash\";\n/**\n * Built-in PII types\n */\nexport type BuiltInPIIType = \"email\" | \"credit_card\" | \"ip\" | \"mac_address\" | \"url\";\n/**\n * Custom detector function that takes content and returns matches\n */\nexport type PIIDetector = (content: string) => PIIMatch[];\nexport type Detector = PIIDetector | RegExp | string;\n/**\n * Configuration for a redaction rule\n */\nexport interface RedactionRuleConfig {\n /**\n * Type of PII to detect (built-in or custom name)\n */\n piiType: BuiltInPIIType | string;\n /**\n * Strategy for handling detected PII\n */\n strategy: PIIStrategy;\n /**\n * Custom detector function or regex pattern string\n */\n detector?: Detector;\n}\n/**\n * Resolved redaction rule with a concrete detector function\n */\nexport interface ResolvedRedactionRule {\n piiType: string;\n strategy: PIIStrategy;\n detector: PIIDetector;\n}\n/**\n * Detect email addresses in content\n */\nexport declare function detectEmail(content: string): PIIMatch[];\n/**\n * Detect credit card numbers in content (validated with Luhn algorithm)\n */\nexport declare function detectCreditCard(content: string): PIIMatch[];\n/**\n * Detect IP addresses in content (validated)\n */\nexport declare function detectIP(content: string): PIIMatch[];\n/**\n * Detect MAC addresses in content\n */\nexport declare function detectMacAddress(content: string): PIIMatch[];\n/**\n * Detect URLs in content\n */\nexport declare function detectUrl(content: string): PIIMatch[];\n/**\n * Resolve a redaction rule to a concrete detector function\n */\nexport declare function resolveRedactionRule(config: RedactionRuleConfig): ResolvedRedactionRule;\n/**\n * Apply strategy to content based on matches\n */\nexport declare function applyStrategy(content: string, matches: PIIMatch[], strategy: PIIStrategy, piiType: string): string;\n/**\n * Configuration schema for PII middleware\n */\ndeclare const contextSchema: z.ZodObject<{\n /**\n * Whether to check user messages before model call\n */\n applyToInput: z.ZodOptional<z.ZodBoolean>;\n /**\n * Whether to check AI messages after model call\n */\n applyToOutput: z.ZodOptional<z.ZodBoolean>;\n /**\n * Whether to check tool result messages after tool execution\n */\n applyToToolResults: z.ZodOptional<z.ZodBoolean>;\n}, \"strip\", z.ZodTypeAny, {\n applyToInput?: boolean | undefined;\n applyToOutput?: boolean | undefined;\n applyToToolResults?: boolean | undefined;\n}, {\n applyToInput?: boolean | undefined;\n applyToOutput?: boolean | undefined;\n applyToToolResults?: boolean | undefined;\n}>;\nexport type PIIMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;\n/**\n * Creates a middleware that detects and handles personally identifiable information (PII)\n * in conversations.\n *\n * This middleware detects common PII types and applies configurable strategies to handle them.\n * It can detect emails, credit cards, IP addresses, MAC addresses, and URLs in both user input\n * and agent output.\n *\n * Built-in PII types:\n * - `email`: Email addresses\n * - `credit_card`: Credit card numbers (validated with Luhn algorithm)\n * - `ip`: IP addresses (validated)\n * - `mac_address`: MAC addresses\n * - `url`: URLs (both `http`/`https` and bare URLs)\n *\n * Strategies:\n * - `block`: Raise an exception when PII is detected\n * - `redact`: Replace PII with `[REDACTED_TYPE]` placeholders\n * - `mask`: Partially mask PII (e.g., `****-****-****-1234` for credit card)\n * - `hash`: Replace PII with deterministic hash (e.g., `<email_hash:a1b2c3d4>`)\n *\n * Strategy Selection Guide:\n * | Strategy | Preserves Identity? | Best For |\n * | -------- | ------------------- | --------------------------------------- |\n * | `block` | N/A | Avoid PII completely |\n * | `redact` | No | General compliance, log sanitization |\n * | `mask` | No | Human readability, customer service UIs |\n * | `hash` | Yes (pseudonymous) | Analytics, debugging |\n *\n * @param piiType - Type of PII to detect. Can be a built-in type (`email`, `credit_card`, `ip`, `mac_address`, `url`) or a custom type name.\n * @param options - Configuration options\n * @param options.strategy - How to handle detected PII. Defaults to `\"redact\"`.\n * @param options.detector - Custom detector function or regex pattern string. If not provided, uses built-in detector for the `piiType`.\n * @param options.applyToInput - Whether to check user messages before model call. Defaults to `true`.\n * @param options.applyToOutput - Whether to check AI messages after model call. Defaults to `false`.\n * @param options.applyToToolResults - Whether to check tool result messages after tool execution. Defaults to `false`.\n *\n * @returns Middleware instance for use with `createAgent`\n *\n * @throws {PIIDetectionError} When PII is detected and strategy is `'block'`\n * @throws {Error} If `piiType` is not built-in and no detector is provided\n *\n * @example Basic usage\n * ```typescript\n * import { piiMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * // Redact all emails in user input\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * middleware: [\n * piiMiddleware(\"email\", { strategy: \"redact\" }),\n * ],\n * });\n * ```\n *\n * @example Different strategies for different PII types\n * ```typescript\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [\n * piiMiddleware(\"credit_card\", { strategy: \"mask\" }),\n * piiMiddleware(\"url\", { strategy: \"redact\" }),\n * piiMiddleware(\"ip\", { strategy: \"hash\" }),\n * ],\n * });\n * ```\n *\n * @example Custom PII type with regex\n * ```typescript\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * middleware: [\n * piiMiddleware(\"api_key\", {\n * detector: \"sk-[a-zA-Z0-9]{32}\",\n * strategy: \"block\",\n * }),\n * ],\n * });\n * ```\n *\n * @public\n */\nexport declare function piiMiddleware(piiType: BuiltInPIIType | string, options?: {\n strategy?: PIIStrategy;\n detector?: Detector;\n applyToInput?: boolean;\n applyToOutput?: boolean;\n applyToToolResults?: boolean;\n}): ReturnType<typeof createMiddleware>;\nexport {};\n"],"mappings":";;;;;;;;AAMA;AAiBqBI,UAjBJD,QAAAA,CAiBqB;EAAA;;;EAGY,IAHHE,EAAAA,MAAAA;EAAK;AAQpD;AAIA;EAIYG,KAAAA,EAAAA,MAAAA;EACAC;;;EAAsB,GAAGC,EAAAA,MAAAA;AAAM;AAI3C;;;AAQcJ,cA7BOF,iBAAAA,SAA0BC,KAAAA,CA6BjCC;EAAW,SAIVG,OAAAA,EAAAA,MAAAA;EAAQ,SAAA,OAAA,EA/BDN,QA+BC,EAAA;EAKNS,WAAAA,CAAAA,OAAAA,EAAAA,MAAqB,EAAA,OAAA,EAnCIT,QAmCJ,EAAA;;;;AAGb;AAKDU,KAtCZP,WAAAA,GAsCuB,OAAmBH,GAAAA,QAAQ,GAAA,MAAA,GAAA,MAAA;AAI9D;AAIA;AA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;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAoFtCM,aAAAA,UAAuBnB;aAChCD;aACAG;;;;IAIXkB,kBAAkBzB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"pii.d.ts","names":["z","InferInteropZodInput","createMiddleware","PIIMatch","PIIDetectionError","Error","PIIStrategy","BuiltInPIIType","PIIDetector","Detector","RegExp","RedactionRuleConfig","ResolvedRedactionRule","detectEmail","detectCreditCard","detectIP","detectMacAddress","detectUrl","resolveRedactionRule","applyStrategy","contextSchema","ZodBoolean","ZodOptional","ZodTypeAny","ZodObject","PIIMiddlewareConfig","piiMiddleware","ReturnType"],"sources":["../../../src/agents/middleware/pii.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport { createMiddleware } from \"../middleware.js\";\n/**\n * Represents a detected PII match in content\n */\nexport interface PIIMatch {\n /**\n * The matched text\n */\n text: string;\n /**\n * The start index of the match\n */\n start: number;\n /**\n * The end index of the match\n */\n end: number;\n}\n/**\n * Error thrown when PII is detected and strategy is 'block'\n */\nexport declare class PIIDetectionError extends Error {\n readonly piiType: string;\n readonly matches: PIIMatch[];\n constructor(piiType: string, matches: PIIMatch[]);\n}\n/**\n * Strategy for handling detected PII\n */\nexport type PIIStrategy = \"block\" | \"redact\" | \"mask\" | \"hash\";\n/**\n * Built-in PII types\n */\nexport type BuiltInPIIType = \"email\" | \"credit_card\" | \"ip\" | \"mac_address\" | \"url\";\n/**\n * Custom detector function that takes content and returns matches\n */\nexport type PIIDetector = (content: string) => PIIMatch[];\nexport type Detector = PIIDetector | RegExp | string;\n/**\n * Configuration for a redaction rule\n */\nexport interface RedactionRuleConfig {\n /**\n * Type of PII to detect (built-in or custom name)\n */\n piiType: BuiltInPIIType | string;\n /**\n * Strategy for handling detected PII\n */\n strategy: PIIStrategy;\n /**\n * Custom detector function or regex pattern string\n */\n detector?: Detector;\n}\n/**\n * Resolved redaction rule with a concrete detector function\n */\nexport interface ResolvedRedactionRule {\n piiType: string;\n strategy: PIIStrategy;\n detector: PIIDetector;\n}\n/**\n * Detect email addresses in content\n */\nexport declare function detectEmail(content: string): PIIMatch[];\n/**\n * Detect credit card numbers in content (validated with Luhn algorithm)\n */\nexport declare function detectCreditCard(content: string): PIIMatch[];\n/**\n * Detect IP addresses in content (validated)\n */\nexport declare function detectIP(content: string): PIIMatch[];\n/**\n * Detect MAC addresses in content\n */\nexport declare function detectMacAddress(content: string): PIIMatch[];\n/**\n * Detect URLs in content\n */\nexport declare function detectUrl(content: string): PIIMatch[];\n/**\n * Resolve a redaction rule to a concrete detector function\n */\nexport declare function resolveRedactionRule(config: RedactionRuleConfig): ResolvedRedactionRule;\n/**\n * Apply strategy to content based on matches\n */\nexport declare function applyStrategy(content: string, matches: PIIMatch[], strategy: PIIStrategy, piiType: string): string;\n/**\n * Configuration schema for PII middleware\n */\ndeclare const contextSchema: z.ZodObject<{\n /**\n * Whether to check user messages before model call\n */\n applyToInput: z.ZodOptional<z.ZodBoolean>;\n /**\n * Whether to check AI messages after model call\n */\n applyToOutput: z.ZodOptional<z.ZodBoolean>;\n /**\n * Whether to check tool result messages after tool execution\n */\n applyToToolResults: z.ZodOptional<z.ZodBoolean>;\n}, \"strip\", z.ZodTypeAny, {\n applyToInput?: boolean | undefined;\n applyToOutput?: boolean | undefined;\n applyToToolResults?: boolean | undefined;\n}, {\n applyToInput?: boolean | undefined;\n applyToOutput?: boolean | undefined;\n applyToToolResults?: boolean | undefined;\n}>;\nexport type PIIMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;\n/**\n * Creates a middleware that detects and handles personally identifiable information (PII)\n * in conversations.\n *\n * This middleware detects common PII types and applies configurable strategies to handle them.\n * It can detect emails, credit cards, IP addresses, MAC addresses, and URLs in both user input\n * and agent output.\n *\n * Built-in PII types:\n * - `email`: Email addresses\n * - `credit_card`: Credit card numbers (validated with Luhn algorithm)\n * - `ip`: IP addresses (validated)\n * - `mac_address`: MAC addresses\n * - `url`: URLs (both `http`/`https` and bare URLs)\n *\n * Strategies:\n * - `block`: Raise an exception when PII is detected\n * - `redact`: Replace PII with `[REDACTED_TYPE]` placeholders\n * - `mask`: Partially mask PII (e.g., `****-****-****-1234` for credit card)\n * - `hash`: Replace PII with deterministic hash (e.g., `<email_hash:a1b2c3d4>`)\n *\n * Strategy Selection Guide:\n * | Strategy | Preserves Identity? | Best For |\n * | -------- | ------------------- | --------------------------------------- |\n * | `block` | N/A | Avoid PII completely |\n * | `redact` | No | General compliance, log sanitization |\n * | `mask` | No | Human readability, customer service UIs |\n * | `hash` | Yes (pseudonymous) | Analytics, debugging |\n *\n * @param piiType - Type of PII to detect. Can be a built-in type (`email`, `credit_card`, `ip`, `mac_address`, `url`) or a custom type name.\n * @param options - Configuration options\n * @param options.strategy - How to handle detected PII. Defaults to `\"redact\"`.\n * @param options.detector - Custom detector function or regex pattern string. If not provided, uses built-in detector for the `piiType`.\n * @param options.applyToInput - Whether to check user messages before model call. Defaults to `true`.\n * @param options.applyToOutput - Whether to check AI messages after model call. Defaults to `false`.\n * @param options.applyToToolResults - Whether to check tool result messages after tool execution. Defaults to `false`.\n *\n * @returns Middleware instance for use with `createAgent`\n *\n * @throws {PIIDetectionError} When PII is detected and strategy is `'block'`\n * @throws {Error} If `piiType` is not built-in and no detector is provided\n *\n * @example Basic usage\n * ```typescript\n * import { piiMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * // Redact all emails in user input\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * middleware: [\n * piiMiddleware(\"email\", { strategy: \"redact\" }),\n * ],\n * });\n * ```\n *\n * @example Different strategies for different PII types\n * ```typescript\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [\n * piiMiddleware(\"credit_card\", { strategy: \"mask\" }),\n * piiMiddleware(\"url\", { strategy: \"redact\" }),\n * piiMiddleware(\"ip\", { strategy: \"hash\" }),\n * ],\n * });\n * ```\n *\n * @example Custom PII type with regex\n * ```typescript\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * middleware: [\n * piiMiddleware(\"api_key\", {\n * detector: \"sk-[a-zA-Z0-9]{32}\",\n * strategy: \"block\",\n * }),\n * ],\n * });\n * ```\n *\n * @public\n */\nexport declare function piiMiddleware(piiType: BuiltInPIIType | string, options?: {\n strategy?: PIIStrategy;\n detector?: Detector;\n applyToInput?: boolean;\n applyToOutput?: boolean;\n applyToToolResults?: boolean;\n}): ReturnType<typeof createMiddleware>;\nexport {};\n"],"mappings":";;;;;;;;AAMA;AAiBqBI,UAjBJD,QAAAA,CAiBqB;EAAA;;;EAGY,IAHHE,EAAAA,MAAAA;EAAK;AAQpD;AAIA;EAIYG,KAAAA,EAAAA,MAAAA;EACAC;;;EAAsB,GAAGC,EAAAA,MAAAA;AAAM;AAI3C;;;AAQcJ,cA7BOF,iBAAAA,SAA0BC,KAAAA,CA6BjCC;EAAW,SAIVG,OAAAA,EAAAA,MAAAA;EAAQ,SAAA,OAAA,EA/BDN,QA+BC,EAAA;EAKNS,WAAAA,CAAAA,OAAAA,EAAAA,MAAqB,EAAA,OAAA,EAnCIT,QAmCJ,EAAA;;;;AAGb;AAKDU,KAtCZP,WAAAA,GAsCuB,OAAmBH,GAAAA,QAAQ,GAAA,MAAA,GAAA,MAAA;AAI9D;AAIA;AAIA;AAIwBc,KAlDZV,cAAAA,GAkDwCJ,OAAQ,GAAA,aAAA,GAAA,IAAA,GAAA,aAAA,GAAA,KAAA;AAI5D;;;AAA2ES,KAlD/DJ,WAAAA,GAkD+DI,CAAAA,OAAAA,EAAAA,MAAAA,EAAAA,GAlD5BT,QAkD4BS,EAAAA;AAAqB,KAjDpFH,QAAAA,GAAWD,WAiDyE,GAjD3DE,MAiD2D,GAAA,MAAA;AAIhG;;;AAAsFJ,UAjDrEK,mBAAAA,CAiDqEL;EAAW;AAA2B;;EAyB1H,OAjBgCe,EArDrBd,cAqDqBc,GAAAA,MAAAA;EAAU;;;EAIZ,QAIQA,EAzD1Bf,WAyD0Be;EAAU;;;EAZV,QAAA,CAAA,EAzCzBZ,QAyCyB;AAsBxC;;;;AAAsD,UA1DrCG,qBAAAA,CA0DqC;EAoF9Bc,OAAAA,EAAAA,MAAAA;EAAa,QAAA,EA5IvBpB,WA4IuB;EAAA,QAAUC,EA3IjCC,WA2IiCD;;;;;AAMjC,iBA5IUM,WAAAA,CA4IV,OAAA,EAAA,MAAA,CAAA,EA5IwCV,QA4IxC,EAAA;;;;iBAxIUW,gBAAAA,mBAAmCX;;;;iBAInCY,QAAAA,mBAA2BZ;;;;iBAI3Ba,gBAAAA,mBAAmCb;;;;iBAInCc,SAAAA,mBAA4Bd;;;;iBAI5Be,oBAAAA,SAA6BP,sBAAsBC;;;;iBAInDO,aAAAA,2BAAwChB,sBAAsBG;;;;cAIxEc,eAAepB,CAAAA,CAAEwB;;;;gBAIbxB,CAAAA,CAAEsB,YAAYtB,CAAAA,CAAEqB;;;;iBAIfrB,CAAAA,CAAEsB,YAAYtB,CAAAA,CAAEqB;;;;sBAIXrB,CAAAA,CAAEsB,YAAYtB,CAAAA,CAAEqB;YAC5BrB,CAAAA,CAAEuB;;;;;;;;;KASFE,mBAAAA,GAAsBxB,4BAA4BmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAoFtCM,aAAAA,UAAuBnB;aAChCD;aACAG;;;;IAIXkB,kBAAkBzB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"piiRedaction.d.cts","names":["z","InferInteropZodInput","createMiddleware","contextSchema","ZodString","RegExp","ZodTypeDef","ZodType","ZodRecord","ZodOptional","ZodTypeAny","Record","ZodObject","PIIRedactionMiddlewareConfig","piiRedactionMiddleware","ReturnType"],"sources":["../../../src/agents/middleware/piiRedaction.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport { createMiddleware } from \"../middleware.js\";\n/**\n * Configuration schema for the Input Guardrails middleware\n */\ndeclare const contextSchema: z.ZodObject<{\n /**\n * A record of PII detection rules to apply\n * @default DEFAULT_PII_RULES (with enabled rules only)\n */\n rules: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodType<RegExp, z.ZodTypeDef, RegExp>>>;\n}, \"strip\", z.ZodTypeAny, {\n rules?: Record<string, RegExp> | undefined;\n}, {\n rules?: Record<string, RegExp> | undefined;\n}>;\n/**\n * @deprecated\n */\nexport type PIIRedactionMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;\n/**\n * Creates a middleware that detects and redacts personally identifiable information (PII)\n * from messages before they are sent to model providers, and restores original values\n * in model responses for tool execution.\n *\n * ## Mechanism\n *\n * The middleware intercepts agent execution at two points:\n *\n * ### Request Phase (`wrapModelCall`)\n * - Applies regex-based pattern matching to all message content (HumanMessage, ToolMessage, SystemMessage, AIMessage)\n * - Processes both message text and AIMessage tool call arguments\n * - Each matched pattern generates:\n * - Unique identifier: `generateRedactionId()` → `\"abc123\"`\n * - Redaction marker: `[REDACTED_{RULE_NAME}_{ID}]` → `\"[REDACTED_SSN_abc123]\"`\n * - Redaction map entry: `{ \"abc123\": \"123-45-6789\" }`\n * - Returns modified request with redacted message content\n *\n * ### Response Phase (`afterModel`)\n * - Scans AIMessage responses for redaction markers matching pattern: `/\\[REDACTED_[A-Z_]+_(\\w+)\\]/g`\n * - Replaces markers with original values from redaction map\n * - Handles both standard responses and structured output (via tool calls or JSON content)\n * - For structured output, restores values in both the tool call arguments and the `structuredResponse` state field\n * - Returns new message instances via RemoveMessage/AIMessage to update state\n *\n * ## Data Flow\n *\n * ```\n * User Input: \"My SSN is 123-45-6789\"\n * ↓ [beforeModel]\n * Model Request: \"My SSN is [REDACTED_SSN_abc123]\"\n * ↓ [model invocation]\n * Model Response: tool_call({ \"ssn\": \"[REDACTED_SSN_abc123]\" })\n * ↓ [afterModel]\n * Tool Execution: tool({ \"ssn\": \"123-45-6789\" })\n * ```\n *\n * ## Limitations\n *\n * This middleware provides model provider isolation only. PII may still be present in:\n * - LangGraph state checkpoints (memory, databases)\n * - Network traffic between client and application server\n * - Application logs and trace data\n * - Tool execution arguments and responses\n * - Final agent output\n *\n * For comprehensive PII protection, implement additional controls at the application,\n * network, and storage layers.\n *\n * @param options - Configuration options\n * @param options.rules - Record of detection rules mapping rule names to regex patterns.\n * Rule names are normalized to uppercase and used in redaction markers.\n * Patterns must use the global flag (`/pattern/g`) to match all occurrences.\n *\n * @returns Middleware instance for use with `createAgent`\n *\n * @example Basic usage with custom rules\n * ```typescript\n * import { piiRedactionMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod/v3\";\n *\n * const PII_RULES = {\n * ssn: /\\b\\d{3}-?\\d{2}-?\\d{4}\\b/g,\n * email: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n * phone: /\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b/g,\n * };\n *\n * const lookupUser = tool(async ({ ssn }) => {\n * // Receives original value: \"123-45-6789\"\n * return { name: \"John Doe\", account: \"active\" };\n * }, {\n * name: \"lookup_user\",\n * description: \"Look up user by SSN\",\n * schema: z.object({ ssn: z.string() })\n * });\n *\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4\" }),\n * tools: [lookupUser],\n * middleware: [piiRedactionMiddleware({ rules: PII_RULES })]\n * });\n *\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Look up SSN 123-45-6789\")]\n * });\n * // Model request: \"Look up SSN [REDACTED_SSN_abc123]\"\n * // Model response: tool_call({ \"ssn\": \"[REDACTED_SSN_abc123]\" })\n * // Tool receives: { \"ssn\": \"123-45-6789\" }\n * ```\n *\n * @example Runtime rule configuration via context\n * ```typescript\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4\" }),\n * tools: [someTool],\n * middleware: [piiRedactionMiddleware()]\n * });\n *\n * // Configure rules at runtime via middleware context\n * const result = await agent.invoke(\n * { messages: [new HumanMessage(\"...\")] },\n * {\n * configurable: {\n * PIIRedactionMiddleware: {\n * rules: {\n * ssn: /\\b\\d{3}-?\\d{2}-?\\d{4}\\b/g,\n * email: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n * }\n * }\n * }\n * }\n * );\n * ```\n *\n * @example Custom rule patterns\n * ```typescript\n * const customRules = {\n * employee_id: /EMP-\\d{6}/g,\n * api_key: /sk-[a-zA-Z0-9]{32}/g,\n * credit_card: /\\b\\d{4}[- ]?\\d{4}[- ]?\\d{4}[- ]?\\d{4}\\b/g,\n * };\n *\n * const middleware = piiRedactionMiddleware({ rules: customRules });\n * // Generates markers like: [REDACTED_EMPLOYEE_ID_xyz789]\n * ```\n *\n * @deprecated\n */\nexport declare function piiRedactionMiddleware(options?: PIIRedactionMiddlewareConfig): ReturnType<typeof createMiddleware>;\nexport {};\n"],"mappings":";;;;;;;;AAEoD;cAItCG,aAUZ,EAV2BH,CAAAA,CAAEY,SAU7B,CAAA;EAAA;;;;EALsF,KAApCL,EAAzCP,CAAAA,CAAES,WAAuCF,CAA3BP,CAAAA,CAAEQ,SAAyBD,CAAfP,CAAAA,CAAEI,SAAaG,EAAFP,CAAAA,CAAEO,OAAAA,CAAQF,MAARE,EAAgBP,CAAAA,CAAEM,UAAlBC,EAA8BF,MAA9BE,CAAAA,CAAAA,CAAAA;CAAO,EAAA,OAAhCC,EACfR,CAAAA,CAAEU,UADaF,EAAAA;EAAS,KAAvBC,CAAAA,EAEDE,MAFCF,CAAAA,MAAAA,EAEcJ,MAFdI,CAAAA,GAAAA,SAAAA;CAAW,EAAA;EACA,KACGJ,CAAAA,EAEfM,MAFeN,CAAAA,MAAAA,EAEAA,MAFAA,CAAAA,GAAAA,SAAAA;CAAM,CAAA;;;;AAPO,KAc5BQ,4BAAAA,GAA+BZ,oBAdH,CAAA,OAc+BE,aAd/B,CAAA;AAcxC;;;;AAA+D;AAmI/D;;;;;AAAkG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAA1EW,sBAAAA,WAAiCD,+BAA+BE,kBAAkBb"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"piiRedaction.d.ts","names":["z","InferInteropZodInput","createMiddleware","contextSchema","ZodString","RegExp","ZodTypeDef","ZodType","ZodRecord","ZodOptional","ZodTypeAny","Record","ZodObject","PIIRedactionMiddlewareConfig","piiRedactionMiddleware","ReturnType"],"sources":["../../../src/agents/middleware/piiRedaction.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport { createMiddleware } from \"../middleware.js\";\n/**\n * Configuration schema for the Input Guardrails middleware\n */\ndeclare const contextSchema: z.ZodObject<{\n /**\n * A record of PII detection rules to apply\n * @default DEFAULT_PII_RULES (with enabled rules only)\n */\n rules: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodType<RegExp, z.ZodTypeDef, RegExp>>>;\n}, \"strip\", z.ZodTypeAny, {\n rules?: Record<string, RegExp> | undefined;\n}, {\n rules?: Record<string, RegExp> | undefined;\n}>;\n/**\n * @deprecated\n */\nexport type PIIRedactionMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;\n/**\n * Creates a middleware that detects and redacts personally identifiable information (PII)\n * from messages before they are sent to model providers, and restores original values\n * in model responses for tool execution.\n *\n * ## Mechanism\n *\n * The middleware intercepts agent execution at two points:\n *\n * ### Request Phase (`wrapModelCall`)\n * - Applies regex-based pattern matching to all message content (HumanMessage, ToolMessage, SystemMessage, AIMessage)\n * - Processes both message text and AIMessage tool call arguments\n * - Each matched pattern generates:\n * - Unique identifier: `generateRedactionId()` → `\"abc123\"`\n * - Redaction marker: `[REDACTED_{RULE_NAME}_{ID}]` → `\"[REDACTED_SSN_abc123]\"`\n * - Redaction map entry: `{ \"abc123\": \"123-45-6789\" }`\n * - Returns modified request with redacted message content\n *\n * ### Response Phase (`afterModel`)\n * - Scans AIMessage responses for redaction markers matching pattern: `/\\[REDACTED_[A-Z_]+_(\\w+)\\]/g`\n * - Replaces markers with original values from redaction map\n * - Handles both standard responses and structured output (via tool calls or JSON content)\n * - For structured output, restores values in both the tool call arguments and the `structuredResponse` state field\n * - Returns new message instances via RemoveMessage/AIMessage to update state\n *\n * ## Data Flow\n *\n * ```\n * User Input: \"My SSN is 123-45-6789\"\n * ↓ [beforeModel]\n * Model Request: \"My SSN is [REDACTED_SSN_abc123]\"\n * ↓ [model invocation]\n * Model Response: tool_call({ \"ssn\": \"[REDACTED_SSN_abc123]\" })\n * ↓ [afterModel]\n * Tool Execution: tool({ \"ssn\": \"123-45-6789\" })\n * ```\n *\n * ## Limitations\n *\n * This middleware provides model provider isolation only. PII may still be present in:\n * - LangGraph state checkpoints (memory, databases)\n * - Network traffic between client and application server\n * - Application logs and trace data\n * - Tool execution arguments and responses\n * - Final agent output\n *\n * For comprehensive PII protection, implement additional controls at the application,\n * network, and storage layers.\n *\n * @param options - Configuration options\n * @param options.rules - Record of detection rules mapping rule names to regex patterns.\n * Rule names are normalized to uppercase and used in redaction markers.\n * Patterns must use the global flag (`/pattern/g`) to match all occurrences.\n *\n * @returns Middleware instance for use with `createAgent`\n *\n * @example Basic usage with custom rules\n * ```typescript\n * import { piiRedactionMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod/v3\";\n *\n * const PII_RULES = {\n * ssn: /\\b\\d{3}-?\\d{2}-?\\d{4}\\b/g,\n * email: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n * phone: /\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b/g,\n * };\n *\n * const lookupUser = tool(async ({ ssn }) => {\n * // Receives original value: \"123-45-6789\"\n * return { name: \"John Doe\", account: \"active\" };\n * }, {\n * name: \"lookup_user\",\n * description: \"Look up user by SSN\",\n * schema: z.object({ ssn: z.string() })\n * });\n *\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4\" }),\n * tools: [lookupUser],\n * middleware: [piiRedactionMiddleware({ rules: PII_RULES })]\n * });\n *\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Look up SSN 123-45-6789\")]\n * });\n * // Model request: \"Look up SSN [REDACTED_SSN_abc123]\"\n * // Model response: tool_call({ \"ssn\": \"[REDACTED_SSN_abc123]\" })\n * // Tool receives: { \"ssn\": \"123-45-6789\" }\n * ```\n *\n * @example Runtime rule configuration via context\n * ```typescript\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4\" }),\n * tools: [someTool],\n * middleware: [piiRedactionMiddleware()]\n * });\n *\n * // Configure rules at runtime via middleware context\n * const result = await agent.invoke(\n * { messages: [new HumanMessage(\"...\")] },\n * {\n * configurable: {\n * PIIRedactionMiddleware: {\n * rules: {\n * ssn: /\\b\\d{3}-?\\d{2}-?\\d{4}\\b/g,\n * email: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n * }\n * }\n * }\n * }\n * );\n * ```\n *\n * @example Custom rule patterns\n * ```typescript\n * const customRules = {\n * employee_id: /EMP-\\d{6}/g,\n * api_key: /sk-[a-zA-Z0-9]{32}/g,\n * credit_card: /\\b\\d{4}[- ]?\\d{4}[- ]?\\d{4}[- ]?\\d{4}\\b/g,\n * };\n *\n * const middleware = piiRedactionMiddleware({ rules: customRules });\n * // Generates markers like: [REDACTED_EMPLOYEE_ID_xyz789]\n * ```\n *\n * @deprecated\n */\nexport declare function piiRedactionMiddleware(options?: PIIRedactionMiddlewareConfig): ReturnType<typeof createMiddleware>;\nexport {};\n"],"mappings":";;;;;;;;AAEoD;cAItCG,aAUZ,EAV2BH,CAAAA,CAAEY,SAU7B,CAAA;EAAA;;;;EALsF,KAApCL,EAAzCP,CAAAA,CAAES,WAAuCF,CAA3BP,CAAAA,CAAEQ,SAAyBD,CAAfP,CAAAA,CAAEI,SAAaG,EAAFP,CAAAA,CAAEO,OAAAA,CAAQF,MAARE,EAAgBP,CAAAA,CAAEM,UAAlBC,EAA8BF,MAA9BE,CAAAA,CAAAA,CAAAA;CAAO,EAAA,OAAhCC,EACfR,CAAAA,CAAEU,UADaF,EAAAA;EAAS,KAAvBC,CAAAA,EAEDE,MAFCF,CAAAA,MAAAA,EAEcJ,MAFdI,CAAAA,GAAAA,SAAAA;CAAW,EAAA;EACA,KACGJ,CAAAA,EAEfM,MAFeN,CAAAA,MAAAA,EAEAA,MAFAA,CAAAA,GAAAA,SAAAA;CAAM,CAAA;;;;AAPO,KAc5BQ,4BAAAA,GAA+BZ,oBAdH,CAAA,OAc+BE,aAd/B,CAAA;AAcxC;;;;AAA+D;AAmI/D;;;;;AAAkG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAA1EW,sBAAAA,WAAiCD,+BAA+BE,kBAAkBb"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"promptCaching.cjs","names":["z","message: string","middlewareOptions?: PromptCachingMiddlewareConfig","createMiddleware"],"sources":["../../../src/agents/middleware/promptCaching.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { ContentBlock } from \"@langchain/core/messages\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\n\nimport { ConfigurableModel } from \"../../chat_models/universal.js\";\nimport { createMiddleware } from \"../middleware.js\";\n\nconst DEFAULT_ENABLE_CACHING = true;\nconst DEFAULT_TTL = \"5m\";\nconst DEFAULT_MIN_MESSAGES_TO_CACHE = 3;\nconst DEFAULT_UNSUPPORTED_MODEL_BEHAVIOR = \"warn\";\n\nconst contextSchema = z.object({\n /**\n * Whether to enable prompt caching.\n * @default true\n */\n enableCaching: z.boolean().optional(),\n /**\n * The time-to-live for the cached prompt.\n * @default \"5m\"\n */\n ttl: z.enum([\"5m\", \"1h\"]).optional(),\n /**\n * The minimum number of messages required before caching is applied.\n * @default 3\n */\n minMessagesToCache: z.number().optional(),\n /**\n * The behavior to take when an unsupported model is used.\n * - \"ignore\" will ignore the unsupported model and continue without caching.\n * - \"warn\" will warn the user and continue without caching.\n * - \"raise\" will raise an error and stop the agent.\n * @default \"warn\"\n */\n unsupportedModelBehavior: z.enum([\"ignore\", \"warn\", \"raise\"]).optional(),\n});\nexport type PromptCachingMiddlewareConfig = Partial<\n InferInteropZodInput<typeof contextSchema>\n>;\n\nclass PromptCachingMiddlewareError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PromptCachingMiddlewareError\";\n }\n}\n\n/**\n * Creates a prompt caching middleware for Anthropic models to optimize API usage.\n *\n * This middleware automatically adds cache control headers to the last messages when using Anthropic models,\n * enabling their prompt caching feature. This can significantly reduce costs for applications with repetitive\n * prompts, long system messages, or extensive conversation histories.\n *\n * ## How It Works\n *\n * The middleware intercepts model requests and adds cache control metadata that tells Anthropic's\n * API to cache processed prompt prefixes. On subsequent requests with matching prefixes, the\n * cached representations are reused, skipping redundant token processing.\n *\n * ## Benefits\n *\n * - **Cost Reduction**: Avoid reprocessing the same tokens repeatedly (up to 90% savings on cached portions)\n * - **Lower Latency**: Cached prompts are processed faster as embeddings are pre-computed\n * - **Better Scalability**: Reduced computational load enables handling more requests\n * - **Consistent Performance**: Stable response times for repetitive queries\n *\n * @param middlewareOptions - Configuration options for the caching behavior\n * @param middlewareOptions.enableCaching - Whether to enable prompt caching (default: `true`)\n * @param middlewareOptions.ttl - Cache time-to-live: `\"5m\"` for 5 minutes or `\"1h\"` for 1 hour (default: `\"5m\"`)\n * @param middlewareOptions.minMessagesToCache - Minimum number of messages required before caching is applied (default: `3`)\n * @param middlewareOptions.unsupportedModelBehavior - The behavior to take when an unsupported model is used (default: `\"warn\"`)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {Error} If used with non-Anthropic models\n *\n * @example\n * Basic usage with default settings\n * ```typescript\n * import { createAgent } from \"langchain\";\n * import { anthropicPromptCachingMiddleware } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * middleware: [\n * anthropicPromptCachingMiddleware()\n * ]\n * });\n * ```\n *\n * @example\n * Custom configuration for longer conversations\n * ```typescript\n * const cachingMiddleware = anthropicPromptCachingMiddleware({\n * ttl: \"1h\", // Cache for 1 hour instead of default 5 minutes\n * minMessagesToCache: 5 // Only cache after 5 messages\n * });\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: \"You are a helpful assistant with deep knowledge of...\", // Long system prompt\n * middleware: [cachingMiddleware]\n * });\n * ```\n *\n * @example\n * Conditional caching based on runtime context\n * ```typescript\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * middleware: [\n * anthropicPromptCachingMiddleware({\n * enableCaching: true,\n * ttl: \"5m\"\n * })\n * ]\n * });\n *\n * // Disable caching for specific requests\n * await agent.invoke(\n * { messages: [new HumanMessage(\"Process this without caching\")] },\n * {\n * configurable: {\n * middleware_context: { enableCaching: false }\n * }\n * }\n * );\n * ```\n *\n * @example\n * Optimal setup for customer support chatbot\n * ```typescript\n * const supportAgent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: `You are a customer support agent for ACME Corp.\n *\n * Company policies:\n * - Always be polite and professional\n * - Refer to knowledge base for product information\n * - Escalate billing issues to human agents\n * ... (extensive policies and guidelines)\n * `,\n * tools: [searchKnowledgeBase, createTicket, checkOrderStatus],\n * middleware: [\n * anthropicPromptCachingMiddleware({\n * ttl: \"1h\", // Long TTL for stable system prompt\n * minMessagesToCache: 1 // Cache immediately due to large system prompt\n * })\n * ]\n * });\n * ```\n *\n * @remarks\n * - **Anthropic Only**: This middleware only works with Anthropic models and will throw an error if used with other providers\n * - **Automatic Application**: Caching is applied automatically when message count exceeds `minMessagesToCache`\n * - **Cache Scope**: Caches are isolated per API key and cannot be shared across different keys\n * - **TTL Options**: Only supports \"5m\" (5 minutes) and \"1h\" (1 hour) as TTL values per Anthropic's API\n * - **Best Use Cases**: Long system prompts, multi-turn conversations, repetitive queries, RAG applications\n * - **Cost Impact**: Cached tokens are billed at 10% of the base input token price, cache writes are billed at 25% of the base\n *\n * @see {@link createAgent} for agent creation\n * @see {@link https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching} Anthropic's prompt caching documentation\n * @public\n */\nexport function anthropicPromptCachingMiddleware(\n middlewareOptions?: PromptCachingMiddlewareConfig\n) {\n return createMiddleware({\n name: \"PromptCachingMiddleware\",\n contextSchema,\n wrapModelCall: (request, handler) => {\n /**\n * Prefer runtime context values over middleware options values over defaults\n */\n const enableCaching =\n request.runtime.context.enableCaching ??\n middlewareOptions?.enableCaching ??\n DEFAULT_ENABLE_CACHING;\n const ttl =\n request.runtime.context.ttl ?? middlewareOptions?.ttl ?? DEFAULT_TTL;\n const minMessagesToCache =\n request.runtime.context.minMessagesToCache ??\n middlewareOptions?.minMessagesToCache ??\n DEFAULT_MIN_MESSAGES_TO_CACHE;\n const unsupportedModelBehavior =\n request.runtime.context.unsupportedModelBehavior ??\n middlewareOptions?.unsupportedModelBehavior ??\n DEFAULT_UNSUPPORTED_MODEL_BEHAVIOR;\n\n // Skip if caching is disabled\n if (!enableCaching || !request.model) {\n return handler(request);\n }\n\n const isAnthropicModel =\n request.model.getName() === \"ChatAnthropic\" ||\n (request.model.getName() === \"ConfigurableModel\" &&\n (request.model as ConfigurableModel)._defaultConfig?.modelProvider ===\n \"anthropic\");\n if (!isAnthropicModel) {\n // Get model name for better error context\n const modelName = request.model.getName();\n const modelInfo =\n request.model.getName() === \"ConfigurableModel\"\n ? `${modelName} (${\n (request.model as ConfigurableModel)._defaultConfig\n ?.modelProvider\n })`\n : modelName;\n\n const baseMessage = `Unsupported model '${modelInfo}'. Prompt caching requires an Anthropic model`;\n\n if (unsupportedModelBehavior === \"raise\") {\n throw new PromptCachingMiddlewareError(\n `${baseMessage} (e.g., 'anthropic:claude-4-0-sonnet').`\n );\n } else if (unsupportedModelBehavior === \"warn\") {\n console.warn(\n `PromptCachingMiddleware: Skipping caching for ${modelName}. Consider switching to an Anthropic model for caching benefits.`\n );\n }\n return handler(request);\n }\n\n const messagesCount =\n request.state.messages.length + (request.systemPrompt ? 1 : 0);\n\n if (messagesCount < minMessagesToCache) {\n return handler(request);\n }\n\n /**\n * Add cache_control to the last message\n */\n const lastMessage = request.messages.at(-1);\n if (!lastMessage) {\n return handler(request);\n }\n\n const NewMessageConstructor =\n Object.getPrototypeOf(lastMessage).constructor;\n if (Array.isArray(lastMessage.content)) {\n const newMessage = new NewMessageConstructor({\n ...lastMessage,\n content: [\n ...lastMessage.content.slice(0, -1),\n {\n ...lastMessage.content.at(-1),\n cache_control: {\n type: \"ephemeral\",\n ttl,\n },\n } as ContentBlock,\n ],\n });\n return handler({\n ...request,\n messages: [...request.messages.slice(0, -1), newMessage],\n });\n } else if (typeof lastMessage.content === \"string\") {\n const newMessage = new NewMessageConstructor({\n ...lastMessage,\n content: [\n {\n type: \"text\",\n text: lastMessage.content,\n cache_control: {\n type: \"ephemeral\",\n ttl,\n },\n },\n ],\n });\n return handler({\n ...request,\n messages: [...request.messages.slice(0, -1), newMessage],\n });\n }\n\n throw new PromptCachingMiddlewareError(\n \"Last message content is not a string or array\"\n );\n },\n });\n}\n"],"mappings":";;;;;AAOA,MAAM,yBAAyB;AAC/B,MAAM,cAAc;AACpB,MAAM,gCAAgC;AACtC,MAAM,qCAAqC;AAE3C,MAAM,gBAAgBA,SAAE,OAAO;CAK7B,eAAeA,SAAE,SAAS,CAAC,UAAU;CAKrC,KAAKA,SAAE,KAAK,CAAC,MAAM,IAAK,EAAC,CAAC,UAAU;CA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C,QAAQ,KACN,CAAC,8CAA8C,EAAE,UAAU,gEAAgE,CAAC,CAC7H;AAEH,WAAO,QAAQ,QAAQ;GACxB;GAED,MAAM,gBACJ,QAAQ,MAAM,SAAS,UAAU,QAAQ,eAAe,IAAI;AAE9D,OAAI,gBAAgB,mBAClB,QAAO,QAAQ,QAAQ;;;;GAMzB,MAAM,cAAc,QAAQ,SAAS,GAAG,GAAG;AAC3C,OAAI,CAAC,YACH,QAAO,QAAQ,QAAQ;GAGzB,MAAM,wBACJ,OAAO,eAAe,YAAY,CAAC;AACrC,OAAI,MAAM,QAAQ,YAAY,QAAQ,EAAE;IACtC,MAAM,aAAa,IAAI,sBAAsB;KAC3C,GAAG;KACH,SAAS,CACP,GAAG,YAAY,QAAQ,MAAM,GAAG,GAAG,EACnC;MACE,GAAG,YAAY,QAAQ,GAAG,GAAG;MAC7B,eAAe;OACb,MAAM;OACN;MACD;KACF,CACF;IACF;AACD,WAAO,QAAQ;KACb,GAAG;KACH,UAAU,CAAC,GAAG,QAAQ,SAAS,MAAM,GAAG,GAAG,EAAE,UAAW;IACzD,EAAC;GACH,WAAU,OAAO,YAAY,YAAY,UAAU;IAClD,MAAM,aAAa,IAAI,sBAAsB;KAC3C,GAAG;KACH,SAAS,CACP;MACE,MAAM;MACN,MAAM,YAAY;MAClB,eAAe;OACb,MAAM;OACN;MACD;KACF,CACF;IACF;AACD,WAAO,QAAQ;KACb,GAAG;KACH,UAAU,CAAC,GAAG,QAAQ,SAAS,MAAM,GAAG,GAAG,EAAE,UAAW;IACzD,EAAC;GACH;AAED,SAAM,IAAI,6BACR;EAEH;CACF,EAAC;AACH"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"promptCaching.d.cts","names":["z","InferInteropZodInput","contextSchema","ZodBoolean","ZodOptional","ZodEnum","ZodNumber","ZodTypeAny","ZodObject","PromptCachingMiddlewareConfig","Partial","anthropicPromptCachingMiddleware","__types_js9","AgentMiddleware"],"sources":["../../../src/agents/middleware/promptCaching.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\ndeclare const contextSchema: z.ZodObject<{\n /**\n * Whether to enable prompt caching.\n * @default true\n */\n enableCaching: z.ZodOptional<z.ZodBoolean>;\n /**\n * The time-to-live for the cached prompt.\n * @default \"5m\"\n */\n ttl: z.ZodOptional<z.ZodEnum<[\"5m\", \"1h\"]>>;\n /**\n * The minimum number of messages required before caching is applied.\n * @default 3\n */\n minMessagesToCache: z.ZodOptional<z.ZodNumber>;\n /**\n * The behavior to take when an unsupported model is used.\n * - \"ignore\" will ignore the unsupported model and continue without caching.\n * - \"warn\" will warn the user and continue without caching.\n * - \"raise\" will raise an error and stop the agent.\n * @default \"warn\"\n */\n unsupportedModelBehavior: z.ZodOptional<z.ZodEnum<[\"ignore\", \"warn\", \"raise\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n enableCaching?: boolean | undefined;\n ttl?: \"1h\" | \"5m\" | undefined;\n minMessagesToCache?: number | undefined;\n unsupportedModelBehavior?: \"ignore\" | \"raise\" | \"warn\" | undefined;\n}, {\n enableCaching?: boolean | undefined;\n ttl?: \"1h\" | \"5m\" | undefined;\n minMessagesToCache?: number | undefined;\n unsupportedModelBehavior?: \"ignore\" | \"raise\" | \"warn\" | undefined;\n}>;\nexport type PromptCachingMiddlewareConfig = Partial<InferInteropZodInput<typeof contextSchema>>;\n/**\n * Creates a prompt caching middleware for Anthropic models to optimize API usage.\n *\n * This middleware automatically adds cache control headers to the last messages when using Anthropic models,\n * enabling their prompt caching feature. This can significantly reduce costs for applications with repetitive\n * prompts, long system messages, or extensive conversation histories.\n *\n * ## How It Works\n *\n * The middleware intercepts model requests and adds cache control metadata that tells Anthropic's\n * API to cache processed prompt prefixes. On subsequent requests with matching prefixes, the\n * cached representations are reused, skipping redundant token processing.\n *\n * ## Benefits\n *\n * - **Cost Reduction**: Avoid reprocessing the same tokens repeatedly (up to 90% savings on cached portions)\n * - **Lower Latency**: Cached prompts are processed faster as embeddings are pre-computed\n * - **Better Scalability**: Reduced computational load enables handling more requests\n * - **Consistent Performance**: Stable response times for repetitive queries\n *\n * @param middlewareOptions - Configuration options for the caching behavior\n * @param middlewareOptions.enableCaching - Whether to enable prompt caching (default: `true`)\n * @param middlewareOptions.ttl - Cache time-to-live: `\"5m\"` for 5 minutes or `\"1h\"` for 1 hour (default: `\"5m\"`)\n * @param middlewareOptions.minMessagesToCache - Minimum number of messages required before caching is applied (default: `3`)\n * @param middlewareOptions.unsupportedModelBehavior - The behavior to take when an unsupported model is used (default: `\"warn\"`)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {Error} If used with non-Anthropic models\n *\n * @example\n * Basic usage with default settings\n * ```typescript\n * import { createAgent } from \"langchain\";\n * import { anthropicPromptCachingMiddleware } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * middleware: [\n * anthropicPromptCachingMiddleware()\n * ]\n * });\n * ```\n *\n * @example\n * Custom configuration for longer conversations\n * ```typescript\n * const cachingMiddleware = anthropicPromptCachingMiddleware({\n * ttl: \"1h\", // Cache for 1 hour instead of default 5 minutes\n * minMessagesToCache: 5 // Only cache after 5 messages\n * });\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: \"You are a helpful assistant with deep knowledge of...\", // Long system prompt\n * middleware: [cachingMiddleware]\n * });\n * ```\n *\n * @example\n * Conditional caching based on runtime context\n * ```typescript\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * middleware: [\n * anthropicPromptCachingMiddleware({\n * enableCaching: true,\n * ttl: \"5m\"\n * })\n * ]\n * });\n *\n * // Disable caching for specific requests\n * await agent.invoke(\n * { messages: [new HumanMessage(\"Process this without caching\")] },\n * {\n * configurable: {\n * middleware_context: { enableCaching: false }\n * }\n * }\n * );\n * ```\n *\n * @example\n * Optimal setup for customer support chatbot\n * ```typescript\n * const supportAgent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: `You are a customer support agent for ACME Corp.\n *\n * Company policies:\n * - Always be polite and professional\n * - Refer to knowledge base for product information\n * - Escalate billing issues to human agents\n * ... (extensive policies and guidelines)\n * `,\n * tools: [searchKnowledgeBase, createTicket, checkOrderStatus],\n * middleware: [\n * anthropicPromptCachingMiddleware({\n * ttl: \"1h\", // Long TTL for stable system prompt\n * minMessagesToCache: 1 // Cache immediately due to large system prompt\n * })\n * ]\n * });\n * ```\n *\n * @remarks\n * - **Anthropic Only**: This middleware only works with Anthropic models and will throw an error if used with other providers\n * - **Automatic Application**: Caching is applied automatically when message count exceeds `minMessagesToCache`\n * - **Cache Scope**: Caches are isolated per API key and cannot be shared across different keys\n * - **TTL Options**: Only supports \"5m\" (5 minutes) and \"1h\" (1 hour) as TTL values per Anthropic's API\n * - **Best Use Cases**: Long system prompts, multi-turn conversations, repetitive queries, RAG applications\n * - **Cost Impact**: Cached tokens are billed at 10% of the base input token price, cache writes are billed at 25% of the base\n *\n * @see {@link createAgent} for agent creation\n * @see {@link https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching} Anthropic's prompt caching documentation\n * @public\n */\nexport declare function anthropicPromptCachingMiddleware(middlewareOptions?: PromptCachingMiddlewareConfig): import(\"./types.js\").AgentMiddleware<undefined, z.ZodObject<{\n /**\n * Whether to enable prompt caching.\n * @default true\n */\n enableCaching: z.ZodOptional<z.ZodBoolean>;\n /**\n * The time-to-live for the cached prompt.\n * @default \"5m\"\n */\n ttl: z.ZodOptional<z.ZodEnum<[\"5m\", \"1h\"]>>;\n /**\n * The minimum number of messages required before caching is applied.\n * @default 3\n */\n minMessagesToCache: z.ZodOptional<z.ZodNumber>;\n /**\n * The behavior to take when an unsupported model is used.\n * - \"ignore\" will ignore the unsupported model and continue without caching.\n * - \"warn\" will warn the user and continue without caching.\n * - \"raise\" will raise an error and stop the agent.\n * @default \"warn\"\n */\n unsupportedModelBehavior: z.ZodOptional<z.ZodEnum<[\"ignore\", \"warn\", \"raise\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n enableCaching?: boolean | undefined;\n ttl?: \"1h\" | \"5m\" | undefined;\n minMessagesToCache?: number | undefined;\n unsupportedModelBehavior?: \"ignore\" | \"raise\" | \"warn\" | undefined;\n}, {\n enableCaching?: boolean | undefined;\n ttl?: \"1h\" | \"5m\" | undefined;\n minMessagesToCache?: number | undefined;\n unsupportedModelBehavior?: \"ignore\" | \"raise\" | \"warn\" | undefined;\n}>, any>;\nexport {};\n"],"mappings":";;;;;cAEcE,eAAeF,CAAAA,CAAEQ;;;AADoC;;EAmCjE,aA7BiCL,EAAhBH,CAAAA,CAAEI,WAAcD,CAAFH,CAAAA,CAAEG,UAAAA,CAAAA;EAAU;;;;EAUI,GAAzBH,EALfA,CAAAA,CAAEI,WAKeA,CALHJ,CAAAA,CAAEK,OAKCD,CAAAA,CAAAA,IAAAA,EAAAA,IAAAA,CAAAA,CAAAA,CAAAA;EAAW;;;;EAfG,kBAAA,EAehBJ,CAAAA,CAAEI,WAfc,CAeFJ,CAAAA,CAAEM,SAfA,CAAA;EAmC5BG;;;;;AAAuC;AAuHnD;EAAwD,wBAAA,EAnI1BT,CAAAA,CAAEI,WAmIwB,CAnIZJ,CAAAA,CAAEK,OAmIU,CAAA,CAAA,QAAA,EAAA,MAAA,EAAA,OAAA,CAAA,CAAA,CAAA;CAAA,EAAA,OAAqBI,EAlIjET,CAAAA,CAAEO,UAkI+DE,EAAAA;EAA6B,aAKvEN,CAAAA,EAAAA,OAAAA,GAAAA,SAAAA;EAAU,GAA1BH,CAAAA,EAAEI,IAAAA,GAAAA,IAAAA,GAAAA,SAAAA;EAAW,kBAKPC,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAO,wBAArBD,CAAAA,EAAAA,QAAAA,GAAAA,OAAAA,GAAAA,MAAAA,GAAAA,SAAAA;CAAW,EAAA;EAK2B,aAAvBA,CAAAA,EAAAA,OAAAA,GAAAA,SAAAA;EAAW,GAQOJ,CAAAA,EAAEK,IAAAA,GAAAA,IAAAA,GAAAA,SAAAA;EAAO,kBAArBD,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAW,wBAC7BG,CAAAA,EAAAA,QAAAA,GAAAA,OAAAA,GAAAA,MAAAA,GAAAA,SAAAA;CAAU,CAAA;AAxBgJ,KAvH5JE,6BAAAA,GAAgCC,OAuH4H,CAvHpHT,oBAuHoH,CAAA,OAvHxFC,aAuHwF,CAAA,CAAA;AAAvB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAzHS,gCAAAA,qBAAqDF,gCAA2F,2BAAXT,CAAAA,CAAEQ;;;;;iBAK5IR,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEG;;;;;OAK1BH,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEK;;;;;sBAKDL,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEM;;;;;;;;4BAQVN,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEK;YAClCL,CAAAA,CAAEO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"promptCaching.d.ts","names":["z","InferInteropZodInput","contextSchema","ZodBoolean","ZodOptional","ZodEnum","ZodNumber","ZodTypeAny","ZodObject","PromptCachingMiddlewareConfig","Partial","anthropicPromptCachingMiddleware","__types_js4","AgentMiddleware"],"sources":["../../../src/agents/middleware/promptCaching.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\ndeclare const contextSchema: z.ZodObject<{\n /**\n * Whether to enable prompt caching.\n * @default true\n */\n enableCaching: z.ZodOptional<z.ZodBoolean>;\n /**\n * The time-to-live for the cached prompt.\n * @default \"5m\"\n */\n ttl: z.ZodOptional<z.ZodEnum<[\"5m\", \"1h\"]>>;\n /**\n * The minimum number of messages required before caching is applied.\n * @default 3\n */\n minMessagesToCache: z.ZodOptional<z.ZodNumber>;\n /**\n * The behavior to take when an unsupported model is used.\n * - \"ignore\" will ignore the unsupported model and continue without caching.\n * - \"warn\" will warn the user and continue without caching.\n * - \"raise\" will raise an error and stop the agent.\n * @default \"warn\"\n */\n unsupportedModelBehavior: z.ZodOptional<z.ZodEnum<[\"ignore\", \"warn\", \"raise\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n enableCaching?: boolean | undefined;\n ttl?: \"1h\" | \"5m\" | undefined;\n minMessagesToCache?: number | undefined;\n unsupportedModelBehavior?: \"ignore\" | \"raise\" | \"warn\" | undefined;\n}, {\n enableCaching?: boolean | undefined;\n ttl?: \"1h\" | \"5m\" | undefined;\n minMessagesToCache?: number | undefined;\n unsupportedModelBehavior?: \"ignore\" | \"raise\" | \"warn\" | undefined;\n}>;\nexport type PromptCachingMiddlewareConfig = Partial<InferInteropZodInput<typeof contextSchema>>;\n/**\n * Creates a prompt caching middleware for Anthropic models to optimize API usage.\n *\n * This middleware automatically adds cache control headers to the last messages when using Anthropic models,\n * enabling their prompt caching feature. This can significantly reduce costs for applications with repetitive\n * prompts, long system messages, or extensive conversation histories.\n *\n * ## How It Works\n *\n * The middleware intercepts model requests and adds cache control metadata that tells Anthropic's\n * API to cache processed prompt prefixes. On subsequent requests with matching prefixes, the\n * cached representations are reused, skipping redundant token processing.\n *\n * ## Benefits\n *\n * - **Cost Reduction**: Avoid reprocessing the same tokens repeatedly (up to 90% savings on cached portions)\n * - **Lower Latency**: Cached prompts are processed faster as embeddings are pre-computed\n * - **Better Scalability**: Reduced computational load enables handling more requests\n * - **Consistent Performance**: Stable response times for repetitive queries\n *\n * @param middlewareOptions - Configuration options for the caching behavior\n * @param middlewareOptions.enableCaching - Whether to enable prompt caching (default: `true`)\n * @param middlewareOptions.ttl - Cache time-to-live: `\"5m\"` for 5 minutes or `\"1h\"` for 1 hour (default: `\"5m\"`)\n * @param middlewareOptions.minMessagesToCache - Minimum number of messages required before caching is applied (default: `3`)\n * @param middlewareOptions.unsupportedModelBehavior - The behavior to take when an unsupported model is used (default: `\"warn\"`)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {Error} If used with non-Anthropic models\n *\n * @example\n * Basic usage with default settings\n * ```typescript\n * import { createAgent } from \"langchain\";\n * import { anthropicPromptCachingMiddleware } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * middleware: [\n * anthropicPromptCachingMiddleware()\n * ]\n * });\n * ```\n *\n * @example\n * Custom configuration for longer conversations\n * ```typescript\n * const cachingMiddleware = anthropicPromptCachingMiddleware({\n * ttl: \"1h\", // Cache for 1 hour instead of default 5 minutes\n * minMessagesToCache: 5 // Only cache after 5 messages\n * });\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: \"You are a helpful assistant with deep knowledge of...\", // Long system prompt\n * middleware: [cachingMiddleware]\n * });\n * ```\n *\n * @example\n * Conditional caching based on runtime context\n * ```typescript\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * middleware: [\n * anthropicPromptCachingMiddleware({\n * enableCaching: true,\n * ttl: \"5m\"\n * })\n * ]\n * });\n *\n * // Disable caching for specific requests\n * await agent.invoke(\n * { messages: [new HumanMessage(\"Process this without caching\")] },\n * {\n * configurable: {\n * middleware_context: { enableCaching: false }\n * }\n * }\n * );\n * ```\n *\n * @example\n * Optimal setup for customer support chatbot\n * ```typescript\n * const supportAgent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: `You are a customer support agent for ACME Corp.\n *\n * Company policies:\n * - Always be polite and professional\n * - Refer to knowledge base for product information\n * - Escalate billing issues to human agents\n * ... (extensive policies and guidelines)\n * `,\n * tools: [searchKnowledgeBase, createTicket, checkOrderStatus],\n * middleware: [\n * anthropicPromptCachingMiddleware({\n * ttl: \"1h\", // Long TTL for stable system prompt\n * minMessagesToCache: 1 // Cache immediately due to large system prompt\n * })\n * ]\n * });\n * ```\n *\n * @remarks\n * - **Anthropic Only**: This middleware only works with Anthropic models and will throw an error if used with other providers\n * - **Automatic Application**: Caching is applied automatically when message count exceeds `minMessagesToCache`\n * - **Cache Scope**: Caches are isolated per API key and cannot be shared across different keys\n * - **TTL Options**: Only supports \"5m\" (5 minutes) and \"1h\" (1 hour) as TTL values per Anthropic's API\n * - **Best Use Cases**: Long system prompts, multi-turn conversations, repetitive queries, RAG applications\n * - **Cost Impact**: Cached tokens are billed at 10% of the base input token price, cache writes are billed at 25% of the base\n *\n * @see {@link createAgent} for agent creation\n * @see {@link https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching} Anthropic's prompt caching documentation\n * @public\n */\nexport declare function anthropicPromptCachingMiddleware(middlewareOptions?: PromptCachingMiddlewareConfig): import(\"./types.js\").AgentMiddleware<undefined, z.ZodObject<{\n /**\n * Whether to enable prompt caching.\n * @default true\n */\n enableCaching: z.ZodOptional<z.ZodBoolean>;\n /**\n * The time-to-live for the cached prompt.\n * @default \"5m\"\n */\n ttl: z.ZodOptional<z.ZodEnum<[\"5m\", \"1h\"]>>;\n /**\n * The minimum number of messages required before caching is applied.\n * @default 3\n */\n minMessagesToCache: z.ZodOptional<z.ZodNumber>;\n /**\n * The behavior to take when an unsupported model is used.\n * - \"ignore\" will ignore the unsupported model and continue without caching.\n * - \"warn\" will warn the user and continue without caching.\n * - \"raise\" will raise an error and stop the agent.\n * @default \"warn\"\n */\n unsupportedModelBehavior: z.ZodOptional<z.ZodEnum<[\"ignore\", \"warn\", \"raise\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n enableCaching?: boolean | undefined;\n ttl?: \"1h\" | \"5m\" | undefined;\n minMessagesToCache?: number | undefined;\n unsupportedModelBehavior?: \"ignore\" | \"raise\" | \"warn\" | undefined;\n}, {\n enableCaching?: boolean | undefined;\n ttl?: \"1h\" | \"5m\" | undefined;\n minMessagesToCache?: number | undefined;\n unsupportedModelBehavior?: \"ignore\" | \"raise\"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