# xai-sdk

> The official Python SDK for the xAI API

- **URL**: https://www.freshcrate.ai/projects/xai-sdk
- **Author**: pypi
- **Category**: RAG & Memory
- **Latest version**: `v1.15.0` (2026-05-30)
- **License**: Unknown
- **Source**: https://github.com/xai-org/xai-sdk-python
- **Homepage**: https://pypi.org/project/xai-sdk/
- **Language**: Python
- **GitHub**: 412 stars, 90 forks
- **Registry**: pypi (`xai-sdk`)
- **Tags**: `pypi`

## Description

<div align="center">
  <img src="https://avatars.githubusercontent.com/u/130314967?s=200&v=4" alt="xAI Logo" width="100" />
  <h1>xAI Python SDK</h1>
  <p>The official Python SDK for xAI's APIs</p>
  <a href="https://pypi.org/project/xai-sdk">
    <img src="https://img.shields.io/pypi/v/xai-sdk" alt="PyPI Version" />
  </a>
  <a href="">
    <img src="https://img.shields.io/pypi/l/xai-sdk" alt="License" />
  </a>
  <a href="">
    <img src="https://img.shields.io/pypi/pyversions/xai-sdk" alt="Python Version" />
  </a>
</div>

<br>

The xAI Python SDK is a gRPC-based Python library for interacting with xAI's APIs. Built for Python 3.10 and above, it offers both **synchronous** and **asynchronous** clients.

Whether you're generating text, images, or structured outputs, the xAI SDK is designed to be intuitive, robust, and developer-friendly.

## Documentation

Comprehensive documentation is available at [docs.x.ai](https://docs.x.ai). Explore detailed guides, API references, and tutorials to get the most out of the xAI SDK.

## Installation

Install from PyPI with pip.

```bash
pip install xai-sdk
```

Alternatively you can also use [uv](https://docs.astral.sh/uv/)

```bash
uv add xai-sdk
```

### Requirements
Python 3.10 or higher is required to use the xAI SDK.

## Usage

The xAI SDK supports both synchronous (`xai_sdk.Client`) and asynchronous (`xai_sdk.AsyncClient`) clients. For a complete set of examples demonstrating the SDK's capabilities, including authentication, chat, image generation, function calling, and more, refer to the [examples folder](https://github.com/xai-org/xai-sdk-python/tree/main/examples).

### Client Instantiation

To use the xAI SDK, you need to instantiate either a synchronous or asynchronous client. By default, the SDK looks for an environment variable named `XAI_API_KEY` for authentication. If this variable is set, you can instantiate the clients without explicitly passing the API key:

```python
from xai_sdk import Client, AsyncClient

# Synchronous client
sync_client = Client()

# Asynchronous client
async_client = AsyncClient()
```

If you prefer to explicitly pass the API key, you can do so using `os.getenv` or by loading it from a `.env` file using the `python-dotenv` package:

```python
import os
from dotenv import load_dotenv
from xai_sdk import Client, AsyncClient

load_dotenv()

api_key = os.getenv("XAI_API_KEY")
sync_client = Client(api_key=api_key)
async_client = AsyncClient(api_key=api_key)
```

Make sure to set the `XAI_API_KEY` environment variable or load it from a `.env` file before using the SDK. This ensures secure handling of your API key without hardcoding it into your codebase.

### Multi-Turn Chat (Synchronous)

The xAI SDK supports multi-turn conversations with a simple `append` method to manage conversation history, making it ideal for interactive applications.

First, create a `chat` instance, start `append`ing messages to it, and finally call `sample` to yield a response from the model. While the underlying APIs are still stateless, this approach makes it easy to manage the message history.

```python
from xai_sdk import Client
from xai_sdk.chat import system, user

client = Client()
chat = client.chat.create(
    model="grok-3",
    messages=[system("You are a pirate assistant.")]
)

while True:
    prompt = input("You: ")
    if prompt.lower() == "exit":
        break
    chat.append(user(prompt))
    response = chat.sample()
    print(f"Grok: {response.content}")
    chat.append(response)
```

### Multi-Turn Chat (Asynchronous)

For async usage, simply import `AsyncClient` instead of `Client`.

```python
import asyncio
from xai_sdk import AsyncClient
from xai_sdk.chat import system, user

async def main():
    client = AsyncClient()
    chat = client.chat.create(
        model="grok-3",
        messages=[system("You are a pirate assistant.")]
    )

    while True:
        prompt = input("You: ")
        if prompt.lower() == "exit":
            break
        chat.append(user(prompt))
        response = await chat.sample()
        print(f"Grok: {response.content}")
        chat.append(response)

if __name__ == "__main__":
    asyncio.run(main())
```

### Streaming

The xAI SDK supports streaming responses, allowing you to process model outputs in real-time, which is ideal for interactive applications like chatbots. The `stream` method returns a tuple containing `response` and `chunk`. The chunks contain the text deltas from the stream, while the `response` variable automatically accumulates the response as the stream progresses.

```python
from xai_sdk import Client
from xai_sdk.chat import user

client = Client()
chat = client.chat.create(model="grok-3")

while True:
    prompt = input("You: ")
    if prompt.lower() == "exit":
        break
    chat.append(user(prompt))
    print("Grok: ", end="", flush=True)
    for response, chunk in chat.stream():
        print(chunk.content, end="", flush=True)
    print()
    chat.append(response)
```

### Image

## Recent releases

| Version | Date | Urgency | Changes |
| --- | --- | --- | --- |
| `v1.15.0` | 2026-05-30 | High | ## What's Changed * Add grok-build-0.1 to ChatModel by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/155 * Add context compaction support by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/156 * Bump version from 1.14.0 to 1.15.0 by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/157   **Full Changelog**: https://github.com/xai-org/xai-sdk-python/compare/v1.14.0...v1.15.0 |
| `v1.14.0` | 2026-05-27 | High | ## What's Changed * Add enable_image_search to web_search and SERVER_SIDE_TOOL_IMAGE_SEARCH enum by @ushiromiya-lion in https://github.com/xai-org/xai-sdk-python/pull/152 * Bump version to 1.14.0 by @ushiromiya-lion in https://github.com/xai-org/xai-sdk-python/pull/153  ## New Contributors * @ushiromiya-lion made their first contribution in https://github.com/xai-org/xai-sdk-python/pull/152  **Full Changelog**: https://github.com/xai-org/xai-sdk-python/compare/v1.13.0...v1.14.0 |
| `v1.13.0` | 2026-05-16 | High | ## What's Changed * feat: add prepare_extension() for batch video extension by @double-di in https://github.com/xai-org/xai-sdk-python/pull/141   **Full Changelog**: https://github.com/xai-org/xai-sdk-python/compare/v1.12.2...v1.13.0 |
| `v1.12.2` | 2026-05-07 | High | ## What's Changed * Add none and medium reasoning effort levels by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/139 * Bump version from 1.12.1 to 1.12.2 by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/140   **Full Changelog**: https://github.com/xai-org/xai-sdk-python/compare/v1.12.1...v1.12.2 |
| `v1.12.1` | 2026-04-30 | High | ## What's Changed * Update the CHANGELOG with missing entries by @Omar-V2 in https://github.com/xai-org/xai-sdk-python/pull/135 * Add grok-4.3 to ChatModel by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/137 * Bump version from 1.12.0 to 1.12.1 by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/138   **Full Changelog**: https://github.com/xai-org/xai-sdk-python/compare/v1.12.0...v1.12.1 |
| `v1.12.0` | 2026-04-29 | High | ## What's Changed * docs: add video generation and extension documentation to README by @double-di in https://github.com/xai-org/xai-sdk-python/pull/127 * Add collection descriptions, field definition updates, and bytes chunking by @Omar-V2 in https://github.com/xai-org/xai-sdk-python/pull/130 * Add `expires_after` to file uploads, drop `team_id` from `File` by @Omar-V2 in https://github.com/xai-org/xai-sdk-python/pull/131 * Add `cost_usd` tracking, model migration, example fixes by @Omar-V2 in |
| `1.11.0` | 2026-04-21 | Low | Imported from PyPI (1.11.0) |
| `v1.11.0` | 2026-03-27 | Medium | ## What's Changed * Support inline file attachments by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/122 * Add url support for FileContent by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/123 * Bump version from 1.10.0 to 1.11.0 by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/124   **Full Changelog**: https://github.com/xai-org/xai-sdk-python/compare/v1.10.0...v1.11.0 |
| `v1.11.0` | 2026-03-27 | Medium | ## What's Changed * Support inline file attachments by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/122 * Add url support for FileContent by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/123 * Bump version from 1.10.0 to 1.11.0 by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/124   **Full Changelog**: https://github.com/xai-org/xai-sdk-python/compare/v1.10.0...v1.11.0 |
| `v1.11.0` | 2026-03-27 | Medium | ## What's Changed * Support inline file attachments by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/122 * Add url support for FileContent by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/123 * Bump version from 1.10.0 to 1.11.0 by @shawnthapa in https://github.com/xai-org/xai-sdk-python/pull/124   **Full Changelog**: https://github.com/xai-org/xai-sdk-python/compare/v1.10.0...v1.11.0 |

## Citation

- HTML: https://www.freshcrate.ai/projects/xai-sdk
- Markdown: https://www.freshcrate.ai/projects/xai-sdk.md
- Dependencies JSON: https://www.freshcrate.ai/api/projects/xai-sdk/deps

_Generated by freshcrate.ai. Indexes pypi releases for AI-agent ecosystem packages._
