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

# xAI Provider

> Create and configure the xAI provider for Grok models

## Overview

The xAI provider connects to the [xAI API](https://docs.x.ai/) for Grok models. It uses the Responses API by default and also supports the legacy Chat Completions API.

## Installation

```bash theme={null}
npm install @core-ai/xai
```

## createXAI()

Create an xAI provider instance.

```typescript theme={null}
import { createXAI } from '@core-ai/xai';

const xai = createXAI({
    apiKey: process.env.XAI_API_KEY,
});
```

### Options

**apiKey** `string`

Your xAI API key.

**baseURL** `string`

Custom API base URL. Defaults to `https://api.x.ai/v1`.

**client** `OpenAI`

Provide your own configured OpenAI SDK client instance.

### Returns

`XAIProvider` with methods:

* `chatModel(modelId)` — Responses API. Use this for new code.
* `chat.chatModel(modelId)` — legacy Chat Completions API.

## Responses API behavior

`xai.chatModel()` sends stateless requests. The provider sets `store: false`, so xAI does not retain your conversations, and requests encrypted reasoning content so reasoning survives multi-turn conversations without server-side state.

Set `providerOptions.xai.store` to `true` to opt in to xAI's server-side storage.

## Supported models

* **grok-4.7**, **grok-4.6**, **grok-4.5**, **grok-4.3** — always-on reasoning with effort control
* **grok-4.20-0309-reasoning**, **grok-4.20-multi-agent-0309** — always-on reasoning without effort control
* **grok-4.20-0309-non-reasoning** — no reasoning
* **grok-build-0.1** — coding model with always-on reasoning and no effort control

Aliases published by xAI, such as `grok-4.5-latest` and `grok-4.20`, resolve to the same capabilities. Unknown model IDs are treated like `grok-4.7`: always-on reasoning with effort control.

## Provider support

| Feature | Support |
| - | - |
| Chat Completion | Yes |
| Streaming | Yes |
| Function Calling | Yes |
| Vision | Yes |
| Reasoning | Yes |
| Structured Output (`generateObject` / `streamObject`) | Yes (native `json_schema`) |
| Embeddings | No |
| Image Generation | No |

xAI's server-side tools (web search, X search, code execution, remote MCP) are not available through this provider.

## Model capabilities

Inspect `model.capabilities` before setting reasoning or tool options:

```typescript theme={null}
const model = xai.chatModel('grok-4.7');
const capabilities = model.capabilities;
```

* `reasoning.mode` is `always-on` for every model except `grok-4.20-0309-non-reasoning`, where it is `unsupported`. xAI lets `grok-4.3` skip reasoning with an effort of `none`, which core-ai does not expose, so `grok-4.3` always reasons.
* `supportedEfforts` is `['low', 'medium', 'high', 'max']` for models with effort control and empty otherwise. `max` is sent as `xhigh`. Other efforts are clamped to the nearest supported value.
* `restrictsSamplingParams` is `false`; `temperature` and `topP` are accepted.
* `modalities.input` is `['text', 'image']` for every model.

An empty effort list does not mean reasoning output is unavailable. It means the model chooses its own reasoning effort, and the provider never sends an effort parameter.

### Strict tool schemas

xAI models report `model.capabilities.tools.strictSchemas` as `{ supported: true }`. Tools with `strict: true` are forwarded per tool with a normalized schema; other tools are sent unchanged. See [Strict tool schemas](https://docs.core-ai.dev/guides/tool-calling.md#strict-tool-schemas) for the schema contract and error reasons.

## Examples

### Basic chat

```typescript theme={null}
import { createXAI } from '@core-ai/xai';
import { generate } from '@core-ai/core-ai';

const xai = createXAI({
    apiKey: process.env.XAI_API_KEY,
});

const model = xai.chatModel('grok-4.7');

const result = await generate({
    model,
    messages: [{ role: 'user', content: 'Explain quantum tunneling briefly.' }],
});

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

### Reasoning effort

```typescript theme={null}
import { createXAI } from '@core-ai/xai';
import { stream } from '@core-ai/core-ai';

const xai = createXAI({ apiKey: process.env.XAI_API_KEY });

const chatStream = await stream({
    model: xai.chatModel('grok-4.7'),
    messages: [{ role: 'user', content: 'Prove that √2 is irrational.' }],
    reasoning: { effort: 'max' },
});

for await (const event of chatStream) {
    if (event.type === 'reasoning-delta') {
        process.stdout.write(event.text);
    }
    if (event.type === 'text-delta') {
        process.stdout.write(event.text);
    }
}
```

### Multi-turn reasoning preservation

Use `resultToMessage()` to carry reasoning into the next turn. On the Responses API, the provider replays encrypted reasoning items. On Chat Completions, it replays `reasoning_content`.

```typescript theme={null}
import { createXAI } from '@core-ai/xai';
import { generate, resultToMessage } from '@core-ai/core-ai';

const xai = createXAI({ apiKey: process.env.XAI_API_KEY });
const model = xai.chatModel('grok-4.7');

const messages = [{ role: 'user', content: 'Plan a refactor.' }];
const firstResult = await generate({ model, messages });

const followUp = await generate({
    model,
    messages: [
        ...messages,
        resultToMessage(firstResult),
        { role: 'user', content: 'Now implement step one.' },
    ],
});
```

Encrypted reasoning is only replayed to xAI. Reasoning produced by another provider is sent as plain text.

### Structured output

```typescript theme={null}
import { createXAI } from '@core-ai/xai';
import { generateObject } from '@core-ai/core-ai';
import { z } from 'zod';

const xai = createXAI({ apiKey: process.env.XAI_API_KEY });

const result = await generateObject({
    model: xai.chatModel('grok-4.7'),
    messages: [{ role: 'user', content: 'Return the weather for Berlin.' }],
    schema: z.object({
        city: z.string(),
        temperatureC: z.number(),
    }),
    schemaName: 'weather_schema',
});

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

## Usage reporting

`usage.outputTokens` includes reasoning tokens on both APIs, and `usage.outputTokenDetails.reasoningTokens` reports them separately. xAI's Chat Completions API excludes reasoning tokens from `completion_tokens`; the provider adds them so totals are comparable across providers.

## Provider-specific options

Pass xAI-specific options via `providerOptions.xai`:

```typescript theme={null}
await generate({
    model: xai.chatModel('grok-4.7'),
    messages: [{ role: 'user', content: 'Hello!' }],
    providerOptions: {
        xai: {
            promptCacheKey: 'conversation-42',
            parallelToolCalls: false,
        },
    },
});
```

Available fields:

* Responses API (`xai.chatModel()`): `store`, `include`, `parallelToolCalls`, `user`, `promptCacheKey`
* Chat Completions API (`xai.chat.chatModel()`): `parallelToolCalls`, `seed`, `user`

`promptCacheKey` routes requests that share a prefix to the same cache, which improves cache hit rates in long conversations.

> [!WARNING]
>
> Stop sequences and frequency or presence penalties are not available. xAI
> reasoning models reject these parameters.

## Error handling

```typescript theme={null}
import { ProviderError } from '@core-ai/core-ai';

try {
    const result = await generate({
        model: xai.chatModel('grok-4.7'),
        messages: [{ role: 'user', content: 'Hello!' }],
    });
} catch (error) {
    if (error instanceof ProviderError) {
        console.error('xAI API error:', error.message);
        console.error('Status:', error.statusCode);
    }
}
```

## Related

> **[OpenAI Provider](https://docs.core-ai.dev/api/providers/openai.md)**
>
> Responses and Chat Completions reference

> **[core-ai Functions](https://docs.core-ai.dev/api/core/generate.md)**
>
> Learn about generate, stream, and more


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.