langchain 1.0.1 → 1.0.3
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 +18 -0
- package/dist/_virtual/rolldown_runtime.cjs +0 -4
- package/dist/_virtual/rolldown_runtime.js +1 -10
- package/dist/agents/ReactAgent.cjs +21 -41
- package/dist/agents/ReactAgent.cjs.map +1 -1
- package/dist/agents/ReactAgent.js +21 -41
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/annotation.cjs +1 -0
- package/dist/agents/annotation.cjs.map +1 -1
- package/dist/agents/annotation.js +1 -0
- package/dist/agents/annotation.js.map +1 -1
- package/dist/agents/index.cjs.map +1 -1
- package/dist/agents/index.d.cts +11 -11
- package/dist/agents/index.d.cts.map +1 -1
- package/dist/agents/index.d.ts +11 -11
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/middleware/callLimit.d.cts.map +1 -1
- package/dist/agents/middleware/callLimit.d.ts.map +1 -1
- package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
- package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
- package/dist/agents/middleware/hitl.cjs +7 -2
- package/dist/agents/middleware/hitl.cjs.map +1 -1
- package/dist/agents/middleware/hitl.d.cts.map +1 -1
- package/dist/agents/middleware/hitl.d.ts.map +1 -1
- package/dist/agents/middleware/hitl.js +7 -2
- package/dist/agents/middleware/hitl.js.map +1 -1
- package/dist/agents/middleware/index.cjs +2 -1
- package/dist/agents/middleware/index.d.cts +15 -0
- package/dist/agents/middleware/index.d.ts +14 -0
- package/dist/agents/middleware/index.js +2 -1
- package/dist/agents/middleware/modelCallLimit.cjs +145 -0
- package/dist/agents/middleware/modelCallLimit.cjs.map +1 -0
- package/dist/agents/middleware/modelCallLimit.d.cts +128 -0
- package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -0
- package/dist/agents/middleware/modelCallLimit.d.ts +128 -0
- package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -0
- package/dist/agents/middleware/modelCallLimit.js +144 -0
- package/dist/agents/middleware/modelCallLimit.js.map +1 -0
- package/dist/agents/middleware/promptCaching.d.cts.map +1 -1
- package/dist/agents/middleware/summarization.cjs +4 -2
- package/dist/agents/middleware/summarization.cjs.map +1 -1
- package/dist/agents/middleware/summarization.d.cts +7 -6
- package/dist/agents/middleware/summarization.d.cts.map +1 -1
- package/dist/agents/middleware/summarization.d.ts +7 -6
- package/dist/agents/middleware/summarization.d.ts.map +1 -1
- package/dist/agents/middleware/summarization.js +4 -2
- package/dist/agents/middleware/summarization.js.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.cjs +205 -92
- package/dist/agents/middleware/toolCallLimit.cjs.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.cts +46 -37
- package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.ts +46 -37
- package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.js +206 -93
- package/dist/agents/middleware/toolCallLimit.js.map +1 -1
- package/dist/agents/middleware/toolRetry.cjs +224 -0
- package/dist/agents/middleware/toolRetry.cjs.map +1 -0
- package/dist/agents/middleware/toolRetry.d.cts +179 -0
- package/dist/agents/middleware/toolRetry.d.cts.map +1 -0
- package/dist/agents/middleware/toolRetry.d.ts +179 -0
- package/dist/agents/middleware/toolRetry.d.ts.map +1 -0
- package/dist/agents/middleware/toolRetry.js +223 -0
- package/dist/agents/middleware/toolRetry.js.map +1 -0
- package/dist/agents/middleware/types.d.cts +21 -19
- package/dist/agents/middleware/types.d.cts.map +1 -1
- package/dist/agents/middleware/types.d.ts +21 -19
- package/dist/agents/middleware/types.d.ts.map +1 -1
- package/dist/agents/middleware/utils.cjs +7 -0
- package/dist/agents/middleware/utils.cjs.map +1 -1
- package/dist/agents/middleware/utils.d.cts.map +1 -1
- package/dist/agents/middleware/utils.d.ts.map +1 -1
- package/dist/agents/middleware/utils.js +7 -1
- package/dist/agents/middleware/utils.js.map +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.map +1 -1
- package/dist/agents/nodes/AgentNode.cjs +21 -47
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js +22 -48
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/nodes/ToolNode.cjs +12 -18
- package/dist/agents/nodes/ToolNode.cjs.map +1 -1
- package/dist/agents/nodes/ToolNode.js +12 -18
- package/dist/agents/nodes/ToolNode.js.map +1 -1
- package/dist/agents/nodes/middleware.cjs +9 -7
- package/dist/agents/nodes/middleware.cjs.map +1 -1
- package/dist/agents/nodes/middleware.js +10 -8
- package/dist/agents/nodes/middleware.js.map +1 -1
- package/dist/agents/nodes/types.d.cts +1 -1
- package/dist/agents/nodes/types.d.cts.map +1 -1
- package/dist/agents/nodes/types.d.ts +1 -1
- package/dist/agents/nodes/types.d.ts.map +1 -1
- package/dist/agents/nodes/utils.cjs +5 -1
- package/dist/agents/nodes/utils.cjs.map +1 -1
- package/dist/agents/nodes/utils.js +5 -1
- package/dist/agents/nodes/utils.js.map +1 -1
- package/dist/agents/runtime.d.cts +11 -27
- package/dist/agents/runtime.d.cts.map +1 -1
- package/dist/agents/runtime.d.ts +11 -27
- package/dist/agents/runtime.d.ts.map +1 -1
- package/dist/agents/state.cjs +45 -0
- package/dist/agents/state.cjs.map +1 -0
- package/dist/agents/state.js +44 -0
- package/dist/agents/state.js.map +1 -0
- package/dist/agents/types.d.cts +1 -1
- package/dist/agents/types.d.cts.map +1 -1
- package/dist/agents/types.d.ts +1 -1
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/agents/utils.cjs +10 -2
- package/dist/agents/utils.cjs.map +1 -1
- package/dist/agents/utils.js +10 -2
- package/dist/agents/utils.js.map +1 -1
- package/dist/chat_models/universal.cjs +4 -3
- package/dist/chat_models/universal.cjs.map +1 -1
- package/dist/chat_models/universal.js +4 -3
- package/dist/chat_models/universal.js.map +1 -1
- package/dist/embeddings/cache_backed.cjs +140 -0
- package/dist/embeddings/cache_backed.cjs.map +1 -0
- package/dist/embeddings/cache_backed.d.cts +107 -0
- package/dist/embeddings/cache_backed.d.cts.map +1 -0
- package/dist/embeddings/cache_backed.d.ts +107 -0
- package/dist/embeddings/cache_backed.d.ts.map +1 -0
- package/dist/embeddings/cache_backed.js +134 -0
- package/dist/embeddings/cache_backed.js.map +1 -0
- package/dist/embeddings/fake.cjs +22 -0
- package/dist/embeddings/fake.cjs.map +1 -0
- package/dist/embeddings/fake.d.cts +1 -0
- package/dist/embeddings/fake.d.ts +1 -0
- package/dist/embeddings/fake.js +12 -0
- package/dist/embeddings/fake.js.map +1 -0
- package/dist/hub/base.cjs +4 -17
- package/dist/hub/base.cjs.map +1 -1
- package/dist/hub/base.js +2 -15
- package/dist/hub/base.js.map +1 -1
- package/dist/index.cjs +6 -18
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +4 -5
- package/dist/index.js.map +1 -1
- package/package.json +6 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.cjs","names":["config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: (ClientTool | ServerTool)[];\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}","middleware: AgentMiddleware<TSchema, TContextSchema, any>"],"sources":["../../src/agents/middleware.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodDefault,\n InteropZodOptional,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\n\nimport type { ClientTool, ServerTool } from \"./tools.js\";\nimport type {\n AgentMiddleware,\n WrapToolCallHook,\n WrapModelCallHook,\n BeforeAgentHook,\n BeforeModelHook,\n AfterModelHook,\n AfterAgentHook,\n} from \"./middleware/types.js\";\n\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.wrapModelCall - The function to wrap model invocation\n * @param config.wrapToolCall - The function to wrap tool invocation\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @param config.beforeAgent - The function to run before the agent execution starts\n * @param config.afterAgent - The function to run after the agent execution completes\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n */\nexport function createMiddleware<\n TSchema extends InteropZodObject | undefined = undefined,\n TContextSchema extends\n | InteropZodObject\n | InteropZodOptional<InteropZodObject>\n | InteropZodDefault<InteropZodObject>\n | undefined = undefined\n>(config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: (ClientTool | ServerTool)[];\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}): AgentMiddleware<TSchema, TContextSchema, any> {\n const middleware: AgentMiddleware<TSchema, TContextSchema, any> = {\n name: config.name,\n stateSchema: config.stateSchema,\n contextSchema: config.contextSchema,\n wrapToolCall: config.wrapToolCall,\n wrapModelCall: config.wrapModelCall,\n beforeAgent: config.beforeAgent,\n beforeModel: config.beforeModel,\n afterModel: config.afterModel,\n afterAgent: config.afterAgent,\n tools: config.tools ?? [],\n };\n\n return middleware;\n}\n\ntype NormalizeContextSchema<\n TContextSchema extends\n | InteropZodObject\n | InteropZodOptional<InteropZodObject>\n | InteropZodDefault<InteropZodObject>\n | undefined = undefined\n> = TContextSchema extends InteropZodObject\n ? InferInteropZodOutput<TContextSchema>\n : TContextSchema extends InteropZodDefault<any>\n ? InferInteropZodOutput<TContextSchema>\n : TContextSchema extends InteropZodOptional<any>\n ? Partial<InferInteropZodOutput<TContextSchema>>\n : never;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAgB,iBAOdA,QA6JgD;CAChD,MAAMC,aAA4D;EAChE,MAAM,OAAO;EACb,aAAa,OAAO;EACpB,eAAe,OAAO;EACtB,cAAc,OAAO;EACrB,eAAe,OAAO;EACtB,aAAa,OAAO;EACpB,aAAa,OAAO;EACpB,YAAY,OAAO;EACnB,YAAY,OAAO;EACnB,OAAO,OAAO,SAAS,CAAE;CAC1B;AAED,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"middleware.cjs","names":["config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: (ClientTool | ServerTool)[];\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}","middleware: AgentMiddleware<TSchema, TContextSchema, any>"],"sources":["../../src/agents/middleware.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport type {\n AgentMiddleware,\n WrapToolCallHook,\n WrapModelCallHook,\n BeforeAgentHook,\n BeforeModelHook,\n AfterModelHook,\n AfterAgentHook,\n} from \"./middleware/types.js\";\n\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.wrapModelCall - The function to wrap model invocation\n * @param config.wrapToolCall - The function to wrap tool invocation\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @param config.beforeAgent - The function to run before the agent execution starts\n * @param config.afterAgent - The function to run after the agent execution completes\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n */\nexport function createMiddleware<\n TSchema extends InteropZodObject | undefined = undefined,\n TContextSchema extends InteropZodObject | undefined = undefined\n>(config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: (ClientTool | ServerTool)[];\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}): AgentMiddleware<TSchema, TContextSchema, any> {\n const middleware: AgentMiddleware<TSchema, TContextSchema, any> = {\n name: config.name,\n stateSchema: config.stateSchema,\n contextSchema: config.contextSchema,\n wrapToolCall: config.wrapToolCall,\n wrapModelCall: config.wrapModelCall,\n beforeAgent: config.beforeAgent,\n beforeModel: config.beforeModel,\n afterModel: config.afterModel,\n afterAgent: config.afterAgent,\n tools: config.tools ?? [],\n };\n\n return middleware;\n}\n\ntype NormalizeContextSchema<\n TContextSchema extends InteropZodObject | undefined = undefined\n> = TContextSchema extends InteropZodObject\n ? InferInteropZodOutput<TContextSchema>\n : never;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,iBAGdA,QA6JgD;CAChD,MAAMC,aAA4D;EAChE,MAAM,OAAO;EACb,aAAa,OAAO;EACpB,eAAe,OAAO;EACtB,cAAc,OAAO;EACrB,eAAe,OAAO;EACtB,aAAa,OAAO;EACpB,aAAa,OAAO;EACpB,YAAY,OAAO;EACnB,YAAY,OAAO;EACnB,OAAO,OAAO,SAAS,CAAE;CAC1B;AAED,QAAO;AACR"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { ClientTool, ServerTool } from "./tools.cjs";
|
|
2
1
|
import { AfterAgentHook, AfterModelHook, AgentMiddleware, BeforeAgentHook, BeforeModelHook, WrapModelCallHook, WrapToolCallHook } from "./middleware/types.cjs";
|
|
3
|
-
import {
|
|
2
|
+
import { ClientTool, ServerTool } from "@langchain/core/tools";
|
|
3
|
+
import { InferInteropZodOutput, InteropZodObject } from "@langchain/core/utils/types";
|
|
4
4
|
|
|
5
5
|
//#region src/agents/middleware.d.ts
|
|
6
6
|
|
|
@@ -37,7 +37,7 @@ import { InferInteropZodOutput, InteropZodDefault, InteropZodObject, InteropZodO
|
|
|
37
37
|
* });
|
|
38
38
|
* ```
|
|
39
39
|
*/
|
|
40
|
-
declare function createMiddleware<TSchema extends InteropZodObject | undefined = undefined, TContextSchema extends InteropZodObject |
|
|
40
|
+
declare function createMiddleware<TSchema extends InteropZodObject | undefined = undefined, TContextSchema extends InteropZodObject | undefined = undefined>(config: {
|
|
41
41
|
/**
|
|
42
42
|
* The name of the middleware
|
|
43
43
|
*/
|
|
@@ -179,7 +179,7 @@ declare function createMiddleware<TSchema extends InteropZodObject | undefined =
|
|
|
179
179
|
*/
|
|
180
180
|
afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;
|
|
181
181
|
}): AgentMiddleware<TSchema, TContextSchema, any>;
|
|
182
|
-
type NormalizeContextSchema<TContextSchema extends InteropZodObject |
|
|
182
|
+
type NormalizeContextSchema<TContextSchema extends InteropZodObject | undefined = undefined> = TContextSchema extends InteropZodObject ? InferInteropZodOutput<TContextSchema> : never;
|
|
183
183
|
//#endregion
|
|
184
184
|
export { createMiddleware };
|
|
185
185
|
//# sourceMappingURL=middleware.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.d.cts","names":["InteropZodObject","InteropZodDefault","InteropZodOptional","InferInteropZodOutput","ClientTool","ServerTool","AgentMiddleware","WrapToolCallHook","WrapModelCallHook","BeforeAgentHook","BeforeModelHook","AfterModelHook","AfterAgentHook","createMiddleware","TSchema","TContextSchema","NormalizeContextSchema","Partial"],"sources":["../../src/agents/middleware.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { InteropZodObject, InteropZodDefault, InteropZodOptional, InferInteropZodOutput } from \"@langchain/core/utils/types\";\nimport type { ClientTool, ServerTool } from \"./tools.js\";\nimport type { AgentMiddleware, WrapToolCallHook, WrapModelCallHook, BeforeAgentHook, BeforeModelHook, AfterModelHook, AfterAgentHook } from \"./middleware/types.js\";\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.wrapModelCall - The function to wrap model invocation\n * @param config.wrapToolCall - The function to wrap tool invocation\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @param config.beforeAgent - The function to run before the agent execution starts\n * @param config.afterAgent - The function to run after the agent execution completes\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n */\nexport declare function createMiddleware<TSchema extends InteropZodObject | undefined = undefined, TContextSchema extends InteropZodObject | InteropZodOptional<InteropZodObject> | InteropZodDefault<InteropZodObject> | undefined = undefined>(config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: (ClientTool | ServerTool)[];\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}): AgentMiddleware<TSchema, TContextSchema, any>;\ntype NormalizeContextSchema<TContextSchema extends InteropZodObject | InteropZodOptional<InteropZodObject> | InteropZodDefault<InteropZodObject> | undefined = undefined> = TContextSchema extends InteropZodObject ? InferInteropZodOutput<TContextSchema> : TContextSchema extends InteropZodDefault<any> ? InferInteropZodOutput<TContextSchema> : TContextSchema extends InteropZodOptional<any> ? Partial<InferInteropZodOutput<TContextSchema>> : never;\nexport {};\n"],"mappings":";;;;;;;AAqCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4IgCc,iBA5IRD,gBA4IQC,CAAAA,gBA5IyBd,gBA4IzBc,GAAAA,SAAAA,GAAAA,SAAAA,EAAAA,uBA5I0Fd,gBA4I1Fc,GA5I6GZ,kBA4I7GY,CA5IgId,gBA4IhIc,CAAAA,GA5IoJb,iBA4IpJa,CA5IsKd,gBA4ItKc,CAAAA,GAAAA,SAAAA,GAAAA,SAAAA,CAAAA,CAAAA,MAAAA,EAAAA;EAAO;;;EAAR,IACXA,EAAAA,MAAAA;EAAO;;AAAR;AAA+B;;;;EACuD,WAAnCZ,CAAAA,EAlIpDY,OAkIoDZ;EAAkB;;;;;;;EAAoL,aAASD,CAAAA,EA1HjQc,cA0HiQd;EAAiB;;;EAA8D,KAASC,CAAAA,EAAAA,CAtHhWE,UAsHgWF,GAtHnVG,UAsHmVH,CAAAA,EAAAA;EAAkB;;;AAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBArE3XK,iBAAiBO,SAASE,uBAAuBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBA+BhDP,kBAAkBM,SAASE,uBAAuBD;;;;;;;;;gBASpDN,gBAAgBK,SAASE,uBAAuBD;;;;;;;;;gBAShDL,gBAAgBI,SAASE,uBAAuBD;;;;;;;;;eASjDJ,eAAeG,SAASE,uBAAuBD;;;;;;;;;eAS/CH,eAAeE,SAASE,uBAAuBD;IAC5DT,gBAAgBQ,SAASC;KACxBC,8CAA8ChB,mBAAmBE,mBAAmBF,oBAAoBC,kBAAkBD,6CAA6Ce,uBAAuBf,mBAAmBG,sBAAsBY,kBAAkBA,uBAAuBd,yBAAyBE,sBAAsBY,kBAAkBA,uBAAuBb,0BAA0Be,QAAQd,sBAAsBY"}
|
|
1
|
+
{"version":3,"file":"middleware.d.cts","names":["InteropZodObject","InferInteropZodOutput","ClientTool","ServerTool","AgentMiddleware","WrapToolCallHook","WrapModelCallHook","BeforeAgentHook","BeforeModelHook","AfterModelHook","AfterAgentHook","createMiddleware","TSchema","TContextSchema","NormalizeContextSchema"],"sources":["../../src/agents/middleware.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { InteropZodObject, InferInteropZodOutput } from \"@langchain/core/utils/types\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport type { AgentMiddleware, WrapToolCallHook, WrapModelCallHook, BeforeAgentHook, BeforeModelHook, AfterModelHook, AfterAgentHook } from \"./middleware/types.js\";\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.wrapModelCall - The function to wrap model invocation\n * @param config.wrapToolCall - The function to wrap tool invocation\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @param config.beforeAgent - The function to run before the agent execution starts\n * @param config.afterAgent - The function to run after the agent execution completes\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n */\nexport declare function createMiddleware<TSchema extends InteropZodObject | undefined = undefined, TContextSchema extends InteropZodObject | undefined = undefined>(config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: (ClientTool | ServerTool)[];\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}): AgentMiddleware<TSchema, TContextSchema, any>;\ntype NormalizeContextSchema<TContextSchema extends InteropZodObject | undefined = undefined> = TContextSchema extends InteropZodObject ? InferInteropZodOutput<TContextSchema> : never;\nexport {};\n"],"mappings":";;;;;;;AAqCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6IoBY,iBA7IID,gBA6IJC,CAAAA,gBA7IqCZ,gBA6IrCY,GAAAA,SAAAA,GAAAA,SAAAA,EAAAA,uBA7IsGZ,gBA6ItGY,GAAAA,SAAAA,GAAAA,SAAAA,CAAAA,CAAAA,MAAAA,EAAAA;EAAO;;AAAR;EACdE,IAAAA,EAAAA,MAAAA;EAAsB;;;;;;AAAmI;gBAlI5IF;;;;;;;;kBAQEC;;;;WAIPX,aAAaC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiDPE,iBAAiBO,SAASE,uBAAuBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBA+BhDP,kBAAkBM,SAASE,uBAAuBD;;;;;;;;;gBASpDN,gBAAgBK,SAASE,uBAAuBD;;;;;;;;;gBAShDL,gBAAgBI,SAASE,uBAAuBD;;;;;;;;;eASjDJ,eAAeG,SAASE,uBAAuBD;;;;;;;;;eAS/CH,eAAeE,SAASE,uBAAuBD;IAC5DT,gBAAgBQ,SAASC;KACxBC,8CAA8Cd,4CAA4Ca,uBAAuBb,mBAAmBC,sBAAsBY"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { ClientTool, ServerTool } from "./tools.js";
|
|
2
1
|
import { AfterAgentHook, AfterModelHook, AgentMiddleware, BeforeAgentHook, BeforeModelHook, WrapModelCallHook, WrapToolCallHook } from "./middleware/types.js";
|
|
3
|
-
import {
|
|
2
|
+
import { ClientTool, ServerTool } from "@langchain/core/tools";
|
|
3
|
+
import { InferInteropZodOutput, InteropZodObject } from "@langchain/core/utils/types";
|
|
4
4
|
|
|
5
5
|
//#region src/agents/middleware.d.ts
|
|
6
6
|
|
|
@@ -37,7 +37,7 @@ import { InferInteropZodOutput, InteropZodDefault, InteropZodObject, InteropZodO
|
|
|
37
37
|
* });
|
|
38
38
|
* ```
|
|
39
39
|
*/
|
|
40
|
-
declare function createMiddleware<TSchema extends InteropZodObject | undefined = undefined, TContextSchema extends InteropZodObject |
|
|
40
|
+
declare function createMiddleware<TSchema extends InteropZodObject | undefined = undefined, TContextSchema extends InteropZodObject | undefined = undefined>(config: {
|
|
41
41
|
/**
|
|
42
42
|
* The name of the middleware
|
|
43
43
|
*/
|
|
@@ -179,7 +179,7 @@ declare function createMiddleware<TSchema extends InteropZodObject | undefined =
|
|
|
179
179
|
*/
|
|
180
180
|
afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;
|
|
181
181
|
}): AgentMiddleware<TSchema, TContextSchema, any>;
|
|
182
|
-
type NormalizeContextSchema<TContextSchema extends InteropZodObject |
|
|
182
|
+
type NormalizeContextSchema<TContextSchema extends InteropZodObject | undefined = undefined> = TContextSchema extends InteropZodObject ? InferInteropZodOutput<TContextSchema> : never;
|
|
183
183
|
//#endregion
|
|
184
184
|
export { createMiddleware };
|
|
185
185
|
//# sourceMappingURL=middleware.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.d.ts","names":["InteropZodObject","InteropZodDefault","InteropZodOptional","InferInteropZodOutput","ClientTool","ServerTool","AgentMiddleware","WrapToolCallHook","WrapModelCallHook","BeforeAgentHook","BeforeModelHook","AfterModelHook","AfterAgentHook","createMiddleware","TSchema","TContextSchema","NormalizeContextSchema","Partial"],"sources":["../../src/agents/middleware.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { InteropZodObject, InteropZodDefault, InteropZodOptional, InferInteropZodOutput } from \"@langchain/core/utils/types\";\nimport type { ClientTool, ServerTool } from \"./tools.js\";\nimport type { AgentMiddleware, WrapToolCallHook, WrapModelCallHook, BeforeAgentHook, BeforeModelHook, AfterModelHook, AfterAgentHook } from \"./middleware/types.js\";\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.wrapModelCall - The function to wrap model invocation\n * @param config.wrapToolCall - The function to wrap tool invocation\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @param config.beforeAgent - The function to run before the agent execution starts\n * @param config.afterAgent - The function to run after the agent execution completes\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n */\nexport declare function createMiddleware<TSchema extends InteropZodObject | undefined = undefined, TContextSchema extends InteropZodObject | InteropZodOptional<InteropZodObject> | InteropZodDefault<InteropZodObject> | undefined = undefined>(config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: (ClientTool | ServerTool)[];\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}): AgentMiddleware<TSchema, TContextSchema, any>;\ntype NormalizeContextSchema<TContextSchema extends InteropZodObject | InteropZodOptional<InteropZodObject> | InteropZodDefault<InteropZodObject> | undefined = undefined> = TContextSchema extends InteropZodObject ? InferInteropZodOutput<TContextSchema> : TContextSchema extends InteropZodDefault<any> ? InferInteropZodOutput<TContextSchema> : TContextSchema extends InteropZodOptional<any> ? Partial<InferInteropZodOutput<TContextSchema>> : never;\nexport {};\n"],"mappings":";;;;;;;AAqCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4IgCc,iBA5IRD,gBA4IQC,CAAAA,gBA5IyBd,gBA4IzBc,GAAAA,SAAAA,GAAAA,SAAAA,EAAAA,uBA5I0Fd,gBA4I1Fc,GA5I6GZ,kBA4I7GY,CA5IgId,gBA4IhIc,CAAAA,GA5IoJb,iBA4IpJa,CA5IsKd,gBA4ItKc,CAAAA,GAAAA,SAAAA,GAAAA,SAAAA,CAAAA,CAAAA,MAAAA,EAAAA;EAAO;;;EAAR,IACXA,EAAAA,MAAAA;EAAO;;AAAR;AAA+B;;;;EACuD,WAAnCZ,CAAAA,EAlIpDY,OAkIoDZ;EAAkB;;;;;;;EAAoL,aAASD,CAAAA,EA1HjQc,cA0HiQd;EAAiB;;;EAA8D,KAASC,CAAAA,EAAAA,CAtHhWE,UAsHgWF,GAtHnVG,UAsHmVH,CAAAA,EAAAA;EAAkB;;;AAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBArE3XK,iBAAiBO,SAASE,uBAAuBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBA+BhDP,kBAAkBM,SAASE,uBAAuBD;;;;;;;;;gBASpDN,gBAAgBK,SAASE,uBAAuBD;;;;;;;;;gBAShDL,gBAAgBI,SAASE,uBAAuBD;;;;;;;;;eASjDJ,eAAeG,SAASE,uBAAuBD;;;;;;;;;eAS/CH,eAAeE,SAASE,uBAAuBD;IAC5DT,gBAAgBQ,SAASC;KACxBC,8CAA8ChB,mBAAmBE,mBAAmBF,oBAAoBC,kBAAkBD,6CAA6Ce,uBAAuBf,mBAAmBG,sBAAsBY,kBAAkBA,uBAAuBd,yBAAyBE,sBAAsBY,kBAAkBA,uBAAuBb,0BAA0Be,QAAQd,sBAAsBY"}
|
|
1
|
+
{"version":3,"file":"middleware.d.ts","names":["InteropZodObject","InferInteropZodOutput","ClientTool","ServerTool","AgentMiddleware","WrapToolCallHook","WrapModelCallHook","BeforeAgentHook","BeforeModelHook","AfterModelHook","AfterAgentHook","createMiddleware","TSchema","TContextSchema","NormalizeContextSchema"],"sources":["../../src/agents/middleware.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { InteropZodObject, InferInteropZodOutput } from \"@langchain/core/utils/types\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport type { AgentMiddleware, WrapToolCallHook, WrapModelCallHook, BeforeAgentHook, BeforeModelHook, AfterModelHook, AfterAgentHook } from \"./middleware/types.js\";\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.wrapModelCall - The function to wrap model invocation\n * @param config.wrapToolCall - The function to wrap tool invocation\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @param config.beforeAgent - The function to run before the agent execution starts\n * @param config.afterAgent - The function to run after the agent execution completes\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n */\nexport declare function createMiddleware<TSchema extends InteropZodObject | undefined = undefined, TContextSchema extends InteropZodObject | undefined = undefined>(config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: (ClientTool | ServerTool)[];\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}): AgentMiddleware<TSchema, TContextSchema, any>;\ntype NormalizeContextSchema<TContextSchema extends InteropZodObject | undefined = undefined> = TContextSchema extends InteropZodObject ? InferInteropZodOutput<TContextSchema> : never;\nexport {};\n"],"mappings":";;;;;;;AAqCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6IoBY,iBA7IID,gBA6IJC,CAAAA,gBA7IqCZ,gBA6IrCY,GAAAA,SAAAA,GAAAA,SAAAA,EAAAA,uBA7IsGZ,gBA6ItGY,GAAAA,SAAAA,GAAAA,SAAAA,CAAAA,CAAAA,MAAAA,EAAAA;EAAO;;AAAR;EACdE,IAAAA,EAAAA,MAAAA;EAAsB;;;;;;AAAmI;gBAlI5IF;;;;;;;;kBAQEC;;;;WAIPX,aAAaC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiDPE,iBAAiBO,SAASE,uBAAuBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBA+BhDP,kBAAkBM,SAASE,uBAAuBD;;;;;;;;;gBASpDN,gBAAgBK,SAASE,uBAAuBD;;;;;;;;;gBAShDL,gBAAgBI,SAASE,uBAAuBD;;;;;;;;;eASjDJ,eAAeG,SAASE,uBAAuBD;;;;;;;;;eAS/CH,eAAeE,SAASE,uBAAuBD;IAC5DT,gBAAgBQ,SAASC;KACxBC,8CAA8Cd,4CAA4Ca,uBAAuBb,mBAAmBC,sBAAsBY"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.js","names":["config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: (ClientTool | ServerTool)[];\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}","middleware: AgentMiddleware<TSchema, TContextSchema, any>"],"sources":["../../src/agents/middleware.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodDefault,\n InteropZodOptional,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\n\nimport type { ClientTool, ServerTool } from \"./tools.js\";\nimport type {\n AgentMiddleware,\n WrapToolCallHook,\n WrapModelCallHook,\n BeforeAgentHook,\n BeforeModelHook,\n AfterModelHook,\n AfterAgentHook,\n} from \"./middleware/types.js\";\n\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.wrapModelCall - The function to wrap model invocation\n * @param config.wrapToolCall - The function to wrap tool invocation\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @param config.beforeAgent - The function to run before the agent execution starts\n * @param config.afterAgent - The function to run after the agent execution completes\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n */\nexport function createMiddleware<\n TSchema extends InteropZodObject | undefined = undefined,\n TContextSchema extends\n | InteropZodObject\n | InteropZodOptional<InteropZodObject>\n | InteropZodDefault<InteropZodObject>\n | undefined = undefined\n>(config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: (ClientTool | ServerTool)[];\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}): AgentMiddleware<TSchema, TContextSchema, any> {\n const middleware: AgentMiddleware<TSchema, TContextSchema, any> = {\n name: config.name,\n stateSchema: config.stateSchema,\n contextSchema: config.contextSchema,\n wrapToolCall: config.wrapToolCall,\n wrapModelCall: config.wrapModelCall,\n beforeAgent: config.beforeAgent,\n beforeModel: config.beforeModel,\n afterModel: config.afterModel,\n afterAgent: config.afterAgent,\n tools: config.tools ?? [],\n };\n\n return middleware;\n}\n\ntype NormalizeContextSchema<\n TContextSchema extends\n | InteropZodObject\n | InteropZodOptional<InteropZodObject>\n | InteropZodDefault<InteropZodObject>\n | undefined = undefined\n> = TContextSchema extends InteropZodObject\n ? InferInteropZodOutput<TContextSchema>\n : TContextSchema extends InteropZodDefault<any>\n ? InferInteropZodOutput<TContextSchema>\n : TContextSchema extends InteropZodOptional<any>\n ? Partial<InferInteropZodOutput<TContextSchema>>\n : never;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAgB,iBAOdA,QA6JgD;CAChD,MAAMC,aAA4D;EAChE,MAAM,OAAO;EACb,aAAa,OAAO;EACpB,eAAe,OAAO;EACtB,cAAc,OAAO;EACrB,eAAe,OAAO;EACtB,aAAa,OAAO;EACpB,aAAa,OAAO;EACpB,YAAY,OAAO;EACnB,YAAY,OAAO;EACnB,OAAO,OAAO,SAAS,CAAE;CAC1B;AAED,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"middleware.js","names":["config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: (ClientTool | ServerTool)[];\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}","middleware: AgentMiddleware<TSchema, TContextSchema, any>"],"sources":["../../src/agents/middleware.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport type {\n AgentMiddleware,\n WrapToolCallHook,\n WrapModelCallHook,\n BeforeAgentHook,\n BeforeModelHook,\n AfterModelHook,\n AfterAgentHook,\n} from \"./middleware/types.js\";\n\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.wrapModelCall - The function to wrap model invocation\n * @param config.wrapToolCall - The function to wrap tool invocation\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @param config.beforeAgent - The function to run before the agent execution starts\n * @param config.afterAgent - The function to run after the agent execution completes\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n */\nexport function createMiddleware<\n TSchema extends InteropZodObject | undefined = undefined,\n TContextSchema extends InteropZodObject | undefined = undefined\n>(config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: (ClientTool | ServerTool)[];\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}): AgentMiddleware<TSchema, TContextSchema, any> {\n const middleware: AgentMiddleware<TSchema, TContextSchema, any> = {\n name: config.name,\n stateSchema: config.stateSchema,\n contextSchema: config.contextSchema,\n wrapToolCall: config.wrapToolCall,\n wrapModelCall: config.wrapModelCall,\n beforeAgent: config.beforeAgent,\n beforeModel: config.beforeModel,\n afterModel: config.afterModel,\n afterAgent: config.afterAgent,\n tools: config.tools ?? [],\n };\n\n return middleware;\n}\n\ntype NormalizeContextSchema<\n TContextSchema extends InteropZodObject | undefined = undefined\n> = TContextSchema extends InteropZodObject\n ? InferInteropZodOutput<TContextSchema>\n : never;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,iBAGdA,QA6JgD;CAChD,MAAMC,aAA4D;EAChE,MAAM,OAAO;EACb,aAAa,OAAO;EACpB,eAAe,OAAO;EACtB,cAAc,OAAO;EACrB,eAAe,OAAO;EACtB,aAAa,OAAO;EACpB,aAAa,OAAO;EACpB,YAAY,OAAO;EACnB,YAAY,OAAO;EACnB,OAAO,OAAO,SAAS,CAAE;CAC1B;AAED,QAAO;AACR"}
|
|
@@ -8,13 +8,11 @@ const require_withAgentName = require('../withAgentName.cjs');
|
|
|
8
8
|
const require_responses = require('../responses.cjs');
|
|
9
9
|
const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
|
|
10
10
|
const __langchain_langgraph = require_rolldown_runtime.__toESM(require("@langchain/langgraph"));
|
|
11
|
-
const zod_v3 = require_rolldown_runtime.__toESM(require("zod/v3"));
|
|
12
11
|
const __langchain_core_utils_types = require_rolldown_runtime.__toESM(require("@langchain/core/utils/types"));
|
|
13
12
|
|
|
14
13
|
//#region src/agents/nodes/AgentNode.ts
|
|
15
14
|
var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
16
15
|
#options;
|
|
17
|
-
#runState = { runModelCallCount: 0 };
|
|
18
16
|
constructor(options) {
|
|
19
17
|
super({
|
|
20
18
|
name: options.name ?? "model",
|
|
@@ -66,24 +64,14 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
66
64
|
/**
|
|
67
65
|
* return directly without invoking the model again
|
|
68
66
|
*/
|
|
69
|
-
return {
|
|
70
|
-
messages: [],
|
|
71
|
-
_privateState: this.getState()._privateState
|
|
72
|
-
};
|
|
73
|
-
const privateState = this.getState()._privateState;
|
|
67
|
+
return { messages: [] };
|
|
74
68
|
const response = await this.#invokeModel(state, config);
|
|
75
|
-
this.#runState.runModelCallCount++;
|
|
76
|
-
const _privateState = {
|
|
77
|
-
...privateState,
|
|
78
|
-
threadLevelCallCount: privateState.threadLevelCallCount + 1
|
|
79
|
-
};
|
|
80
69
|
/**
|
|
81
70
|
* if we were able to generate a structured response, return it
|
|
82
71
|
*/
|
|
83
72
|
if ("structuredResponse" in response) return {
|
|
84
73
|
messages: [...state.messages, ...response.messages || []],
|
|
85
|
-
structuredResponse: response.structuredResponse
|
|
86
|
-
_privateState
|
|
74
|
+
structuredResponse: response.structuredResponse
|
|
87
75
|
};
|
|
88
76
|
/**
|
|
89
77
|
* if we need to direct the agent to the model, return the update
|
|
@@ -91,18 +79,12 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
91
79
|
if (response instanceof __langchain_langgraph.Command) return response;
|
|
92
80
|
response.name = this.name;
|
|
93
81
|
response.lc_kwargs.name = this.name;
|
|
94
|
-
if (this.#areMoreStepsNeeded(state, response)) return {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
_privateState
|
|
101
|
-
};
|
|
102
|
-
return {
|
|
103
|
-
messages: [response],
|
|
104
|
-
_privateState
|
|
105
|
-
};
|
|
82
|
+
if (this.#areMoreStepsNeeded(state, response)) return { messages: [new __langchain_core_messages.AIMessage({
|
|
83
|
+
content: "Sorry, need more steps to process this request.",
|
|
84
|
+
name: this.name,
|
|
85
|
+
id: response.id
|
|
86
|
+
})] };
|
|
87
|
+
return { messages: [response] };
|
|
106
88
|
}
|
|
107
89
|
/**
|
|
108
90
|
* Derive the model from the options.
|
|
@@ -185,9 +167,7 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
185
167
|
/**
|
|
186
168
|
* Create runtime
|
|
187
169
|
*/
|
|
188
|
-
const privateState = this.getState()._privateState;
|
|
189
170
|
const runtime = Object.freeze({
|
|
190
|
-
...privateState,
|
|
191
171
|
context,
|
|
192
172
|
writer: lgConfig.writer,
|
|
193
173
|
interrupt: lgConfig.interrupt,
|
|
@@ -199,6 +179,7 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
199
179
|
const requestWithStateAndRuntime = {
|
|
200
180
|
...request,
|
|
201
181
|
state: {
|
|
182
|
+
...middleware.stateSchema ? (0, __langchain_core_utils_types.interopParse)((0, __langchain_core_utils_types.interopZodObjectPartial)(middleware.stateSchema), state) : {},
|
|
202
183
|
...currentGetState(),
|
|
203
184
|
messages: state.messages
|
|
204
185
|
},
|
|
@@ -246,9 +227,8 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
246
227
|
systemPrompt: this.#options.systemPrompt,
|
|
247
228
|
messages: state.messages,
|
|
248
229
|
tools: this.#options.toolClasses,
|
|
249
|
-
state
|
|
230
|
+
state,
|
|
250
231
|
runtime: Object.freeze({
|
|
251
|
-
...this.getState()._privateState,
|
|
252
232
|
context: lgConfig?.context,
|
|
253
233
|
writer: lgConfig.writer,
|
|
254
234
|
interrupt: lgConfig.interrupt,
|
|
@@ -278,7 +258,15 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
278
258
|
const structuredResponse = tool.parse(toolCall.args);
|
|
279
259
|
return {
|
|
280
260
|
structuredResponse,
|
|
281
|
-
messages: [
|
|
261
|
+
messages: [
|
|
262
|
+
response,
|
|
263
|
+
new __langchain_core_messages.ToolMessage({
|
|
264
|
+
tool_call_id: toolCall.id ?? "",
|
|
265
|
+
content: JSON.stringify(structuredResponse),
|
|
266
|
+
name: toolCall.name
|
|
267
|
+
}),
|
|
268
|
+
new __langchain_core_messages.AIMessage(lastMessage ?? `Returning structured response: ${JSON.stringify(structuredResponse)}`)
|
|
269
|
+
]
|
|
282
270
|
};
|
|
283
271
|
} catch (error) {
|
|
284
272
|
return this.#handleToolStrategyError(error, response, toolCall, responseFormat);
|
|
@@ -402,26 +390,12 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
402
390
|
const modelRunnable = require_utils.getPromptRunnable(preparedOptions?.systemPrompt ?? this.#options.systemPrompt).pipe(this.#options.includeAgentName === "inline" ? require_withAgentName.withAgentName(modelWithTools, this.#options.includeAgentName) : modelWithTools);
|
|
403
391
|
return modelRunnable;
|
|
404
392
|
}
|
|
405
|
-
static get nodeOptions() {
|
|
406
|
-
return { input: zod_v3.z.object({
|
|
407
|
-
messages: zod_v3.z.array(zod_v3.z.custom()),
|
|
408
|
-
_privateState: zod_v3.z.object({ threadLevelCallCount: zod_v3.z.number() })
|
|
409
|
-
}) };
|
|
410
|
-
}
|
|
411
393
|
getState() {
|
|
412
394
|
const state = super.getState();
|
|
413
|
-
const origState = state && !(state instanceof __langchain_langgraph.Command) ? state : {
|
|
414
|
-
threadLevelCallCount: 0,
|
|
415
|
-
runModelCallCount: 0
|
|
416
|
-
} };
|
|
395
|
+
const origState = state && !(state instanceof __langchain_langgraph.Command) ? state : {};
|
|
417
396
|
return {
|
|
418
397
|
messages: [],
|
|
419
|
-
...origState
|
|
420
|
-
_privateState: {
|
|
421
|
-
threadLevelCallCount: 0,
|
|
422
|
-
...origState._privateState ?? {},
|
|
423
|
-
...this.#runState
|
|
424
|
-
}
|
|
398
|
+
...origState
|
|
425
399
|
};
|
|
426
400
|
}
|
|
427
401
|
};
|