📄 ai-sdk/docs/reference/ai-sdk-core/generate-text

File: generate-text.md | Updated: 11/15/2025

Source: https://ai-sdk.dev/docs/reference/ai-sdk-core/generate-text

AI SDK

Menu

v5 (Latest)

AI SDK 5.x

AI SDK by Vercel

AI SDK 6 Beta

Foundations

Overview

Providers and Models

Prompts

Tools

Streaming

Getting Started

Navigating the Library

Next.js App Router

Next.js Pages Router

Svelte

Vue.js (Nuxt)

Node.js

Expo

Agents

Agents

Building Agents

Workflow Patterns

Loop Control

AI SDK Core

Overview

Generating Text

Generating Structured Data

Tool Calling

Model Context Protocol (MCP) Tools

Prompt Engineering

Settings

Embeddings

Image Generation

Transcription

Speech

Language Model Middleware

Provider & Model Management

Error Handling

Testing

Telemetry

AI SDK UI

Overview

Chatbot

Chatbot Message Persistence

Chatbot Resume Streams

Chatbot Tool Usage

Generative User Interfaces

Completion

Object Generation

Streaming Custom Data

Error Handling

Transport

Reading UIMessage Streams

Message Metadata

Stream Protocols

AI SDK RSC

Advanced

Reference

AI SDK Core

generateText

streamText

generateObject

streamObject

embed

embedMany

generateImage

transcribe

generateSpeech

tool

dynamicTool

experimental_createMCPClient

Experimental_StdioMCPTransport

jsonSchema

zodSchema

valibotSchema

ModelMessage

UIMessage

validateUIMessages

safeValidateUIMessages

createProviderRegistry

customProvider

cosineSimilarity

wrapLanguageModel

LanguageModelV2Middleware

extractReasoningMiddleware

simulateStreamingMiddleware

defaultSettingsMiddleware

stepCountIs

hasToolCall

simulateReadableStream

smoothStream

generateId

createIdGenerator

AI SDK UI

AI SDK RSC

Stream Helpers

AI SDK Errors

Migration Guides

Troubleshooting

Copy markdown

generateText()

=============================================================================================

Generates text and calls tools for a given prompt using a language model.

It is ideal for non-interactive use cases such as automation tasks where you need to write text (e.g. drafting email or summarizing web pages) and for agents that use tools.

import { openai } from '@ai-sdk/openai';import { generateText } from 'ai';
const { text } = await generateText({  model: openai('gpt-4o'),  prompt: 'Invent a new holiday and describe its traditions.',});
console.log(text);

To see generateText in action, check out these examples .

Import


import { generateText } from "ai"

API Signature


Parameters

model:

LanguageModel

The language model to use. Example: openai('gpt-4o')

system:

string

The system prompt to use that specifies the behavior of the model.

prompt:

string | Array<SystemModelMessage | UserModelMessage | AssistantModelMessage | ToolModelMessage>

The input prompt to generate the text from.

messages:

Array<SystemModelMessage | UserModelMessage | AssistantModelMessage | ToolModelMessage>

A list of messages that represent a conversation. Automatically converts UI messages from the useChat hook.

SystemModelMessage

role:

'system'

The role for the system message.

content:

string

The content of the message.

UserModelMessage

role:

'user'

The role for the user message.

content:

string | Array<TextPart | ImagePart | FilePart>

The content of the message.

TextPart

type:

'text'

The type of the message part.

text:

string

The text content of the message part.

ImagePart

type:

'image'

The type of the message part.

image:

string | Uint8Array | Buffer | ArrayBuffer | URL

The image content of the message part. String are either base64 encoded content, base64 data URLs, or http(s) URLs.

mediaType?:

string

The IANA media type of the image. Optional.

FilePart

type:

'file'

The type of the message part.

data:

string | Uint8Array | Buffer | ArrayBuffer | URL

The file content of the message part. String are either base64 encoded content, base64 data URLs, or http(s) URLs.

mediaType:

string

The IANA media type of the file.

AssistantModelMessage

role:

'assistant'

The role for the assistant message.

content:

string | Array<TextPart | FilePart | ReasoningPart | ToolCallPart>

The content of the message.

TextPart

type:

'text'

The type of the message part.

text:

string

The text content of the message part.

ReasoningPart

type:

'reasoning'

The type of the message part.

text:

string

The reasoning text.

FilePart

type:

'file'

The type of the message part.

data:

string | Uint8Array | Buffer | ArrayBuffer | URL

The file content of the message part. String are either base64 encoded content, base64 data URLs, or http(s) URLs.

mediaType:

string

The IANA media type of the file.

filename?:

string

The name of the file.

ToolCallPart

type:

'tool-call'

The type of the message part.

toolCallId:

string

The id of the tool call.

toolName:

string

The name of the tool, which typically would be the name of the function.

input:

object based on zod schema

Input (parameters) generated by the model to be used by the tool.

ToolModelMessage

role:

'tool'

The role for the assistant message.

content:

Array<ToolResultPart>

The content of the message.

ToolResultPart

type:

'tool-result'

The type of the message part.

toolCallId:

string

The id of the tool call the result corresponds to.

toolName:

string

The name of the tool the result corresponds to.

output:

unknown

The result returned by the tool after execution.

isError?:

boolean

Whether the result is an error or an error message.

tools:

ToolSet

Tools that are accessible to and can be called by the model. The model needs to support calling tools.

Tool

description?:

string

Information about the purpose of the tool including details on how and when it can be used by the model.

inputSchema:

Zod Schema | JSON Schema

The schema of the input that the tool expects. The language model will use this to generate the input. It is also used to validate the output of the language model. Use descriptions to make the input understandable for the language model. You can either pass in a Zod schema or a JSON schema (using the `jsonSchema` function).

execute?:

async (parameters: T, options: ToolExecutionOptions) => RESULT

An async function that is called with the arguments from the tool call and produces a result. If not provided, the tool will not be executed automatically.

ToolExecutionOptions

toolCallId:

string

The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.

messages:

ModelMessage[]

Messages that were sent to the language model to initiate the response that contained the tool call. The messages do not include the system prompt nor the assistant response that contained the tool call.

abortSignal:

AbortSignal

An optional abort signal that indicates that the overall operation should be aborted.

toolChoice?:

"auto" | "none" | "required" | { "type": "tool", "toolName": string }

The tool choice setting. It specifies how tools are selected for execution. The default is "auto". "none" disables tool execution. "required" requires tools to be executed. { "type": "tool", "toolName": string } specifies a specific tool to execute.

maxOutputTokens?:

number

Maximum number of tokens to generate.

temperature?:

number

Temperature setting. The value is passed through to the provider. The range depends on the provider and model. It is recommended to set either `temperature` or `topP`, but not both.

topP?:

number

Nucleus sampling. The value is passed through to the provider. The range depends on the provider and model. It is recommended to set either `temperature` or `topP`, but not both.

topK?:

number

Only sample from the top K options for each subsequent token. Used to remove "long tail" low probability responses. Recommended for advanced use cases only. You usually only need to use temperature.

presencePenalty?:

number

Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt. The value is passed through to the provider. The range depends on the provider and model.

frequencyPenalty?:

number

Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases. The value is passed through to the provider. The range depends on the provider and model.

stopSequences?:

string[]

Sequences that will stop the generation of the text. If the model generates any of these sequences, it will stop generating further text.

seed?:

number

The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results.

maxRetries?:

number

Maximum number of retries. Set to 0 to disable retries. Default: 2.

abortSignal?:

AbortSignal

An optional abort signal that can be used to cancel the call.

headers?:

Record<string, string>

Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.

experimental_telemetry?:

TelemetrySettings

Telemetry configuration. Experimental feature.

TelemetrySettings

isEnabled?:

boolean

Enable or disable telemetry. Disabled by default while experimental.

recordInputs?:

boolean

Enable or disable input recording. Enabled by default.

recordOutputs?:

boolean

Enable or disable output recording. Enabled by default.

functionId?:

string

Identifier for this function. Used to group telemetry data by function.

metadata?:

Record<string, string | number | boolean | Array<null | undefined | string> | Array<null | undefined | number> | Array<null | undefined | boolean>>

Additional information to include in the telemetry data.

providerOptions?:

Record<string,Record<string,JSONValue>> | undefined

Provider-specific options. The outer key is the provider name. The inner values are the metadata. Details depend on the provider.

activeTools?:

Array<TOOLNAME>

Limits the tools that are available for the model to call without changing the tool call and result types in the result. All tools are active by default.

stopWhen?:

StopCondition<TOOLS> | Array<StopCondition<TOOLS>>

Condition for stopping the generation when there are tool results in the last step. When the condition is an array, any of the conditions can be met to stop the generation. Default: stepCountIs(1).

prepareStep?:

(options: PrepareStepOptions) => PrepareStepResult<TOOLS> | Promise<PrepareStepResult<TOOLS>>

Optional function that you can use to provide different settings for a step. You can modify the model, tool choices, active tools, system prompt, and input messages for each step.

PrepareStepFunction<TOOLS>

options:

object

The options for the step.

PrepareStepOptions

steps:

Array<StepResult<TOOLS>>

The steps that have been executed so far.

stepNumber:

number

The number of the step that is being executed.

model:

LanguageModel

The model that is being used.

messages:

Array<ModelMessage>

The messages that will be sent to the model for the current step.

PrepareStepResult<TOOLS>

model?:

LanguageModel

Change the model for this step.

toolChoice?:

ToolChoice<TOOLS>

Change the tool choice strategy for this step.

activeTools?:

Array<keyof TOOLS>

Change which tools are active for this step.

system?:

string

Change the system prompt for this step.

messages?:

Array<ModelMessage>

Modify the input messages for this step.

experimental_context?:

unknown

Context that is passed into tool execution. Experimental (can break in patch releases).

experimental_download?:

(requestedDownloads: Array<{ url: URL; isUrlSupportedByModel: boolean }>) => Promise<Array<null | { data: Uint8Array; mediaType?: string }>>

Custom download function to control how URLs are fetched when they appear in prompts. By default, files are downloaded if the model does not support the URL for the given media type. Experimental feature. Return null to pass the URL directly to the model (when supported), or return downloaded content with data and media type.

experimental_repairToolCall?:

(options: ToolCallRepairOptions) => Promise<LanguageModelV2ToolCall | null>

A function that attempts to repair a tool call that failed to parse. Return either a repaired tool call or null if the tool call cannot be repaired.

ToolCallRepairOptions

system:

string | undefined

The system prompt.

messages:

ModelMessage[]

The messages in the current generation step.

toolCall:

LanguageModelV2ToolCall

The tool call that failed to parse.

tools:

TOOLS

The tools that are available.

parameterSchema:

(options: { toolName: string }) => JSONSchema7

A function that returns the JSON Schema for a tool.

error:

NoSuchToolError | InvalidToolInputError

The error that occurred while parsing the tool call.

experimental_output?:

Output

Experimental setting for generating structured outputs.

Output

Output.text():

Output

Forward text output.

Output.object():

Output

Generate a JSON object of type OBJECT.

Options

schema:

Schema<OBJECT>

The schema of the JSON object to generate.

onStepFinish?:

(result: OnStepFinishResult) => Promise<void> | void

Callback that is called when a step is finished.

OnStepFinishResult

finishReason:

"stop" | "length" | "content-filter" | "tool-calls" | "error" | "other" | "unknown"

The reason the model finished generating the text for the step.

usage:

LanguageModelUsage

The token usage of the step.

LanguageModelUsage

inputTokens:

number | undefined

The number of input (prompt) tokens used.

outputTokens:

number | undefined

The number of output (completion) tokens used.

totalTokens:

number | undefined

The total number of tokens as reported by the provider. This number might be different from the sum of inputTokens and outputTokens and e.g. include reasoning tokens or other overhead.

reasoningTokens?:

number | undefined

The number of reasoning tokens used.

cachedInputTokens?:

number | undefined

The number of cached input tokens.

text:

string

The full text that has been generated.

toolCalls:

ToolCall[]

The tool calls that have been executed.

toolResults:

ToolResult[]

The tool results that have been generated.

warnings:

Warning[] | undefined

Warnings from the model provider (e.g. unsupported settings).

response?:

Response

Response metadata.

Response

id:

string

The response identifier. The AI SDK uses the ID from the provider response when available, and generates an ID otherwise.

modelId:

string

The model that was used to generate the response. The AI SDK uses the response model from the provider response when available, and the model from the function call otherwise.

timestamp:

Date

The timestamp of the response. The AI SDK uses the response timestamp from the provider response when available, and creates a timestamp otherwise.

headers?:

Record<string, string>

Optional response headers.

body?:

unknown

Optional response body.

isContinued:

boolean

True when there will be a continuation step with a continuation text.

providerMetadata?:

Record<string,Record<string,JSONValue>> | undefined

Optional metadata from the provider. The outer key is the provider name. The inner values are the metadata. Details depend on the provider.

Returns

content:

Array<ContentPart<TOOLS>>

The content that was generated in the last step.

text:

string

The generated text by the model.

reasoning:

Array<ReasoningOutput>

The full reasoning that the model has generated in the last step.

ReasoningOutput

type:

'reasoning'

The type of the message part.

text:

string

The reasoning text.

providerMetadata?:

SharedV2ProviderMetadata

Additional provider metadata for the source.

reasoningText:

string | undefined

The reasoning text that the model has generated in the last step. Can be undefined if the model has only generated text.

sources:

Array<Source>

Sources that have been used as input to generate the response. For multi-step generation, the sources are accumulated from all steps.

Source

sourceType:

'url'

A URL source. This is return by web search RAG models.

id:

string

The ID of the source.

url:

string

The URL of the source.

title?:

string

The title of the source.

providerMetadata?:

SharedV2ProviderMetadata

Additional provider metadata for the source.

files:

Array<GeneratedFile>

Files that were generated in the final step.

GeneratedFile

base64:

string

File as a base64 encoded string.

uint8Array:

Uint8Array

File as a Uint8Array.

mediaType:

string

The IANA media type of the file.

toolCalls:

ToolCallArray<TOOLS>

The tool calls that were made in the last step.

toolResults:

ToolResultArray<TOOLS>

The results of the tool calls from the last step.

finishReason:

'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'

The reason the model finished generating the text.

usage:

LanguageModelUsage

The token usage of the last step.

LanguageModelUsage

inputTokens:

number | undefined

The number of input (prompt) tokens used.

outputTokens:

number | undefined

The number of output (completion) tokens used.

totalTokens:

number | undefined

The total number of tokens as reported by the provider. This number might be different from the sum of inputTokens and outputTokens and e.g. include reasoning tokens or other overhead.

reasoningTokens?:

number | undefined

The number of reasoning tokens used.

cachedInputTokens?:

number | undefined

The number of cached input tokens.

totalUsage:

CompletionTokenUsage

The total token usage of all steps. When there are multiple steps, the usage is the sum of all step usages.

LanguageModelUsage

inputTokens:

number | undefined

The number of input (prompt) tokens used.

outputTokens:

number | undefined

The number of output (completion) tokens used.

totalTokens:

number | undefined

The total number of tokens as reported by the provider. This number might be different from the sum of inputTokens and outputTokens and e.g. include reasoning tokens or other overhead.

reasoningTokens?:

number | undefined

The number of reasoning tokens used.

cachedInputTokens?:

number | undefined

The number of cached input tokens.

request?:

LanguageModelRequestMetadata

Request metadata.

LanguageModelRequestMetadata

body:

string

Raw request HTTP body that was sent to the provider API as a string (JSON should be stringified).

response?:

LanguageModelResponseMetadata

Response metadata.

LanguageModelResponseMetadata

id:

string

The response identifier. The AI SDK uses the ID from the provider response when available, and generates an ID otherwise.

modelId:

string

The model that was used to generate the response. The AI SDK uses the response model from the provider response when available, and the model from the function call otherwise.

timestamp:

Date

The timestamp of the response. The AI SDK uses the response timestamp from the provider response when available, and creates a timestamp otherwise.

headers?:

Record<string, string>

Optional response headers.

body?:

unknown

Optional response body.

messages:

Array<ResponseMessage>

The response messages that were generated during the call. It consists of an assistant message, potentially containing tool calls. When there are tool results, there is an additional tool message with the tool results that are available. If there are tools that do not have execute functions, they are not included in the tool results and need to be added separately.

warnings:

CallWarning[] | undefined

Warnings from the model provider (e.g. unsupported settings).

providerMetadata:

ProviderMetadata | undefined

Optional metadata from the provider. The outer key is the provider name. The inner values are the metadata. Details depend on the provider.

experimental_output?:

Output

Experimental setting for generating structured outputs.

steps:

Array<StepResult<TOOLS>>

Response information for every step. You can use this to get information about intermediate steps, such as the tool calls or the response headers.

StepResult

content:

Array<ContentPart<TOOLS>>

The content that was generated in the last step.

text:

string

The generated text.

reasoning:

Array<ReasoningPart>

The reasoning that was generated during the generation.

ReasoningPart

type:

'reasoning'

The type of the message part.

text:

string

The reasoning text.

reasoningText:

string | undefined

The reasoning text that was generated during the generation.

files:

Array<GeneratedFile>

The files that were generated during the generation.

GeneratedFile

base64:

string

File as a base64 encoded string.

uint8Array:

Uint8Array

File as a Uint8Array.

mediaType:

string

The IANA media type of the file.

sources:

Array<Source>

The sources that were used to generate the text.

Source

sourceType:

'url'

A URL source. This is return by web search RAG models.

id:

string

The ID of the source.

url:

string

The URL of the source.

title?:

string

The title of the source.

providerMetadata?:

SharedV2ProviderMetadata

Additional provider metadata for the source.

toolCalls:

ToolCallArray<TOOLS>

The tool calls that were made during the generation.

toolResults:

ToolResultArray<TOOLS>

The results of the tool calls.

finishReason:

'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'

The reason why the generation finished.

usage:

LanguageModelUsage

The token usage of the generated text.

LanguageModelUsage

inputTokens:

number | undefined

The number of input (prompt) tokens used.

outputTokens:

number | undefined

The number of output (completion) tokens used.

totalTokens:

number | undefined

The total number of tokens as reported by the provider. This number might be different from the sum of inputTokens and outputTokens and e.g. include reasoning tokens or other overhead.

reasoningTokens?:

number | undefined

The number of reasoning tokens used.

cachedInputTokens?:

number | undefined

The number of cached input tokens.

warnings:

CallWarning[] | undefined

Warnings from the model provider (e.g. unsupported settings).

request:

LanguageModelRequestMetadata

Additional request information.

LanguageModelRequestMetadata

body:

string

Raw request HTTP body that was sent to the provider API as a string (JSON should be stringified).

response:

LanguageModelResponseMetadata

Additional response information.

LanguageModelResponseMetadata

id:

string

The response identifier. The AI SDK uses the ID from the provider response when available, and generates an ID otherwise.

modelId:

string

The model that was used to generate the response. The AI SDK uses the response model from the provider response when available, and the model from the function call otherwise.

timestamp:

Date

The timestamp of the response. The AI SDK uses the response timestamp from the provider response when available, and creates a timestamp otherwise.

headers?:

Record<string, string>

Optional response headers.

body?:

unknown

Response body (available only for providers that use HTTP requests).

messages:

Array<ResponseMessage>

The response messages that were generated during the call. Response messages can be either assistant messages or tool messages. They contain a generated id.

providerMetadata:

ProviderMetadata | undefined

Additional provider-specific metadata. They are passed through from the provider to the AI SDK and enable provider-specific results that can be fully encapsulated in the provider.

Examples


Learn to generate text using a language model in Next.js Learn to generate a chat completion using a language model in Next.js Learn to call tools using a language model in Next.js Learn to render a React component as a tool call using a language model in Next.js Learn to generate text using a language model in Node.js Learn to generate chat completions using a language model in Node.js

On this page

generateText()

Import

API Signature

Parameters

Returns

Examples

Deploy and Scale AI Apps with Vercel.

Vercel delivers the infrastructure and developer experience you need to ship reliable AI-powered applications at scale.

Trusted by industry leaders:

  • OpenAI
  • Photoroom
  • leonardo-ai Logoleonardo-ai Logo
  • zapier Logozapier Logo

Talk to an expert