Generating Text
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:generateText: Generates text in a single requeststreamText: Streams text as it’s generated
generateText
UsegenerateText for non-interactive use cases where you need the complete response before proceeding. This is ideal for:
- Batch processing
- Email drafting
- Content summarization
- Agents that use tools
Basic Usage
System Messages
Use system messages to set the behavior and context for the model:Multi-Turn Conversations
For conversations, use themessages array:
Result Object
ThegenerateText function returns a comprehensive result object:
Result Properties
string
The generated text content
Array<ContentPart>
The structured content including text and tool calls
'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'
The reason the model stopped generating
object
Token usage information:
promptTokens: Tokens in the promptcompletionTokens: Tokens in the completiontotalTokens: Total tokens used
object
Response metadata including:
id: Response IDmodelId: Model usedtimestamp: Response timestampmessages: Generated messagesheaders: HTTP response headers
onFinish Callback
Execute code when generation completes:streamText
UsestreamText for interactive applications where you want to display text as it’s generated. This provides a better user experience for:
- Chatbots
- Real-time content generation
- Interactive assistants
Basic Usage
Text Stream
ThetextStream property is both a ReadableStream and an AsyncIterable:
Full Stream
For advanced use cases, access all stream events withfullStream:
Stream Event Types
start: Stream beginstext-delta: New text chunktext-end: Text generation completetool-call: Model called a tooltool-result: Tool execution resultfinish: Stream completeerror: An error occurred
Promises
streamText provides promises that resolve when streaming completes:
Callbacks
onChunk
Process each chunk as it arrives:onFinish
Execute code when streaming completes:onError
Handle errors in the stream:Common Parameters
BothgenerateText and streamText support these parameters:
LanguageModel
required
The language model to use (e.g.,
openai('gpt-5'))string
Simple text prompt (cannot be used with
messages)Array<Message>
Array of conversation messages
string
System message to set model behavior
number
Maximum number of tokens to generate
number
Randomness in generation (0 = deterministic, higher = more random)
object
Tools the model can use (see Tool Calling)
Output
Structured output specification (see Structured Data)
Examples
Email Draft Generator
Interactive Chatbot
Next Steps
Structured Data
Generate type-safe structured data
Tool Calling
Enable models to use tools
Settings
Configure generation parameters
Prompt Engineering
Write effective prompts