xai-org/xai-sdk-python
Python
Captured source
source ↗xai-org/xai-sdk-python
Description: The official Python SDK for the xAI API
Language: Python
License: Apache-2.0
Stars: 475
Forks: 124
Open issues: 18
Created: 2025-06-09T22:19:19Z
Pushed: 2026-06-10T17:15:07Z
Default branch: main
Fork: no
Archived: no
README:
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.
pip install xai-sdk
Alternatively you can also use uv
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](/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:
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:
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.
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.
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.
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 Understanding
You can easily interleave images and text together, making tasks like image understanding and analysis easy.
from xai_sdk import Client
from xai_sdk.chat import image, user
client = Client()
chat = client.chat.create(model="grok-2-vision")
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}")Video Generation
Generate videos from text prompts using the grok-imagine-video model. The SDK handles the asynchronous polling workflow automatically — you submit a prompt and receive the completed video response.
from xai_sdk import Client
client = Client()
response = client.video.generate(
prompt="A serene lake at sunrise with mist rolling over the water",
model="grok-imagine-video",
duration=5,
aspect_ratio="16:9",
resolution="720p",
)
print(f"Video URL: {response.url}")
print(f"Duration: {response.duration}s")You can also generate videos from an input image (image-to-video):
response = client.video.generate(
prompt="The camera slowly zooms in as the scene comes to life",
model="grok-imagine-video",
image_url="https://example.com/landscape.jpg",
duration=5,
)
print(f"Video URL: {response.url}")Or use reference images to guide the style and content of the generated video:
response = client.video.generate(
prompt="A person walking through a futuristic city",
model="grok-imagine-video",
reference_image_urls=[
"https://example.com/style-ref1.jpg",
"https://example.com/style-ref2.jpg",
],
duration=10,
aspect_ratio="16:9",
)
print(f"Video URL: {response.url}")Video Editing
Edit an existing video based on a text prompt by passing video_url to generate():
response = client.video.generate( prompt="Add a…
Excerpt shown — open the source for the full document.
Notability
notability 5.0/10New SDK release with moderate stars, notable but not major