Skip to main content

xAI logoxAI

Access 12 xAI models through Mastra's model router. Authentication is handled automatically using the XAI_API_KEY environment variable.

Learn more in the xAI documentation.

.env
XAI_API_KEY=your-api-key
src/mastra/agents/my-agent.ts
import { Agent } from "@mastra/core/agent";

const agent = new Agent({
id: "my-agent",
name: "My Agent",
instructions: "You are a helpful assistant",
model: "xai/grok-4.20-0309-non-reasoning"
});

// Generate a response
const response = await agent.generate("Hello!");

// Stream a response
const stream = await agent.stream("Tell me a story");
for await (const chunk of stream) {
console.log(chunk);
}

Models
Direct link to Models

ModelContextToolsReasoningImageAudioVideoInput $/1MOutput $/1M
xai/grok-4.20-0309-non-reasoning1.0M$1$3
xai/grok-4.20-0309-reasoning1.0M$1$3
xai/grok-4.20-multi-agent-03091.0M$1$3
xai/grok-4.31.0M$1$3
xai/grok-4.5500K$2$6
xai/grok-4.6500K$2$6
xai/grok-build-0.1256K$1$2
xai/grok-imagine-image16K
xai/grok-imagine-image-2.064K
xai/grok-imagine-image-quality16K
xai/grok-imagine-video1K
xai/grok-imagine-video-1.51K
12 available models

Model availability, capabilities, context windows, and pricing are sourced from models.dev and may change.

Advanced configuration
Direct link to Advanced configuration

Custom headers
Direct link to Custom headers

src/mastra/agents/my-agent.ts
const agent = new Agent({
id: "custom-agent",
name: "custom-agent",
model: {
id: "xai/grok-4.20-0309-non-reasoning",
apiKey: process.env.XAI_API_KEY,
headers: {
"X-Custom-Header": "value"
}
}
});

Dynamic model selection
Direct link to Dynamic model selection

src/mastra/agents/my-agent.ts
const agent = new Agent({
id: "dynamic-agent",
name: "Dynamic Agent",
model: ({ requestContext }) => {
const useAdvanced = requestContext.task === "complex";
return useAdvanced
? "xai/grok-imagine-video-1.5"
: "xai/grok-4.20-0309-non-reasoning";
}
});

Provider Options
Direct link to Provider Options

xAI supports the following provider-specific options via the providerOptions parameter:

const response = await agent.generate("Hello!", {
providerOptions: {
xai: {
// See available options in the table below
}
}
});

Available Options
Direct link to Available Options

reasoningEffort?:

"none" | "low" | "medium" | "high" | undefined

logprobs?:

boolean | undefined

topLogprobs?:

number | undefined

parallel_function_calling?:

boolean | undefined

searchParameters?:

{ mode: "off" | "auto" | "on"; returnCitations?: boolean | undefined; fromDate?: string | undefined; toDate?: string | undefined; maxSearchResults?: number | undefined; sources?: ({ ...; } | ... 2 more ... | { ...; })[] | undefined; } | undefined