Large language models (LLMs) generate text in response to prompts containing instructions and information. The AI SDK Core provides two primary functions for text generation:
Use system messages to set the behavior and context for the model:
const { text } = await generateText({ model: openai('gpt-5'), system: 'You are a professional writer. You write simple, clear, and concise content.', prompt: 'Summarize the following article in 3-5 sentences: ${article}',});
import { generateText } from 'ai';import { openai } from '@ai-sdk/openai';const { text } = await generateText({ model: openai('gpt-5'), messages: [ { role: 'user', content: 'Hi, my name is Alice.' }, { role: 'assistant', content: 'Hello Alice! How can I help you today?' }, { role: 'user', content: 'What is my name?' }, ],});console.log(text); // "Your name is Alice."
const result = await generateText({ model: openai('gpt-5'), prompt: 'Invent a new holiday and describe its traditions.', onFinish({ text, finishReason, usage }) { // Save to database, log usage, etc. console.log('Generated text:', text); console.log('Tokens used:', usage.totalTokens); },});
import { streamText } from 'ai';import { openai } from '@ai-sdk/openai';const result = streamText({ model: openai('gpt-5'), prompt: 'Write a short story about a robot learning to paint.',});// Stream as an async iterablefor await (const textPart of result.textStream) { process.stdout.write(textPart);}
For advanced use cases, access all stream events with fullStream:
import { streamText } from 'ai';import { openai } from '@ai-sdk/openai';const result = streamText({ model: openai('gpt-5'), prompt: 'Tell me about the solar system',});for await (const part of result.fullStream) { switch (part.type) { case 'text-delta': process.stdout.write(part.text); break; case 'finish': console.log('\nFinish reason:', part.finishReason); break; }}
import { generateText } from 'ai';import { openai } from '@ai-sdk/openai';const { text } = await generateText({ model: openai('gpt-5'), system: 'You are a professional email writer. Write clear, concise emails.', prompt: `Write a follow-up email to a client about project status. Context: The redesign project is 80% complete and on track for next week's deadline.`,});console.log(text);
import { streamText } from 'ai';import { openai } from '@ai-sdk/openai';const messages = [ { role: 'user', content: 'What are some good books about AI?' },];const result = streamText({ model: openai('gpt-5'), messages,});// Display text as it streamsfor await (const chunk of result.textStream) { process.stdout.write(chunk);}// Add response to conversationconst response = await result.response;messages.push(...response.messages);