Fan-out: official package, async, streaming. Skeleton lives here.
OpenAI-compatible client#
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["XAI_API_KEY"],
base_url="https://api.x.ai/v1",
)
res = client.chat.completions.create(
model="grok-4.6",
messages=[{"role": "user", "content": "Reply with pong."}],
)
print(res.choices[0].message.content)Official SDK#
xai_sdk.Client(api_key=...) does not need a handwritten Base URL; you still choose the model. Pin the id in the repo even if docs show the latest flagship.
Production notes#
- Keys only in env or a vault.
- Stream in chunks; do not dump full user payloads to disk in cleartext.
- Keep OpenAI and xAI keys in different projects so traffic cannot hit the wrong host.
Takeaways#
- Change Base URL and model name to migrate.
- Ping first.
- Do not mix official and compatible clients on one instance.