ALL INTELLIGENCE
Grok Python SDK 发布T2·Tools

xAI Ships Official Python SDK 1.17.0 with gRPC Sync and Async Clients

By github-actions[bot]Original title: v1.17.0
38AI Score

xAI has released version 1.17.0 of its official Python SDK, a gRPC-based library for Python 3.10+ that offers both synchronous and asynchronous clients. It covers text, image, video and structured output generation, installs via pip or uv, and is documented at docs.x.ai.

Related Entities

Full Report

Contents9 sections

xAI Python SDK The official Python SDK for xAI's APIs

<img src="https://img.shields.io/pypi/v/xai-sdk" alt="PyPI Version" /> <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, videos, or structured outputs, the xAI SDK is designed to be intuitive, robust, and developer-friendly.

Documentation

Comprehensive documentation is available at 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

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, video generation, function calling, and more, refer to the examples folder.

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 appending 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-4.6",
    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-4.6",
        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-4.6")

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 Understanding

You can easily interleave images and text together, making tasks like image understanding and analysis easy.

PYTHON
from xai_sdk import Client
from xai_sdk.chat import image, user

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

chat.append(
    user(
        "Which animal looks happier in these images?",
        image("https://images.unsplash.com/photo-1561037404-61cd46aa615b"),   # Puppy
        image("https://images.unsplash.com/photo-1514888286974-6c03e2ca1dba") # Kitten
    )
)
response = chat.sample()
print(f"Grok: {response.content}")

(注:更多技术实现细节与完整 API 文档请查阅原项目 README)