langchain 1.2.0 → 2.0.0-dev-1765937705265
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.
- package/CHANGELOG.md +7 -0
- package/dist/agents/ReactAgent.cjs +28 -0
- package/dist/agents/ReactAgent.cjs.map +1 -1
- package/dist/agents/ReactAgent.d.cts +50 -14
- package/dist/agents/ReactAgent.d.cts.map +1 -1
- package/dist/agents/ReactAgent.d.ts +50 -14
- package/dist/agents/ReactAgent.d.ts.map +1 -1
- package/dist/agents/ReactAgent.js +28 -0
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/index.cjs.map +1 -1
- package/dist/agents/index.d.cts +41 -29
- package/dist/agents/index.d.cts.map +1 -1
- package/dist/agents/index.d.ts +41 -29
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/middleware/contextEditing.d.cts +2 -1
- package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
- package/dist/agents/middleware/contextEditing.d.ts +2 -1
- package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.cts +2 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.ts +2 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
- package/dist/agents/middleware/hitl.d.cts +9 -1
- package/dist/agents/middleware/hitl.d.cts.map +1 -1
- package/dist/agents/middleware/hitl.d.ts +9 -1
- package/dist/agents/middleware/hitl.d.ts.map +1 -1
- package/dist/agents/middleware/llmToolSelector.d.cts +4 -4
- package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
- package/dist/agents/middleware/llmToolSelector.d.ts +4 -4
- package/dist/agents/middleware/llmToolSelector.d.ts.map +1 -1
- package/dist/agents/middleware/modelCallLimit.d.cts +6 -1
- package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -1
- package/dist/agents/middleware/modelCallLimit.d.ts +6 -1
- package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts +7 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts.map +1 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts +7 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts.map +1 -1
- package/dist/agents/middleware/summarization.d.cts +30 -7
- package/dist/agents/middleware/summarization.d.cts.map +1 -1
- package/dist/agents/middleware/summarization.d.ts +30 -7
- package/dist/agents/middleware/summarization.d.ts.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.cts +42 -1
- package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.ts +42 -1
- package/dist/agents/middleware/todoListMiddleware.d.ts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.cts +2 -1
- package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.ts +2 -1
- package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
- package/dist/agents/middleware/types.cjs.map +1 -1
- package/dist/agents/middleware/types.d.cts +125 -32
- package/dist/agents/middleware/types.d.cts.map +1 -1
- package/dist/agents/middleware/types.d.ts +125 -32
- package/dist/agents/middleware/types.d.ts.map +1 -1
- package/dist/agents/middleware/types.js.map +1 -1
- package/dist/agents/middleware.cjs +1 -1
- package/dist/agents/middleware.cjs.map +1 -1
- package/dist/agents/middleware.d.cts +4 -4
- package/dist/agents/middleware.d.cts.map +1 -1
- package/dist/agents/middleware.d.ts +4 -4
- package/dist/agents/middleware.d.ts.map +1 -1
- package/dist/agents/middleware.js +1 -1
- package/dist/agents/middleware.js.map +1 -1
- package/dist/agents/types.d.cts +254 -8
- package/dist/agents/types.d.cts.map +1 -1
- package/dist/agents/types.d.ts +254 -8
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/package.json +5 -5
- package/chat_models/universal.cjs +0 -1
- package/chat_models/universal.d.cts +0 -1
- package/chat_models/universal.d.ts +0 -1
- package/chat_models/universal.js +0 -1
- package/hub/node.cjs +0 -1
- package/hub/node.d.cts +0 -1
- package/hub/node.d.ts +0 -1
- package/hub/node.js +0 -1
- package/hub.cjs +0 -1
- package/hub.d.cts +0 -1
- package/hub.d.ts +0 -1
- package/hub.js +0 -1
- package/load/serializable.cjs +0 -1
- package/load/serializable.d.cts +0 -1
- package/load/serializable.d.ts +0 -1
- package/load/serializable.js +0 -1
- package/load.cjs +0 -1
- package/load.d.cts +0 -1
- package/load.d.ts +0 -1
- package/load.js +0 -1
- package/storage/encoder_backed.cjs +0 -1
- package/storage/encoder_backed.d.cts +0 -1
- package/storage/encoder_backed.d.ts +0 -1
- package/storage/encoder_backed.js +0 -1
- package/storage/file_system.cjs +0 -1
- package/storage/file_system.d.cts +0 -1
- package/storage/file_system.d.ts +0 -1
- package/storage/file_system.js +0 -1
- package/storage/in_memory.cjs +0 -1
- package/storage/in_memory.d.cts +0 -1
- package/storage/in_memory.d.ts +0 -1
- package/storage/in_memory.js +0 -1
package/dist/agents/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n any\n >"],"sources":["../../src/agents/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\n\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 {\n ToolStrategy,\n TypedToolStrategy,\n ProviderStrategy,\n ResponseFormat,\n JsonSchemaFormat,\n} from \"./responses.js\";\nimport { ReactAgent } from \"./ReactAgent.js\";\n\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 function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n T,\n StateSchema,\n ContextSchema,\n InteropZodType<T>\n > & {\n responseFormat: InteropZodType<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)\nexport function createAgent<\n T extends readonly InteropZodType<any>[],\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n StateSchema,\n ContextSchema,\n T\n > & {\n responseFormat: T;\n middleware?: TMiddleware;\n }\n): ReactAgent<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n StateSchema,\n ContextSchema,\n TMiddleware\n>;\n\n// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat\n > & {\n responseFormat: JsonSchemaFormat;\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat[];\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat | JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat | JsonSchemaFormat[];\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n T,\n StateSchema,\n ContextSchema,\n TypedToolStrategy<T>\n > & {\n responseFormat: TypedToolStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 6: With responseFormat as single ToolStrategy instance\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<T, StateSchema, ContextSchema, ToolStrategy<T>> & {\n responseFormat: ToolStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 7: With responseFormat as ProviderStrategy\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n T,\n StateSchema,\n ContextSchema,\n ProviderStrategy<T>\n > & {\n responseFormat: ProviderStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 8: Without responseFormat property at all - with proper middleware state typing\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: Omit<\n CreateAgentParams<\n ResponseFormatUndefined,\n StateSchema,\n ContextSchema,\n never\n >,\n \"responseFormat\"\n > & { middleware?: TMiddleware }\n): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 9: With responseFormat explicitly undefined\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: Omit<\n CreateAgentParams<\n ResponseFormatUndefined,\n StateSchema,\n ContextSchema,\n never\n >,\n \"responseFormat\"\n > & {\n responseFormat?: undefined;\n middleware?: TMiddleware;\n }\n): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 10: For other ResponseFormat values (failsafe)\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n ResponseFormat\n > & {\n responseFormat: ResponseFormat;\n middleware?: TMiddleware;\n }\n): ReactAgent<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware\n>;\n\n// Implementation\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any>,\n StateSchema extends AnyAnnotationRoot | InteropZodObject,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n TMiddleware extends readonly AgentMiddleware[] = []\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n any\n >\n): ReactAgent<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware\n> {\n return new ReactAgent(params);\n}\n\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 {\n toolStrategy,\n providerStrategy,\n ToolStrategy,\n ProviderStrategy,\n type ResponseFormat,\n type ResponseFormatUndefined,\n} from \"./responses.js\";\nexport { createMiddleware } from \"./middleware.js\";\nexport { MIDDLEWARE_BRAND } from \"./middleware/types.js\";\nexport type * from \"./middleware/types.js\";\nexport { FakeToolCallingModel } from \"./tests/utils.js\";\nexport type { ReactAgent } from \"./ReactAgent.js\";\n"],"mappings":";;;;;;;;AA+YA,SAAgB,YAMdA,QAWA;AACA,QAAO,IAAI,WAAW;AACvB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n any\n >"],"sources":["../../src/agents/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport type { ResponseFormatUndefined } from \"./responses.js\";\nimport type {\n CreateAgentParams,\n AgentTypeConfig,\n CombineTools,\n} from \"./types.js\";\nimport type { AgentMiddleware, AnyAnnotationRoot } from \"./middleware/types.js\";\nimport type { ExtractZodArrayTypes } from \"./types.js\";\nimport type {\n ToolStrategy,\n TypedToolStrategy,\n ProviderStrategy,\n ResponseFormat,\n JsonSchemaFormat,\n} from \"./responses.js\";\nimport { ReactAgent } from \"./ReactAgent.js\";\n\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 function createAgent<\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[],\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[]\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n InteropZodType<StructuredResponseFormat>\n > & {\n responseFormat: InteropZodType<StructuredResponseFormat>;\n middleware?: TMiddleware;\n tools?: TTools;\n }\n): ReactAgent<\n AgentTypeConfig<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware,\n CombineTools<TTools, TMiddleware>\n >\n>;\n\n// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)\nexport function createAgent<\n StructuredResponseFormat extends readonly InteropZodType<any>[],\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[],\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[]\n>(\n params: CreateAgentParams<\n ExtractZodArrayTypes<StructuredResponseFormat> extends Record<string, any>\n ? ExtractZodArrayTypes<StructuredResponseFormat>\n : Record<string, any>,\n StateSchema,\n ContextSchema,\n StructuredResponseFormat\n > & {\n responseFormat: StructuredResponseFormat;\n middleware?: TMiddleware;\n tools?: TTools;\n }\n): ReactAgent<\n AgentTypeConfig<\n ExtractZodArrayTypes<StructuredResponseFormat> extends Record<string, any>\n ? ExtractZodArrayTypes<StructuredResponseFormat>\n : Record<string, any>,\n StateSchema,\n ContextSchema,\n TMiddleware,\n CombineTools<TTools, TMiddleware>\n >\n>;\n\n// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[],\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat\n > & {\n responseFormat: JsonSchemaFormat;\n middleware?: TMiddleware;\n tools?: TTools;\n }\n): ReactAgent<\n AgentTypeConfig<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n TMiddleware,\n CombineTools<TTools, TMiddleware>\n >\n>;\n\n// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[],\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat[];\n middleware?: TMiddleware;\n tools?: TTools;\n }\n): ReactAgent<\n AgentTypeConfig<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n TMiddleware,\n CombineTools<TTools, TMiddleware>\n >\n>;\n\n// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[],\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat | JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat | JsonSchemaFormat[];\n middleware?: TMiddleware;\n tools?: TTools;\n }\n): ReactAgent<\n AgentTypeConfig<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n TMiddleware,\n CombineTools<TTools, TMiddleware>\n >\n>;\n\n// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[],\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[]\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TypedToolStrategy<StructuredResponseFormat>\n > & {\n responseFormat: TypedToolStrategy<StructuredResponseFormat>;\n middleware?: TMiddleware;\n tools?: TTools;\n }\n): ReactAgent<\n AgentTypeConfig<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware,\n CombineTools<TTools, TMiddleware>\n >\n>;\n\n// Overload 6: With responseFormat as single ToolStrategy instance\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[],\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[]\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n ToolStrategy<StructuredResponseFormat>\n > & {\n responseFormat: ToolStrategy<StructuredResponseFormat>;\n middleware?: TMiddleware;\n tools?: TTools;\n }\n): ReactAgent<\n AgentTypeConfig<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware,\n CombineTools<TTools, TMiddleware>\n >\n>;\n\n// Overload 7: With responseFormat as ProviderStrategy\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[],\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[]\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n ProviderStrategy<StructuredResponseFormat>\n > & {\n responseFormat: ProviderStrategy<StructuredResponseFormat>;\n middleware?: TMiddleware;\n tools?: TTools;\n }\n): ReactAgent<\n AgentTypeConfig<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware,\n CombineTools<TTools, TMiddleware>\n >\n>;\n\n// Overload 8: Without responseFormat property at all - with proper middleware state typing\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[],\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[]\n>(\n params: Omit<\n CreateAgentParams<\n ResponseFormatUndefined,\n StateSchema,\n ContextSchema,\n never\n >,\n \"responseFormat\"\n > & { middleware?: TMiddleware; tools?: TTools }\n): ReactAgent<\n AgentTypeConfig<\n ResponseFormatUndefined,\n StateSchema,\n ContextSchema,\n TMiddleware,\n CombineTools<TTools, TMiddleware>\n >\n>;\n\n// Overload 9: With responseFormat explicitly undefined\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[],\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[]\n>(\n params: Omit<\n CreateAgentParams<\n ResponseFormatUndefined,\n StateSchema,\n ContextSchema,\n never\n >,\n \"responseFormat\"\n > & {\n responseFormat?: undefined;\n middleware?: TMiddleware;\n tools?: TTools;\n }\n): ReactAgent<\n AgentTypeConfig<\n ResponseFormatUndefined,\n StateSchema,\n ContextSchema,\n TMiddleware,\n CombineTools<TTools, TMiddleware>\n >\n>;\n\n// Overload 10: For other ResponseFormat values (failsafe)\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[],\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[]\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n ResponseFormat\n > & {\n responseFormat: ResponseFormat;\n middleware?: TMiddleware;\n tools?: TTools;\n }\n): ReactAgent<\n AgentTypeConfig<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware,\n CombineTools<TTools, TMiddleware>\n >\n>;\n\n// Implementation\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any>,\n StateSchema extends AnyAnnotationRoot | InteropZodObject,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[],\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[]\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n any\n >\n): ReactAgent<\n AgentTypeConfig<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware,\n CombineTools<TTools, TMiddleware>\n >\n> {\n return new ReactAgent(params);\n}\n\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 {\n toolStrategy,\n providerStrategy,\n ToolStrategy,\n ProviderStrategy,\n type ResponseFormat,\n type ResponseFormatUndefined,\n} from \"./responses.js\";\nexport { createMiddleware } from \"./middleware.js\";\nexport { MIDDLEWARE_BRAND } from \"./middleware/types.js\";\nexport type * from \"./middleware/types.js\";\nexport { FakeToolCallingModel } from \"./tests/utils.js\";\nexport type { ReactAgent } from \"./ReactAgent.js\";\n"],"mappings":";;;;;;;;AA6hBA,SAAgB,YAUdA,QAcA;AACA,QAAO,IAAI,WAAW;AACvB"}
|
|
@@ -2,6 +2,7 @@ import { AgentMiddleware } from "./types.cjs";
|
|
|
2
2
|
import { ContextSize, KeepSize, TokenCounter } from "./summarization.cjs";
|
|
3
3
|
import { BaseLanguageModel } from "@langchain/core/language_models/base";
|
|
4
4
|
import { BaseMessage } from "@langchain/core/messages";
|
|
5
|
+
import * as _langchain_core_tools5 from "@langchain/core/tools";
|
|
5
6
|
|
|
6
7
|
//#region src/agents/middleware/contextEditing.d.ts
|
|
7
8
|
|
|
@@ -333,7 +334,7 @@ interface ContextEditingMiddlewareConfig {
|
|
|
333
334
|
* @param config - Configuration options for the middleware
|
|
334
335
|
* @returns A middleware instance that can be used with `createAgent`
|
|
335
336
|
*/
|
|
336
|
-
declare function contextEditingMiddleware(config?: ContextEditingMiddlewareConfig): AgentMiddleware<undefined, undefined,
|
|
337
|
+
declare function contextEditingMiddleware(config?: ContextEditingMiddlewareConfig): AgentMiddleware<undefined, undefined, unknown, readonly (_langchain_core_tools5.ServerTool | _langchain_core_tools5.ClientTool)[]>;
|
|
337
338
|
//#endregion
|
|
338
339
|
export { ClearToolUsesEdit, ClearToolUsesEditConfig, ContextEdit, ContextEditingMiddlewareConfig, contextEditingMiddleware };
|
|
339
340
|
//# sourceMappingURL=contextEditing.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contextEditing.d.cts","names":["BaseMessage","BaseLanguageModel","ContextSize","KeepSize","TokenCounter","ContextEdit","Promise","ClearToolUsesEditConfig","ClearToolUsesEdit","Set","ContextEditingMiddlewareConfig","contextEditingMiddleware","__types_js10","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 { HumanMessage, type ContextEdit, type BaseMessage } from \"langchain\";\n *\n * class RemoveOldHumanMessages implements ContextEdit {\n * constructor(private keepRecent: number = 10) {}\n *\n * async apply({ messages, countTokens }) {\n * // Check current token count\n * const tokens = await countTokens(messages);\n *\n * // Remove old human messages if over limit, keeping the most recent ones\n * if (tokens > 50000) {\n * const humanMessages: number[] = [];\n *\n * // Find all human message indices\n * for (let i = 0; i < messages.length; i++) {\n * if (HumanMessage.isInstance(messages[i])) {\n * humanMessages.push(i);\n * }\n * }\n *\n * // Remove old human messages (keep only the most recent N)\n * const toRemove = humanMessages.slice(0, -this.keepRecent);\n * for (let i = toRemove.length - 1; i >= 0; i--) {\n * messages.splice(toRemove[i]!, 1);\n * }\n * }\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//# sourceMappingURL=contextEditing.d.ts.map"],"mappings":";;;;;;;AA2EsB;AAKtB;;;;AAqCmB;AAkEnB;;;;;;;;;;;;AAA6D;AAmB7D;AAyIA;;;;;;;;;;;;;;;;;;;UAjSiBK,WAAAA;;;;;;;;;;;;;;;;cAgBCL;;;;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,iCAAAA"}
|
|
1
|
+
{"version":3,"file":"contextEditing.d.cts","names":["__types_js10","BaseMessage","BaseLanguageModel","ContextSize","KeepSize","TokenCounter","ContextEdit","Promise","ClearToolUsesEditConfig","ClearToolUsesEdit","Set","ContextEditingMiddlewareConfig","contextEditingMiddleware","_langchain_core_tools5","ServerTool","ClientTool","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 { HumanMessage, type ContextEdit, type BaseMessage } from \"langchain\";\n *\n * class RemoveOldHumanMessages implements ContextEdit {\n * constructor(private keepRecent: number = 10) {}\n *\n * async apply({ messages, countTokens }) {\n * // Check current token count\n * const tokens = await countTokens(messages);\n *\n * // Remove old human messages if over limit, keeping the most recent ones\n * if (tokens > 50000) {\n * const humanMessages: number[] = [];\n *\n * // Find all human message indices\n * for (let i = 0; i < messages.length; i++) {\n * if (HumanMessage.isInstance(messages[i])) {\n * humanMessages.push(i);\n * }\n * }\n *\n * // Remove old human messages (keep only the most recent N)\n * const toRemove = humanMessages.slice(0, -this.keepRecent);\n * for (let i = toRemove.length - 1; i >= 0; i--) {\n * messages.splice(toRemove[i]!, 1);\n * }\n * }\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, unknown, readonly (import(\"@langchain/core/tools\").ServerTool | import(\"@langchain/core/tools\").ClientTool)[]>;\n//# sourceMappingURL=contextEditing.d.ts.map"],"mappings":";;;;;;;;;AA2EsB;AAKtB;;;;AAqCmB;AAkEnB;;;;;;;;;;;;AAA6D;AAmB7D;AAyIA;;;;;AAA+H;;;;;;;;;;;;;UAjS9GM,WAAAA;;;;;;;;;;;;;;;;cAgBCL;;;;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,0FAA8BE,sBAAAA,CAAiHC,UAAAA,GAAUD,sBAAAA,CAAmCE"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { AgentMiddleware } from "./types.js";
|
|
2
2
|
import { ContextSize, KeepSize, TokenCounter } from "./summarization.js";
|
|
3
3
|
import { BaseMessage } from "@langchain/core/messages";
|
|
4
|
+
import * as _langchain_core_tools5 from "@langchain/core/tools";
|
|
4
5
|
import { BaseLanguageModel } from "@langchain/core/language_models/base";
|
|
5
6
|
|
|
6
7
|
//#region src/agents/middleware/contextEditing.d.ts
|
|
@@ -333,7 +334,7 @@ interface ContextEditingMiddlewareConfig {
|
|
|
333
334
|
* @param config - Configuration options for the middleware
|
|
334
335
|
* @returns A middleware instance that can be used with `createAgent`
|
|
335
336
|
*/
|
|
336
|
-
declare function contextEditingMiddleware(config?: ContextEditingMiddlewareConfig): AgentMiddleware<undefined, undefined,
|
|
337
|
+
declare function contextEditingMiddleware(config?: ContextEditingMiddlewareConfig): AgentMiddleware<undefined, undefined, unknown, readonly (_langchain_core_tools5.ServerTool | _langchain_core_tools5.ClientTool)[]>;
|
|
337
338
|
//#endregion
|
|
338
339
|
export { ClearToolUsesEdit, ClearToolUsesEditConfig, ContextEdit, ContextEditingMiddlewareConfig, contextEditingMiddleware };
|
|
339
340
|
//# sourceMappingURL=contextEditing.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contextEditing.d.ts","names":["BaseMessage","BaseLanguageModel","ContextSize","KeepSize","TokenCounter","ContextEdit","Promise","ClearToolUsesEditConfig","ClearToolUsesEdit","Set","ContextEditingMiddlewareConfig","contextEditingMiddleware","__types_js10","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 { HumanMessage, type ContextEdit, type BaseMessage } from \"langchain\";\n *\n * class RemoveOldHumanMessages implements ContextEdit {\n * constructor(private keepRecent: number = 10) {}\n *\n * async apply({ messages, countTokens }) {\n * // Check current token count\n * const tokens = await countTokens(messages);\n *\n * // Remove old human messages if over limit, keeping the most recent ones\n * if (tokens > 50000) {\n * const humanMessages: number[] = [];\n *\n * // Find all human message indices\n * for (let i = 0; i < messages.length; i++) {\n * if (HumanMessage.isInstance(messages[i])) {\n * humanMessages.push(i);\n * }\n * }\n *\n * // Remove old human messages (keep only the most recent N)\n * const toRemove = humanMessages.slice(0, -this.keepRecent);\n * for (let i = toRemove.length - 1; i >= 0; i--) {\n * messages.splice(toRemove[i]!, 1);\n * }\n * }\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//# sourceMappingURL=contextEditing.d.ts.map"],"mappings":";;;;;;;AA2EsB;AAKtB;;;;AAqCmB;AAkEnB;;;;;;;;;;;;AAA6D;AAmB7D;AAyIA;;;;;;;;;;;;;;;;;;;UAjSiBK,WAAAA;;;;;;;;;;;;;;;;cAgBCL;;;;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,iCAAAA"}
|
|
1
|
+
{"version":3,"file":"contextEditing.d.ts","names":["__types_js10","BaseMessage","BaseLanguageModel","ContextSize","KeepSize","TokenCounter","ContextEdit","Promise","ClearToolUsesEditConfig","ClearToolUsesEdit","Set","ContextEditingMiddlewareConfig","contextEditingMiddleware","_langchain_core_tools5","ServerTool","ClientTool","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 { HumanMessage, type ContextEdit, type BaseMessage } from \"langchain\";\n *\n * class RemoveOldHumanMessages implements ContextEdit {\n * constructor(private keepRecent: number = 10) {}\n *\n * async apply({ messages, countTokens }) {\n * // Check current token count\n * const tokens = await countTokens(messages);\n *\n * // Remove old human messages if over limit, keeping the most recent ones\n * if (tokens > 50000) {\n * const humanMessages: number[] = [];\n *\n * // Find all human message indices\n * for (let i = 0; i < messages.length; i++) {\n * if (HumanMessage.isInstance(messages[i])) {\n * humanMessages.push(i);\n * }\n * }\n *\n * // Remove old human messages (keep only the most recent N)\n * const toRemove = humanMessages.slice(0, -this.keepRecent);\n * for (let i = toRemove.length - 1; i >= 0; i--) {\n * messages.splice(toRemove[i]!, 1);\n * }\n * }\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, unknown, readonly (import(\"@langchain/core/tools\").ServerTool | import(\"@langchain/core/tools\").ClientTool)[]>;\n//# sourceMappingURL=contextEditing.d.ts.map"],"mappings":";;;;;;;;;AA2EsB;AAKtB;;;;AAqCmB;AAkEnB;;;;;;;;;;;;AAA6D;AAmB7D;AAyIA;;;;;AAA+H;;;;;;;;;;;;;UAjS9GM,WAAAA;;;;;;;;;;;;;;;;cAgBCL;;;;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,0FAA8BE,sBAAAA,CAAiHC,UAAAA,GAAUD,sBAAAA,CAAmCE"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { AgentBuiltInState, Runtime } from "../runtime.cjs";
|
|
2
2
|
import { AgentMiddleware } from "./types.cjs";
|
|
3
3
|
import { SystemMessage } from "@langchain/core/messages";
|
|
4
|
+
import * as _langchain_core_tools0 from "@langchain/core/tools";
|
|
4
5
|
|
|
5
6
|
//#region src/agents/middleware/dynamicSystemPrompt.d.ts
|
|
6
7
|
type DynamicSystemPromptMiddlewareConfig<TContextSchema> = (state: AgentBuiltInState, runtime: Runtime<TContextSchema>) => string | SystemMessage | Promise<string | SystemMessage>;
|
|
@@ -42,7 +43,7 @@ type DynamicSystemPromptMiddlewareConfig<TContextSchema> = (state: AgentBuiltInS
|
|
|
42
43
|
*
|
|
43
44
|
* @public
|
|
44
45
|
*/
|
|
45
|
-
declare function dynamicSystemPromptMiddleware<TContextSchema = unknown>(fn: DynamicSystemPromptMiddlewareConfig<TContextSchema>): AgentMiddleware<undefined, undefined,
|
|
46
|
+
declare function dynamicSystemPromptMiddleware<TContextSchema = unknown>(fn: DynamicSystemPromptMiddlewareConfig<TContextSchema>): AgentMiddleware<undefined, undefined, unknown, readonly (_langchain_core_tools0.ServerTool | _langchain_core_tools0.ClientTool)[]>;
|
|
46
47
|
//#endregion
|
|
47
48
|
export { DynamicSystemPromptMiddlewareConfig, dynamicSystemPromptMiddleware };
|
|
48
49
|
//# sourceMappingURL=dynamicSystemPrompt.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamicSystemPrompt.d.cts","names":["SystemMessage","Runtime","AgentBuiltInState","DynamicSystemPromptMiddlewareConfig","TContextSchema","Promise","dynamicSystemPromptMiddleware","
|
|
1
|
+
{"version":3,"file":"dynamicSystemPrompt.d.cts","names":["__types_js0","SystemMessage","Runtime","AgentBuiltInState","DynamicSystemPromptMiddlewareConfig","TContextSchema","Promise","dynamicSystemPromptMiddleware","_langchain_core_tools0","ServerTool","ClientTool","AgentMiddleware"],"sources":["../../../src/agents/middleware/dynamicSystemPrompt.d.ts"],"sourcesContent":["import { SystemMessage } from \"@langchain/core/messages\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nexport type DynamicSystemPromptMiddlewareConfig<TContextSchema> = (state: AgentBuiltInState, runtime: Runtime<TContextSchema>) => string | SystemMessage | Promise<string | SystemMessage>;\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, unknown, readonly (import(\"@langchain/core/tools\").ServerTool | import(\"@langchain/core/tools\").ClientTool)[]>;\n//# sourceMappingURL=dynamicSystemPrompt.d.ts.map"],"mappings":";;;;;;KAEYI,8DAA8DD,4BAA4BD,QAAQG,6BAA6BJ,gBAAgBK,iBAAiBL;;;;AAA5K;;;;;;;AAAkK;AAuClK;;;;;;AAA8K;;;;;;;;;;;;;;;;;;;;;iBAAtJM,4DAA4DH,oCAAoCC,2EAADG,sBAAAA,CAAiIC,UAAAA,GAAUD,sBAAAA,CAAmCE"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { AgentBuiltInState, Runtime } from "../runtime.js";
|
|
2
2
|
import { AgentMiddleware } from "./types.js";
|
|
3
3
|
import { SystemMessage } from "@langchain/core/messages";
|
|
4
|
+
import * as _langchain_core_tools3 from "@langchain/core/tools";
|
|
4
5
|
|
|
5
6
|
//#region src/agents/middleware/dynamicSystemPrompt.d.ts
|
|
6
7
|
type DynamicSystemPromptMiddlewareConfig<TContextSchema> = (state: AgentBuiltInState, runtime: Runtime<TContextSchema>) => string | SystemMessage | Promise<string | SystemMessage>;
|
|
@@ -42,7 +43,7 @@ type DynamicSystemPromptMiddlewareConfig<TContextSchema> = (state: AgentBuiltInS
|
|
|
42
43
|
*
|
|
43
44
|
* @public
|
|
44
45
|
*/
|
|
45
|
-
declare function dynamicSystemPromptMiddleware<TContextSchema = unknown>(fn: DynamicSystemPromptMiddlewareConfig<TContextSchema>): AgentMiddleware<undefined, undefined,
|
|
46
|
+
declare function dynamicSystemPromptMiddleware<TContextSchema = unknown>(fn: DynamicSystemPromptMiddlewareConfig<TContextSchema>): AgentMiddleware<undefined, undefined, unknown, readonly (_langchain_core_tools3.ServerTool | _langchain_core_tools3.ClientTool)[]>;
|
|
46
47
|
//#endregion
|
|
47
48
|
export { DynamicSystemPromptMiddlewareConfig, dynamicSystemPromptMiddleware };
|
|
48
49
|
//# sourceMappingURL=dynamicSystemPrompt.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamicSystemPrompt.d.ts","names":["SystemMessage","Runtime","AgentBuiltInState","DynamicSystemPromptMiddlewareConfig","TContextSchema","Promise","dynamicSystemPromptMiddleware","
|
|
1
|
+
{"version":3,"file":"dynamicSystemPrompt.d.ts","names":["__types_js9","SystemMessage","Runtime","AgentBuiltInState","DynamicSystemPromptMiddlewareConfig","TContextSchema","Promise","dynamicSystemPromptMiddleware","_langchain_core_tools3","ServerTool","ClientTool","AgentMiddleware"],"sources":["../../../src/agents/middleware/dynamicSystemPrompt.d.ts"],"sourcesContent":["import { SystemMessage } from \"@langchain/core/messages\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nexport type DynamicSystemPromptMiddlewareConfig<TContextSchema> = (state: AgentBuiltInState, runtime: Runtime<TContextSchema>) => string | SystemMessage | Promise<string | SystemMessage>;\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, unknown, readonly (import(\"@langchain/core/tools\").ServerTool | import(\"@langchain/core/tools\").ClientTool)[]>;\n//# sourceMappingURL=dynamicSystemPrompt.d.ts.map"],"mappings":";;;;;;KAEYI,8DAA8DD,4BAA4BD,QAAQG,6BAA6BJ,gBAAgBK,iBAAiBL;;;;AAA5K;;;;;;;AAAkK;AAuClK;;;;;;AAA8K;;;;;;;;;;;;;;;;;;;;;iBAAtJM,4DAA4DH,oCAAoCC,2EAADG,sBAAAA,CAAiIC,UAAAA,GAAUD,sBAAAA,CAAmCE"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { AgentBuiltInState, Runtime } from "../runtime.cjs";
|
|
2
2
|
import { AgentMiddleware } from "./types.cjs";
|
|
3
3
|
import { ToolCall } from "@langchain/core/messages";
|
|
4
|
+
import * as _langchain_core_tools1 from "@langchain/core/tools";
|
|
4
5
|
import { InferInteropZodInput } from "@langchain/core/utils/types";
|
|
5
6
|
import { z } from "zod/v3";
|
|
6
7
|
|
|
@@ -605,7 +606,14 @@ declare function humanInTheLoopMiddleware(options: NonNullable<HumanInTheLoopMid
|
|
|
605
606
|
argsSchema?: Record<string, any> | undefined;
|
|
606
607
|
}> | undefined;
|
|
607
608
|
descriptionPrefix?: string | undefined;
|
|
608
|
-
}>,
|
|
609
|
+
}>, {
|
|
610
|
+
interruptOn?: Record<string, boolean | {
|
|
611
|
+
allowedDecisions: ("approve" | "edit" | "reject")[];
|
|
612
|
+
description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;
|
|
613
|
+
argsSchema?: Record<string, any> | undefined;
|
|
614
|
+
}> | undefined;
|
|
615
|
+
descriptionPrefix: string;
|
|
616
|
+
}, readonly (_langchain_core_tools1.ServerTool | _langchain_core_tools1.ClientTool)[]>;
|
|
609
617
|
//#endregion
|
|
610
618
|
export { Action, ActionRequest, ApproveDecision, Decision, DecisionType, DescriptionFactory, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, RejectDecision, ReviewConfig, humanInTheLoopMiddleware };
|
|
611
619
|
//# sourceMappingURL=hitl.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
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_js7","AgentMiddleware"],"sources":["../../../src/agents/middleware/hitl.d.ts"],"sourcesContent":["import { 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;\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,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
|
+
{"version":3,"file":"hitl.d.cts","names":["__types_js8","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","_langchain_core_tools1","ServerTool","ClientTool","AgentMiddleware"],"sources":["../../../src/agents/middleware/hitl.d.ts"],"sourcesContent":["import { 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}>, {\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}, readonly (import(\"@langchain/core/tools\").ServerTool | import(\"@langchain/core/tools\").ClientTool)[]>;\nexport {};\n//# sourceMappingURL=hitl.d.ts.map"],"mappings":";;;;;;;;cAIcM,2BAA2BL,CAAAA,CAAEc,YAAYd,CAAAA,CAAEU,UAAUV,CAAAA,CAAEQ,QAAQP,iBAAiBK,sBAAsBN,CAAAA,CAAEO,YAAYN,iBAAiBK,u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8BH,2BAA2BC,kDAAkDqB;iBAChJnB;;;;gBAIHA;;qCAEuBL,iBAAiBK,8BAA8BH,2BAA2BC,kDAAkDqB;iBAChJnB;;;aAHGsC,sBAAAA,CAMqBC,UAAAA,GAAUD,sBAAAA,CAAmCE"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { AgentBuiltInState, Runtime } from "../runtime.js";
|
|
2
2
|
import { AgentMiddleware } from "./types.js";
|
|
3
3
|
import { ToolCall } from "@langchain/core/messages";
|
|
4
|
+
import * as _langchain_core_tools0 from "@langchain/core/tools";
|
|
4
5
|
import { z } from "zod/v3";
|
|
5
6
|
import { InferInteropZodInput } from "@langchain/core/utils/types";
|
|
6
7
|
|
|
@@ -605,7 +606,14 @@ declare function humanInTheLoopMiddleware(options: NonNullable<HumanInTheLoopMid
|
|
|
605
606
|
argsSchema?: Record<string, any> | undefined;
|
|
606
607
|
}> | undefined;
|
|
607
608
|
descriptionPrefix?: string | undefined;
|
|
608
|
-
}>,
|
|
609
|
+
}>, {
|
|
610
|
+
interruptOn?: Record<string, boolean | {
|
|
611
|
+
allowedDecisions: ("approve" | "edit" | "reject")[];
|
|
612
|
+
description?: string | ((args_0: ToolCall<string, Record<string, any>>, args_1: AgentBuiltInState, args_2: Runtime<unknown>, ...args: unknown[]) => string | Promise<string>) | undefined;
|
|
613
|
+
argsSchema?: Record<string, any> | undefined;
|
|
614
|
+
}> | undefined;
|
|
615
|
+
descriptionPrefix: string;
|
|
616
|
+
}, readonly (_langchain_core_tools0.ServerTool | _langchain_core_tools0.ClientTool)[]>;
|
|
609
617
|
//#endregion
|
|
610
618
|
export { Action, ActionRequest, ApproveDecision, Decision, DecisionType, DescriptionFactory, EditDecision, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, InterruptOnConfig, RejectDecision, ReviewConfig, humanInTheLoopMiddleware };
|
|
611
619
|
//# sourceMappingURL=hitl.d.ts.map
|