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 send using the
Authorization
header. It defaults to theXAI_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-beta
.
const model = xai('grok-beta');
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-beta'), prompt: 'Write a vegetarian lasagna recipe for 4 people.',});
xAI language models can also be used in the streamText
, generateObject
, streamObject
, and streamUI
functions
(see AI SDK Core and AI SDK RSC).
Chat Models
xAI chat models also support some model specific settings that are not part of the standard call settings. You can pass them as an options argument:
const model = xai('grok-beta', { user: 'test-user', // optional unique user identifier});
The following optional settings are available for xAI chat models:
-
user string
A unique identifier representing your end-user, which can help xAI to monitor and detect abuse.
Model Capabilities
xAI available models are listed in the xAI console under "View models", including:
Model | Image Input | Object Generation | Tool Usage | Tool Streaming |
---|---|---|---|---|
grok-beta |
You can also pass any available provider model ID as a string if needed.