xAI Grok Provider

The xAI Grok provider contains language model support for the xAI API.

Setup

The xAI Grok provider is available via the @ai-sdk/xai module. You can install it with

pnpm add @ai-sdk/xai

Provider Instance

You can import the default provider instance xai from @ai-sdk/xai:

import { xai } from '@ai-sdk/xai';

If you need a customized setup, you can import createXai from @ai-sdk/xai and create a provider instance with your settings:

import { createXai } from '@ai-sdk/xai';
const xai = createXai({
apiKey: 'your-api-key',
});

You can use the following optional settings to customize the xAI provider instance:

  • baseURL string

    Use a different URL prefix for API calls, e.g. to use proxy servers. The default prefix is https://api.x.ai/v1.

  • apiKey string

    API key that is being sent using the Authorization header. It defaults to the XAI_API_KEY environment variable.

  • headers Record<string,string>

    Custom headers to include in the requests.

  • fetch (input: RequestInfo, init?: RequestInit) => Promise<Response>

    Custom fetch implementation. Defaults to the global fetch function. You can use it as a middleware to intercept requests, or to provide a custom fetch implementation for e.g. testing.

Language Models

You can create xAI models using a provider instance. The first argument is the model id, e.g. grok-3.

const model = xai('grok-3');

By default, xai(modelId) uses the Chat API. To use the Responses API with server-side agentic tools, explicitly use xai.responses(modelId).

Example

You can use xAI language models to generate text with the generateText function:

import { xai } from '@ai-sdk/xai';
import { generateText } from 'ai';
const { text } = await generateText({
model: xai('grok-3'),
prompt: 'Write a vegetarian lasagna recipe for 4 people.',
});

xAI language models can also be used in the streamText, generateObject, and streamObject functions (see AI SDK Core).

Provider Options

xAI chat models support additional provider options that are not part of the standard call settings. You can pass them in the providerOptions argument:

const model = xai('grok-3-mini');
await generateText({
model,
providerOptions: {
xai: {
reasoningEffort: 'high',
},
},
});

The following optional provider options are available for xAI chat models:

  • reasoningEffort 'low' | 'medium' | 'high'

    Reasoning effort for reasoning models.

  • store boolean

    Whether to store the generation. Defaults to true.

  • previousResponseId string

    The ID of the previous response. You can use it to continue a conversation. Defaults to undefined.

Responses API (Agentic Tools)

You can use the xAI Responses API with the xai.responses(modelId) factory method for server-side agentic tool calling. This enables the model to autonomously orchestrate tool calls and research on xAI's servers.

const model = xai.responses('grok-4-fast');

The Responses API provides server-side tools that the model can autonomously execute during its reasoning process:

  • web_search: Real-time web search and page browsing
  • x_search: Search X (Twitter) posts, users, and threads
  • code_execution: Execute Python code for calculations and data analysis

Web Search Tool

The web search tool enables autonomous web research with optional domain filtering and image understanding:

import { xai } from '@ai-sdk/xai';
import { generateText } from 'ai';
const { text, sources } = await generateText({
model: xai.responses('grok-4-fast'),
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);

Web Search Parameters

  • allowedDomains string[]

    Only search within specified domains (max 5). Cannot be used with excludedDomains.

  • excludedDomains string[]

    Exclude specified domains from search (max 5). Cannot be used with allowedDomains.

  • enableImageUnderstanding boolean

    Enable the model to view and analyze images found during search. Increases token usage.

X Search Tool

The X search tool enables searching X (Twitter) for posts, with filtering by handles and date ranges:

const { text, sources } = await generateText({
model: xai.responses('grok-4-fast'),
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,
}),
},
});

X Search Parameters

  • allowedXHandles string[]

    Only search posts from specified X handles (max 10). Cannot be used with excludedXHandles.

  • excludedXHandles string[]

    Exclude posts from specified X handles (max 10). Cannot be used with allowedXHandles.

  • fromDate string

    Start date for posts in ISO8601 format (YYYY-MM-DD).

  • toDate string

    End date for posts in ISO8601 format (YYYY-MM-DD).

  • enableImageUnderstanding boolean

    Enable the model to view and analyze images in X posts.

  • enableVideoUnderstanding boolean

    Enable the model to view and analyze videos in X posts.

Code Execution Tool

The code execution tool enables the model to write and execute Python code for calculations and data analysis:

const { text } = await generateText({
model: xai.responses('grok-4-fast'),
prompt:
'Calculate the compound interest for $10,000 at 5% annually for 10 years',
tools: {
code_execution: xai.tools.codeExecution(),
},
});

Multiple Tools

You can combine multiple server-side tools for comprehensive research:

import { xai } from '@ai-sdk/xai';
import { streamText } from 'ai';
const { fullStream } = streamText({
model: xai.responses('grok-4-fast'),
prompt: 'Research AI safety developments and calculate risk metrics',
tools: {
web_search: xai.tools.webSearch(),
x_search: xai.tools.xSearch(),
code_execution: xai.tools.codeExecution(),
},
});
for await (const part of fullStream) {
if (part.type === 'text-delta') {
process.stdout.write(part.text);
} else if (part.type === 'source' && part.sourceType === 'url') {
console.log('\nSource:', part.url);
}
}

Provider Options

The Responses API supports the following provider options:

import { xai } from '@ai-sdk/xai';
import { generateText } from 'ai';
const result = await generateText({
model: xai.responses('grok-4-fast'),
providerOptions: {
xai: {
reasoningEffort: 'high',
},
},
// ...
});

The following provider options are available:

  • reasoningEffort 'low' | 'high'

    Control the reasoning effort for the model. Higher effort may produce more thorough results at the cost of increased latency and token usage.

The Responses API only supports server-side tools. You cannot mix server-side tools with client-side function tools in the same request.

xAI models support Live Search functionality, allowing them to query real-time data from various sources and include it in responses with citations.

To enable search, specify searchParameters with a search mode:

import { xai } from '@ai-sdk/xai';
import { generateText } from 'ai';
const { text, sources } = await generateText({
model: xai('grok-3-latest'),
prompt: 'What are the latest developments in AI?',
providerOptions: {
xai: {
searchParameters: {
mode: 'auto', // 'auto', 'on', or 'off'
returnCitations: true,
maxSearchResults: 5,
},
},
},
});
console.log(text);
console.log('Sources:', sources);

Search Parameters

The following search parameters are available:

  • mode 'auto' | 'on' | 'off'

    Search mode preference:

    • 'auto' (default): Model decides whether to search
    • 'on': Always enables search
    • 'off': Disables search completely
  • returnCitations boolean

    Whether to return citations in the response. Defaults to true.

  • fromDate string

    Start date for search data in ISO8601 format (YYYY-MM-DD).

  • toDate string

    End date for search data in ISO8601 format (YYYY-MM-DD).

  • maxSearchResults number

    Maximum number of search results to consider. Defaults to 20, max 50.

  • sources Array<SearchSource>

    Data sources to search from. Defaults to ["web", "x"] if not specified.

Search Sources

You can specify different types of data sources for search:

const result = await generateText({
model: xai('grok-3-latest'),
prompt: 'Best ski resorts in Switzerland',
providerOptions: {
xai: {
searchParameters: {
mode: 'on',
sources: [
{
type: 'web',
country: 'CH', // ISO alpha-2 country code
allowedWebsites: ['ski.com', 'snow-forecast.com'],
safeSearch: true,
},
],
},
},
},
});

Web source parameters

  • country string: ISO alpha-2 country code
  • allowedWebsites string[]: Max 5 allowed websites
  • excludedWebsites string[]: Max 5 excluded websites
  • safeSearch boolean: Enable safe search (default: true)
const result = await generateText({
model: xai('grok-3-latest'),
prompt: 'Latest updates on Grok AI',
providerOptions: {
xai: {
searchParameters: {
mode: 'on',
sources: [
{
type: 'x',
includedXHandles: ['grok', 'xai'],
excludedXHandles: ['openai'],
postFavoriteCount: 10,
postViewCount: 100,
},
],
},
},
},
});

X source parameters

  • includedXHandles string[]: Array of X handles to search (without @ symbol)
  • excludedXHandles string[]: Array of X handles to exclude from search (without @ symbol)
  • postFavoriteCount number: Minimum favorite count of the X posts to consider.
  • postViewCount number: Minimum view count of the X posts to consider.
const result = await generateText({
model: xai('grok-3-latest'),
prompt: 'Recent tech industry news',
providerOptions: {
xai: {
searchParameters: {
mode: 'on',
sources: [
{
type: 'news',
country: 'US',
excludedWebsites: ['tabloid.com'],
safeSearch: true,
},
],
},
},
},
});

News source parameters

  • country string: ISO alpha-2 country code
  • excludedWebsites string[]: Max 5 excluded websites
  • safeSearch boolean: Enable safe search (default: true)
const result = await generateText({
model: xai('grok-3-latest'),
prompt: 'Latest status updates',
providerOptions: {
xai: {
searchParameters: {
mode: 'on',
sources: [
{
type: 'rss',
links: ['https://status.x.ai/feed.xml'],
},
],
},
},
},
});

RSS source parameters

  • links string[]: Array of RSS feed URLs (max 1 currently supported)

Multiple Sources

You can combine multiple data sources in a single search:

const result = await generateText({
model: xai('grok-3-latest'),
prompt: 'Comprehensive overview of recent AI breakthroughs',
providerOptions: {
xai: {
searchParameters: {
mode: 'on',
returnCitations: true,
maxSearchResults: 15,
sources: [
{
type: 'web',
allowedWebsites: ['arxiv.org', 'openai.com'],
},
{
type: 'news',
country: 'US',
},
{
type: 'x',
includedXHandles: ['openai', 'deepmind'],
},
],
},
},
},
});

Sources and Citations

When search is enabled with returnCitations: true, the response includes sources that were used to generate the answer:

const { text, sources } = await generateText({
model: xai('grok-3-latest'),
prompt: 'What are the latest developments in AI?',
providerOptions: {
xai: {
searchParameters: {
mode: 'auto',
returnCitations: true,
},
},
},
});
// Access the sources used
for (const source of sources) {
if (source.sourceType === 'url') {
console.log('Source:', source.url);
}
}

Live Search works with streaming responses. Citations are included when the stream completes:

import { streamText } from 'ai';
const result = streamText({
model: xai('grok-3-latest'),
prompt: 'What has happened in tech recently?',
providerOptions: {
xai: {
searchParameters: {
mode: 'auto',
returnCitations: true,
},
},
},
});
for await (const textPart of result.textStream) {
process.stdout.write(textPart);
}
console.log('Sources:', await result.sources);

Model Capabilities

ModelImage InputObject GenerationTool UsageTool StreamingReasoning
grok-4-fast-non-reasoning
grok-4-fast-reasoning
grok-code-fast-1
grok-4
grok-3
grok-3-latest
grok-3-fast
grok-3-fast-latest
grok-3-mini
grok-3-mini-latest
grok-3-mini-fast
grok-3-mini-fast-latest
grok-2
grok-2-latest
grok-2-1212
grok-2-vision
grok-2-vision-latest
grok-2-vision-1212
grok-beta
grok-vision-beta

The table above lists popular models. Please see the xAI docs for a full list of available models. The table above lists popular models. You can also pass any available provider model ID as a string if needed.

Image Models

You can create xAI image models using the .image() factory method. For more on image generation with the AI SDK see generateImage().

import { xai } from '@ai-sdk/xai';
import { experimental_generateImage as generateImage } from 'ai';
const { image } = await generateImage({
model: xai.image('grok-2-image'),
prompt: 'A futuristic cityscape at sunset',
});

The xAI image model does not currently support the aspectRatio or size parameters. Image size defaults to 1024x768.

Model-specific options

You can customize the image generation behavior with model-specific settings:

import { xai } from '@ai-sdk/xai';
import { experimental_generateImage as generateImage } from 'ai';
const { images } = await generateImage({
model: xai.image('grok-2-image'),
prompt: 'A futuristic cityscape at sunset',
maxImagesPerCall: 5, // Default is 10
n: 2, // Generate 2 images
});

Model Capabilities

ModelSizesNotes
grok-2-image1024x768 (default)xAI's text-to-image generation model, designed to create high-quality images from text prompts. It's trained on a diverse dataset and can generate images across various styles, subjects, and settings.