UNPKG

@convex-dev/agent

Version:

A agent component for Convex.

58 lines 1.93 kB
import { tool } from "ai"; /** * This is a wrapper around the ai.tool function that adds extra context to the * tool call, including the action context, userId, threadId, and messageId. * @param tool The tool. See https://sdk.vercel.ai/docs/ai-sdk-core/tools-and-tool-calling * but swap parameters for args and handler for execute. * @returns A tool to be used with the AI SDK. */ export function createTool(def) { const t = tool({ type: "function", __acceptsCtx: true, ctx: def.ctx, description: def.description, inputSchema: def.args, execute(args, options) { if (!getCtx(this)) { throw new Error("To use a Convex tool, you must either provide the ctx" + " at definition time (dynamically in an action), or use the Agent to" + " call it (which injects the ctx, userId and threadId)"); } return def.handler(getCtx(this), args, options); }, providerOptions: def.providerOptions, }); if (def.onInputStart) { t.onInputStart = def.onInputStart.bind(t, getCtx(t)); } if (def.onInputDelta) { t.onInputDelta = def.onInputDelta.bind(t, getCtx(t)); } if (def.onInputAvailable) { t.onInputAvailable = def.onInputAvailable.bind(t, getCtx(t)); } return t; } function getCtx(tool) { return tool.ctx; } export function wrapTools(ctx, ...toolSets) { const output = {}; for (const toolSet of toolSets) { if (!toolSet) { continue; } for (const [name, tool] of Object.entries(toolSet)) { if (tool && !tool.__acceptsCtx) { output[name] = tool; } else { const out = { ...tool, ctx }; output[name] = out; } } } return output; } //# sourceMappingURL=createTool.js.map