UNPKG

@langgraph-js/sdk

Version:

The UI SDK for LangGraph - seamlessly integrate your AI agents with frontend interfaces

95 lines (94 loc) 3.19 kB
import { actionParametersToJsonSchema, convertJsonSchemaToZodRawShape } from "./utils.js"; import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; /** 用于格式校验 */ export const createTool = (tool) => { return tool; }; /** * create Type Safe Tool with zod and UI Render Feature */ export const createUITool = (tool) => { const execute = tool.execute || (async (args, context) => { var _a; try { const result = await ((_a = tool.handler) === null || _a === void 0 ? void 0 : _a.call(tool, args, context)); if (typeof result === "string") { return [{ type: "text", text: result }]; } return [{ type: "text", text: JSON.stringify(result) }]; } catch (error) { return [{ type: "text", text: `Error: ${error}` }]; } }); return { ...tool, execute, }; }; /** * 提供一种兼容 copilotkit 的定义方式,简化定义形式 * 来自 copilotkit 的 frontend action */ export const createFETool = (tool) => { return { render: tool.render, onlyRender: tool.onlyRender, name: tool.name, description: tool.description || "", parameters: convertJsonSchemaToZodRawShape(actionParametersToJsonSchema(tool.parameters || [])), returnDirect: tool.returnDirect, callbackMessage: tool.callbackMessage, allowAgent: tool.allowAgent, allowGraph: tool.allowGraph, async execute(args, context) { var _a; try { const result = await ((_a = tool.handler) === null || _a === void 0 ? void 0 : _a.call(tool, args, context)); if (typeof result === "string") { return [{ type: "text", text: result }]; } return [{ type: "text", text: JSON.stringify(result) }]; } catch (error) { return [{ type: "text", text: `Error: ${error}` }]; } }, }; }; ///======= UnionTool 到 各种工具的辅助函数 export const createJSONDefineTool = (tool) => { return { name: tool.name, description: tool.description, parameters: tool.isPureParams ? tool.parameters : zodToJsonSchema(z.object(tool.parameters)), }; }; export const createMCPTool = (tool) => { return [ tool.name, tool.description, tool.parameters, async (args) => { var _a; try { const result = await ((_a = tool.execute) === null || _a === void 0 ? void 0 : _a.call(tool, args)); if (typeof result === "string") { return { content: [{ type: "text", text: result }] }; } return { content: result, }; } catch (error) { return { content: [{ type: "text", text: `Error: ${error}` }], isError: true }; } }, ]; }; /** * @deprecated Use createUITool instead */ export const createToolUI = createFETool;