langchain 1.2.6 → 1.2.7
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 +11 -0
- package/dist/agents/ReactAgent.cjs +28 -0
- package/dist/agents/ReactAgent.cjs.map +1 -1
- package/dist/agents/ReactAgent.d.cts +50 -14
- package/dist/agents/ReactAgent.d.cts.map +1 -1
- package/dist/agents/ReactAgent.d.ts +50 -14
- package/dist/agents/ReactAgent.d.ts.map +1 -1
- package/dist/agents/ReactAgent.js +28 -0
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/index.cjs.map +1 -1
- package/dist/agents/index.d.cts +41 -29
- package/dist/agents/index.d.cts.map +1 -1
- package/dist/agents/index.d.ts +41 -29
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/middleware/contextEditing.d.cts +2 -1
- package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
- package/dist/agents/middleware/contextEditing.d.ts +2 -1
- package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.cts +2 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.ts +2 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
- package/dist/agents/middleware/hitl.d.cts +9 -1
- package/dist/agents/middleware/hitl.d.cts.map +1 -1
- package/dist/agents/middleware/hitl.d.ts +9 -1
- package/dist/agents/middleware/hitl.d.ts.map +1 -1
- package/dist/agents/middleware/llmToolSelector.d.cts +4 -4
- package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
- package/dist/agents/middleware/llmToolSelector.d.ts +4 -4
- package/dist/agents/middleware/llmToolSelector.d.ts.map +1 -1
- package/dist/agents/middleware/modelCallLimit.d.cts +6 -1
- package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -1
- package/dist/agents/middleware/modelCallLimit.d.ts +6 -1
- package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts +7 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts.map +1 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts +7 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts.map +1 -1
- package/dist/agents/middleware/summarization.d.cts +30 -7
- package/dist/agents/middleware/summarization.d.cts.map +1 -1
- package/dist/agents/middleware/summarization.d.ts +30 -7
- package/dist/agents/middleware/summarization.d.ts.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.cjs +42 -2
- package/dist/agents/middleware/todoListMiddleware.cjs.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.cts +45 -2
- package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.ts +45 -2
- package/dist/agents/middleware/todoListMiddleware.d.ts.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.js +43 -3
- package/dist/agents/middleware/todoListMiddleware.js.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.cts +2 -1
- package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.ts +2 -1
- package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
- package/dist/agents/middleware/types.cjs.map +1 -1
- package/dist/agents/middleware/types.d.cts +125 -32
- package/dist/agents/middleware/types.d.cts.map +1 -1
- package/dist/agents/middleware/types.d.ts +125 -32
- package/dist/agents/middleware/types.d.ts.map +1 -1
- package/dist/agents/middleware/types.js.map +1 -1
- package/dist/agents/middleware.cjs +1 -1
- package/dist/agents/middleware.cjs.map +1 -1
- package/dist/agents/middleware.d.cts +4 -4
- package/dist/agents/middleware.d.cts.map +1 -1
- package/dist/agents/middleware.d.ts +4 -4
- package/dist/agents/middleware.d.ts.map +1 -1
- package/dist/agents/middleware.js +1 -1
- package/dist/agents/middleware.js.map +1 -1
- package/dist/agents/responses.d.cts.map +1 -1
- package/dist/agents/types.d.cts +254 -8
- package/dist/agents/types.d.cts.map +1 -1
- package/dist/agents/types.d.ts +254 -8
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/load/import_constants.cjs +5 -5
- package/dist/load/import_constants.cjs.map +1 -1
- package/dist/load/import_constants.js +5 -5
- package/dist/load/import_constants.js.map +1 -1
- package/package.json +6 -6
|
@@ -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 InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport {\n MIDDLEWARE_BRAND,\n type AgentMiddleware,\n type WrapToolCallHook,\n type WrapModelCallHook,\n type BeforeAgentHook,\n type BeforeModelHook,\n type AfterModelHook,\n type 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 [MIDDLEWARE_BRAND]: true as const,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAgB,iBAGdA,QA6JgD;CAChD,MAAMC,aAA4D;GAC/D,mBAAmB;EACpB,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?: TTools;\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<\n TSchema,\n TContextSchema,\n NormalizeContextSchema<TContextSchema>,\n TTools\n >"],"sources":["../../src/agents/middleware.ts"],"sourcesContent":["import type {\n InteropZodObject,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport {\n MIDDLEWARE_BRAND,\n type AgentMiddleware,\n type WrapToolCallHook,\n type WrapModelCallHook,\n type BeforeAgentHook,\n type BeforeModelHook,\n type AfterModelHook,\n type 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 const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\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?: TTools;\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<\n TSchema,\n TContextSchema,\n NormalizeContextSchema<TContextSchema>,\n TTools\n> {\n const middleware: AgentMiddleware<\n TSchema,\n TContextSchema,\n NormalizeContextSchema<TContextSchema>,\n TTools\n > = {\n [MIDDLEWARE_BRAND]: true as const,\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 : unknown;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,iBAOdA,QAkKA;CACA,MAAMC,aAKF;GACD,mBAAmB;EACpB,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;CACf;AAED,QAAO;AACR"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"responses.d.cts","names":["InteropZodObject","InteropZodType","AIMessage","LanguageModelLike","FunctionDefinition","StructuredOutputParsingError","MultipleStructuredOutputsError","ResponseFormatUndefined","ToolStrategy","S","_T","Record","ToolStrategyOptions","U","ProviderStrategy","T","ResponseFormat","transformResponseFormat","JsonSchemaFormat","TypedToolStrategy","Array","ToolStrategyError","Promise","toolStrategy","K","providerStrategy","hasSupportForJsonSchemaOutput"],"sources":["../../src/agents/responses.d.ts"],"sourcesContent":["import { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\nimport { StructuredOutputParsingError, MultipleStructuredOutputsError } from \"./errors.js\";\n/**\n * Special type to indicate that no response format is provided.\n * When this type is used, the structuredResponse property should not be present in the result.\n */\nexport type ResponseFormatUndefined = {\n __responseFormatUndefined: true;\n};\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport declare class ToolStrategy<_T = unknown> {\n readonly schema: Record<string, unknown>;\n readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n };\n readonly options?: ToolStrategyOptions | undefined;\n private constructor();\n get name(): string;\n static fromSchema<S extends InteropZodObject>(schema: S, outputOptions?: ToolStrategyOptions): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n static fromSchema(schema: Record<string, unknown>, outputOptions?: ToolStrategyOptions): ToolStrategy<Record<string, unknown>>;\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown>;\n}\nexport declare class ProviderStrategy<T = unknown> {\n private _schemaType?;\n /**\n * The schema to use for the provider strategy\n */\n readonly schema: Record<string, unknown>;\n /**\n * Whether to use strict mode for the provider strategy\n */\n readonly strict: boolean;\n private constructor();\n private constructor();\n static fromSchema<T>(schema: InteropZodType<T>, strict?: boolean): ProviderStrategy<T>;\n static fromSchema(schema: Record<string, unknown>, strict?: boolean): ProviderStrategy<Record<string, unknown>>;\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param response - The AI message response to parse\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage): any;\n}\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n/**\n * Handle user input for `responseFormat` parameter of `CreateAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat - The response format to transform, provided by the user\n * @param options - The response format options for tool strategy\n * @param model - The model to check if it supports JSON schema output\n * @returns\n */\nexport declare function transformResponseFormat(responseFormat?: InteropZodType<any> | InteropZodType<any>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | ToolStrategy<any>[] | ResponseFormatUndefined, options?: ToolStrategyOptions, model?: LanguageModelLike | string): ResponseFormat[];\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown> extends Array<ToolStrategy<any>> {\n _schemaType?: T;\n}\nexport type ToolStrategyError = StructuredOutputParsingError | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Allows you to customize the message that appears in the conversation history when structured\n * output is generated.\n */\n toolMessageContent?: string;\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n *\n * @default true\n */\n handleError?: boolean | string | ((error: ToolStrategyError) => Promise<string> | string);\n}\nexport declare function toolStrategy<T extends InteropZodType<any>>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function toolStrategy<T extends readonly InteropZodType<any>[]>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<{\n [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never;\n}[number]>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat, options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat[], options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\n/**\n * Creates a provider strategy for structured output using native JSON schema support.\n *\n * This function is used to configure structured output for agents when the underlying model\n * supports native JSON schema output (e.g., OpenAI's `gpt-4o`, `gpt-4o-mini`, and newer models).\n * Unlike `toolStrategy`, which uses function calling to extract structured output, `providerStrategy`\n * leverages the provider's native structured output capabilities, resulting in more efficient\n * and reliable schema enforcement.\n *\n * When used with a model that supports JSON schema output, the model will return responses\n * that directly conform to the provided schema without requiring tool calls. This is the\n * recommended approach for structured output when your model supports it.\n *\n * @param responseFormat - The schema to enforce, either a Zod schema, a JSON schema object, or an options object with `schema` and optional `strict` flag\n * @returns A `ProviderStrategy` instance that can be used as the `responseFormat` in `createAgent`\n *\n * @example\n * ```ts\n * import { providerStrategy, createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy(\n * z.object({\n * answer: z.string().describe(\"The answer to the question\"),\n * confidence: z.number().min(0).max(1),\n * })\n * ),\n * });\n * ```\n *\n * @example\n * ```ts\n * // Using strict mode for stricter schema enforcement\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy({\n * schema: z.object({\n * name: z.string(),\n * age: z.number(),\n * }),\n * strict: true\n * }),\n * });\n * ```\n */\nexport declare function providerStrategy<T extends InteropZodType<unknown>>(responseFormat: T | {\n schema: T;\n strict?: boolean;\n}): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function providerStrategy(responseFormat: JsonSchemaFormat | {\n schema: JsonSchemaFormat;\n strict?: boolean;\n}): ProviderStrategy<Record<string, unknown>>;\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type: \"null\" | \"boolean\" | \"object\" | \"array\" | \"number\" | \"string\" | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n __brand?: never;\n};\n/**\n * Identifies the models that support JSON schema output\n * @param model - The model to check\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport declare function hasSupportForJsonSchemaOutput(model?: LanguageModelLike | string): boolean;\n//# sourceMappingURL=responses.d.ts.map"],"mappings":";;;;;;;;AASA;AASA;;AAIkBI,KAbNG,uBAAAA,GAaMH;EAEKQ,yBAAAA,EAAAA,IAAAA;CAGSZ;;;;;;;AACFW,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,WAAWvB,0BAA0BY;iBAEnCU,YAAAA,iBAA6BL,4BAA4BN,sBAAsBO,kBAAkBR;iBACjGY,YAAAA,iBAA6BL,8BAA8BN,sBAAsBO,kBAAkBR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgDnGc,2BAA2BxB,yCAAyCc;UAChFA;;IAERD,iBAAiBC,UAAUd,0BAA0BY;iBACjCY,gBAAAA,iBAAiCP;UAC7CA;;IAERJ,iBAAiBH;;;;;KAKTO,gBAAAA;;eAEKP"}
|
|
1
|
+
{"version":3,"file":"responses.d.cts","names":["InteropZodObject","InteropZodType","AIMessage","LanguageModelLike","FunctionDefinition","StructuredOutputParsingError","MultipleStructuredOutputsError","ResponseFormatUndefined","ToolStrategy","S","_T","Record","ToolStrategyOptions","U","ProviderStrategy","T","ResponseFormat","transformResponseFormat","JsonSchemaFormat","TypedToolStrategy","Array","ToolStrategyError","Promise","toolStrategy","K","providerStrategy","hasSupportForJsonSchemaOutput"],"sources":["../../src/agents/responses.d.ts"],"sourcesContent":["import { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\nimport { StructuredOutputParsingError, MultipleStructuredOutputsError } from \"./errors.js\";\n/**\n * Special type to indicate that no response format is provided.\n * When this type is used, the structuredResponse property should not be present in the result.\n */\nexport type ResponseFormatUndefined = {\n __responseFormatUndefined: true;\n};\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport declare class ToolStrategy<_T = unknown> {\n readonly schema: Record<string, unknown>;\n readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n };\n readonly options?: ToolStrategyOptions | undefined;\n private constructor();\n get name(): string;\n static fromSchema<S extends InteropZodObject>(schema: S, outputOptions?: ToolStrategyOptions): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n static fromSchema(schema: Record<string, unknown>, outputOptions?: ToolStrategyOptions): ToolStrategy<Record<string, unknown>>;\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown>;\n}\nexport declare class ProviderStrategy<T = unknown> {\n private _schemaType?;\n /**\n * The schema to use for the provider strategy\n */\n readonly schema: Record<string, unknown>;\n /**\n * Whether to use strict mode for the provider strategy\n */\n readonly strict: boolean;\n private constructor();\n private constructor();\n static fromSchema<T>(schema: InteropZodType<T>, strict?: boolean): ProviderStrategy<T>;\n static fromSchema(schema: Record<string, unknown>, strict?: boolean): ProviderStrategy<Record<string, unknown>>;\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param response - The AI message response to parse\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage): any;\n}\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n/**\n * Handle user input for `responseFormat` parameter of `CreateAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat - The response format to transform, provided by the user\n * @param options - The response format options for tool strategy\n * @param model - The model to check if it supports JSON schema output\n * @returns\n */\nexport declare function transformResponseFormat(responseFormat?: InteropZodType<any> | InteropZodType<any>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | ToolStrategy<any>[] | ResponseFormatUndefined, options?: ToolStrategyOptions, model?: LanguageModelLike | string): ResponseFormat[];\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown> extends Array<ToolStrategy<any>> {\n _schemaType?: T;\n}\nexport type ToolStrategyError = StructuredOutputParsingError | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Allows you to customize the message that appears in the conversation history when structured\n * output is generated.\n */\n toolMessageContent?: string;\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n *\n * @default true\n */\n handleError?: boolean | string | ((error: ToolStrategyError) => Promise<string> | string);\n}\nexport declare function toolStrategy<T extends InteropZodType<any>>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function toolStrategy<T extends readonly InteropZodType<any>[]>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<{\n [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never;\n}[number]>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat, options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat[], options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\n/**\n * Creates a provider strategy for structured output using native JSON schema support.\n *\n * This function is used to configure structured output for agents when the underlying model\n * supports native JSON schema output (e.g., OpenAI's `gpt-4o`, `gpt-4o-mini`, and newer models).\n * Unlike `toolStrategy`, which uses function calling to extract structured output, `providerStrategy`\n * leverages the provider's native structured output capabilities, resulting in more efficient\n * and reliable schema enforcement.\n *\n * When used with a model that supports JSON schema output, the model will return responses\n * that directly conform to the provided schema without requiring tool calls. This is the\n * recommended approach for structured output when your model supports it.\n *\n * @param responseFormat - The schema to enforce, either a Zod schema, a JSON schema object, or an options object with `schema` and optional `strict` flag\n * @returns A `ProviderStrategy` instance that can be used as the `responseFormat` in `createAgent`\n *\n * @example\n * ```ts\n * import { providerStrategy, createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy(\n * z.object({\n * answer: z.string().describe(\"The answer to the question\"),\n * confidence: z.number().min(0).max(1),\n * })\n * ),\n * });\n * ```\n *\n * @example\n * ```ts\n * // Using strict mode for stricter schema enforcement\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy({\n * schema: z.object({\n * name: z.string(),\n * age: z.number(),\n * }),\n * strict: true\n * }),\n * });\n * ```\n */\nexport declare function providerStrategy<T extends InteropZodType<unknown>>(responseFormat: T | {\n schema: T;\n strict?: boolean;\n}): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function providerStrategy(responseFormat: JsonSchemaFormat | {\n schema: JsonSchemaFormat;\n strict?: boolean;\n}): ProviderStrategy<Record<string, unknown>>;\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type: \"null\" | \"boolean\" | \"object\" | \"array\" | \"number\" | \"string\" | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n __brand?: never;\n};\n/**\n * Identifies the models that support JSON schema output\n * @param model - The model to check\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport declare function hasSupportForJsonSchemaOutput(model?: LanguageModelLike | string): boolean;\n//# sourceMappingURL=responses.d.ts.map"],"mappings":";;;;;;;;AASA;AASA;;AAIkBI,KAbNG,uBAAAA,GAaMH;EAEKQ,yBAAAA,EAAAA,IAAAA;CAGSZ;;;;;;;AACFW,cAVTH,YAUSG,CAAAA,KAAAA,OAAAA,CAAAA,CAAAA;EAAyCC,SAAAA,MAAAA,EATlDD,MASkDC,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;EAAmCD,S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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgDnGc,2BAA2BxB,yCAAyCc;UAChFA;;IAERD,iBAAiBC,UAAUd,0BAA0BY;iBACjCY,gBAAAA,iBAAiCP;UAC7CA;;IAERJ,iBAAiBH;;;;;KAKTO,gBAAAA;;eAEKP"}
|
package/dist/agents/types.d.cts
CHANGED
|
@@ -1,15 +1,261 @@
|
|
|
1
1
|
import { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy, TypedToolStrategy } from "./responses.cjs";
|
|
2
2
|
import { JumpToTarget } from "./constants.cjs";
|
|
3
|
-
import { AgentMiddleware, AnyAnnotationRoot, InferSchemaInput } from "./middleware/types.cjs";
|
|
3
|
+
import { AgentMiddleware, AnyAnnotationRoot, InferMiddlewareContexts, InferMiddlewareStates, InferSchemaInput } from "./middleware/types.cjs";
|
|
4
4
|
import { LanguageModelLike } from "@langchain/core/language_models/base";
|
|
5
|
-
import { BaseMessage, SystemMessage } from "@langchain/core/messages";
|
|
6
|
-
import { ClientTool, ServerTool } from "@langchain/core/tools";
|
|
5
|
+
import { BaseMessage, MessageStructure, MessageToolDefinition, SystemMessage } from "@langchain/core/messages";
|
|
6
|
+
import { ClientTool, DynamicStructuredTool, ServerTool, StructuredToolInterface } from "@langchain/core/tools";
|
|
7
7
|
import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
|
|
8
8
|
import { END, START, StateGraph } from "@langchain/langgraph";
|
|
9
9
|
import { BaseCheckpointSaver, BaseStore } from "@langchain/langgraph-checkpoint";
|
|
10
10
|
import { Messages } from "@langchain/langgraph/";
|
|
11
11
|
|
|
12
12
|
//#region src/agents/types.d.ts
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Type bag that encapsulates all agent type parameters.
|
|
16
|
+
*
|
|
17
|
+
* This interface bundles all the generic type parameters used throughout the agent system
|
|
18
|
+
* into a single configuration object. This pattern simplifies type signatures and makes
|
|
19
|
+
* it easier to add new type parameters without changing multiple function signatures.
|
|
20
|
+
*
|
|
21
|
+
* @typeParam TResponse - The structured response type when using `responseFormat`.
|
|
22
|
+
* Defaults to `Record<string, any>`. Set to `ResponseFormatUndefined` when no
|
|
23
|
+
* response format is configured.
|
|
24
|
+
*
|
|
25
|
+
* @typeParam TState - The custom state schema type. Can be an `AnnotationRoot`,
|
|
26
|
+
* `InteropZodObject`, or `undefined`. The state persists across agent invocations
|
|
27
|
+
* when using a checkpointer.
|
|
28
|
+
*
|
|
29
|
+
* @typeParam TContext - The context schema type. Context is read-only and not
|
|
30
|
+
* persisted between invocations. Defaults to `AnyAnnotationRoot`.
|
|
31
|
+
*
|
|
32
|
+
* @typeParam TMiddleware - The middleware array type. Must be a readonly array
|
|
33
|
+
* of `AgentMiddleware` instances.
|
|
34
|
+
*
|
|
35
|
+
* @typeParam TTools - The combined tools type from both `createAgent` tools parameter
|
|
36
|
+
* and middleware tools. This is a readonly array of `ClientTool | ServerTool`.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```typescript
|
|
40
|
+
* // Define a type configuration
|
|
41
|
+
* type MyAgentTypes = AgentTypeConfig<
|
|
42
|
+
* { name: string; email: string }, // Response type
|
|
43
|
+
* typeof MyStateSchema, // State schema
|
|
44
|
+
* typeof MyContextSchema, // Context schema
|
|
45
|
+
* typeof myMiddleware, // Middleware array
|
|
46
|
+
* typeof myTools // Tools array
|
|
47
|
+
* >;
|
|
48
|
+
*
|
|
49
|
+
* // Use with ReactAgent
|
|
50
|
+
* const agent: ReactAgent<MyAgentTypes> = createAgent({ ... });
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
interface AgentTypeConfig<TResponse extends Record<string, any> | ResponseFormatUndefined = Record<string, any> | ResponseFormatUndefined, TState extends AnyAnnotationRoot | InteropZodObject | undefined = AnyAnnotationRoot | InteropZodObject | undefined, TContext extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot | InteropZodObject, TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[], TTools$1 extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {
|
|
54
|
+
/** The structured response type when using `responseFormat` */
|
|
55
|
+
Response: TResponse;
|
|
56
|
+
/** The custom state schema type */
|
|
57
|
+
State: TState;
|
|
58
|
+
/** The context schema type */
|
|
59
|
+
Context: TContext;
|
|
60
|
+
/** The middleware array type */
|
|
61
|
+
Middleware: TMiddleware;
|
|
62
|
+
/** The combined tools type from agent and middleware */
|
|
63
|
+
Tools: TTools$1;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Default type configuration for agents.
|
|
67
|
+
* Used when no explicit type parameters are provided.
|
|
68
|
+
*/
|
|
69
|
+
interface DefaultAgentTypeConfig extends AgentTypeConfig {
|
|
70
|
+
Response: Record<string, any>;
|
|
71
|
+
State: undefined;
|
|
72
|
+
Context: AnyAnnotationRoot;
|
|
73
|
+
Middleware: readonly AgentMiddleware[];
|
|
74
|
+
Tools: readonly (ClientTool | ServerTool)[];
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Helper type to infer tools from a single middleware instance.
|
|
78
|
+
* Extracts the TTools type parameter from AgentMiddleware.
|
|
79
|
+
*/
|
|
80
|
+
type InferMiddlewareTools<T extends AgentMiddleware> = T extends AgentMiddleware<any, any, any, infer TTools> ? TTools extends readonly (ClientTool | ServerTool)[] ? TTools : readonly [] : readonly [];
|
|
81
|
+
/**
|
|
82
|
+
* Helper type to infer and merge tools from an array of middleware.
|
|
83
|
+
* Recursively extracts tools from each middleware and combines them into a single tuple.
|
|
84
|
+
*/
|
|
85
|
+
type InferMiddlewareToolsArray<T extends readonly AgentMiddleware[]> = T extends readonly [] ? readonly [] : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? readonly [...InferMiddlewareTools<First>, ...InferMiddlewareToolsArray<Rest>] : InferMiddlewareTools<First> : readonly [] : readonly [];
|
|
86
|
+
/**
|
|
87
|
+
* Helper type to combine agent tools with middleware tools into a single readonly array.
|
|
88
|
+
*/
|
|
89
|
+
type CombineTools<TAgentTools extends readonly (ClientTool | ServerTool)[], TMiddleware extends readonly AgentMiddleware[]> = readonly [...TAgentTools, ...InferMiddlewareToolsArray<TMiddleware>];
|
|
90
|
+
/**
|
|
91
|
+
* Helper type to extract the tool name, input type, and output type from a tool.
|
|
92
|
+
* Converts a single tool to a MessageToolDefinition entry.
|
|
93
|
+
*/
|
|
94
|
+
type ExtractToolDefinition<T> = T extends DynamicStructuredTool<infer _SchemaT, infer _SchemaOutputT, infer SchemaInputT, infer ToolOutputT, infer _NameT> ? MessageToolDefinition<SchemaInputT, ToolOutputT> : T extends StructuredToolInterface<infer _SchemaT, infer SchemaInputT, infer ToolOutputT> ? MessageToolDefinition<SchemaInputT, ToolOutputT> : MessageToolDefinition;
|
|
95
|
+
/**
|
|
96
|
+
* Helper type to convert an array of tools (ClientTool | ServerTool)[] to a MessageToolSet.
|
|
97
|
+
* This maps each tool's name (as a literal type) to its MessageToolDefinition containing
|
|
98
|
+
* the input and output types.
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* ```typescript
|
|
102
|
+
* const myTool = tool(async (input: { a: number }) => 42, {
|
|
103
|
+
* name: "myTool",
|
|
104
|
+
* schema: z.object({ a: z.number() })
|
|
105
|
+
* });
|
|
106
|
+
*
|
|
107
|
+
* // Results in: { myTool: MessageToolDefinition<{ a: number }, number> }
|
|
108
|
+
* type ToolSet = ToolsToMessageToolSet<readonly [typeof myTool]>;
|
|
109
|
+
* ```
|
|
110
|
+
*/
|
|
111
|
+
type ToolsToMessageToolSet<T extends readonly (ClientTool | ServerTool)[]> = { [K in T[number] as K extends {
|
|
112
|
+
name: infer N extends string;
|
|
113
|
+
} ? N : never]: ExtractToolDefinition<K> };
|
|
114
|
+
/**
|
|
115
|
+
* Helper type to resolve an AgentTypeConfig from either:
|
|
116
|
+
* - An AgentTypeConfig directly
|
|
117
|
+
* - A ReactAgent instance (using `typeof agent`)
|
|
118
|
+
*
|
|
119
|
+
* @example
|
|
120
|
+
* ```typescript
|
|
121
|
+
* const agent = createAgent({ ... });
|
|
122
|
+
*
|
|
123
|
+
* // From ReactAgent instance
|
|
124
|
+
* type Types = ResolveAgentTypeConfig<typeof agent>;
|
|
125
|
+
*
|
|
126
|
+
* // From AgentTypeConfig directly
|
|
127
|
+
* type Types2 = ResolveAgentTypeConfig<AgentTypeConfig<...>>;
|
|
128
|
+
* ```
|
|
129
|
+
*/
|
|
130
|
+
type ResolveAgentTypeConfig<T> = T extends {
|
|
131
|
+
"~agentTypes": infer Types;
|
|
132
|
+
} ? Types extends AgentTypeConfig ? Types : never : T extends AgentTypeConfig ? T : never;
|
|
133
|
+
/**
|
|
134
|
+
* Helper type to extract any property from an AgentTypeConfig or ReactAgent.
|
|
135
|
+
*
|
|
136
|
+
* @typeParam T - The AgentTypeConfig or ReactAgent to extract from
|
|
137
|
+
* @typeParam K - The property key to extract ("Response" | "State" | "Context" | "Middleware" | "Tools")
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* ```typescript
|
|
141
|
+
* const agent = createAgent({ tools: [myTool], ... });
|
|
142
|
+
*
|
|
143
|
+
* // Extract from agent instance
|
|
144
|
+
* type Tools = InferAgentType<typeof agent, "Tools">;
|
|
145
|
+
*
|
|
146
|
+
* // Extract from type config
|
|
147
|
+
* type Response = InferAgentType<MyTypeConfig, "Response">;
|
|
148
|
+
* ```
|
|
149
|
+
*/
|
|
150
|
+
type InferAgentType<T, K$1 extends keyof AgentTypeConfig> = ResolveAgentTypeConfig<T>[K$1];
|
|
151
|
+
/**
|
|
152
|
+
* Shorthand helper to extract the Response type from an AgentTypeConfig or ReactAgent.
|
|
153
|
+
*
|
|
154
|
+
* @example
|
|
155
|
+
* ```typescript
|
|
156
|
+
* const agent = createAgent({ responseFormat: z.object({ name: z.string() }), ... });
|
|
157
|
+
* type Response = InferAgentResponse<typeof agent>; // { name: string }
|
|
158
|
+
* ```
|
|
159
|
+
*/
|
|
160
|
+
type InferAgentResponse<T> = InferAgentType<T, "Response">;
|
|
161
|
+
/**
|
|
162
|
+
* Shorthand helper to extract the raw State schema type from an AgentTypeConfig or ReactAgent.
|
|
163
|
+
* This returns just the `stateSchema` type passed to `createAgent`, not merged with middleware.
|
|
164
|
+
*
|
|
165
|
+
* For the complete merged state (what `invoke` returns), use {@link InferAgentState}.
|
|
166
|
+
*
|
|
167
|
+
* @example
|
|
168
|
+
* ```typescript
|
|
169
|
+
* const agent = createAgent({ stateSchema: mySchema, ... });
|
|
170
|
+
* type Schema = InferAgentStateSchema<typeof agent>;
|
|
171
|
+
* ```
|
|
172
|
+
*/
|
|
173
|
+
type InferAgentStateSchema<T> = InferAgentType<T, "State">;
|
|
174
|
+
/**
|
|
175
|
+
* Helper type to infer the full merged state from an agent, including:
|
|
176
|
+
* - The agent's own state schema (if provided via `stateSchema`)
|
|
177
|
+
* - All middleware states
|
|
178
|
+
*
|
|
179
|
+
* This matches the state type returned by `invoke` and used throughout the agent.
|
|
180
|
+
*
|
|
181
|
+
* @example
|
|
182
|
+
* ```typescript
|
|
183
|
+
* const middleware = createMiddleware({
|
|
184
|
+
* name: "counter",
|
|
185
|
+
* stateSchema: z.object({ count: z.number() }),
|
|
186
|
+
* });
|
|
187
|
+
*
|
|
188
|
+
* const agent = createAgent({
|
|
189
|
+
* model: "gpt-4",
|
|
190
|
+
* tools: [],
|
|
191
|
+
* stateSchema: z.object({ userId: z.string() }),
|
|
192
|
+
* middleware: [middleware],
|
|
193
|
+
* });
|
|
194
|
+
*
|
|
195
|
+
* type State = InferAgentState<typeof agent>;
|
|
196
|
+
* // { userId: string; count: number }
|
|
197
|
+
* ```
|
|
198
|
+
*/
|
|
199
|
+
type InferAgentState<T> = InferSchemaInput<InferAgentType<T, "State">> & InferMiddlewareStates<InferAgentType<T, "Middleware">>;
|
|
200
|
+
/**
|
|
201
|
+
* Shorthand helper to extract the raw Context schema type from an AgentTypeConfig or ReactAgent.
|
|
202
|
+
* This returns just the `contextSchema` type passed to `createAgent`, not merged with middleware.
|
|
203
|
+
*
|
|
204
|
+
* For the complete merged context (agent context + middleware contexts), use {@link InferAgentContext}.
|
|
205
|
+
*
|
|
206
|
+
* @example
|
|
207
|
+
* ```typescript
|
|
208
|
+
* const agent = createAgent({ contextSchema: myContextSchema, ... });
|
|
209
|
+
* type Schema = InferAgentContextSchema<typeof agent>;
|
|
210
|
+
* ```
|
|
211
|
+
*/
|
|
212
|
+
type InferAgentContextSchema<T> = InferAgentType<T, "Context">;
|
|
213
|
+
/**
|
|
214
|
+
* Helper type to infer the full merged context from an agent, including:
|
|
215
|
+
* - The agent's own context schema (if provided via `contextSchema`)
|
|
216
|
+
* - All middleware context schemas
|
|
217
|
+
*
|
|
218
|
+
* This matches the context type available throughout the agent runtime.
|
|
219
|
+
*
|
|
220
|
+
* @example
|
|
221
|
+
* ```typescript
|
|
222
|
+
* const middleware = createMiddleware({
|
|
223
|
+
* name: "auth",
|
|
224
|
+
* contextSchema: z.object({ userId: z.string() }),
|
|
225
|
+
* });
|
|
226
|
+
*
|
|
227
|
+
* const agent = createAgent({
|
|
228
|
+
* model: "gpt-4",
|
|
229
|
+
* tools: [],
|
|
230
|
+
* contextSchema: z.object({ sessionId: z.string() }),
|
|
231
|
+
* middleware: [middleware],
|
|
232
|
+
* });
|
|
233
|
+
*
|
|
234
|
+
* type Context = InferAgentContext<typeof agent>;
|
|
235
|
+
* // { sessionId: string; userId: string }
|
|
236
|
+
* ```
|
|
237
|
+
*/
|
|
238
|
+
type InferAgentContext<T> = InferSchemaInput<InferAgentType<T, "Context">> & InferMiddlewareContexts<InferAgentType<T, "Middleware">>;
|
|
239
|
+
/**
|
|
240
|
+
* Shorthand helper to extract the Middleware type from an AgentTypeConfig or ReactAgent.
|
|
241
|
+
*
|
|
242
|
+
* @example
|
|
243
|
+
* ```typescript
|
|
244
|
+
* const agent = createAgent({ middleware: [authMiddleware, loggingMiddleware], ... });
|
|
245
|
+
* type Middleware = InferAgentMiddleware<typeof agent>;
|
|
246
|
+
* ```
|
|
247
|
+
*/
|
|
248
|
+
type InferAgentMiddleware<T> = InferAgentType<T, "Middleware">;
|
|
249
|
+
/**
|
|
250
|
+
* Shorthand helper to extract the Tools type from an AgentTypeConfig or ReactAgent.
|
|
251
|
+
*
|
|
252
|
+
* @example
|
|
253
|
+
* ```typescript
|
|
254
|
+
* const agent = createAgent({ tools: [searchTool, calculatorTool], ... });
|
|
255
|
+
* type Tools = InferAgentTools<typeof agent>; // readonly [typeof searchTool, typeof calculatorTool]
|
|
256
|
+
* ```
|
|
257
|
+
*/
|
|
258
|
+
type InferAgentTools<T> = InferAgentType<T, "Tools">;
|
|
13
259
|
type N = typeof START | "model_request" | "tools";
|
|
14
260
|
/**
|
|
15
261
|
* Represents information about an interrupt.
|
|
@@ -24,8 +270,8 @@ interface Interrupt<TValue = unknown> {
|
|
|
24
270
|
*/
|
|
25
271
|
value: TValue;
|
|
26
272
|
}
|
|
27
|
-
interface BuiltInState {
|
|
28
|
-
messages: BaseMessage[];
|
|
273
|
+
interface BuiltInState<TMessageStructure extends MessageStructure = MessageStructure> {
|
|
274
|
+
messages: BaseMessage<TMessageStructure>[];
|
|
29
275
|
__interrupt__?: Interrupt[];
|
|
30
276
|
/**
|
|
31
277
|
* Optional property to control routing after afterModel middleware execution.
|
|
@@ -376,7 +622,7 @@ type CreateAgentParams<StructuredResponseType extends Record<string, any> = Reco
|
|
|
376
622
|
*
|
|
377
623
|
* @see {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}
|
|
378
624
|
*/
|
|
379
|
-
middleware?: readonly AgentMiddleware
|
|
625
|
+
middleware?: readonly AgentMiddleware[];
|
|
380
626
|
/**
|
|
381
627
|
* An optional name for the agent.
|
|
382
628
|
*/
|
|
@@ -414,7 +660,7 @@ type CreateAgentParams<StructuredResponseType extends Record<string, any> = Reco
|
|
|
414
660
|
* Type helper to extract union type from an array of Zod schemas
|
|
415
661
|
*/
|
|
416
662
|
type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;
|
|
417
|
-
type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;
|
|
663
|
+
type WithStateGraphNodes<K$1 extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K$1, I, O, C> : never;
|
|
418
664
|
//#endregion
|
|
419
|
-
export { BuiltInState, CreateAgentParams, ExecutedToolCall, ExtractZodArrayTypes, Interrupt, JumpTo, N, ToolCall$1 as ToolCall, ToolResult, UserInput, WithStateGraphNodes };
|
|
665
|
+
export { AgentTypeConfig, BuiltInState, CombineTools, CreateAgentParams, DefaultAgentTypeConfig, ExecutedToolCall, ExtractZodArrayTypes, InferAgentContext, InferAgentContextSchema, InferAgentMiddleware, InferAgentResponse, InferAgentState, InferAgentStateSchema, InferAgentTools, InferAgentType, InferMiddlewareTools, InferMiddlewareToolsArray, Interrupt, JumpTo, N, ResolveAgentTypeConfig, ToolCall$1 as ToolCall, ToolResult, ToolsToMessageToolSet, UserInput, WithStateGraphNodes };
|
|
420
666
|
//# sourceMappingURL=types.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.cts","names":["InteropZodObject","InteropZodType","START","END","StateGraph","LanguageModelLike","BaseMessage","SystemMessage","BaseCheckpointSaver","BaseStore","Messages","ClientTool","ServerTool","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","JsonSchemaFormat","ResponseFormatUndefined","AgentMiddleware","AnyAnnotationRoot","InferSchemaInput","JumpToTarget","N","Interrupt","TValue","BuiltInState","UserInput","TStateSchema","ToolCall","Record","ToolResult","JumpTo","ExecutedToolCall","CreateAgentParams","StructuredResponseType","StateSchema","ContextSchema","ResponseFormatType","AbortSignal","ExtractZodArrayTypes","T","Rest","A","WithStateGraphNodes","K","Graph","SD","S","U","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { START, END, StateGraph } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseMessage, SystemMessage } from \"@langchain/core/messages\";\nimport type { BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { Messages } from \"@langchain/langgraph/\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, JsonSchemaFormat, ResponseFormatUndefined } from \"./responses.js\";\nimport type { AgentMiddleware, AnyAnnotationRoot, InferSchemaInput } from \"./middleware/types.js\";\nimport type { JumpToTarget } from \"./constants.js\";\nexport type N = typeof START | \"model_request\" | \"tools\";\n/**\n * Represents information about an interrupt.\n */\nexport interface Interrupt<TValue = unknown> {\n /**\n * The ID of the interrupt.\n */\n id: string;\n /**\n * The requests for human input.\n */\n value: TValue;\n}\nexport interface BuiltInState {\n messages: BaseMessage[];\n __interrupt__?: Interrupt[];\n /**\n * Optional property to control routing after afterModel middleware execution.\n * When set by middleware, the agent will jump to the specified node instead of\n * following normal routing logic. The property is automatically cleared after use.\n *\n * - \"model_request\": Jump back to the model for another LLM call\n * - \"tools\": Jump to tool execution (requires tools to be available)\n */\n jumpTo?: JumpToTarget;\n}\n/**\n * Base input type for `.invoke` and `.stream` methods.\n */\nexport type UserInput<TStateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined> = InferSchemaInput<TStateSchema> & {\n messages: Messages;\n};\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ToolCall {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, any>;\n /**\n * The result of the tool call.\n */\n result?: unknown;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * Information about a tool result from a tool execution.\n */\nexport interface ToolResult {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The result of the tool call.\n */\n result: any;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * jump targets (internal)\n */\nexport type JumpTo = \"model_request\" | \"tools\" | typeof END;\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\nexport type CreateAgentParams<StructuredResponseType extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /**\n * Defines a model to use for the agent. You can either pass in an instance of a LangChain chat model\n * or a string. If a string is provided the agent initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n *\n * @example\n * ```ts\n * import { ChatOpenAI } from \"@langchain/openai\";\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * // ...\n * });\n * ```\n */\n model: string | LanguageModelLike;\n /**\n * A list of tools or a ToolNode.\n *\n * @example\n * ```ts\n * import { tool } from \"langchain\";\n *\n * const weatherTool = tool(() => \"Sunny!\", {\n * name: \"get_weather\",\n * description: \"Get the weather for a location\",\n * schema: z.object({\n * location: z.string().describe(\"The location to get weather for\"),\n * }),\n * });\n *\n * const agent = createAgent({\n * tools: [weatherTool],\n * // ...\n * });\n * ```\n */\n tools?: (ServerTool | ClientTool)[];\n /**\n * An optional system message for the model.\n *\n * **Use a `string`** for simple, static system prompts. This is the most common use case\n * and works well with template literals for dynamic content. When a string is provided,\n * it's converted to a single text block internally.\n *\n * **Use a `SystemMessage`** when you need advanced features that require structured content:\n * - **Anthropic cache control**: Use `SystemMessage` with array content to enable per-block\n * cache control settings (e.g., `cache_control: { type: \"ephemeral\" }`). This allows you\n * to have different cache settings for different parts of your system prompt.\n * - **Multiple content blocks**: When you need multiple text blocks with different metadata\n * or formatting requirements.\n * - **Integration with existing code**: When working with code that already produces\n * `SystemMessage` instances.\n *\n * @example Using a string (recommended for most cases)\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: \"You are a helpful assistant.\",\n * // ...\n * });\n * ```\n *\n * @example Using a string with template literals\n * ```ts\n * const userRole = \"premium\";\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: `You are a helpful assistant for ${userRole} users.`,\n * // ...\n * });\n * ```\n *\n * @example Using SystemMessage with cache control (Anthropic)\n * ```ts\n * import { SystemMessage } from \"@langchain/core/messages\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: new SystemMessage({\n * content: [\n * {\n * type: \"text\",\n * text: \"You are a helpful assistant.\",\n * },\n * {\n * type: \"text\",\n * text: \"Today's date is 2024-06-01.\",\n * cache_control: { type: \"ephemeral\" },\n * },\n * ],\n * }),\n * // ...\n * });\n * ```\n *\n * @example Using SystemMessage (simple)\n * ```ts\n * import { SystemMessage } from \"@langchain/core/messages\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: new SystemMessage(\"You are a helpful assistant.\"),\n * // ...\n * });\n * ```\n */\n systemPrompt?: string | SystemMessage;\n /**\n * An optional schema for the agent state. It allows you to define custom state properties that persist\n * across agent invocations and can be accessed in hooks, middleware, and throughout the agent's execution.\n * The state is persisted when using a checkpointer and can be updated by middleware or during execution.\n *\n * As opposed to the context (defined in `contextSchema`), the state is persisted between agent invocations\n * when using a checkpointer, making it suitable for maintaining conversation history, user preferences,\n * or any other data that should persist across multiple interactions.\n *\n * @example\n * ```ts\n * import { z } from \"zod\";\n * import { createAgent } from \"@langchain/langgraph\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather],\n * stateSchema: z.object({\n * userPreferences: z.object({\n * temperatureUnit: z.enum([\"celsius\", \"fahrenheit\"]).default(\"celsius\"),\n * location: z.string().optional(),\n * }).optional(),\n * conversationCount: z.number().default(0),\n * }),\n * prompt: (state, config) => {\n * const unit = state.userPreferences?.temperatureUnit || \"celsius\";\n * return [\n * new SystemMessage(`You are a helpful assistant. Use ${unit} for temperature.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new HumanMessage(\"What's the weather like?\"),\n * ],\n * userPreferences: {\n * temperatureUnit: \"fahrenheit\",\n * location: \"New York\",\n * },\n * conversationCount: 1,\n * });\n * ```\n */\n stateSchema?: StateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt` and middleware.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /**\n * An optional checkpoint saver to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/persistence | Checkpointing}\n */\n checkpointer?: BaseCheckpointSaver | boolean;\n /**\n * An optional store to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Long-term memory}\n */\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * Middleware instances to run during agent execution.\n * Each middleware can define its own state schema and hook into the agent lifecycle.\n *\n * @see {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}\n */\n middleware?: readonly AgentMiddleware<any, any, any>[];\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\n//# sourceMappingURL=types.d.ts.map"],"mappings":";;;;;;;;;;;;KAUYuB,CAAAA,UAAWrB;;AAAvB;AAIA;AAUiBwB,UAVAF,SAUY,CAAA,SAAA,OAAA,CAAA,CAAA;EACflB;;;EAUW,EAAA,EAAA,MAAA;EAKbqB;;;EAAgHC,KAAAA,EAlBjHH,MAkBiHG;;AAC9GlB,UAjBGgB,YAAAA,CAiBHhB;EAAQ,QAAA,EAhBRJ,WAgBQ,EAAA;EAKLuB,aAAQ,CAAA,EApBLL,SAgCVM,EAAAA;EAaOC;AAiBjB;AAIA;AAkBA;;;;;EAAgNX,MAAAA,CAAAA,EA3EnME,YA2EmMF;;;;;AAAwHnB,KAtE5T0B,SAsE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;;;;;;;;;;;;;;;;;;;kBAkCEC;;;;;iBAKD7B;;;;;UAKPC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mBAsDS6B;;;;;;;wBAOKnB;;;;;;;;;;;;;;;;;;;;WAoBboB;;;;;;;;;;;;;;;;;KAiBDC,wCAAwCvC,yBAAyBwC,oBAAoBxC,0CAA0CyC,sBAAsBzC,wBAAwB0C,IAAIH,qBAAqBE,QAAQC;KAC9MC,+CAA+CE,cAAc1C,6EAA6EA,WAAW2C,IAAIC,GAAGC,GAAG1B,IAAIsB,GAAGK,GAAGC,GAAGC"}
|
|
1
|
+
{"version":3,"file":"types.d.cts","names":["InteropZodObject","InteropZodType","START","END","StateGraph","LanguageModelLike","BaseMessage","SystemMessage","MessageStructure","MessageToolDefinition","BaseCheckpointSaver","BaseStore","Messages","ClientTool","ServerTool","DynamicStructuredTool","StructuredToolInterface","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","JsonSchemaFormat","ResponseFormatUndefined","AgentMiddleware","AnyAnnotationRoot","InferSchemaInput","InferMiddlewareStates","InferMiddlewareContexts","JumpToTarget","AgentTypeConfig","TResponse","TState","TContext","TMiddleware","TTools","Record","DefaultAgentTypeConfig","InferMiddlewareTools","T","InferMiddlewareToolsArray","First","Rest","CombineTools","TAgentTools","ExtractToolDefinition","SchemaInputT","ToolOutputT","ToolsToMessageToolSet","K","N","ResolveAgentTypeConfig","Types","InferAgentType","InferAgentResponse","InferAgentStateSchema","InferAgentState","InferAgentContextSchema","InferAgentContext","InferAgentMiddleware","InferAgentTools","Interrupt","TValue","BuiltInState","TMessageStructure","UserInput","TStateSchema","ToolCall","ToolResult","JumpTo","ExecutedToolCall","CreateAgentParams","StructuredResponseType","StateSchema","ContextSchema","ResponseFormatType","AbortSignal","ExtractZodArrayTypes","A","WithStateGraphNodes","Graph","SD","S","U","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { START, END, StateGraph } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseMessage, SystemMessage, MessageStructure, MessageToolDefinition } from \"@langchain/core/messages\";\nimport type { BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { Messages } from \"@langchain/langgraph/\";\nimport type { ClientTool, ServerTool, DynamicStructuredTool, StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, JsonSchemaFormat, ResponseFormatUndefined } from \"./responses.js\";\nimport type { AgentMiddleware, AnyAnnotationRoot, InferSchemaInput, InferMiddlewareStates, InferMiddlewareContexts } from \"./middleware/types.js\";\nimport type { JumpToTarget } from \"./constants.js\";\n/**\n * Type bag that encapsulates all agent type parameters.\n *\n * This interface bundles all the generic type parameters used throughout the agent system\n * into a single configuration object. This pattern simplifies type signatures and makes\n * it easier to add new type parameters without changing multiple function signatures.\n *\n * @typeParam TResponse - The structured response type when using `responseFormat`.\n * Defaults to `Record<string, any>`. Set to `ResponseFormatUndefined` when no\n * response format is configured.\n *\n * @typeParam TState - The custom state schema type. Can be an `AnnotationRoot`,\n * `InteropZodObject`, or `undefined`. The state persists across agent invocations\n * when using a checkpointer.\n *\n * @typeParam TContext - The context schema type. Context is read-only and not\n * persisted between invocations. Defaults to `AnyAnnotationRoot`.\n *\n * @typeParam TMiddleware - The middleware array type. Must be a readonly array\n * of `AgentMiddleware` instances.\n *\n * @typeParam TTools - The combined tools type from both `createAgent` tools parameter\n * and middleware tools. This is a readonly array of `ClientTool | ServerTool`.\n *\n * @example\n * ```typescript\n * // Define a type configuration\n * type MyAgentTypes = AgentTypeConfig<\n * { name: string; email: string }, // Response type\n * typeof MyStateSchema, // State schema\n * typeof MyContextSchema, // Context schema\n * typeof myMiddleware, // Middleware array\n * typeof myTools // Tools array\n * >;\n *\n * // Use with ReactAgent\n * const agent: ReactAgent<MyAgentTypes> = createAgent({ ... });\n * ```\n */\nexport interface AgentTypeConfig<TResponse extends Record<string, any> | ResponseFormatUndefined = Record<string, any> | ResponseFormatUndefined, TState extends AnyAnnotationRoot | InteropZodObject | undefined = AnyAnnotationRoot | InteropZodObject | undefined, TContext extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot | InteropZodObject, TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[], TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {\n /** The structured response type when using `responseFormat` */\n Response: TResponse;\n /** The custom state schema type */\n State: TState;\n /** The context schema type */\n Context: TContext;\n /** The middleware array type */\n Middleware: TMiddleware;\n /** The combined tools type from agent and middleware */\n Tools: TTools;\n}\n/**\n * Default type configuration for agents.\n * Used when no explicit type parameters are provided.\n */\nexport interface DefaultAgentTypeConfig extends AgentTypeConfig {\n Response: Record<string, any>;\n State: undefined;\n Context: AnyAnnotationRoot;\n Middleware: readonly AgentMiddleware[];\n Tools: readonly (ClientTool | ServerTool)[];\n}\n/**\n * Helper type to infer tools from a single middleware instance.\n * Extracts the TTools type parameter from AgentMiddleware.\n */\nexport type InferMiddlewareTools<T extends AgentMiddleware> = T extends AgentMiddleware<any, any, any, infer TTools> ? TTools extends readonly (ClientTool | ServerTool)[] ? TTools : readonly [] : readonly [];\n/**\n * Helper type to infer and merge tools from an array of middleware.\n * Recursively extracts tools from each middleware and combines them into a single tuple.\n */\nexport type InferMiddlewareToolsArray<T extends readonly AgentMiddleware[]> = T extends readonly [] ? readonly [] : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? readonly [\n ...InferMiddlewareTools<First>,\n ...InferMiddlewareToolsArray<Rest>\n] : InferMiddlewareTools<First> : readonly [] : readonly [];\n/**\n * Helper type to combine agent tools with middleware tools into a single readonly array.\n */\nexport type CombineTools<TAgentTools extends readonly (ClientTool | ServerTool)[], TMiddleware extends readonly AgentMiddleware[]> = readonly [...TAgentTools, ...InferMiddlewareToolsArray<TMiddleware>];\n/**\n * Helper type to extract the tool name, input type, and output type from a tool.\n * Converts a single tool to a MessageToolDefinition entry.\n */\ntype ExtractToolDefinition<T> = T extends DynamicStructuredTool<infer _SchemaT, infer _SchemaOutputT, infer SchemaInputT, infer ToolOutputT, infer _NameT> ? MessageToolDefinition<SchemaInputT, ToolOutputT> : T extends StructuredToolInterface<infer _SchemaT, infer SchemaInputT, infer ToolOutputT> ? MessageToolDefinition<SchemaInputT, ToolOutputT> : MessageToolDefinition;\n/**\n * Helper type to convert an array of tools (ClientTool | ServerTool)[] to a MessageToolSet.\n * This maps each tool's name (as a literal type) to its MessageToolDefinition containing\n * the input and output types.\n *\n * @example\n * ```typescript\n * const myTool = tool(async (input: { a: number }) => 42, {\n * name: \"myTool\",\n * schema: z.object({ a: z.number() })\n * });\n *\n * // Results in: { myTool: MessageToolDefinition<{ a: number }, number> }\n * type ToolSet = ToolsToMessageToolSet<readonly [typeof myTool]>;\n * ```\n */\nexport type ToolsToMessageToolSet<T extends readonly (ClientTool | ServerTool)[]> = {\n [K in T[number] as K extends {\n name: infer N extends string;\n } ? N : never]: ExtractToolDefinition<K>;\n};\n/**\n * Helper type to resolve an AgentTypeConfig from either:\n * - An AgentTypeConfig directly\n * - A ReactAgent instance (using `typeof agent`)\n *\n * @example\n * ```typescript\n * const agent = createAgent({ ... });\n *\n * // From ReactAgent instance\n * type Types = ResolveAgentTypeConfig<typeof agent>;\n *\n * // From AgentTypeConfig directly\n * type Types2 = ResolveAgentTypeConfig<AgentTypeConfig<...>>;\n * ```\n */\nexport type ResolveAgentTypeConfig<T> = T extends {\n \"~agentTypes\": infer Types;\n} ? Types extends AgentTypeConfig ? Types : never : T extends AgentTypeConfig ? T : never;\n/**\n * Helper type to extract any property from an AgentTypeConfig or ReactAgent.\n *\n * @typeParam T - The AgentTypeConfig or ReactAgent to extract from\n * @typeParam K - The property key to extract (\"Response\" | \"State\" | \"Context\" | \"Middleware\" | \"Tools\")\n *\n * @example\n * ```typescript\n * const agent = createAgent({ tools: [myTool], ... });\n *\n * // Extract from agent instance\n * type Tools = InferAgentType<typeof agent, \"Tools\">;\n *\n * // Extract from type config\n * type Response = InferAgentType<MyTypeConfig, \"Response\">;\n * ```\n */\nexport type InferAgentType<T, K extends keyof AgentTypeConfig> = ResolveAgentTypeConfig<T>[K];\n/**\n * Shorthand helper to extract the Response type from an AgentTypeConfig or ReactAgent.\n *\n * @example\n * ```typescript\n * const agent = createAgent({ responseFormat: z.object({ name: z.string() }), ... });\n * type Response = InferAgentResponse<typeof agent>; // { name: string }\n * ```\n */\nexport type InferAgentResponse<T> = InferAgentType<T, \"Response\">;\n/**\n * Shorthand helper to extract the raw State schema type from an AgentTypeConfig or ReactAgent.\n * This returns just the `stateSchema` type passed to `createAgent`, not merged with middleware.\n *\n * For the complete merged state (what `invoke` returns), use {@link InferAgentState}.\n *\n * @example\n * ```typescript\n * const agent = createAgent({ stateSchema: mySchema, ... });\n * type Schema = InferAgentStateSchema<typeof agent>;\n * ```\n */\nexport type InferAgentStateSchema<T> = InferAgentType<T, \"State\">;\n/**\n * Helper type to infer the full merged state from an agent, including:\n * - The agent's own state schema (if provided via `stateSchema`)\n * - All middleware states\n *\n * This matches the state type returned by `invoke` and used throughout the agent.\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"counter\",\n * stateSchema: z.object({ count: z.number() }),\n * });\n *\n * const agent = createAgent({\n * model: \"gpt-4\",\n * tools: [],\n * stateSchema: z.object({ userId: z.string() }),\n * middleware: [middleware],\n * });\n *\n * type State = InferAgentState<typeof agent>;\n * // { userId: string; count: number }\n * ```\n */\nexport type InferAgentState<T> = InferSchemaInput<InferAgentType<T, \"State\">> & InferMiddlewareStates<InferAgentType<T, \"Middleware\">>;\n/**\n * Shorthand helper to extract the raw Context schema type from an AgentTypeConfig or ReactAgent.\n * This returns just the `contextSchema` type passed to `createAgent`, not merged with middleware.\n *\n * For the complete merged context (agent context + middleware contexts), use {@link InferAgentContext}.\n *\n * @example\n * ```typescript\n * const agent = createAgent({ contextSchema: myContextSchema, ... });\n * type Schema = InferAgentContextSchema<typeof agent>;\n * ```\n */\nexport type InferAgentContextSchema<T> = InferAgentType<T, \"Context\">;\n/**\n * Helper type to infer the full merged context from an agent, including:\n * - The agent's own context schema (if provided via `contextSchema`)\n * - All middleware context schemas\n *\n * This matches the context type available throughout the agent runtime.\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"auth\",\n * contextSchema: z.object({ userId: z.string() }),\n * });\n *\n * const agent = createAgent({\n * model: \"gpt-4\",\n * tools: [],\n * contextSchema: z.object({ sessionId: z.string() }),\n * middleware: [middleware],\n * });\n *\n * type Context = InferAgentContext<typeof agent>;\n * // { sessionId: string; userId: string }\n * ```\n */\nexport type InferAgentContext<T> = InferSchemaInput<InferAgentType<T, \"Context\">> & InferMiddlewareContexts<InferAgentType<T, \"Middleware\">>;\n/**\n * Shorthand helper to extract the Middleware type from an AgentTypeConfig or ReactAgent.\n *\n * @example\n * ```typescript\n * const agent = createAgent({ middleware: [authMiddleware, loggingMiddleware], ... });\n * type Middleware = InferAgentMiddleware<typeof agent>;\n * ```\n */\nexport type InferAgentMiddleware<T> = InferAgentType<T, \"Middleware\">;\n/**\n * Shorthand helper to extract the Tools type from an AgentTypeConfig or ReactAgent.\n *\n * @example\n * ```typescript\n * const agent = createAgent({ tools: [searchTool, calculatorTool], ... });\n * type Tools = InferAgentTools<typeof agent>; // readonly [typeof searchTool, typeof calculatorTool]\n * ```\n */\nexport type InferAgentTools<T> = InferAgentType<T, \"Tools\">;\nexport type N = typeof START | \"model_request\" | \"tools\";\n/**\n * Represents information about an interrupt.\n */\nexport interface Interrupt<TValue = unknown> {\n /**\n * The ID of the interrupt.\n */\n id: string;\n /**\n * The requests for human input.\n */\n value: TValue;\n}\nexport interface BuiltInState<TMessageStructure extends MessageStructure = MessageStructure> {\n messages: BaseMessage<TMessageStructure>[];\n __interrupt__?: Interrupt[];\n /**\n * Optional property to control routing after afterModel middleware execution.\n * When set by middleware, the agent will jump to the specified node instead of\n * following normal routing logic. The property is automatically cleared after use.\n *\n * - \"model_request\": Jump back to the model for another LLM call\n * - \"tools\": Jump to tool execution (requires tools to be available)\n */\n jumpTo?: JumpToTarget;\n}\n/**\n * Base input type for `.invoke` and `.stream` methods.\n */\nexport type UserInput<TStateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined> = InferSchemaInput<TStateSchema> & {\n messages: Messages;\n};\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ToolCall {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, any>;\n /**\n * The result of the tool call.\n */\n result?: unknown;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * Information about a tool result from a tool execution.\n */\nexport interface ToolResult {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The result of the tool call.\n */\n result: any;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * jump targets (internal)\n */\nexport type JumpTo = \"model_request\" | \"tools\" | typeof END;\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\nexport type CreateAgentParams<StructuredResponseType extends Record<string, any> = Record<string, any>, StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined = undefined, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /**\n * Defines a model to use for the agent. You can either pass in an instance of a LangChain chat model\n * or a string. If a string is provided the agent initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n *\n * @example\n * ```ts\n * import { ChatOpenAI } from \"@langchain/openai\";\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * // ...\n * });\n * ```\n */\n model: string | LanguageModelLike;\n /**\n * A list of tools or a ToolNode.\n *\n * @example\n * ```ts\n * import { tool } from \"langchain\";\n *\n * const weatherTool = tool(() => \"Sunny!\", {\n * name: \"get_weather\",\n * description: \"Get the weather for a location\",\n * schema: z.object({\n * location: z.string().describe(\"The location to get weather for\"),\n * }),\n * });\n *\n * const agent = createAgent({\n * tools: [weatherTool],\n * // ...\n * });\n * ```\n */\n tools?: (ServerTool | ClientTool)[];\n /**\n * An optional system message for the model.\n *\n * **Use a `string`** for simple, static system prompts. This is the most common use case\n * and works well with template literals for dynamic content. When a string is provided,\n * it's converted to a single text block internally.\n *\n * **Use a `SystemMessage`** when you need advanced features that require structured content:\n * - **Anthropic cache control**: Use `SystemMessage` with array content to enable per-block\n * cache control settings (e.g., `cache_control: { type: \"ephemeral\" }`). This allows you\n * to have different cache settings for different parts of your system prompt.\n * - **Multiple content blocks**: When you need multiple text blocks with different metadata\n * or formatting requirements.\n * - **Integration with existing code**: When working with code that already produces\n * `SystemMessage` instances.\n *\n * @example Using a string (recommended for most cases)\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: \"You are a helpful assistant.\",\n * // ...\n * });\n * ```\n *\n * @example Using a string with template literals\n * ```ts\n * const userRole = \"premium\";\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: `You are a helpful assistant for ${userRole} users.`,\n * // ...\n * });\n * ```\n *\n * @example Using SystemMessage with cache control (Anthropic)\n * ```ts\n * import { SystemMessage } from \"@langchain/core/messages\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: new SystemMessage({\n * content: [\n * {\n * type: \"text\",\n * text: \"You are a helpful assistant.\",\n * },\n * {\n * type: \"text\",\n * text: \"Today's date is 2024-06-01.\",\n * cache_control: { type: \"ephemeral\" },\n * },\n * ],\n * }),\n * // ...\n * });\n * ```\n *\n * @example Using SystemMessage (simple)\n * ```ts\n * import { SystemMessage } from \"@langchain/core/messages\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemPrompt: new SystemMessage(\"You are a helpful assistant.\"),\n * // ...\n * });\n * ```\n */\n systemPrompt?: string | SystemMessage;\n /**\n * An optional schema for the agent state. It allows you to define custom state properties that persist\n * across agent invocations and can be accessed in hooks, middleware, and throughout the agent's execution.\n * The state is persisted when using a checkpointer and can be updated by middleware or during execution.\n *\n * As opposed to the context (defined in `contextSchema`), the state is persisted between agent invocations\n * when using a checkpointer, making it suitable for maintaining conversation history, user preferences,\n * or any other data that should persist across multiple interactions.\n *\n * @example\n * ```ts\n * import { z } from \"zod\";\n * import { createAgent } from \"@langchain/langgraph\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather],\n * stateSchema: z.object({\n * userPreferences: z.object({\n * temperatureUnit: z.enum([\"celsius\", \"fahrenheit\"]).default(\"celsius\"),\n * location: z.string().optional(),\n * }).optional(),\n * conversationCount: z.number().default(0),\n * }),\n * prompt: (state, config) => {\n * const unit = state.userPreferences?.temperatureUnit || \"celsius\";\n * return [\n * new SystemMessage(`You are a helpful assistant. Use ${unit} for temperature.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new HumanMessage(\"What's the weather like?\"),\n * ],\n * userPreferences: {\n * temperatureUnit: \"fahrenheit\",\n * location: \"New York\",\n * },\n * conversationCount: 1,\n * });\n * ```\n */\n stateSchema?: StateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt` and middleware.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /**\n * An optional checkpoint saver to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/persistence | Checkpointing}\n */\n checkpointer?: BaseCheckpointSaver | boolean;\n /**\n * An optional store to persist the agent's state.\n * @see {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Long-term memory}\n */\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * Middleware instances to run during agent execution.\n * Each middleware can define its own state schema and hook into the agent lifecycle.\n *\n * @see {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}\n */\n middleware?: readonly AgentMiddleware[];\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\nexport {};\n//# source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