You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
To use [`XaiModel`][pydantic_ai.models.xai.XaiModel], you need to either install `pydantic-ai`, or install `pydantic-ai-slim` with the `xai` optional group:
6
+
7
+
```bash
8
+
pip/uv-add "pydantic-ai-slim[xai]"
9
+
```
10
+
11
+
## Configuration
12
+
13
+
To use xAI models from [xAI](https://x.ai/api) through their API, go to [console.x.ai](https://console.x.ai/team/default/api-keys) to create an API key.
14
+
15
+
[`GrokModelName`][pydantic_ai.providers.grok.GrokModelName] contains a list of available xAI models.
16
+
17
+
## Environment variable
18
+
19
+
Once you have the API key, you can set it as an environment variable:
20
+
21
+
```bash
22
+
export XAI_API_KEY='your-api-key'
23
+
```
24
+
25
+
You can then use [`XaiModel`][pydantic_ai.models.xai.XaiModel] by name:
26
+
27
+
```python
28
+
from pydantic_ai import Agent
29
+
30
+
agent = Agent('xai:grok-4-1-fast-non-reasoning')
31
+
...
32
+
```
33
+
34
+
Or initialise the model directly:
35
+
36
+
```python
37
+
from pydantic_ai import Agent
38
+
from pydantic_ai.models.xai import XaiModel
39
+
40
+
# Uses XAI_API_KEY environment variable
41
+
model = XaiModel('grok-4-1-fast-non-reasoning')
42
+
agent = Agent(model)
43
+
...
44
+
```
45
+
46
+
You can also customize the [`XaiModel`][pydantic_ai.models.xai.XaiModel] with a custom provider:
47
+
48
+
```python
49
+
from pydantic_ai import Agent
50
+
from pydantic_ai.models.xai import XaiModel
51
+
from pydantic_ai.providers.xai import XaiProvider
52
+
53
+
# Custom API key
54
+
provider = XaiProvider(api_key='your-api-key')
55
+
model = XaiModel('grok-4-1-fast-non-reasoning', provider=provider)
56
+
agent = Agent(model)
57
+
...
58
+
```
59
+
60
+
Or with a custom `xai_sdk.AsyncClient`:
61
+
62
+
```python
63
+
from xai_sdk import AsyncClient
64
+
from pydantic_ai import Agent
65
+
from pydantic_ai.models.xai import XaiModel
66
+
from pydantic_ai.providers.xai import XaiProvider
67
+
68
+
xai_client = AsyncClient(api_key='your-api-key')
69
+
provider = XaiProvider(xai_client=xai_client)
70
+
model = XaiModel('grok-4-1-fast-non-reasoning', provider=provider)
0 commit comments