UNPKG

@directus/api

Version:

Directus is a real-time API and App dashboard for managing SQL database content

38 lines (37 loc) 1.73 kB
import { InvalidPayloadError } from '@directus/errors'; import {} from '@directus/types'; import { jsonSchema, tool, zodSchema } from 'ai'; import { fromZodError } from 'zod-validation-error'; import { ALL_TOOLS } from '../../tools/index.js'; export const chatRequestToolToAiSdkTool = ({ chatRequestTool, accountability, schema, toolApprovals, }) => { if (typeof chatRequestTool === 'string') { const directusTool = ALL_TOOLS.find(({ name }) => name === chatRequestTool); if (!directusTool) { throw new InvalidPayloadError({ reason: `Tool by name "${chatRequestTool}" does not exist` }); } // Determine if tool needs approval based on client settings // Default to 'ask' (needs approval) if not specified const approvalMode = toolApprovals?.[chatRequestTool] ?? 'ask'; const needsApproval = approvalMode !== 'always'; const inputSchema = zodSchema(directusTool.inputSchema); return tool({ description: directusTool.description, inputSchema, needsApproval, execute: async (rawArgs) => { const { error, data: args } = directusTool.validateSchema?.safeParse(rawArgs) ?? { data: rawArgs, }; if (error) { throw new InvalidPayloadError({ reason: fromZodError(error).message }); } return directusTool.handler({ args, accountability, schema }); }, }); } // Local/client-side tool (schema only, executed on client) return tool({ description: chatRequestTool.description, inputSchema: jsonSchema(chatRequestTool.inputSchema), }); };