This quickstart guide will walk you through building your first AI application using the AI SDK. You’ll learn how to generate text, stream responses, and create structured outputs.
Let’s start with the most basic example - generating text from a prompt.Create a file called generate-text.ts:
import { generateText } from 'ai';import { openai } from '@ai-sdk/openai';const result = await generateText({ model: openai('gpt-4o'), prompt: 'Invent a new holiday and describe its traditions.',});console.log(result.text);console.log('Usage:', result.usage);console.log('Finish reason:', result.finishReason);
For longer responses, streaming provides a better user experience by showing results as they’re generated.Create a file called stream-text.ts:
import { streamText } from 'ai';import { openai } from '@ai-sdk/openai';const result = streamText({ model: openai('gpt-4o'), prompt: 'Invent a new holiday and describe its traditions.',});// Stream the textfor await (const chunk of result.textStream) { process.stdout.write(chunk);}console.log('\n\nUsage:', await result.usage);console.log('Finish reason:', await result.finishReason);
If you prefer using the Vercel AI Gateway instead of direct provider packages:
import { generateText } from 'ai';// No provider import needed - gateway is included in 'ai'const result = await generateText({ model: 'openai/gpt-4o', // Use string format: 'provider/model' prompt: 'What is an agent?',});console.log(result.text);