|
| 1 | +import { |
| 2 | + ExperimentalMessage, |
| 3 | + ToolCallPart, |
| 4 | + ToolResultPart, |
| 5 | + experimental_streamText, |
| 6 | +} from 'ai'; |
| 7 | +import { google } from 'ai/google'; |
| 8 | +import dotenv from 'dotenv'; |
| 9 | +import * as readline from 'node:readline/promises'; |
| 10 | +import { weatherTool } from '../tools/weather-tool'; |
| 11 | + |
| 12 | +dotenv.config(); |
| 13 | + |
| 14 | +const terminal = readline.createInterface({ |
| 15 | + input: process.stdin, |
| 16 | + output: process.stdout, |
| 17 | +}); |
| 18 | + |
| 19 | +const messages: ExperimentalMessage[] = []; |
| 20 | + |
| 21 | +async function main() { |
| 22 | + let toolResponseAvailable = false; |
| 23 | + |
| 24 | + while (true) { |
| 25 | + if (!toolResponseAvailable) { |
| 26 | + const userInput = await terminal.question('You: '); |
| 27 | + messages.push({ role: 'user', content: userInput }); |
| 28 | + } |
| 29 | + |
| 30 | + const result = await experimental_streamText({ |
| 31 | + model: google.generativeAI('models/gemini-pro'), |
| 32 | + tools: { weatherTool }, |
| 33 | + system: `You are a helpful, respectful and honest assistant.`, |
| 34 | + messages, |
| 35 | + }); |
| 36 | + |
| 37 | + toolResponseAvailable = false; |
| 38 | + let fullResponse = ''; |
| 39 | + const toolCalls: ToolCallPart[] = []; |
| 40 | + const toolResponses: ToolResultPart[] = []; |
| 41 | + |
| 42 | + for await (const delta of result.fullStream) { |
| 43 | + switch (delta.type) { |
| 44 | + case 'text-delta': { |
| 45 | + if (fullResponse.length === 0) { |
| 46 | + process.stdout.write('\nAssistant: '); |
| 47 | + } |
| 48 | + |
| 49 | + fullResponse += delta.textDelta; |
| 50 | + process.stdout.write(delta.textDelta); |
| 51 | + break; |
| 52 | + } |
| 53 | + |
| 54 | + case 'tool-call': { |
| 55 | + toolCalls.push(delta); |
| 56 | + |
| 57 | + process.stdout.write( |
| 58 | + `\nTool call: '${delta.toolName}' ${JSON.stringify(delta.args)}`, |
| 59 | + ); |
| 60 | + break; |
| 61 | + } |
| 62 | + |
| 63 | + case 'tool-result': { |
| 64 | + toolResponses.push(delta); |
| 65 | + |
| 66 | + process.stdout.write( |
| 67 | + `\nTool response: '${delta.toolName}' ${JSON.stringify( |
| 68 | + delta.result, |
| 69 | + )}`, |
| 70 | + ); |
| 71 | + break; |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + process.stdout.write('\n\n'); |
| 76 | + |
| 77 | + messages.push({ |
| 78 | + role: 'assistant', |
| 79 | + content: [{ type: 'text', text: fullResponse }, ...toolCalls], |
| 80 | + }); |
| 81 | + |
| 82 | + if (toolResponses.length > 0) { |
| 83 | + messages.push({ role: 'tool', content: toolResponses }); |
| 84 | + } |
| 85 | + |
| 86 | + toolResponseAvailable = toolCalls.length > 0; |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +main().catch(console.error); |
0 commit comments