UNPKG

langchain

Version:
66 lines (65 loc) • 2.17 kB
import { createMiddleware } from "../middleware.js"; import { ToolMessage } from "@langchain/core/messages"; import { isGraphBubbleUp } from "@langchain/langgraph"; // src/agents/middleware/toolError.ts /** * Tool error middleware for agents. */ /** * Converts selected tool execution errors into error `ToolMessage`s. * * Handling is opt-in: {@link ToolErrorMiddlewareConfig.onError} must return * content for an error to be sent to the model. Returning nothing propagates * the original error unchanged. LangGraph control-flow signals always * propagate and are never passed to `onError`. * * Prefer returning content that identifies the error type without including * the raw error message, which may contain sensitive or internal details. * * This middleware does not retry. To retry before handling an error, place * `toolRetryMiddleware({ onFailure: "error" })` after this middleware. * * @example * ```ts * import { createAgent, toolErrorMiddleware } from "langchain"; * * const agent = createAgent({ * model, * tools: [searchTool], * middleware: [ * toolErrorMiddleware({ * onError: (error, request) => { * if (error instanceof TypeError) { * return `Tool '${request.toolCall.name}' failed with TypeError.`; * } * }, * }), * ], * }); * ``` */ function toolErrorMiddleware(config) { const toolFilter = config.tools?.map((tool) => typeof tool === "string" ? tool : tool.name); return createMiddleware({ name: "toolErrorMiddleware", wrapToolCall: async (request, handler) => { const toolName = request.tool?.name ?? request.toolCall.name; if (toolFilter !== void 0 && !toolFilter.includes(toolName)) return handler(request); try { return await handler(request); } catch (error) { if (isGraphBubbleUp(error)) throw error; const content = await config.onError(error, request); if (content === void 0) throw error; return new ToolMessage({ content, tool_call_id: request.toolCall.id ?? "", ...typeof toolName === "string" ? { name: toolName } : {}, status: "error" }); } } }); } export { toolErrorMiddleware }; //# sourceMappingURL=toolError.js.map