Skip to content

Getting Started with xAI

This guide shows how to set up a minimal deployment to use the TensorZero Gateway with the xAI API.

Simple Setup

You can use the short-hand xai::model_name to use an xAI model with TensorZero, unless you need advanced features like fallbacks or custom credentials.

You can use xAI models in your TensorZero variants by setting the model field to xai::model_name. For example:

[functions.my_function_name.variants.my_variant_name]
type = "chat_completion"
model = "xai::grok-2-1212"

Additionally, you can set model_name in the inference request to use a specific xAI model, without having to configure a function and variant in TensorZero.

Terminal window
curl -X POST http://localhost:3000/inference \
-H "Content-Type: application/json" \
-d '{
"model_name": "xai::grok-2-1212",
"input": {
"messages": [
{
"role": "user",
"content": "What is the capital of Japan?"
}
]
}
}'

Advanced Setup

In more complex scenarios (e.g. fallbacks, custom credentials), you can configure your own model and xAI provider in TensorZero.

For this minimal setup, you’ll need just two files in your project directory:

  • Directoryconfig/
    • tensorzero.toml
  • docker-compose.yml

For production deployments, see our Deployment Guide.

Configuration

Create a minimal configuration file that defines a model and a simple chat function:

config/tensorzero.toml
[models.grok_2_1212]
routing = ["xai"]
[models.grok_2_1212.providers.xai]
type = "xai"
model_name = "grok-2-1212"
[functions.my_function_name]
type = "chat"
[functions.my_function_name.variants.my_variant_name]
type = "chat_completion"
model = "grok_2_1212"

See the list of models available on xAI.

Credentials

You must set the XAI_API_KEY environment variable before running the gateway.

You can customize the credential location by setting the api_key_location to env::YOUR_ENVIRONMENT_VARIABLE or dynamic::ARGUMENT_NAME. See the Credential Management guide and Configuration Reference for more information.

Deployment (Docker Compose)

Create a minimal Docker Compose configuration:

docker-compose.yml
# This is a simplified example for learning purposes. Do not use this in production.
# For production-ready deployments, see: https://www.tensorzero.com/docs/gateway/deployment
services:
gateway:
image: tensorzero/gateway
volumes:
- ./config:/app/config:ro
environment:
- XAI_API_KEY=${XAI_API_KEY:?Environment variable XAI_API_KEY must be set.}
ports:
- "3000:3000"
extra_hosts:
- "host.docker.internal:host-gateway"

You can start the gateway with docker compose up.

Inference

Make an inference request to the gateway:

Terminal window
curl -X POST http://localhost:3000/inference \
-H "Content-Type: application/json" \
-d '{
"function_name": "my_function_name",
"input": {
"messages": [
{
"role": "user",
"content": "What is the capital of Japan?"
}
]
}
}'