Getting Started

Getting Started

View as Markdown

Welcome! In this guide, we'll walk you through the basics of using the xAI API, from creating an account to making your first request.

Step 1: Create an xAI account

Sign up for an account at accounts.x.ai, then load it with credits to start using the API.

Step 2: Generate an API key

Create an API key via the API Keys page in the xAI Console. Then make it available to your code. Either export it in your terminal:

Bash

export XAI_API_KEY="your_api_key"

Or add it to a .env file in your project directory:

Bash

XAI_API_KEY=your_api_key

The xAI SDKs are configured to automatically read your API key from the XAI_API_KEY environment variable.

Step 3: Install an SDK

Pick your language and install the SDK:

pip install xai-sdk

Step 4: Make your first request

Send a prompt to Grok and get a response:

import os
from xai_sdk import Client
from xai_sdk.chat import user, system

client = Client(api_key=os.getenv("XAI_API_KEY"))

chat = client.chat.create(model="grok-4-1-fast-reasoning")
chat.append(system("You are Grok, a highly intelligent, helpful AI assistant."))
chat.append(user("What is the meaning of life, the universe, and everything?"))

response = chat.sample()
print(response.content)

Certain models also support Structured Outputs, which allows you to enforce a schema for the LLM output. For an in-depth guide about using Grok for text responses, check out the Text Generation Guide.

Step 5: Analyze an image

Grok can accept both text and images as input. Pass an image URL alongside your prompt:

import os
from xai_sdk import Client
from xai_sdk.chat import user, image

client = Client(api_key=os.getenv("XAI_API_KEY"))

chat = client.chat.create(model="grok-4")
chat.append(
    user(
        "What's in this image?",
        image("https://science.nasa.gov/wp-content/uploads/2023/09/web-first-images-release.png"),
    )
)

response = chat.sample()
print(response.content)

To learn how to use Grok vision for more advanced use cases, check out Image Understanding.


What's next

Now that you've made your first request, explore what Grok can do:

Resources


Did you find this page helpful?