|
| 1 | +/** |
| 2 | + * This example demonstrates the meta tools pattern (tool_search + tool_execute) |
| 3 | + * for LLM-driven tool discovery and execution. |
| 4 | + * |
| 5 | + * Instead of loading all tools upfront, the LLM autonomously searches for |
| 6 | + * relevant tools and executes them — keeping token usage minimal. |
| 7 | + * |
| 8 | + * @example |
| 9 | + * ```bash |
| 10 | + * # Run with required environment variables: |
| 11 | + * STACKONE_API_KEY=your-key OPENAI_API_KEY=your-key STACKONE_ACCOUNT_ID=your-account npx tsx examples/meta-tools.ts |
| 12 | + * ``` |
| 13 | + */ |
| 14 | + |
| 15 | +import process from 'node:process'; |
| 16 | +import { openai } from '@ai-sdk/openai'; |
| 17 | +import { StackOneToolSet } from '@stackone/ai'; |
| 18 | +import { generateText, stepCountIs } from 'ai'; |
| 19 | + |
| 20 | +const apiKey = process.env.STACKONE_API_KEY; |
| 21 | +if (!apiKey) { |
| 22 | + console.error('STACKONE_API_KEY environment variable is required'); |
| 23 | + process.exit(1); |
| 24 | +} |
| 25 | + |
| 26 | +if (!process.env.OPENAI_API_KEY) { |
| 27 | + console.error('OPENAI_API_KEY environment variable is required'); |
| 28 | + process.exit(1); |
| 29 | +} |
| 30 | + |
| 31 | +const accountId = process.env.STACKONE_ACCOUNT_ID; |
| 32 | + |
| 33 | +/** |
| 34 | + * Example 1: Meta tools with Vercel AI SDK |
| 35 | + * |
| 36 | + * The LLM receives only tool_search and tool_execute — two small tool definitions |
| 37 | + * regardless of how many tools exist. It searches for what it needs and executes. |
| 38 | + */ |
| 39 | +const metaToolsWithAISDK = async (): Promise<void> => { |
| 40 | + console.log('Example 1: Meta tools with Vercel AI SDK\n'); |
| 41 | + |
| 42 | + const toolset = new StackOneToolSet({ |
| 43 | + search: { method: 'semantic', topK: 3 }, |
| 44 | + ...(accountId ? { accountId } : {}), |
| 45 | + }); |
| 46 | + |
| 47 | + // Get meta tools — returns a Tools collection with tool_search + tool_execute |
| 48 | + const accountIds = accountId ? [accountId] : []; |
| 49 | + const metaTools = toolset.getMetaTools({ accountIds }); |
| 50 | + |
| 51 | + console.log(`Meta tools: ${metaTools.toArray().map((t) => t.name).join(', ')}`); |
| 52 | + console.log(); |
| 53 | + |
| 54 | + // Pass to the LLM — it will search for calendly tools, then execute |
| 55 | + const { text, steps } = await generateText({ |
| 56 | + model: openai('gpt-4o'), |
| 57 | + tools: await metaTools.toAISDK(), |
| 58 | + prompt: 'List my upcoming Calendly events for the next week.', |
| 59 | + stopWhen: stepCountIs(10), |
| 60 | + }); |
| 61 | + |
| 62 | + console.log('AI Response:', text); |
| 63 | + console.log('\nSteps taken:'); |
| 64 | + for (const step of steps) { |
| 65 | + for (const call of step.toolCalls ?? []) { |
| 66 | + const argsStr = call.args ? JSON.stringify(call.args).slice(0, 100) : '{}'; |
| 67 | + console.log(` - ${call.toolName}(${argsStr})`); |
| 68 | + } |
| 69 | + } |
| 70 | +}; |
| 71 | + |
| 72 | +/** |
| 73 | + * Example 2: Meta tools with OpenAI Chat Completions |
| 74 | + * |
| 75 | + * Same pattern, different framework. The meta tools convert to any format. |
| 76 | + */ |
| 77 | +const metaToolsWithOpenAI = async (): Promise<void> => { |
| 78 | + console.log('\nExample 2: Meta tools with OpenAI Chat Completions\n'); |
| 79 | + |
| 80 | + const { default: OpenAI } = await import('openai'); |
| 81 | + |
| 82 | + const toolset = new StackOneToolSet({ |
| 83 | + search: { method: 'semantic', topK: 3 }, |
| 84 | + ...(accountId ? { accountId } : {}), |
| 85 | + }); |
| 86 | + |
| 87 | + const accountIds = accountId ? [accountId] : []; |
| 88 | + const metaTools = toolset.getMetaTools({ accountIds }); |
| 89 | + const openaiTools = metaTools.toOpenAI(); |
| 90 | + |
| 91 | + const client = new OpenAI(); |
| 92 | + const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [ |
| 93 | + { |
| 94 | + role: 'system', |
| 95 | + content: |
| 96 | + 'You are a helpful scheduling assistant. Use tool_search to find relevant tools, then tool_execute to run them. Always read the parameter schemas from tool_search results carefully. If a tool needs a user URI, first search for and call a "get current user" tool to obtain it. If a tool execution fails, try different parameters or a different tool.', |
| 97 | + }, |
| 98 | + { |
| 99 | + role: 'user', |
| 100 | + content: 'Check my upcoming Calendly events and list them.', |
| 101 | + }, |
| 102 | + ]; |
| 103 | + |
| 104 | + // Agent loop — let the LLM drive search and execution |
| 105 | + let continueLoop = true; |
| 106 | + while (continueLoop) { |
| 107 | + const response = await client.chat.completions.create({ |
| 108 | + model: 'gpt-4o', |
| 109 | + messages, |
| 110 | + tools: openaiTools, |
| 111 | + tool_choice: 'auto', |
| 112 | + }); |
| 113 | + |
| 114 | + const choice = response.choices[0]; |
| 115 | + |
| 116 | + if (!choice.message.tool_calls?.length) { |
| 117 | + console.log('Final response:', choice.message.content); |
| 118 | + continueLoop = false; |
| 119 | + break; |
| 120 | + } |
| 121 | + |
| 122 | + // Add assistant message with tool calls |
| 123 | + messages.push(choice.message); |
| 124 | + |
| 125 | + // Execute each tool call |
| 126 | + for (const toolCall of choice.message.tool_calls) { |
| 127 | + console.log(`LLM called: ${toolCall.function.name}(${toolCall.function.arguments})`); |
| 128 | + |
| 129 | + const tool = metaTools.getTool(toolCall.function.name); |
| 130 | + if (!tool) { |
| 131 | + messages.push({ |
| 132 | + role: 'tool', |
| 133 | + tool_call_id: toolCall.id, |
| 134 | + content: JSON.stringify({ error: `Unknown tool: ${toolCall.function.name}` }), |
| 135 | + }); |
| 136 | + continue; |
| 137 | + } |
| 138 | + |
| 139 | + const result = await tool.execute(toolCall.function.arguments); |
| 140 | + messages.push({ |
| 141 | + role: 'tool', |
| 142 | + tool_call_id: toolCall.id, |
| 143 | + content: JSON.stringify(result), |
| 144 | + }); |
| 145 | + } |
| 146 | + } |
| 147 | +}; |
| 148 | + |
| 149 | +// Main execution |
| 150 | +const main = async (): Promise<void> => { |
| 151 | + try { |
| 152 | + await metaToolsWithAISDK(); |
| 153 | + await metaToolsWithOpenAI(); |
| 154 | + } catch (error) { |
| 155 | + console.error('Error running examples:', error); |
| 156 | + } |
| 157 | +}; |
| 158 | + |
| 159 | +await main(); |
0 commit comments