> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/vercel/ai/llms.txt
> Use this file to discover all available pages before exploring further.

# generateText

> API reference for the generateText function

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

This function does not stream the output. If you want to stream the output, use [`streamText`](/reference/ai-sdk-core/stream-text) instead.

```typescript theme={null}
import { generateText } from 'ai';

const result = await generateText({
  model: openai('gpt-4-turbo'),
  prompt: 'Invent a new holiday.',
});

console.log(result.text);
```

## Parameters

<ParamField path="model" type="LanguageModel" required>
  The language model to use.
</ParamField>

<ParamField path="prompt" type="string">
  A simple text prompt. You can either use `prompt` or `messages` but not both.
</ParamField>

<ParamField path="messages" type="Array<CoreMessage>">
  A list of messages. You can either use `prompt` or `messages` but not both.
</ParamField>

<ParamField path="system" type="string">
  A system message that will be part of the prompt.
</ParamField>

<ParamField path="tools" type="ToolSet">
  Tools that are accessible to and can be called by the model. The model needs to support calling tools.
</ParamField>

<ParamField path="toolChoice" type="ToolChoice">
  The tool choice strategy. Default: `'auto'`.
</ParamField>

<ParamField path="maxOutputTokens" type="number">
  Maximum number of tokens to generate.
</ParamField>

<ParamField path="temperature" type="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.
</ParamField>

<ParamField path="topP" type="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.
</ParamField>

<ParamField path="topK" type="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.
</ParamField>

<ParamField path="presencePenalty" type="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.
</ParamField>

<ParamField path="frequencyPenalty" type="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.
</ParamField>

<ParamField path="stopSequences" type="Array<string>">
  Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated.
</ParamField>

<ParamField path="seed" type="number">
  The seed (integer) to use for random sampling.
  If set and supported by the model, calls will generate deterministic results.
</ParamField>

<ParamField path="maxRetries" type="number" default="2">
  Maximum number of retries. Set to 0 to disable retries.
</ParamField>

<ParamField path="abortSignal" type="AbortSignal">
  An optional abort signal that can be used to cancel the call.
</ParamField>

<ParamField path="timeout" type="number">
  An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout.
</ParamField>

<ParamField path="headers" type="Record<string, string>">
  Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
</ParamField>

<ParamField path="stopWhen" type="StopCondition | Array<StopCondition>" default="stepCountIs(1)">
  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.
</ParamField>

<ParamField path="output" type="Output">
  Optional specification for parsing structured outputs from the LLM response.
</ParamField>

<ParamField path="activeTools" type="Array<keyof TOOLS>">
  Limits the tools that are available for the model to call without changing the tool call and result types in the result.
</ParamField>

<ParamField path="prepareStep" type="PrepareStepFunction">
  Optional function that you can use to provide different settings for a step.
</ParamField>

<ParamField path="experimental_repairToolCall" type="ToolCallRepairFunction">
  A function that attempts to repair a tool call that failed to parse.
</ParamField>

<ParamField path="experimental_download" type="DownloadFunction">
  Custom download function to use for URLs.
  By default, files are downloaded if the model does not support the URL for the given media type.
</ParamField>

<ParamField path="experimental_context" type="unknown">
  Context that is passed into tool execution.
</ParamField>

<ParamField path="experimental_telemetry" type="TelemetrySettings">
  Optional telemetry configuration (experimental).
</ParamField>

<ParamField path="providerOptions" type="ProviderOptions">
  Additional provider-specific options. They are passed through to the provider from the AI SDK
  and enable provider-specific functionality that can be fully encapsulated in the provider.
</ParamField>

<ParamField path="experimental_onStart" type="(event: OnStartEvent) => void">
  Callback invoked when generation begins, before any LLM calls.
</ParamField>

<ParamField path="experimental_onStepStart" type="(event: OnStepStartEvent) => void">
  Callback invoked when each step begins, before the provider is called.
</ParamField>

<ParamField path="experimental_onToolCallStart" type="(event: OnToolCallStartEvent) => void">
  Callback invoked before each tool execution begins.
</ParamField>

<ParamField path="experimental_onToolCallFinish" type="(event: OnToolCallFinishEvent) => void">
  Callback invoked after each tool execution completes.
</ParamField>

<ParamField path="onStepFinish" type="(event: OnStepFinishEvent) => void">
  Callback that is called when each step (LLM call) is finished, including intermediate steps.
</ParamField>

<ParamField path="onFinish" type="(event: OnFinishEvent) => void">
  Callback that is called when all steps are finished and the response is complete.
</ParamField>

## Returns

<ResponseField name="text" type="string">
  The generated text.
</ResponseField>

<ResponseField name="content" type="Array<ContentPart>">
  The content parts from the final step.
</ResponseField>

<ResponseField name="toolCalls" type="Array<ToolCall>">
  The tool calls from the final step.
</ResponseField>

<ResponseField name="toolResults" type="Array<ToolResult>">
  The tool results from the final step.
</ResponseField>

<ResponseField name="finishReason" type="FinishReason">
  The reason why the generation finished.
</ResponseField>

<ResponseField name="usage" type="LanguageModelUsage">
  The token usage of the final step.
</ResponseField>

<ResponseField name="totalUsage" type="LanguageModelUsage">
  The total token usage across all steps.
</ResponseField>

<ResponseField name="warnings" type="Array<CallWarning>">
  Warnings from the model provider (e.g., unsupported settings).
</ResponseField>

<ResponseField name="steps" type="Array<StepResult>">
  Details for all steps.
</ResponseField>

<ResponseField name="response" type="LanguageModelResponseMetadata">
  Response metadata from the final step.
</ResponseField>

<ResponseField name="output" type="OUTPUT">
  The parsed output (only when using the `output` parameter).
</ResponseField>

## Examples

### Basic text generation

```typescript theme={null}
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';

const result = await generateText({
  model: openai('gpt-4-turbo'),
  prompt: 'Invent a new holiday.',
});

console.log(result.text);
```

### With tools

```typescript theme={null}
import { generateText, tool } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';

const result = await generateText({
  model: openai('gpt-4-turbo'),
  prompt: 'What is the weather in San Francisco?',
  tools: {
    weather: tool({
      description: 'Get the weather for a location',
      inputSchema: z.object({
        location: z.string(),
      }),
      execute: async ({ location }) => {
        // Call weather API
        return { temperature: 72, condition: 'sunny' };
      },
    }),
  },
});

console.log(result.text);
console.log(result.toolCalls);
console.log(result.toolResults);
```

### With structured output

```typescript theme={null}
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';

const result = await generateText({
  model: openai('gpt-4-turbo'),
  prompt: 'Generate a person profile',
  output: object({
    schema: z.object({
      name: z.string(),
      age: z.number(),
      occupation: z.string(),
    }),
  }),
});

console.log(result.output);
```
