Structured output with generateText and Output.object()
Use generateText with Output.object() to generate structured data from a prompt. The schema is also used to validate the generated data, ensuring type safety and correctness. Example: const { output } = await generateText({ model: __MODEL__, output: Output.object({ schema: z.object({ recipe: z.object({ name: z.string(), ingredients: z.array(z.object({ name: z.string(), amount: z.string() })), steps: z.array(z.string()) }) }) }), prompt: 'Generate a lasagna recipe.' });
Output.text() for plain text generation
Use Output.text() to generate plain text from a model. This option doesn't enforce any schema on the result; you simply receive the model's text as a string. This is the default behavior when no output is specified.
Accessing response headers and body from generateText
You can access the raw response headers and body using the response property on the result: console.log(JSON.stringify(result.response.headers, null, 2)); console.log(JSON.stringify(result.response.body, null, 2));
generateText legacy span types
For generateText with LegacyOpenTelemetry, 3 types of spans are recorded: (1) ai.generateText - full generateText call span containing 1+ ai.generateText.doGenerate spans; (2) ai.generateText.doGenerate - provider doGenerate call span, can contain ai.toolCall spans; (3) ai.toolCall - tool call span made as part of generation.
generateText main purpose
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.
generateText import statement
import { generateText } from 'ai';
generateText prompt parameter
The 'prompt' parameter accepts type 'string | Array<SystemModelMessage | UserModelMessage | AssistantModelMessage | ToolModelMessage>'. It is the input prompt to generate the text from.
generateText messages parameter
The 'messages' parameter accepts 'Array<SystemModelMessage | UserModelMessage | AssistantModelMessage | ToolModelMessage>'. It is a list of messages that represent a conversation. It automatically converts UI messages from the useChat hook.
SystemModelMessage type definition
SystemModelMessage has two properties: role (type 'system', required) and content (type 'string', required). It represents a system message in the conversation.
AssistantModelMessage type definition
AssistantModelMessage has two properties: role (literal 'assistant', required) and content (type 'string | Array<TextPart | FilePart | ReasoningPart | ReasoningFilePart | ToolCallPart>', required). It represents an assistant message in the conversation.
ReasoningPart content type
ReasoningPart has two properties: type (literal 'reasoning', required) and text (type 'string', required). It represents reasoning text from the model.
ToolCallPart content type
ToolCallPart has four properties: type (literal 'tool-call', required), toolCallId (type 'string', required), toolName (type 'string', required), and input (type 'object based on zod schema', required). It represents a tool call made by the model.
ToolModelMessage type definition
ToolModelMessage has two properties: role (literal 'tool', required) and content (type 'Array<ToolResultPart>', required). It represents tool results in the conversation.
ToolResultPart content type
ToolResultPart has five properties: type (literal 'tool-result', required), toolCallId (type 'string', required), toolName (type 'string', required), output (type 'unknown', required), and isError (type 'boolean', optional). It represents the result of executing a tool.
LanguageModelCallPerformance properties
LanguageModelCallPerformance has properties: responseTimeMs (type 'number', time in milliseconds spent waiting for the language model response), effectiveOutputTokensPerSecond (type 'number'), outputTokensPerSecond (type 'number | undefined'), inputTokensPerSecond (type 'number | undefined'), effectiveTotalTokensPerSecond (type 'number'), and timeToFirstOutputMs (type 'number | undefined'). Additional property timeBetweenOutputChunksMs exists with type OutputChunkTimingStats.
generateText onStart callback parameter
The 'onStart' parameter is optional (type '(event: GenerateTextStartEvent) => PromiseLike<void> | void'). It is a callback that is called when the generateText operation begins, before any LLM calls are made. Errors thrown in this callback are silently caught and do not break the generation flow.
providerMetadata field in generateText response
The providerMetadata field is of type ProviderMetadata | undefined and contains additional provider-specific metadata passed through from the provider to the AI SDK, enabling provider-specific results fully encapsulated in the provider.
GenerateTextStartEvent type definition
GenerateTextStartEvent has 20 properties: provider (type 'string', the provider identifier), modelId (type 'string', the specific model identifier), instructions (type 'Instructions | undefined'), messages (type 'Array<ModelMessage>', required), tools (type 'TOOLS | undefined'), toolChoice (type 'ToolChoice<TOOLS> | undefined'), activeTools (type 'ActiveTools<TOOLS>'), toolOrder (type 'ToolOrder<TOOLS>'), maxOutputTokens (type 'number | undefined'), temperature (type 'number | undefined'), topP (type 'number | undefined'), topK (type 'number | undefined'), presencePenalty (type 'number | undefined'), frequencyPenalty (type 'number | undefined'), stopSequences (type 'string[] | undefined'), seed (type 'number | undefined'), maxRetries (type 'number'), timeout (type 'number | { totalMs?: number; stepMs?: number; chunkMs?: number } | undefined'), headers (type 'Record<string, string | undefined> | undefined'), and providerOptions (type 'ProviderOptions | undefined').
GenerateTextStartEvent additional properties
GenerateTextStartEvent also has: output (type 'OUTPUT | undefined', the output specification for structured outputs), abortSignal (type 'AbortSignal | undefined'), include (type '{ requestBody?: boolean; requestMessages?: boolean; responseBody?: boolean } | undefined', settings for controlling what data is included in step results), runtimeContext (type 'CONTEXT'), and toolsContext (type 'InferToolSetContext<TOOLS>').
generateText onStepStart callback parameter
The 'onStepStart' parameter is optional (type '(event: GenerateTextStepStartEvent) => PromiseLike<void> | void'). It is a callback that is called when a step (LLM call) begins, before the provider is called. Errors thrown in this callback are silently caught and do not break the generation flow.
GenerateTextStepStartEvent type definition
GenerateTextStepStartEvent has 18 properties: stepNumber (type 'number', zero-based index of current step), provider (type 'string'), modelId (type 'string'), instructions (type 'Instructions | undefined'), messages (type 'Array<ModelMessage>', uses user-facing ModelMessage format, may be overridden by prepareStep), tools (type 'TOOLS | undefined'), toolChoice (type 'LanguageModelV4ToolChoice | undefined'), activeTools (type 'ActiveTools<TOOLS>'), toolOrder (type 'ToolOrder<TOOLS>'), steps (type 'ReadonlyArray<StepResult<TOOLS>>', array of results from previous steps, empty for first step), providerOptions (type 'ProviderOptions | undefined'), timeout (type 'number | { totalMs?: number; stepMs?: number; chunkMs?: number } | undefined'), headers (type 'Record<string, string | undefined> | undefined'), stopWhen (type 'StopCondition<TOOLS> | Array<StopCondition<TOOLS>> | undefined'), output (type 'OUTPUT | undefined'), abortSignal (type 'AbortSignal | undefined'), include (type '{ requestBody?: boolean; requestMessages?: boolean; responseBody?: boolean } | undefined'), and runtimeContext (type 'CONTEXT', user-defined context that may be updated between steps).
GenerateTextStepStartEvent toolsContext property
GenerateTextStepStartEvent also has toolsContext (type 'InferToolSetContext<TOOLS>', per-tool context map that may be updated between steps).
LanguageModelCallStartEvent type definition
LanguageModelCallStartEvent has six properties: callId (type 'string', unique identifier for the generation call), provider (type 'string'), modelId (type 'string'), instructions (type 'Instructions | undefined'), messages (type 'Array<ModelMessage>', the messages that will be sent to the model), and tools (type 'ReadonlyArray<Record<string, unknown>> | undefined', prepared tool definitions for the model call if any).
generateText onLanguageModelCallEnd callback parameter
The 'onLanguageModelCallEnd' parameter is optional (type '(event: LanguageModelCallEndEvent) => PromiseLike<void> | void'). It is a callback that is called after the model response has been normalized and parsed, but before any client-side tool execution begins. Errors thrown in this callback are silently caught and do not break the generation flow.
LanguageModelCallEndEvent properties
LanguageModelCallEndEvent has nine properties: callId (type 'string', unique identifier), provider (type 'string'), modelId (type 'string', provider-returned model identifier), finishReason (type 'FinishReason', unified reason why the model call finished), usage (type 'LanguageModelUsage', token usage reported by the model call), content (type 'ReadonlyArray<ContentPart<TOOLS>>', content parts produced by the model), responseId (type 'string', provider-returned response ID), providerMetadata (type 'ProviderMetadata | undefined', provider-specific metadata when returned), and performance (type '{ responseTimeMs: number; effectiveOutputTokensPerSecond: number; outputTokensPerSecond: number | undefined; inputTokensPerSecond: number | undefined; effectiveTotalTokensPerSecond: number; timeToFirstOutputMs: number | undefined; timeBetweenOutputChunksMs?: OutputChunkTimingStats }', performance metrics for the model call).
generateText onStepEnd callback parameters
The onStepEnd callback receives a StepResult object with the following properties: stepNumber (zero-based index), model (provider and modelId), runtimeContext (user-defined shared context), toolsContext (per-tool context map), content (generated content array), text (generated text string), reasoning (array of ReasoningPart or ReasoningFilePart), reasoningText (optional reasoning text string), files (generated files array), sources (sources used array), toolCalls (array of TypedToolCall<TOOLS>), toolResults (array of tool results), finishReason (stop | length | content-filter | tool-calls), rawFinishReason (provider-specific reason string or undefined), usage (LanguageModelUsage object), performance (StepResultPerformance object), warnings (CallWarning array or undefined), request (LanguageModelRequestMetadata object), response (LanguageModelResponseMetadata object), and responseMessages (accumulated response messages array).
generateText onEnd callback structure
onEnd is an optional callback with type (event: GenerateTextEndEvent<TOOLS>) => PromiseLike<void> | void. It is called when the entire generation completes (all steps finished). The event includes: stepNumber, model, finishReason, rawFinishReason, usage (token usage from final step only, not aggregated), totalUsage (aggregated token usage across all steps), content (content generated in all steps), providerMetadata, text (full generated text), reasoningText, reasoning (array of ReasoningDetail objects), sources, files, toolCalls, toolResults, staticToolCalls, dynamicToolCalls, staticToolResults, dynamicToolResults, warnings, request, response, steps (array of StepResult for every step), finalStep (shortcut for steps.at(-1)), and responseMessages.
generateText return type structure
generateText returns an object with the following properties: content (Array<ContentPart<TOOLS>>), text (concatenation of all text parts from final step, empty string if no text parts), reasoning (deprecated, use finalStep.reasoning), reasoningText (deprecated, use finalStep.reasoningText), sources (accumulated from all steps), files, toolCalls, toolResults, staticToolCalls, dynamicToolCalls, staticToolResults, dynamicToolResults, finishReason ('stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other'), rawFinishReason, usage (total token usage of all steps), totalUsage (deprecated, use usage), request (deprecated, use finalStep.request), response (deprecated, use finalStep.response), warnings, responseMessages, providerMetadata (deprecated, use finalStep.providerMetadata), output (InferCompleteOutput<OUTPUT>, throws NoOutputGeneratedError if unavailable), steps (array of StepResult<TOOLS>), and finalStep.
LanguageModelUsage token details structure
LanguageModelUsage has inputTokens (number or undefined), inputTokenDetails (LanguageModelInputTokenDetails with noCacheTokens, cacheReadTokens, cacheWriteTokens all optional numbers), outputTokens (number or undefined), outputTokenDetails (LanguageModelOutputTokenDetails with textTokens and reasoningTokens both optional numbers), totalTokens (number or undefined), and raw (optional object with provider's original usage information).
StepResultPerformance metrics
StepResultPerformance contains: effectiveOutputTokensPerSecond (number), outputTokensPerSecond (number or undefined, undefined for generateText since not streamed), inputTokensPerSecond (number or undefined, undefined for generateText since not streamed), effectiveTotalTokensPerSecond (number), stepTimeMs (number, total time including LM response and tool execution), responseTimeMs (number, time waiting for LM response), toolExecutionMs (Readonly<Record<string, number>>, keyed by tool call ID), timeToFirstOutputMs (number or undefined, undefined for generateText), and timeBetweenOutputChunksMs (OutputChunkTimingStats or undefined, undefined for generateText).
ReasoningDetail type with text variant
ReasoningDetail with type 'text' contains: type (literal 'text'), text (string content), and optional signature (string).
ReasoningDetail type with redacted variant
ReasoningDetail with type 'redacted' contains: type (literal 'redacted') and data (string for redacted data content).
Source URL type structure
Source with sourceType 'url' contains: sourceType (literal 'url', used by web search RAG models), id (string), url (string), optional title (string), and optional providerMetadata (SharedV2ProviderMetadata).
onStepFinish and onFinish callbacks deprecated
onStepFinish is deprecated and should use onStepEnd instead. onFinish is deprecated and should use onEnd instead. onStepFinish is only used as fallback when onStepEnd is not provided. onFinish is a deprecated alias for onEnd.
StepResult structure for individual generation step
StepResult contains: stepNumber (zero-based index), model (object with provider and modelId), runtimeContext (CONTEXT user-defined shared context), toolsContext (InferToolSetContext<TOOLS> per-tool context map), content (Array<ContentPart<TOOLS>>), text (concatenation of all text parts, empty string if no text parts), reasoning (Array<ReasoningPart | ReasoningFilePart>), reasoningText (optional string), files (Array<GeneratedFile>), sources (Array<Source>), toolCalls (ToolCallArray<TOOLS>), toolResults (ToolResultArray<TOOLS>), finishReason (stop | length | content-filter | tool-calls), rawFinishReason (optional string from provider).
finishReason field in generateText response
The finishReason field indicates the reason why text generation finished. It is of type string and has the following possible values: 'stop', 'length', 'content-filter', 'tool-calls', 'error', or 'other'.
rawFinishReason field in generateText response
The rawFinishReason field contains the raw reason why generation finished as returned directly from the provider. It is of type string | undefined.
LanguageModelInputTokenDetails type structure
LanguageModelInputTokenDetails contains: noCacheTokens (number | undefined) - number of non-cached input prompt tokens used; cacheReadTokens (number | undefined) - number of cached input prompt tokens read; cacheWriteTokens (number | undefined) - number of cached input prompt tokens written.
LanguageModelOutputTokenDetails type structure
LanguageModelOutputTokenDetails contains: textTokens (number | undefined) - number of text tokens used; reasoningTokens (number | undefined) - number of reasoning tokens used.
warnings field in generateText response
The warnings field contains an array of Warning objects or is undefined. It includes warnings from the model provider, such as unsupported settings.
generateText model parameter
The 'model' parameter is required and accepts a LanguageModel type. Example: openai('gpt-4o'). It specifies the language model to use.
LanguageModelResponseMetadata type structure
LanguageModelResponseMetadata contains: id (string) - the response identifier from provider response when available, or generated otherwise; modelId (string) - the model used to generate the response from provider response when available, or from function call otherwise; timestamp (Date) - response timestamp from provider when available, or created otherwise; headers (Record<string, string>, optional) - optional response headers; body (unknown, optional) - response body available only for providers using HTTP requests; messages (Array<ResponseMessage>) - response messages generated during this step, can be assistant or tool messages with generated id.
generateText instructions parameter
The 'instructions' parameter is optional and accepts an Instructions type. It specifies the behavior of the model.
finalStep field in generateText response
The finalStep field is of type StepResult<TOOLS> and is a shortcut for steps.at(-1), providing the final step of the generation.
generateText basic usage example
const { text } = await generateText({
model: __MODEL__,
prompt: 'Invent a new holiday and describe its traditions.',
});
console.log(text);