xAI Python SDK

repository·main·Indexed 19 days ago

https://github.com/xai-org/xai-sdk-python

The official gRPC-based Python SDK for the xAI API, providing synchronous and asynchronous access to generative models. It supports text, vision, image, and video capabilities, including multi-turn chat with the grok-3 and grok-2-vision models. The SDK features real-time response streaming, video generation and editing via grok-imagine-video, and OpenTelemetry integration for observability and tracing.

Tokens
11.3K
Snippets
39
Records
51
Agent score
67%

What's inside xai-sdk

  1. How multi-turn chat works with the `append` method

    main

    The SDK manages conversation history through a chat object. Instead of manually managing a list of messages, you use the append method to add new messages (using system, user, or assistant helpers) to the chat instance.

    To get a response from the model, call chat.sample(). For asynchronous workflows, use AsyncClient and await chat.sample().

    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.")]
    )
    
    # Add a user message
    chat.append(user("Hello!"))
    # Get model response
    response = chat.sample()
    # Add the assistant response back to history to maintain context
    chat.append(response)
  2. Configure Retries and Retry Policies

    main

    The SDK enables retries by default for UNAVAILABLE errors using exponential backoff.

    Default Policy:

    • Max Attempts: 5
    • Initial Backoff: 0.1s
    • Max Backoff: 1s
    • Multiplier: 2

    Disable Retries

    Pass channel_options=[("grpc.enable_retries", 0)] to the client constructor.

    Custom Retry Policy

    Provide a JSON string via the grpc.service_config channel option to define custom behavior (e.g., changing maxAttempts, initialBackoff, or retryableStatusCodes).

    import json
    from xai_sdk import Client
    
    # Example: Custom retry policy
    custom_retry_policy = json.dumps({
        "methodConfig": [{
            "name": [{}], # Applies to all methods
            "retryPolicy": {
                "maxAttempts": 3,
                "initialBackoff": "0.5s",
                "maxBackoff": "2s",
                "backoffMultiplier": 1.5,
                "retryableStatusCodes": ["UNAVAILABLE", "RESOURCE_EXHAUSTED"]
            }
        }]
    })
    
    client = Client(channel_options=[
        ("grpc.service_config", custom_retry_policy)
    ])
  3. Instantiate synchronous and asynchronous clients

    main

    The SDK provides two client types: xai_sdk.Client for synchronous operations and xai_sdk.AsyncClient for asynchronous operations.

    By default, the SDK automatically authenticates using the XAI_API_KEY environment variable. If you need to pass the key explicitly, use the api_key parameter.

    from xai_sdk import Client, AsyncClient
    import os
    
    # Option 1: Automatic authentication via XAI_API_KEY env var
    sync_client = Client()
    async_client = AsyncClient()
    
    # Option 2: Explicitly passing the API key
    api_key = os.getenv("XAI_API_KEY")
    sync_client = Client(api_key=api_key)
    async_client = AsyncClient(api_key=api_key)
  4. Check the installed xAI SDK version

    main

    You can verify which version of the xai-sdk is installed in your environment using terminal commands or programmatically within Python.

    # Using pip
    pip show xai-sdk
    
    # Using uv
    uv pip show xai-sdk
    import xai_sdk
    print(xai_sdk.__version__)
  5. Configure Telemetry & Observability

    main

    The xAI SDK supports exporting OpenTelemetry traces to monitor and debug API calls. Traces include metadata like input prompts, model responses, and token usage. Traces follow OpenTelemetry GenAI Semantic Conventions.

    Telemetry is not enabled by default and must be explicitly configured using the Telemetry class.

    from xai_sdk.telemetry import Telemetry
    
    telemetry = Telemetry()
    # Choose an exporter method below
    telemetry.setup_console_exporter() # For development
    # OR
    telemetry.setup_otlp_exporter(endpoint="...", headers={...}) # For production
  6. Install Telemetry Dependencies

    main

    The telemetry feature requires extra dependencies depending on your chosen export protocol. Install them using pip or uv:

    • HTTP OTLP export: xai-sdk[telemetry-http]
    • gRPC OTLP export: xai-sdk[telemetry-grpc]
    # For HTTP OTLP export
    pip install xai-sdk[telemetry-http]
    # or
    uv add xai-sdk[telemetry-http]
    
    # For gRPC OTLP export
    pip install xai-sdk[telemetry-grpc]
    # or
    uv add xai-sdk[telemetry-grpc]
  7. Track file upload progress

    main

    The SDK supports progress tracking during file uploads via the ProgressCallback type. You can provide:

    1. A callable (function) that accepts either (cumulative_bytes, total_bytes) or just (chunk_size) for incremental updates.
    2. A tqdm-like object that implements an .update(n) method, where n is the number of units (bytes) to increment the progress bar by.
    3. None to disable progress tracking.
    # Example using a simple callable
    def my_progress(current, total):
        print(f"Uploaded {current}/{total} bytes")
    
    # Example using a tqdm-like object
    class MyProgressBar:
        def update(self, n: int):
            print(f"Added {n} bytes")
  8. Configure Authentication and Metadata

    main

    The xAI SDK uses gRPC metadata for authentication and request context.

    1. Authentication: The SDK automatically injects the authorization: Bearer <api_key> header into every request using an internal _APIAuthPlugin.
    2. Custom Metadata: You can pass additional metadata as a tuple of tuples (e.g., (('key', 'value'),)) during client initialization.
    3. Automatic SDK Metadata: The SDK automatically appends xai-sdk-version (e.g., python/1.17.1) and xai-sdk-language (e.g., python/3.10) to all outgoing requests to assist with telemetry and debugging.
  9. Provide image inputs for generation

    main

    When performing image-to-image or multi-image tasks, you can provide reference images using several methods. Note that these are mutually exclusive for single-image requests, but can be mixed in multi-image requests:

    1. Single Image Reference:

      • image_url: A single URL string.
      • image_file_id: A single file ID string.
    2. Multi-Image Reference:

      • image_urls: A sequence of URL strings.
      • image_file_ids: A sequence of file ID strings.

    Constraint Note: If you provide both image_file_ids and image_urls in a single request, the file IDs are processed first. This allows you to predict the positional indices (<IMAGE_N>) used in your prompt.

  10. Configure document chunking strategies

    main

    When setting up collections, you can define how documents are split into chunks using ChunkConfiguration. You must specify exactly one of the following three strategies:

    • chars_configuration: Character-based chunking. Requires max_chunk_size_chars and chunk_overlap_chars.
    • tokens_configuration: Token-based chunking. Requires max_chunk_size_tokens, chunk_overlap_tokens, and encoding_name.
    • bytes_configuration: Byte-based chunking. Requires max_chunk_size_bytes and chunk_overlap_bytes.

    Additional options:

    • strip_whitespace: Boolean to remove whitespace.
    • inject_name_into_chunks: Boolean to include names in chunks.
    # Example: Token-based chunking configuration
    chunk_config = {
        "tokens_configuration": {
            "max_chunk_size_tokens": 512,
            "chunk_overlap_tokens": 50,
            "encoding_name": "cl100k_base"
        },
        "strip_whitespace": True
    }
  11. Update FieldDefinitions using add or delete operations

    main

    You can modify a collection's schema by adding or deleting field definitions using a FieldDefinitionUpdate structure. This is handled via two specific operation types:

    1. Add a field: Use operation: "add" and provide the full field_definition object.
    2. Delete a field: Use operation: "delete" and provide only the key of the field. Note that deleting a field definition also removes that field's value from every document in the collection.
    # To add a field
    add_op = {
        "operation": "add",
        "field_definition": {
            "key": "isbn",
            "required": False,
            "inject_into_chunk": False,
            "unique": True
        }
    }
    
    # To delete a field
    delete_op = {
        "operation": "delete",
        "key": "isbn"
    }