xAI (Grok)
Import: from air.providers.xai import XAIProvider
Class name: XAIProvider
Provider name (used in routing, health tracking, ChatResponse.provider): "xai"
Constructor
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. RaisesAuthenticationErrorimmediately at construction time if empty or falsy.model(required): the model name to use, for example"grok-4-0709", unless overridden per request byChatRequest.model.base_url(optional): defaults tohttps://api.x.ai/v1.timeout(optional): request timeout in seconds, default 60.transport(optional): anhttpx.AsyncBaseTransport, mainly useful for testing withhttpx.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
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
QuotaExceededErrorif the error body'scodeis one ofpermission-denied,insufficient_quota,quota_exceeded, or its message mentions credit, quota, or license; otherwiseAuthenticationError. - 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.