generateText client-side POST request pattern
To use generateText on the server, create a route handler that accepts a POST request with the prompt in the JSON body. Call generateText with the appropriate model and prompt parameters, then return the text property as JSON to the client.
generateText server-side example with OpenAI
const { text } = await generateText({ model: 'openai/gpt-4o', system: 'You are a helpful assistant.', prompt });
This example shows generateText configured with OpenAI's gpt-4o model, a system prompt providing instructions, and a user prompt. The destructured text property contains the generated response.
generateText model parameter format
The model parameter uses the format 'provider/model-id', for example 'openai/gpt-4o'. This specifies both which AI provider to use and which specific model variant from that provider.
generateText function basic usage with Next.js
The generateText function is imported from the 'ai' module and generates text based on an input prompt. It accepts an object parameter with at minimum: model (string), system (string for system prompt), and prompt (string). It returns an object with a text property containing the generated response.
generateText returns responseMessages for chat-based generation
When generateText is called with a messages parameter for chat completion, it returns an object containing a responseMessages field. This field contains the generated assistant response as part of the conversation history.
ModelMessage type structure for chat prompts
The ModelMessage type has a role field (which can be 'user', 'assistant', or other system roles) and a content field that can be either a string or an array of content parts with type and text properties.
Chat completion example with OpenAI gpt-4o model
const { responseMessages } = await generateText({ model: 'openai/gpt-4o', system: 'You are a helpful assistant.', messages });
streamText function with tools and stopWhen parameter
The streamText function from the ai module accepts a configuration object with model, system, messages, stopWhen, and tools parameters. The model parameter takes a string like 'openai/gpt-4o'. The messages are converted using convertToModelMessages. The stopWhen parameter can use isStepCount(n) to allow multiple consecutive tool calls up to n steps. The tools parameter accepts a ToolSet object containing tool definitions.
Tool schema example with multiple parameters
A tool's inputSchema can define multiple parameters using zod. For example, the getWeather tool uses z.object with city as z.string().describe('The city to get the weather for') and unit as z.enum(['C', 'F']).describe('The unit to display the temperature in'). Each field can have its own type and description.
Multi-step tool calling workflow
To enable a model to call tools in multiple sequential steps during the same generation, use the stopWhen parameter with isStepCount(5) to allow up to 5 tool calls. This is useful when tools are dependent on each other and need to be executed in sequence. The model will automatically determine when to call each tool based on the conversation context and previous tool results.
Converting AI SDK types for type safety
Use InferUITools to extract the tool type from a ToolSet definition for TypeScript type safety. Use UIMessage<never, UIDataTypes, ChatTools> to define message types that include tool information. This allows TypeScript to validate message structures and tool interactions at compile time.
Image content format in generateText messages
Images can be included in the content array of a message with type 'file', specifying mediaType as 'image', and providing the image data as a URL using the data property with a new URL() constructor.
generateText with image and tool use example
The generateText function can accept images as part of the message content array and simultaneously use tools. Images are included as content objects with type 'file', mediaType 'image', and a URL data source. Tools are defined in the tools parameter as an object with tool names as keys. The example shows a logFood tool that accepts name (string) and calories (number) parameters via Zod schema.
Tool definition structure in generateText
Tools in generateText are defined as an object where each key is a tool name. Each tool is created with the tool() function, accepting a description string, an inputSchema defined with Zod, and an execute function that receives the input parameters.
Multi-step tool calls with stopWhen and isStepCount
Enable multi-step tool calls in generateText by defining stopping conditions with stopWhen. You can use isStepCount to define the conditions for which an agent should stop when the model generates a tool call. The example shows stopWhen: isStepCount(5) to stop after 5 steps.
generateText returns text and steps properties
The generateText function returns an object containing text and steps properties. The steps property contains information about each step of tool execution in multi-step agent scenarios.
tools parameter in generateText accepts object with named tool definitions
The tools parameter in generateText accepts an object where keys are tool names and values are tool definitions created with the tool function. Tools are identified by their name in the object.
Multi-step tool use example with weather tool
Example showing multi-step tool use: generateText is called with model 'openai/gpt-4.1', stopWhen: isStepCount(5), a weather tool that takes a location parameter and returns temperature data, and a prompt asking about San Francisco weather. The function returns both text and steps.
isStepCount import from 'ai' package
The isStepCount function is imported from the 'ai' package and is used with stopWhen to define stopping conditions based on the number of steps in multi-step tool execution.
generateText basic usage pattern
The generateText function accepts a model and prompt parameter, and returns an object with a text property containing the generated response.
streamText function for server-side text generation
The streamText function from the 'ai' module accepts a model parameter (e.g., 'openai/gpt-4o'), a system prompt string, and messages array. It returns an object with a stream property containing the streamed response. Use convertToModelMessages to transform UIMessage objects into model-compatible format before passing to streamText.
convertToModelMessages function
The convertToModelMessages function is imported from the 'ai' package and converts UI messages to model-compatible message format. It is used as an async function: messages: await convertToModelMessages(messages).
streamText function for PDF processing with Anthropic
The streamText function can process messages and PDFs using Anthropic's Claude model. It accepts a model parameter (e.g., 'anthropic/claude-sonnet-4') and messages converted via convertToModelMessages.
convertToModelMessages function usage
convertToModelMessages is used to convert UIMessage objects from the client into the format expected by the model for processing.
Complete PDF chat route handler implementation
Server-side implementation for PDF chat:
```tsx
import {
convertToModelMessages,
createUIMessageStreamResponse,
streamText,
toUIMessageStream,
type UIMessage,
} from 'ai';
export async function POST(req: Request) {
const { messages }: { messages: UIMessage[] } = await req.json();
const result = streamText({
model: 'anthropic/claude-sonnet-4',
messages: await convertToModelMessages(messages),
});
return createUIMessageStreamResponse({
stream: toUIMessageStream({ stream: result.stream }),
});
}
```
generateText function signature for file inputs
The generateText function accepts a configuration object with model (string), messages (array of message objects), and output (structured output definition) parameters. Each message object has a role and content field. Content can be an array of objects with type 'text' or 'file', where text objects have a text field and file objects have data (base64 URL) and mediaType fields.
File type in message content for PDF prompts
When sending PDFs in prompts, use a message content object with type 'file', a data field containing a base64-encoded data URL in the format 'data:application/pdf;base64,{base64Data}', and mediaType set to 'application/pdf'.
Generate object with structured output example
The following example shows how to use generateText with Output.object to generate structured output from a PDF:
```typescript
import { generateText, Output } from 'ai';
import { z } from 'zod';
const result = await generateText({
model: 'openai/gpt-4o',
messages: [
{
role: 'user',
content: [
{
type: 'text',
text: 'Analyze the following PDF and generate a summary.',
},
{
type: 'file',
data: fileDataUrl,
mediaType: 'application/pdf',
},
],
},
],
output: Output.object({
schema: z.object({
people: z
.object({
name: z.string().describe('The name of the person.'),
age: z.number().min(0).describe('The age of the person.'),
})
.array()
.describe('An array of people.'),
}),
}),
});
```
This example sends a PDF to OpenAI's gpt-4o model and generates a structured JSON object containing an array of people with name and age fields.
Converting file to base64 data URL for PDF prompts
To convert a PDF File object to a base64 data URL for use in prompts: (1) obtain the file's ArrayBuffer via arrayBuffer(), (2) convert to Uint8Array, (3) convert to binary string using String.fromCharCode, (4) encode to base64 using btoa(), and (5) prepend 'data:application/pdf;base64,' to create the final data URL.
generateText function with chat prompt example
The generateText function accepts a messages array parameter to generate text based on a series of chat interactions. The example shows calling generateText with model 'openai/gpt-4o', maxOutputTokens set to 1024, a system prompt 'You are a helpful chatbot.', and an array of message objects. Each message has a role ('user' or 'assistant') and content array containing objects with type 'text' and text property. The function returns a result object with a text property containing the generated response.
generateText messages parameter format
The messages parameter in generateText accepts an array of message objects. Each message object must have a role property (either 'user' or 'assistant') and a content property which is an array of content objects. Each content object must have a type property (such as 'text') and a corresponding data property (such as text for type 'text').
generateText maxOutputTokens parameter
The generateText function accepts a maxOutputTokens parameter to limit the maximum number of tokens in the generated output. In the example, maxOutputTokens is set to 1024.
generateText system prompt parameter
The generateText function accepts a system parameter to provide a system prompt that instructs the model's behavior. The system prompt is provided as a string separate from the messages array.
Chat completion use case for generateText
A chat completion allows generating text based on a series of messages representing interactions between systems. The most common use case is a series of messages representing a conversation between a user and a model, where the generateText function can process this conversation history to generate appropriate responses.
File content in AI SDK messages
Messages can include file content alongside text by using the content array format. Each item in the content array can have type 'text' or type 'file'. File items must include data (buffer), mediaType (string), and are useful for document analysis, data extraction, and other file-based tasks.
tool function definition with description, inputSchema, and execute
Define tools using the tool function with three properties: description (a string describing what the tool does), inputSchema (a Zod schema defining the input parameters using z.object with typed fields), and execute (an async function that receives the validated input parameters and returns a string result). Individual schema fields can have describe() method for additional documentation. The execute property performs the tool action and returns the result based on the parsed input according to inputSchema.
Repair malformed JSON with generateText and jsonrepair
The pattern to repair malformed JSON in AI SDK v6 is: (1) generate plain text from the model using Output.text(), (2) repair malformed JSON with jsonrepair(result.text), (3) parse safely and validate with safeParseJSON and schema validation. Example code: const result = await generateText({ model: __MODEL__, output: Output.text(), prompt: 'Generate a lasagna recipe.' }); const repairedText = jsonrepair(result.text); const parseResult = safeParseJSON({ text: repairedText }); if (!parseResult.success) { throw parseResult.error; } const output = recipeSchema.parse(parseResult.value);
generateText function accepts messages parameter for chat completion
The generateText function accepts a messages parameter which is an array of message objects with role and content properties. This allows generating text based on a series of messages representing a conversation, rather than just a single prompt or system prompt.
Chat message object structure: role and content
Chat messages passed to generateText use an object structure with two properties: role (which can be 'user' or 'assistant') and content (a string containing the message text).
generateText returns text property
The generateText function returns an object with a text property containing the generated response text.
generateText accepts model, system, and messages parameters
The generateText function accepts at minimum three parameters: model (a string identifier like 'openai/gpt-5.4'), system (a system prompt string), and messages (an array of message objects).
Example: generateText with chat prompt for conversation
import { generateText } from 'ai';
export interface Message {
role: 'user' | 'assistant';
content: string;
}
export async function continueConversation(history: Message[]) {
'use server';
const { text } = await generateText({
model: 'openai/gpt-5.4',
system: 'You are a friendly assistant!',
messages: history,
});
return {
messages: [
...history,
{
role: 'assistant' as const,
content: text,
},
],
};
}
This example shows how to implement a server action that generates text based on a conversation history, appending both the user message and the generated assistant response to maintain the conversation state.
generateText function for non-interactive text generation
The generateText function generates text and tool calls. It is ideal for non-interactive use cases such as automation tasks where you need to write text (for example drafting emails or summarizing web pages) and for agents that use tools.
generateText and streamText support structured output
Both generateText and streamText functions support structured output via the output property (for example Output.object(), Output.array()), allowing generation of typed, schema-validated data for information extraction, synthetic data generation, classification tasks, and streaming generated UIs.
generateText function is part of the AI SDK
The generateText function is imported from the 'ai' package, which is the Vercel AI SDK. This function provides a unified interface for text generation across different providers.
generateText function generates text from a prompt
The generateText function takes a model identifier and a prompt string, and returns the generated text. It is called with model 'openai/gpt-4o' and a prompt string, returning { text } where text is the generated response.
generateText with provider registry language model
Use generateText with model: registry.languageModel('openai:gpt-5.1') to generate text using a language model accessed from a provider registry.
AssistantModelMessage type definition
AssistantModelMessage has role 'assistant' and content property of type AssistantContent, which is either a string or an array of TextPart, CustomPart, or ToolCallPart. The Zod schema can be accessed via assistantModelMessageSchema export.
SystemModelMessage type definition
SystemModelMessage has role 'system' and content property of type string. The Zod schema can be accessed via systemModelMessageSchema export. System messages in prompt or messages fields are rejected by default unless allowSystemInMessages is set to true. The top-level instructions property should be used instead of a system message for system instructions, as opting in to allowSystemInMessages can create a prompt injection risk if users can inject system messages.
UserModelMessage type definition
UserModelMessage has role 'user' and content property of type UserContent, which is either a string or an array of TextPart, ImagePart, or FilePart. The Zod schema can be accessed via userModelMessageSchema export.
CustomPart structure
CustomPart has type 'custom', a kind property in the format '{provider}.{provider-type}' that identifies the content type, and an optional providerOptions property for provider-specific metadata.
ModelMessage Zod schema export
The Zod schema for ModelMessage can be accessed with the modelMessageSchema export.
TextPart structure
TextPart has type 'text' and a text property containing a string of text content.
ImagePart is deprecated
ImagePart is deprecated and should be replaced with FilePart using mediaType: 'image' or a more specific image/* subtype.
FilePart structure
FilePart has type 'file', data property (FileData | DataContent | URL | ProviderReference), optional filename property, and required mediaType property that is either a full IANA media type (type/subtype, e.g. image/png) or just the top-level IANA segment (e.g. image, audio, video, text). FileData can be: {type: 'data'; data: DataContent}, {type: 'url'; url: URL}, {type: 'reference'; reference: ProviderReference}, or {type: 'text'; text: string}.
streamText function signature includes model and messages parameters
The streamText function accepts an object with model (string identifier like 'openai/gpt-4.1') and messages (array of converted model messages) parameters.
streamText function with tools parameter
The streamText function from ai accepts a tools parameter containing a ToolSet object. It also accepts stopWhen parameter (e.g., isStepCount(5)) to control stream termination. The function returns a result object with a stream property.