|
| 1 | +import { ExperimentalMessage, experimental_generateText } from 'ai'; |
| 2 | +import { anthropic } from 'ai/anthropic'; |
| 3 | +import dotenv from 'dotenv'; |
| 4 | +import * as readline from 'node:readline/promises'; |
| 5 | +import { weatherTool } from '../tools/weather-tool'; |
| 6 | + |
| 7 | +dotenv.config(); |
| 8 | + |
| 9 | +const terminal = readline.createInterface({ |
| 10 | + input: process.stdin, |
| 11 | + output: process.stdout, |
| 12 | +}); |
| 13 | + |
| 14 | +const messages: ExperimentalMessage[] = []; |
| 15 | + |
| 16 | +async function main() { |
| 17 | + let toolResponseAvailable = false; |
| 18 | + |
| 19 | + while (true) { |
| 20 | + if (!toolResponseAvailable) { |
| 21 | + const userInput = await terminal.question('You: '); |
| 22 | + messages.push({ role: 'user', content: userInput }); |
| 23 | + } |
| 24 | + |
| 25 | + const { text, toolCalls, toolResults } = await experimental_generateText({ |
| 26 | + model: anthropic.messages('claude-3-opus-20240229'), |
| 27 | + tools: { weatherTool }, |
| 28 | + system: `You are a helpful, respectful and honest assistant.`, |
| 29 | + messages, |
| 30 | + }); |
| 31 | + |
| 32 | + toolResponseAvailable = false; |
| 33 | + |
| 34 | + if (text) { |
| 35 | + process.stdout.write(`\nAssistant: ${text}`); |
| 36 | + } |
| 37 | + |
| 38 | + for (const { toolName, args } of toolCalls) { |
| 39 | + process.stdout.write( |
| 40 | + `\nTool call: '${toolName}' ${JSON.stringify(args)}`, |
| 41 | + ); |
| 42 | + } |
| 43 | + |
| 44 | + for (const { toolName, result } of toolResults) { |
| 45 | + process.stdout.write( |
| 46 | + `\nTool response: '${toolName}' ${JSON.stringify(result)}`, |
| 47 | + ); |
| 48 | + } |
| 49 | + |
| 50 | + process.stdout.write('\n\n'); |
| 51 | + |
| 52 | + messages.push({ |
| 53 | + role: 'assistant', |
| 54 | + content: [{ type: 'text', text }, ...(toolCalls ?? [])], |
| 55 | + }); |
| 56 | + |
| 57 | + if (toolResults.length > 0) { |
| 58 | + messages.push({ role: 'tool', content: toolResults }); |
| 59 | + } |
| 60 | + |
| 61 | + toolResponseAvailable = toolCalls.length > 0; |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +main().catch(console.error); |
0 commit comments