xAI provider configuration options
The `createXai` function accepts the following optional settings: baseURL (string, default `https://api.x.ai/v1`), apiKey (string, defaults to `XAI_API_KEY` environment variable), headers (Record<string,string> for custom headers), and fetch (custom fetch implementation).
xAI Responses API default behavior
Since AI SDK 7, `xai(modelId)` uses the xAI Responses API by default. To use the Chat Completions API (legacy), use `xai.chat(modelId)` instead.
xAI reasoning effort parameter
Control reasoning effort for supported models using `providerOptions.xai.reasoningEffort`. Accepted values are 'none', 'low', 'medium', and 'high'. Support and defaults are model-specific: grok-4.3 supports all values; grok-4.5 supports 'low', 'medium', 'high' (defaults to 'high', cannot disable); grok-4.20-reasoning and grok-4.20-non-reasoning do not accept this option; grok-4.20-multi-agent uses values to control number of agents instead of reasoning depth.
xAI reasoning effort example
Example of setting reasoning effort:
```ts
import { xai } from '@ai-sdk/xai';
import { generateText } from 'ai';
const { text } = await generateText({
model: xai('grok-4.3'),
prompt: 'Explain quantum entanglement.',
providerOptions: {
xai: { reasoningEffort: 'medium' },
},
});
```
xAI Responses API server-side tools
The Responses API provides the following server-side tools that the model can autonomously execute: web_search (real-time web search and page browsing), x_search (search X/Twitter posts, users, threads), code_execution (execute Python code), view_image (view and analyze images), view_x_video (view and analyze X videos), mcp_server (connect to remote MCP servers), file_search (search documents in vector stores).
xAI image input with vision
The Responses API supports image input with vision models. Pass images using `type: 'file'` with `mediaType: 'image'` in the content array.
xAI image detail provider option
Control image processing resolution with `providerOptions.xai.imageDetail` on the image part. Accepted values are 'low' (reduced resolution, fewer tokens), 'high' (full resolution), and 'auto' (API decides). Default is full resolution when not set.
xAI image detail example
Example of setting image detail:
```ts
import { xai } from '@ai-sdk/xai';
import { generateText } from 'ai';
const { text } = await generateText({
model: xai('grok-4.3'),
messages: [
{
role: 'user',
content: [
{ type: 'text', text: 'What do you see in this image?' },
{
type: 'file',
mediaType: 'image/png',
data: fs.readFileSync('./image.png'),
providerOptions: {
xai: { imageDetail: 'low' },
},
},
],
},
],
});
```
xAI web search tool parameters
Web search tool configuration parameters: allowedDomains (string[], max 5, cannot be used with excludedDomains), excludedDomains (string[], max 5, cannot be used with allowedDomains), enableImageSearch (boolean, allows separate image search mode), enableImageUnderstanding (boolean, view and analyze found images, increases token usage).
xAI web search tool example
Example of using web search tool:
```ts
import { xai } from '@ai-sdk/xai';
import { generateText } from 'ai';
const { text, sources } = await generateText({
model: xai.responses('grok-4.20-non-reasoning'),
prompt: 'What are the latest developments in AI?',
tools: {
web_search: xai.tools.webSearch({
allowedDomains: ['arxiv.org', 'openai.com'],
enableImageUnderstanding: true,
}),
},
});
console.log(text);
console.log('Citations:', sources);
```
xAI X search tool parameters
X search tool configuration parameters: allowedXHandles (string[], max 10, cannot be used with excludedXHandles), excludedXHandles (string[], max 10, cannot be used with allowedXHandles), fromDate (string, ISO8601 format YYYY-MM-DD), toDate (string, ISO8601 format YYYY-MM-DD), enableImageUnderstanding (boolean), enableVideoUnderstanding (boolean).
xAI X search tool example
Example of using X search tool:
```ts
const { text, sources } = await generateText({
model: xai.responses('grok-4.20-non-reasoning'),
prompt: 'What are people saying about AI on X this week?',
tools: {
x_search: xai.tools.xSearch({
allowedXHandles: ['elonmusk', 'xai'],
fromDate: '2025-10-23',
toDate: '2025-10-30',
enableImageUnderstanding: true,
enableVideoUnderstanding: true,
}),
},
});
```
xAI code execution tool example
Example of using code execution tool:
```ts
const { text } = await generateText({
model: xai.responses('grok-4.20-non-reasoning'),
prompt:
'Calculate the compound interest for $10,000 at 5% annually for 10 years',
tools: {
code_execution: xai.tools.codeExecution(),
},
});
```
xAI image generation tool example
Example of using image generation tool with Grok Imagine:
```ts
import { xai } from '@ai-sdk/xai';
import { generateText } from 'ai';
const result = await generateText({
model: xai.responses('grok-4.5'),
prompt:
'Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print',
tools: {
image_generation: xai.tools.imageGeneration(),
},
});
for (const toolResult of result.staticToolResults) {
if (toolResult.toolName === 'image_generation') {
const base64Image = toolResult.output.result;
}
}
```
xAI image generation tool parameters
Image generation tool configuration: action ('auto' | 'generate' | 'edit', defaults to 'auto'). 'auto' allows generate and edit, 'generate' is text-to-image only, 'edit' is image editing only. The tool takes no size or format parameters; the model picks aspect ratio for each call.
xAI MCP server tool parameters
MCP server tool configuration: serverUrl (string, required), serverLabel (string), serverDescription (string), allowedTools (string[], list of allowed tool names, all allowed if not specified), headers (Record<string, string>), authorization (string, e.g., 'Bearer token123').
xAI MCP server tool example
Example of using MCP server tool:
```ts
const { text } = await generateText({
model: xai.responses('grok-4.20-non-reasoning'),
prompt: 'Use the weather tool to check conditions in San Francisco',
tools: {
weather_server: xai.tools.mcpServer({
serverUrl: 'https://example.com/mcp',
serverLabel: 'weather-service',
serverDescription: 'Weather data provider',
allowedTools: ['get_weather', 'get_forecast'],
}),
},
});
```
xAI file search tool parameters
File search tool configuration: vectorStoreIds (string[], required, IDs of vector stores/collections to search), maxNumResults (number, maximum results to return).
xAI file search provider options
File search provider options via providerOptions.xai: include (Array<'file_search_call.results'>, when set to ['file_search_call.results'] includes actual search results with file content and scores).
xAI file search example
Example of using file search tool:
```ts
import { xai, type XaiLanguageModelResponsesOptions } from '@ai-sdk/xai';
import { streamText } from 'ai';
const result = streamText({
model: xai.responses('grok-4.20-reasoning'),
prompt: 'What documents do you have access to?',
tools: {
file_search: xai.tools.fileSearch({
vectorStoreIds: ['collection_your-collection-id'],
maxNumResults: 10,
}),
},
providerOptions: {
xai: {
include: ['file_search_call.results'],
} satisfies XaiLanguageModelResponsesOptions,
},
});
```
xAI Responses API provider options
Responses API provider options: reasoningEffort ('none' | 'low' | 'medium' | 'high'), logprobs (boolean, return log probabilities), topLogprobs (number, 0-8, most likely tokens per position, auto-enables logprobs), include (Array<'file_search_call.results'>), store (boolean, defaults to true, store messages for later retrieval), previousResponseId (string, continue conversation from previous response).
xAI generateSpeech parameters
xAI generateSpeech parameters: text (string, required, can include speech tags like [pause], [laugh], <whisper>...</whisper>), voice (string, defaults to 'eve', built-in IDs are 'eve', 'ara', 'rex', 'sal', 'leo', custom IDs accepted), language (BCP-47 code or 'auto' for auto-detection, defaults to 'auto'), speed (number, 0.7 to 1.5), outputFormat (string, 'mp3', 'wav', 'pcm', 'mulaw', 'alaw', defaults to 'mp3').
xAI speech provider options
xAI speech provider options via providerOptions.xai: sampleRate (8000 | 16000 | 22050 | 24000 | 44100 | 48000), bitRate (32000 | 64000 | 96000 | 128000 | 192000, MP3 only), optimizeStreamingLatency (0 | 1 | 2, higher reduces latency with quality tradeoff), textNormalization (boolean).
xAI speech provider options example
Example of setting speech provider options:
```ts
import { xai, type XaiSpeechModelOptions } from '@ai-sdk/xai';
import { generateSpeech } from 'ai';
const result = await generateSpeech({
model: xai.speech(),
text: 'A high fidelity narration sample.',
outputFormat: 'mp3',
providerOptions: {
xai: {
sampleRate: 44100,
bitRate: 192000,
optimizeStreamingLatency: 1,
textNormalization: true,
} satisfies XaiSpeechModelOptions,
},
});
```
xAI transcription provider options
xAI transcription provider options via providerOptions.xai: audioFormat ('pcm' | 'mulaw' | 'alaw', for raw headerless audio), sampleRate (8000 | 16000 | 22050 | 24000 | 44100 | 48000), language (string, language code for inverse text normalization), format (boolean, enables inverse text normalization, requires language), multichannel (boolean), channels (2 | 3 | 4 | 5 | 6 | 7 | 8), diarize (boolean, enables speaker diarization), keyterm (string | string[], bias transcription toward terms), fillerWords (boolean, include 'uh', 'um' in transcript), streaming (object with interimResults, endpointing, smartTurn, smartTurnTimeout for WebSocket streaming).
xAI transcription example with options
Example of xAI transcription with provider options:
```ts
import { xai, type XaiTranscriptionModelOptions } from '@ai-sdk/xai';
import { transcribe } from 'ai';
import { readFile } from 'fs/promises';
const result = await transcribe({
model: xai.transcription(),
audio: await readFile('meeting.mp3'),
providerOptions: {
xai: {
language: 'en',
format: true,
keyterm: ['AI SDK', 'Grok'],
diarize: true,
} satisfies XaiTranscriptionModelOptions,
},
});
```
xAI image generation aspect ratios
xAI image models support `aspectRatio` parameter instead of `size`. Supported aspect ratios: 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 2:1, 1:2, 19.5:9, 9:19.5, 20:9, 9:20, and auto.
xAI image provider options
xAI image provider options via providerOptions.xai: resolution ('1k' | '2k', 1k produces ~1024×1024, 2k produces ~2048×2048, available for grok-imagine-image-pro), quality ('low' | 'medium' | 'high', higher quality may increase generation time).
xAI image provider options example
Example of image generation with provider options:
```ts
import { xai, type XaiImageModelOptions } from '@ai-sdk/xai';
import { generateImage } from 'ai';
const { images } = await generateImage({
model: xai.image('grok-imagine-image-pro'),
prompt: 'A futuristic cityscape at sunset',
aspectRatio: '16:9',
providerOptions: {
xai: {
resolution: '2k',
quality: 'high',
} satisfies XaiImageModelOptions,
},
});
```
xAI reference-to-video image limits
Reference-to-video mode supports up to 7 reference images per request. Use <IMAGE_1>, <IMAGE_2>, etc. in the prompt to reference specific images.
xAI video editing constraints
Video editing accepts input videos up to 8.7 seconds long. The duration, aspectRatio, and resolution parameters are not supported for editing. The output matches the input video's properties and is capped at 720p (e.g., 1080p input will be downsized to 720p).
xAI video extension constraints
Video extension does not support custom aspectRatio or resolution. The output inherits those from the source video. The duration parameter is supported and controls only the extension length, not the total video length.
xAI video provider options
xAI video provider options via providerOptions.xai: pollIntervalMs (number, polling interval in ms, defaults to 5000), pollTimeoutMs (number, max wait in ms, defaults to 600000/10 minutes), resolution ('480p' | '720p', 1280x720 maps to 720p, 854x480 maps to 480p), user (string, opaque identifier for end user), mode ('edit-video' | 'extend-video' | 'reference-to-video'), videoUrl (string, URL for edit/extend modes), referenceImageUrls (string[], 1-7 images for reference-to-video).
xAI video aspect ratios and resolution defaults
Text-to-video supports both aspectRatio and resolution. Default aspect ratio is 16:9, default resolution is 480p. Image-to-video defaults to input image's aspect ratio, can be overridden. Video editing output matches input aspect ratio/resolution, capped at 720p. Video extension inherits input aspect ratio/resolution. Reference-to-video supports custom duration, aspectRatio, and resolution like text-to-video.
xAI Responses API tool restriction
The Responses API only supports server-side tools. You cannot mix server-side tools with client-side function tools in the same request.
xAI image editing mask support
xAI image editing does not support masks. Editing is prompt-driven - describe what you want to change in the text prompt.
xAI input image formats for editing
Input images for image editing can be provided as Buffer, ArrayBuffer, Uint8Array, or base64-encoded strings.
xAI reference-to-video precedence
When both frameImages and inputReferences are provided, frameImages takes precedence. When both inputReferences and referenceImageUrls are provided, inputReferences takes precedence. Providing inputReferences automatically selects reference-to-video mode.
xAI video generation asynchronous nature
Video generation is an asynchronous process that can take several minutes. Generated video URLs are ephemeral and should be downloaded promptly. Consider setting pollTimeoutMs to at least 10 minutes (600000ms) for reliable operation.
xAI video editing first-last-frame limitation
xAI does not support first-last-frame interpolation. A last_frame entry in frameImages is ignored with a warning. Use extend-video mode instead to continue from a video's last frame.
xAI Responses API URL access
The xAI-hosted video URL is available in providerMetadata.xai.videoUrl, useful for chaining sequential edits or branching into concurrent edits.