| 1 | import { openai } from '@ai-sdk/openai'; |
| 2 | import { generateText, streamText } from 'ai'; |
| 3 | |
| 4 | const vapiOpenAI = openai({ |
| 5 | apiKey: 'YOUR_VAPI_API_KEY', |
| 6 | baseURL: 'https://api.vapi.ai/chat' |
| 7 | }); |
| 8 | |
| 9 | // Non-streaming text generation |
| 10 | async function generateWithVapi(prompt: string, assistantId: string): Promise<string> { |
| 11 | const response = await fetch('https://api.vapi.ai/chat/responses', { |
| 12 | method: 'POST', |
| 13 | headers: { |
| 14 | 'Authorization': `Bearer YOUR_VAPI_API_KEY`, |
| 15 | 'Content-Type': 'application/json' |
| 16 | }, |
| 17 | body: JSON.stringify({ |
| 18 | model: 'gpt-4o', |
| 19 | input: prompt, |
| 20 | assistantId: assistantId, |
| 21 | stream: false |
| 22 | }) |
| 23 | }); |
| 24 | |
| 25 | const data = await response.json(); |
| 26 | return data.output[0].content[0].text; |
| 27 | } |
| 28 | |
| 29 | // Streaming implementation |
| 30 | async function streamWithVapi(prompt: string, assistantId: string): Promise<void> { |
| 31 | const response = await fetch('https://api.vapi.ai/chat/responses', { |
| 32 | method: 'POST', |
| 33 | headers: { |
| 34 | 'Authorization': `Bearer YOUR_VAPI_API_KEY`, |
| 35 | 'Content-Type': 'application/json' |
| 36 | }, |
| 37 | body: JSON.stringify({ |
| 38 | model: 'gpt-4o', |
| 39 | input: prompt, |
| 40 | assistantId: assistantId, |
| 41 | stream: true |
| 42 | }) |
| 43 | }); |
| 44 | |
| 45 | const reader = response.body?.getReader(); |
| 46 | if (!reader) return; |
| 47 | |
| 48 | const decoder = new TextDecoder(); |
| 49 | |
| 50 | while (true) { |
| 51 | const { done, value } = await reader.read(); |
| 52 | if (done) break; |
| 53 | |
| 54 | const chunk = decoder.decode(value); |
| 55 | |
| 56 | // Parse and process SSE events |
| 57 | const lines = chunk.split('\n').filter(line => line.trim()); |
| 58 | for (const line of lines) { |
| 59 | if (line.startsWith('data: ')) { |
| 60 | try { |
| 61 | const event = JSON.parse(line.slice(6)); |
| 62 | if (event.path && event.delta) { |
| 63 | process.stdout.write(event.delta); |
| 64 | } |
| 65 | } catch (e) { |
| 66 | console.error('Invalid JSON line:', line); |
| 67 | continue; |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | // Usage examples |
| 75 | const text = await generateWithVapi( |
| 76 | "Explain the benefits of microservices architecture", |
| 77 | "your-assistant-id" |
| 78 | ); |
| 79 | console.log(text); |