AIR

xAI (Grok)

Import: from air.providers.xai import XAIProvider

Class name: XAIProvider

Provider name (used in routing, health tracking, ChatResponse.provider): "xai"

Constructor

python
XAIProvider(
    api_key: str,
    model: str,
    base_url: str = "https://api.x.ai/v1",
    timeout: float = 60.0,
    transport: httpx.AsyncBaseTransport | None = None,
)
  • api_key (required): your xAI API key. Raises AuthenticationError immediately at construction time if empty or falsy.
  • model (required): the model name to use, for example "grok-4-0709", unless overridden per request by ChatRequest.model.
  • base_url (optional): defaults to https://api.x.ai/v1.
  • timeout (optional): request timeout in seconds, default 60.
  • transport (optional): an httpx.AsyncBaseTransport, mainly useful for testing with httpx.MockTransport.

Authentication

XAIProvider does not read any environment variable itself. Read your key from wherever you store it (for example os.environ["XAI_API_KEY"]) and pass it to the constructor.

Minimal setup

python
import os
from air import AIR
from air.providers.xai import XAIProvider
 
air = AIR()
air.add_provider(XAIProvider(api_key=os.environ["XAI_API_KEY"], model="grok-4-0709"))
response = await air.chat("Hello")

Request format

Sends a POST to {base_url}/chat/completions with an OpenAI style body: {"model": ..., "messages": [{"role": ..., "content": ...}, ...]}, plus temperature and max_tokens if set on the ChatRequest.

Response parsing

Reads choices[0].message.content for the reply text, model for the model actually used, and usage.prompt_tokens / usage.completion_tokens / usage.total_tokens if the response includes a usage object.

Error behavior

  • HTTP 401 or 403: classified as QuotaExceededError if the error body's code is one of permission-denied, insufficient_quota, quota_exceeded, or its message mentions credit, quota, or license; otherwise AuthenticationError.
  • HTTP 429: RateLimitError.
  • Any other HTTP 400+: ProviderAPIError.
  • Network timeout: ProviderTimeoutError.
  • Other network/connection errors: ProviderAPIError.
  • Non-JSON or unexpected response shape: ProviderResponseError.

See reference/exceptions.md for which of these trigger automatic fallback.

Limitations

xAI does not expose a remaining-quota endpoint that AIR can query. Capacity tracking, if you configure limits={"tokens": ...}, only reflects usage xAI actually reports back on each response.