UNPKG

create-mf2-app

Version:

The stack AI moves fast with.

83 lines (80 loc) 2.64 kB
import { components } from "../_generated/api"; import { Agent, createTool } from "@convex-dev/agent"; import { openai } from "@ai-sdk/openai"; import z from "zod"; import { action } from "../_generated/server"; import { tool } from "ai"; export const runAgentAsTool = action({ args: {}, handler: async (ctx) => { const agentWithTools = new Agent(components.agent, { chat: openai.chat("gpt-4o-mini"), textEmbedding: openai.embedding("text-embedding-3-small"), instructions: "You are a helpful assistant.", tools: { doSomething: tool({ description: "Call this function when asked to do something", parameters: z.object({}), execute: async (args, options) => { console.log("doingSomething", options.toolCallId); return "hello"; }, }), doSomethingElse: tool({ description: "Call this function when asked to do something else", parameters: z.object({}), execute: async (args, options) => { console.log("doSomethingElse", options.toolCallId); return "hello"; }, }), }, maxSteps: 20, }); const agentWithToolsAsTool = createTool({ description: "agentWithTools which can either doSomething or doSomethingElse", args: z.object({ whatToDo: z.union([ z.literal("doSomething"), z.literal("doSomethingElse"), ]), }), handler: async (ctx, args) => { const { thread } = await agentWithTools.createThread(ctx, { userId: ctx.userId, }); const result = await thread.generateText({ messages: [ { role: "assistant", content: `I'll do this now: ${args.whatToDo}`, }, ], }); return result.text; }, }); const dispatchAgent = new Agent(components.agent, { chat: openai.chat("gpt-4o-mini"), textEmbedding: openai.embedding("text-embedding-3-small"), instructions: "You can call agentWithToolsAsTool as many times as told with the argument whatToDo.", tools: { agentWithToolsAsTool }, maxSteps: 5, }); const { thread } = await dispatchAgent.createThread(ctx); console.time("overall"); const result = await thread.generateText({ messages: [ { role: "user", content: "Call fastAgent with whatToDo set to doSomething three times and doSomethingElse one time", }, ], }); console.timeEnd("overall"); return result.text; }, });