### Install Dependencies with uv Source: https://github.com/xai-org/xai-sdk-python/blob/main/CONTRIBUTING.md Installs project dependencies and sets up the virtual environment using uv. Ensure Python version is 3.10+ and uv is installed. ```bash uv sync ``` -------------------------------- ### Install xAI Python SDK Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Install the SDK using pip or uv. Ensure Python 3.10 or higher is used. ```bash pip install xai-sdk ``` ```bash uv add xai-sdk ``` -------------------------------- ### Install Telemetry Dependencies Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Installs the necessary dependencies for HTTP or gRPC OTLP export for the telemetry feature. ```bash # For HTTP OTLP export pip install xai-sdk[telemetry-http] # or uv add xai-sdk[telemetry-http] ``` ```bash # For gRPC OTLP export pip install xai-sdk[telemetry-grpc] # or uv add xai-sdk[telemetry-grpc] ``` -------------------------------- ### Video Generation from Image Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Illustrates how to generate a video starting from an input image URL. ```APIDOC ### Image-to-Video Generation Generate videos from an input image. ### Method ```python 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}") ``` ``` -------------------------------- ### Image Generation and Editing Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Examples of using the `client.image.sample` and `client.image.sample_batch` methods for various image generation and editing tasks. ```APIDOC ## Image-to-image (editing with a reference) `client.image.sample` can be used to edit an image based on a prompt and a reference image URL. ### Parameters - **prompt** (string) - Required - The text prompt describing the desired image. - **model** (string) - Required - The model to use for generation (e.g., "grok-imagine-image"). - **image_url** (string) - Required - The URL of the image to edit. - **aspect_ratio** (string) - Optional - The desired aspect ratio (e.g., "16:9"). - **image_format** (string) - Optional - The desired output format (e.g., "base64"). ### Request Example ```python edited = client.image.sample( prompt="Same scene but during a snow storm", model="grok-imagine-image", image_url="https://example.com/lake.jpg", aspect_ratio="16:9", image_format="base64", ) print(f"Base64 prefix: {edited.base64[:40]}...") ``` ## Multi-reference editing Multiple image URLs can be provided to influence the generation. ### Parameters - **prompt** (string) - Required - The text prompt describing the desired image. - **model** (string) - Required - The model to use for generation (e.g., "grok-imagine-image"). - **image_urls** (list of strings) - Required - A list of URLs of reference images. ### Request Example ```python multi = client.image.sample( prompt="Combine these two styles", model="grok-imagine-image", image_urls=["https://example.com/style1.jpg", "https://example.com/style2.jpg"], ) ``` ## Generate a batch of images `client.image.sample_batch` generates multiple images based on a prompt. ### Parameters - **prompt** (string) - Required - The text prompt describing the desired images. - **model** (string) - Required - The model to use for generation (e.g., "grok-imagine-image"). - **n** (integer) - Required - The number of images to generate. - **aspect_ratio** (string) - Optional - The desired aspect ratio (e.g., "1:1"). ### Request Example ```python batch = client.image.sample_batch( prompt="A futuristic city skyline", model="grok-imagine-image", n=4, aspect_ratio="1:1", ) for i, img in enumerate(batch): print(f"Image {i+1}: {img.url}") ``` ``` -------------------------------- ### Install pre-commit Hooks Source: https://github.com/xai-org/xai-sdk-python/blob/main/CONTRIBUTING.md Installs pre-commit hooks for linting, formatting, and secret detection. This helps prevent erroneous changes from being committed. ```bash uv run pre-commit install ``` -------------------------------- ### List and Get Language, Image, and Embedding Models Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Query available model metadata such as pricing and token limits. Ensure the Client is initialized before use. ```python from xai_sdk import Client client = Client() # List all language models models = client.models.list_language_models() for m in models: print(f"{m.name}: max_prompt={m.max_prompt_length} tokens") # Get specific model details model = client.models.get_language_model("grok-4.20-non-reasoning") print(f"Model: {model.name}") print(f"Aliases: {list(model.aliases)}") # List image generation models img_models = client.models.list_image_generation_models() for m in img_models: print(m.name) # List embedding models emb_models = client.models.list_embedding_models() for m in emb_models: print(m.name) ``` -------------------------------- ### Custom TracerProvider Configuration Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Shows how to provide a custom TracerProvider for the xAI SDK, useful when integrating with an existing OpenTelemetry setup. Ensure OpenTelemetry is installed. ```python from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.resources import Resource from xai_sdk.telemetry import Telemetry # Create custom provider with specific configuration custom_resource = Resource.create({"service.name": "my-app"}) custom_provider = TracerProvider(resource=custom_resource) # Use the custom tracer provider telemetry = Telemetry(provider=custom_provider) telemetry.setup_otlp_exporter() ``` -------------------------------- ### Setup OTLP Telemetry Exporter with Custom Provider Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Configures the Telemetry SDK for OTLP export using a custom TracerProvider. Suitable for production environments or when integrating with existing OpenTelemetry setups. ```python # OTLP export (production) — reads OTEL_EXPORTER_OTLP_* env vars # telemetry.setup_otlp_exporter( # endpoint="https://your-platform.com/traces", # headers={\"Authorization\": \"Bearer token\"}, # ) # Custom TracerProvider (for apps already using OTel) provider = TracerProvider(resource=Resource.create({"service.name": "my-app"})) telemetry2 = Telemetry(provider=provider) telemetry2.setup_otlp_exporter() ``` -------------------------------- ### Generate Video with Reference Images Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Guide video generation style and content by providing reference image URLs. This allows for more specific aesthetic control. ```python 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}") ``` -------------------------------- ### Setup OTLP Telemetry Exporter Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Configure the Telemetry class to export OpenTelemetry traces to an OTLP-compliant backend for production environments. Requires endpoint and authorization. ```python from xai_sdk.telemetry import Telemetry telemetry = Telemetry() telemetry.setup_otlp_exporter( endpoint="https://your-observability-platform.com/traces", headers={"Authorization": "Bearer your-token"} ) client = Client() ``` -------------------------------- ### Generate Video from Input Image Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Create a video from an input image URL using the `grok-imagine-video` model. The prompt guides the scene's animation. ```python 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}") ``` -------------------------------- ### Setup Console Telemetry Exporter Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Configures the Telemetry SDK to export traces to the console. Ideal for development and debugging. ```python from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.resources import Resource from xai_sdk import Client from xai_sdk.chat import user from xai_sdk.telemetry import Telemetry client = Client() # Console export (development / debugging) telemetry = Telemetry() telemetry.setup_console_exporter() ``` -------------------------------- ### Get xAI SDK Version Programmatically in Python Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Import the xAI SDK in your Python code and access the `__version__` attribute to retrieve the installed version. This is useful for debugging or ensuring compatibility. ```python import xai_sdk print(xai_sdk.__version__) ``` -------------------------------- ### Video Generation with Reference Images Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Demonstrates using reference image URLs to guide the style and content of the generated video. ```APIDOC ### Video Generation with Reference Images Use reference images to guide the style and content of the generated video. ### Method ```python 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}") ``` ``` -------------------------------- ### File Management Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Documentation for `client.files` methods including upload, list, get, delete, and content retrieval. ```APIDOC ## files.upload() / files.list() / files.get() / files.delete() / files.content() `client.files.upload(file, *, filename, on_progress, expires_after)` — streams a file to xAI servers in 3 MiB chunks. Accepts a file path string, raw bytes, or a binary file-like object. Files can be referenced in chat messages via `chat.file(file_id)` or in collections. The returned `File` proto includes `.id`, `.filename`, `.size`, and `.created_at`. ### Parameters for `upload()` - **file** (string or bytes or file-like object) - Required - The file content to upload. - **filename** (string) - Optional - The desired filename for the uploaded file. - **on_progress** (callable) - Optional - A callback function to track upload progress. - **expires_after** (datetime.timedelta) - Optional - Duration after which the file will expire. ### Request Example (Upload from file path) ```python file_meta = client.files.upload("document.pdf") print(f"File ID: {file_meta.id}, Name: {file_meta.filename}") ``` ### Request Example (Upload from bytes with expiry) ```python data = b"col1,col2\n1,2\n3,4" file_meta2 = client.files.upload( data, filename="data.csv", expires_after=datetime.timedelta(hours=24), ) ``` ### Request Example (Upload from file object) ```python with open("report.pdf", "rb") as f: file_meta3 = client.files.upload(f) ``` ### Request Example (Upload with progress bar) ```python from tqdm import tqdm import os path = "large_file.zip" with tqdm(total=os.path.getsize(path), unit="B", unit_scale=True) as pbar: file_meta4 = client.files.upload(path, on_progress=pbar) ``` ### Request Example (Batch upload) ```python results = client.files.batch_upload( ["file1.pdf", "file2.pdf", "file3.pdf"], batch_size=10, on_file_complete=lambda idx, f, r: print(f"[{idx}] {'OK' if not isinstance(r, Exception) else r}"), ) ``` ### File Operations #### List files `client.files.list(limit, order, sort_by)` ```python listing = client.files.list(limit=50, order="desc", sort_by="created_at") for f in listing.files: print(f.id, f.filename) ``` #### Get file metadata `client.files.get(file_id)` ```python meta = client.files.get(file_meta.id) ``` #### Get file content `client.files.content(file_id)` ```python content_bytes = client.files.content(file_meta.id) ``` #### Delete file `client.files.delete(file_id)` ```python client.files.delete(file_meta.id) ``` ``` -------------------------------- ### Create a Basic Chat Conversation Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Initializes a chat conversation with a specified model and system message. You can set parameters like temperature, max tokens, and seed. The `sample()` method is used to get a response from the model. ```python from xai_sdk import Client from xai_sdk.chat import system, user, assistant client = Client() # Basic multi-turn conversation chat = client.chat.create( model="grok-4.20-non-reasoning", messages=[system("You are a helpful pirate assistant.")], temperature=0.7, max_tokens=512, seed=42, ) chat.append(user("What is the capital of France?")) response = chat.sample() print(response.content) # "Paris, ye landlubber!" print(response.finish_reason) # "FINISH_REASON_STOP" print(response.usage.total_tokens) # e.g. 42 print(response.cost_usd) # e.g. 0.0001 or None # Continue the conversation chat.append(response) chat.append(user("And what is its population?")) response2 = chat.sample() print(response2.content) ``` -------------------------------- ### Asynchronous Multi-Turn Chat Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Perform multi-turn conversations asynchronously using `AsyncClient`. This example requires `asyncio` and demonstrates the async chat flow. ```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()) ``` -------------------------------- ### File Management with xAI SDK Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Illustrates file operations using `client.files` methods, including upload from various sources (path, bytes, object), progress tracking, batch uploads, listing, getting metadata, downloading content, and deleting files. ```python from xai_sdk import Client import datetime import io client = Client() # Upload from file path file_meta = client.files.upload("document.pdf") print(f"File ID: {file_meta.id}, Name: {file_meta.filename}") ``` ```python # Upload from bytes with expiry data = b"col1,col2\n1,2\n3,4" file_meta2 = client.files.upload( data, filename="data.csv", expires_after=datetime.timedelta(hours=24), ) ``` ```python # Upload from file object with open("report.pdf", "rb") as f: file_meta3 = client.files.upload(f) ``` ```python # Upload with tqdm progress bar from tqdm import tqdm import os path = "large_file.zip" with tqdm(total=os.path.getsize(path), unit="B", unit_scale=True) as pbar: file_meta4 = client.files.upload(path, on_progress=pbar) ``` ```python # Batch upload with concurrency results = client.files.batch_upload( ["file1.pdf", "file2.pdf", "file3.pdf"], batch_size=10, on_file_complete=lambda idx, f, r: print(f"[{idx}] {'OK' if not isinstance(r, Exception) else r}"), ) ``` ```python # List, get, download, delete listing = client.files.list(limit=50, order="desc", sort_by="created_at") for f in listing.files: print(f.id, f.filename) meta = client.files.get(file_meta.id) content_bytes = client.files.content(file_meta.id) client.files.delete(file_meta.id) ``` -------------------------------- ### Setup Console Telemetry Exporter Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Configure the Telemetry class to export OpenTelemetry traces to the console in JSON format. This is useful for development and debugging. ```python from xai_sdk.telemetry import Telemetry telemetry = Telemetry() telemetry.setup_console_exporter() client = Client() # The call to sample will now generate a trace that you will be able to see in the console chat = client.chat.create(model="grok-3") chat.append(user("Hello, how are you?")) response = chat.sample() print(f"Response: {response.content}") ``` -------------------------------- ### Interleave Images and Text for Analysis Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Use the `grok-2-vision` model to analyze interleaved images and text. Ensure the `xai_sdk` library is installed. ```python 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}") ``` -------------------------------- ### Check xAI SDK Version with uv Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Use this command in your terminal to display detailed information about the installed xAI SDK package, including its version number. ```bash uv pip show xai-sdk ``` -------------------------------- ### Check xAI SDK Version with pip Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Use this command in your terminal to display detailed information about the installed xAI SDK package, including its version number. ```bash pip show xai-sdk ``` -------------------------------- ### Define and Use Client-Side Tools with Pydantic Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Defines a client-side tool for getting weather information using Pydantic models for parameter schema generation. It demonstrates the workflow of appending user messages, sampling responses, and handling tool calls by executing the tool and appending its result. ```python import json from typing import Literal from pydantic import BaseModel, Field from xai_sdk import Client from xai_sdk.chat import system, user, tool, tool_result, required_tool client = Client() class WeatherRequest(BaseModel): city: str = Field(description="City name") units: Literal["C", "F"] = Field(description="Temperature units") def get_weather(city: str, units: str) -> str: temp = 22 if units == "C" else 72 return f"Sunny, {temp}°{units} in {city}" chat = client.chat.create( model="grok-4.20-non-reasoning", messages=[system("You are a weather assistant.")], tools=[ tool( name="get_weather", description="Get current weather for a city.", parameters=WeatherRequest.model_json_schema(), ) ], # tool_choice="auto" # default; use required_tool("get_weather") to force it ) chat.append(user("What's the weather in London in Celsius?")) response = chat.sample() chat.append(response) if response.tool_calls: for tc in response.tool_calls: args = json.loads(tc.function.arguments) result = get_weather(args["city"], args["units"]) chat.append(tool_result(result, tool_call_id=tc.id)) final = chat.sample() print(final.content) # "It's sunny and 22°C in London." ``` -------------------------------- ### Client Instantiation Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Demonstrates how to instantiate the synchronous and asynchronous clients for the xAI Python SDK, including options for API key and timeout configuration. ```APIDOC ## Client Instantiation `Client` / `AsyncClient` — entry point for all SDK interactions. Both clients read `XAI_API_KEY` from the environment by default. The synchronous client supports the context manager protocol; the async client supports `async with`. Both accept optional `timeout`, `channel_options`, `metadata`, `api_host`, and `use_insecure_channel` parameters. ```python import os from xai_sdk import Client, AsyncClient # Synchronous — reads XAI_API_KEY from environment automatically client = Client() # Explicit API key + custom timeout (seconds) client = Client(api_key=os.environ["XAI_API_KEY"], timeout=300) # Context manager for automatic channel cleanup with Client() as client: chat = client.chat.create(model="grok-4.20-non-reasoning") # Asynchronous client import asyncio async def main(): async with AsyncClient() as client: chat = client.chat.create(model="grok-4.20-non-reasoning") asyncio.run(main()) # Check installed version import xai_sdk print(xai_sdk.__version__) # "1.12.2" ``` ``` -------------------------------- ### Create and Sample Chat Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Demonstrates creating a chat instance, appending a user message, and sampling a response. This generates a trace visible in your observability platform. ```python chat = client.chat.create(model="grok-3") chat.append(user("Hello, how are you?")) response = chat.sample() print(f"Response: {response.content}") ``` -------------------------------- ### Instantiate xAI Python SDK Clients Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Demonstrates how to instantiate both synchronous and asynchronous clients. Clients automatically read the API key from the environment or accept it explicitly. The synchronous client supports context management for automatic cleanup. ```python import os from xai_sdk import Client, AsyncClient # Synchronous — reads XAI_API_KEY from environment automatically client = Client() # Explicit API key + custom timeout (seconds) client = Client(api_key=os.environ["XAI_API_KEY"], timeout=300) # Context manager for automatic channel cleanup with Client() as client: chat = client.chat.create(model="grok-4.20-non-reasoning") # Asynchronous client import asyncio async def main(): async with AsyncClient() as client: chat = client.chat.create(model="grok-4.20-non-reasoning") asyncio.run(main()) # Check installed version import xai_sdk print(xai_sdk.__version__) # "1.12.2" ``` -------------------------------- ### Image Generation with xAI SDK Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Demonstrates image generation using the `client.image.sample` and `client.image.sample_batch` methods. Supports various parameters like prompt, model, image URL, aspect ratio, and batch size. ```python edited = client.image.sample( prompt="Same scene but during a snow storm", model="grok-imagine-image", image_url="https://example.com/lake.jpg", aspect_ratio="16:9", image_format="base64", ) print(f"Base64 prefix: {edited.base64[:40]}...") ``` ```python multi = client.image.sample( prompt="Combine these two styles", model="grok-imagine-image", image_urls=["https://example.com/style1.jpg", "https://example.com/style2.jpg"], ) ``` ```python batch = client.image.sample_batch( prompt="A futuristic city skyline", model="grok-imagine-image", n=4, aspect_ratio="1:1", ) for i, img in enumerate(batch): print(f"Image {i+1}: {img.url}") ``` -------------------------------- ### Video Generation with xAI SDK Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Shows how to generate videos using `client.video.generate()`. Supports text-to-video, image-to-video, reference-to-video, and video editing. Includes options for duration, aspect ratio, resolution, and timeout. ```python from xai_sdk import Client import datetime client = Client() # Text-to-video response = client.video.generate( prompt="A timelapse of a sunset over the ocean with dramatic clouds", model="grok-imagine-video", duration=8, aspect_ratio="16:9", resolution="720p", timeout=datetime.timedelta(minutes=15), ) print(f"Video URL (24h): {response.url}") print(f"Duration: {response.duration}s") ``` ```python # Image-to-video (first frame driven) i2v = client.video.generate( prompt="The scene slowly comes to life with gentle waves", model="grok-imagine-video", image_url="https://example.com/lake.jpg", duration=5, ) print(f"I2V URL: {i2v.url}") ``` ```python # Reference-to-video r2v = client.video.generate( prompt="A cinematic scene inspired by these references", model="grok-imagine-video", reference_image_urls=[ "https://example.com/ref1.jpg", "https://example.com/ref2.jpg", ], ) ``` ```python # Video editing (video-to-video) edited = client.video.generate( prompt="Add a rainbow arching across the sky", model="grok-imagine-video", video_url="https://example.com/my-video.mp4", ) print(f"Edited video: {edited.url}") ``` -------------------------------- ### Video Generation from Text Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Shows how to generate videos from text prompts using the `grok-imagine-video` model, including specifying duration, aspect ratio, and resolution. ```APIDOC ## Video Generation Generate videos from text prompts using the `grok-imagine-video` model. The SDK handles asynchronous polling automatically. ### Method ```python 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") ``` ``` -------------------------------- ### chat.create() Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Creates a chat conversation object without making a network request, allowing for the setup of conversation parameters and initial messages. ```APIDOC ## chat.create() `client.chat.create(model, *, messages, tools, response_format, reasoning_effort, search_parameters, ...)` — creates a mutable chat conversation object without making any network request. Returns a `Chat` object that holds the conversation state. All sampling methods (`sample`, `stream`, `parse`, `defer`) are called on this object. Supports tool definitions, Pydantic response schemas, reasoning effort control, search parameters, stored messages, encrypted reasoning content, multi-agent modes, and more. ```python from xai_sdk import Client from xai_sdk.chat import system, user, assistant client = Client() # Basic multi-turn conversation chat = client.chat.create( model="grok-4.20-non-reasoning", messages=[system("You are a pirate assistant.")], temperature=0.7, max_tokens=512, seed=42, ) chat.append(user("What is the capital of France?")) response = chat.sample() print(response.content) # "Paris, ye landlubber!" print(response.finish_reason) # "FINISH_REASON_STOP" print(response.usage.total_tokens) # e.g. 42 print(response.cost_usd) # e.g. 0.0001 or None # Continue the conversation chat.append(response) chat.append(user("And what is its population?")) response2 = chat.sample() print(response2.content) ``` ``` -------------------------------- ### Generate an Image from a Prompt Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Use client.image.sample() to generate an image from a text prompt or reference image(s). Specify model, aspect ratio, resolution, and image format. The response includes a URL or raw image bytes. ```python from xai_sdk import Client client = Client() # Text-to-image response = client.image.sample( prompt="A serene mountain lake at golden hour, photorealistic", model="grok-imagine-image", aspect_ratio="16:9", resolution="2k", image_format="url", ) print(f"URL: {response.url}") print(f"Cost: ${response.cost_usd:.4f}") # Download raw bytes image_bytes = response.image # auto-downloads from URL with open("output.jpg", "wb") as f: f.write(image_bytes) ``` -------------------------------- ### Video Extension with xAI SDK Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Demonstrates extending existing videos using `client.video.extend()`. Supports chaining extensions by passing the previous extension's URL as input. ```python from xai_sdk import Client client = Client() # Extend an existing video ext1 = client.video.extend( prompt="The camera slowly pulls back to reveal a vast valley", model="grok-imagine-video", video_url="https://example.com/my-video.mp4", duration=6, ) print(f"Extended video: {ext1.url}") ``` ```python # Chain a second extension ext2 = client.video.extend( prompt="A flock of birds flies across the evening sky", model="grok-imagine-video", video_url=ext1.url, # use result of first extension duration=5, ) print(f"Chain-extended video: {ext2.url}") ``` -------------------------------- ### Instantiate Synchronous and Asynchronous Clients Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Instantiate synchronous and asynchronous clients. The SDK defaults to using the XAI_API_KEY environment variable for authentication. ```python from xai_sdk import Client, AsyncClient # Synchronous client sync_client = Client() # Asynchronous client async_client = AsyncClient() ``` ```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) ``` -------------------------------- ### Configure and Use Server-Side Agentic Tools Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Sets up a chat with a model capable of autonomously using server-side tools like web search and code execution. It demonstrates streaming responses and extracting tool calls, tool outputs, citations, and cost information. ```python import datetime from xai_sdk import Client from xai_sdk.chat import user from xai_sdk.tools import web_search, x_search, code_execution, collections_search, mcp client = Client() chat = client.chat.create( model="grok-4.20", tools=[ web_search( excluded_domains=["spam-site.com"], enable_image_understanding=True, user_location_country="US", user_location_city="San Francisco", user_location_timezone="America/Los_Angeles", ), x_search( from_date=datetime.datetime(2025, 1, 1), allowed_x_handles=["xai"], enable_image_understanding=True, ), code_execution(), # collections_search(collection_ids=["col_abc123"], limit=5, retrieval_mode="semantic"), # mcp(server_url="https://mcp.example.com", authorization="Bearer token123"), ], include=["verbose_streaming", "code_execution_call_output"], ) chat.append(user("What is the 50th Fibonacci number? Show me the code used.")) for response, chunk in chat.stream(): for tc in chunk.tool_calls: print(f"[Tool call] {tc.function.name}: {tc.function.arguments}") for to in chunk.tool_outputs: if to.content: print(f"[Tool output] {to.content}") if chunk.content: print(chunk.content, end="", flush=True) print(f"\nCitations: {response.citations}") print(f"Server-side tools used: {response.server_side_tool_usage}") if response.cost_usd is not None: print(f"Total cost (all turns): ${response.cost_usd:.6f}") ``` -------------------------------- ### Synchronous Multi-Turn Chat Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Engage in multi-turn conversations using the synchronous client. Use `append` to manage history and `sample` to get a response. Ensure the `XAI_API_KEY` is set. ```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) ``` -------------------------------- ### Generate Video from Text Prompt Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Generate a video from a text description using the `grok-imagine-video` model. The SDK handles asynchronous polling. Specify duration and aspect ratio. ```python 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") ``` -------------------------------- ### Chained Video Extensions Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Illustrates how to chain video extensions by feeding the URL from a previous extension as input to the next. ```APIDOC ### Chained Extensions Extensions can be chained — feed the returned URL back as input. ### Method ```python response = client.video.extend( prompt="A bird flies across the sky", model="grok-imagine-video", video_url=response.url, ) print(f"Extended Video URL: {response.url}") ``` ``` -------------------------------- ### Image Understanding in Chat Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Demonstrates how to use the SDK to send images along with text prompts for analysis, leveraging models like grok-2-vision. ```APIDOC ## Image Understanding This section details how to interleave images and text for tasks like image understanding and analysis using the SDK. ### Method ```python 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 Extension Source: https://github.com/xai-org/xai-sdk-python/blob/main/README.md Details how to extend an existing video by appending new generated content using the `client.video.extend()` method. ```APIDOC #### Video Extension Extend an existing video by appending new generated content using `client.video.extend()`. ### Method ```python response = client.video.extend( prompt="The camera slowly zooms out to reveal the city skyline", model="grok-imagine-video", video_url="https://example.com/my-video.mp4", duration=6, ) print(f"Video URL: {response.url}") ``` ``` -------------------------------- ### chat.sample() Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Sends a single completion request and returns a Response object, blocking until the full response is received. The Response object contains detailed information about the completion. ```APIDOC ## chat.sample() ### Description Sends a single completion request and returns a `Response` object. This method blocks until the full response is received. The returned `Response` object exposes various attributes like `.content`, `.reasoning_content`, `.tool_calls`, `.citations`, `.inline_citations`, `.usage`, `.cost_usd`, `.finish_reason`, `.id`, `.role`, and `.request_settings`. ### Method `chat.sample()` ### Parameters None ### Request Example ```python from xai_sdk import Client from xai_sdk.chat import user client = Client() chat = client.chat.create(model="grok-4.20-non-reasoning", seed=0) chat.append(user("Explain quantum entanglement in one sentence.")) response = chat.sample() print(response.content) ``` ### Response #### Success Response A `Response` object containing the completion details. #### Response Example ```python # Assuming response.content is 'Quantum entanglement is a phenomenon where two particles become correlated...' print(response.content) print(response.usage.prompt_tokens) print(response.usage.completion_tokens) print(response.usage.reasoning_tokens) if response.cost_usd is not None: print(f"Cost: ${response.cost_usd:.6f}") ``` ``` -------------------------------- ### Video Generation Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Documentation for `client.video.generate()`, which supports text-to-video, image-to-video, reference-to-video, and video editing. ```APIDOC ## video.generate() `client.video.generate(prompt, model, *, image_url, video_url, duration, aspect_ratio, resolution, reference_image_urls, timeout, interval)` — generates a video and polls until complete. Supports text-to-video, image-to-video, reference-to-video (R2V), and video editing. Returns a `VideoResponse` with `.url` (valid 24h), `.duration`, `.model`, `.usage`, and `.cost_usd`. Default timeout is 10 minutes. ### Parameters - **prompt** (string) - Required - The text prompt describing the desired video. - **model** (string) - Required - The model to use for generation (e.g., "grok-imagine-video"). - **image_url** (string) - Optional - URL of an image to use as the first frame for image-to-video. - **video_url** (string) - Optional - URL of a video to use for video editing. - **duration** (integer) - Optional - Desired duration of the video in seconds. - **aspect_ratio** (string) - Optional - Desired aspect ratio (e.g., "16:9"). - **resolution** (string) - Optional - Desired resolution (e.g., "720p"). - **reference_image_urls** (list of strings) - Optional - List of URLs for reference images in reference-to-video. - **timeout** (datetime.timedelta) - Optional - Maximum time to wait for video generation. Defaults to 10 minutes. - **interval** (integer) - Optional - Polling interval in seconds. ### Request Example (Text-to-video) ```python response = client.video.generate( prompt="A timelapse of a sunset over the ocean with dramatic clouds", model="grok-imagine-video", duration=8, aspect_ratio="16:9", resolution="720p", timeout=datetime.timedelta(minutes=15), ) print(f"Video URL (24h): {response.url}") print(f"Duration: {response.duration}s") ``` ### Request Example (Image-to-video) ```python i2v = client.video.generate( prompt="The scene slowly comes to life with gentle waves", model="grok-imagine-video", image_url="https://example.com/lake.jpg", duration=5, ) print(f"I2V URL: {i2v.url}") ``` ### Request Example (Reference-to-video) ```python r2v = client.video.generate( prompt="A cinematic scene inspired by these references", model="grok-imagine-video", reference_image_urls=[ "https://example.com/ref1.jpg", "https://example.com/ref2.jpg", ], ) ``` ### Request Example (Video editing) ```python edited = client.video.generate( prompt="Add a rainbow arching across the sky", model="grok-imagine-video", video_url="https://example.com/my-video.mp4", ) print(f"Edited video: {edited.url}") ``` ``` -------------------------------- ### Send a single completion request with chat.sample() Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Use `chat.sample()` to send a single completion request and receive a full `Response` object. This method blocks until the entire response is received. Access various response attributes like `.content`, `.usage`, and `.cost_usd`. ```python from xai_sdk import Client from xai_sdk.chat import user client = Client() chat = client.chat.create(model="grok-4.20-non-reasoning", seed=0) chat.append(user("Explain quantum entanglement in one sentence.")) response = chat.sample() print(response.content) # "Quantum entanglement is a phenomenon where two particles become correlated..." print(response.usage.prompt_tokens) # input tokens print(response.usage.completion_tokens) # output tokens print(response.usage.reasoning_tokens) # reasoning tokens (reasoning models) if response.cost_usd is not None: print(f"Cost: ${response.cost_usd:.6f}") ``` -------------------------------- ### Check Code Formatting Source: https://github.com/xai-org/xai-sdk-python/blob/main/CONTRIBUTING.md Checks if the code adheres to project formatting standards. If issues are found, run `uv run ruff format` to automatically fix them. ```bash uv run ruff format --check ``` -------------------------------- ### Configure Search Parameters for Chat Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Use SearchParameters to enable contextual web, news, X, or RSS search for chat responses. Pass the configured search_parameters to client.chat.create(). ```python import datetime from xai_sdk import Client from xai_sdk.chat import user from xai_sdk.search import SearchParameters, web_source, news_source, x_source, rss_source client = Client() search_config = SearchParameters( sources=[ web_source(country="US", excluded_websites=["wikipedia.org"], safe_search=True), news_source(country="US"), x_source(included_x_handles=["xai"], post_view_count=1000), rss_source(links=["https://feeds.bbci.co.uk/news/rss.xml"]), ], mode="on", from_date=datetime.datetime(2025, 1, 1), to_date=datetime.datetime.now(), return_citations=True, max_search_results=10, ) chat = client.chat.create( model="grok-4.20-non-reasoning", search_parameters=search_config, ) chat.append(user("What are the latest developments in AI safety research?")) response = chat.sample() print(response.content) print("\nSources consulted:") for citation in response.citations: print(f" - {citation}") # Inline citations with character positions for ic in response.inline_citations: print(f" [{ic.id}] chars {ic.start_index}-{ic.end_index}") ``` -------------------------------- ### Async Video Generation Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Generates a video asynchronously from a text prompt. Ideal for non-blocking video creation workflows. ```python # Async video generation video = await client.video.generate( prompt="A waterfall in a tropical forest", model="grok-imagine-video", duration=5, ) print(f"Video URL: {video.url}") ``` -------------------------------- ### Server-Side Tools: web_search, x_search, code_execution, collections_search, mcp Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Enables the creation of server-side agentic tools that the model executes autonomously. These include web searching, X (Twitter) querying, code execution, vector collection searching, and MCP server connections. ```APIDOC ## Server-side Tools (web_search, x_search, code_execution, collections_search, mcp) Functions in `xai_sdk.tools` — create server-side agentic tools that the model executes automatically without client intervention. The model autonomously decides when to call these tools and iterates through an internal agentic loop. `web_search()` enables live web retrieval, `x_search()` queries X (Twitter), `code_execution()` runs Python code, `collections_search()` queries vector collections, and `mcp()` connects to remote MCP servers. ```python import datetime from xai_sdk import Client from xai_sdk.chat import user from xai_sdk.tools import web_search, x_search, code_execution, collections_search, mcp client = Client() chat = client.chat.create( model="grok-4.20", tools=[ web_search( excluded_domains=["spam-site.com"], enable_image_understanding=True, user_location_country="US", user_location_city="San Francisco", user_location_timezone="America/Los_Angeles", ), x_search( from_date=datetime.datetime(2025, 1, 1), allowed_x_handles=["xai"], enable_image_understanding=True, ), code_execution(), # collections_search(collection_ids=["col_abc123"], limit=5, retrieval_mode="semantic"), # mcp(server_url="https://mcp.example.com", authorization="Bearer token123"), ], include=["verbose_streaming", "code_execution_call_output"], ) chat.append(user("What is the 50th Fibonacci number? Show me the code used.")) for response, chunk in chat.stream(): for tc in chunk.tool_calls: print(f"[Tool call] {tc.function.name}: {tc.function.arguments}") for to in chunk.tool_outputs: if to.content: print(f"[Tool output] {to.content}") if chunk.content: print(chunk.content, end="", flush=True) print(f"\nCitations: {response.citations}") print(f"Server-side tools used: {response.server_side_tool_usage}") if response.cost_usd is not None: print(f"Total cost (all turns): ${response.cost_usd:.6f}") ``` ``` -------------------------------- ### Image Generation Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Generate a single image from a text prompt or reference image(s) using `client.image.sample()`. Returns an `ImageResponse` object with image details and cost. ```APIDOC ## image.sample() `client.image.sample(prompt, model, *, aspect_ratio, resolution, image_url, image_urls, image_format)` — generates a single image from a text prompt or reference image(s). Returns an `ImageResponse` with `.url`, `.base64`, `.image` (raw bytes), `.model`, `.usage`, and `.cost_usd`. The `.image` property downloads the image automatically if only a URL was returned. ```python from xai_sdk import Client client = Client() # Text-to-image response = client.image.sample( prompt="A serene mountain lake at golden hour, photorealistic", model="grok-imagine-image", aspect_ratio="16:9", resolution="2k", image_format="url", ) print(f"URL: {response.url}") print(f"Cost: ${response.cost_usd:.4f}") # Download raw bytes image_bytes = response.image # auto-downloads from URL with open("output.jpg", "wb") as f: f.write(image_bytes) ``` ``` -------------------------------- ### Tokenize Text with a Specific Model Source: https://context7.com/xai-org/xai-sdk-python/llms.txt Tokenize input text using the specified model's tokenizer. The `Client` must be initialized. ```python from xai_sdk import Client client = Client() tokens = client.tokenize.tokenize_text( text="Hello, world! How are you doing today?", model="grok-4.20-non-reasoning", ) print(f"Token count: {len(tokens)}") for token in tokens: print(f" ID={token.token_id} str={repr(token.string_value)}") ```