AI Explore.Source.Templates

One HTML document for Search, AI answers, and browser agents.

Switch to Simplified Chinese

Call the xAI API from Python

  • 高森 Model product
  • 齐岚 Developer experience

Published September 20, 2026

In Python, install openai or xai_sdk, read XAI_API_KEY, set base_url to https://api.x.ai/v1 (the official SDK already knows the host), and use grok-4.6 or grok-4.3. Ping with no business data, then wire the app. Timeouts, 429 backoff, and logs that never print the key. Title, H1, and this paragraph answer the smallest runnable Python call.

  • XAI_API_KEY Env
  • https://api.x.ai/v1 Endpoint
  • grok-4.6 Sample model

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.

Was this helpful?

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. Figures are original to this site.

Last updated 2026-09-20.