SDK Integration

The XAI XAPI is designed to be fully compatible with the OpenAI and Anthropic SDKs, allowing you to easily migrate your existing applications with almost no code changes.

OpenAI SDK Integration

You only need to point the base_url to the XAI XAPI address when initializing the OpenAI client.

Python

import os
from openai import OpenAI

# It's recommended to read your key from environment variables
client = OpenAI(
    api_key=os.environ.get("XAI_API_KEY"),
    base_url="https://api.xaixapi.com/v1",
)

chat_completion = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "user", "content": "Write a Hello World program in Python"},
    ],
)

print(chat_completion.choices[0].message.content)

JavaScript / TypeScript

import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: process.env.XAI_API_KEY, // Your XAI API Key
  baseURL: "https://api.xaixapi.com/v1",
});

async function main() {
  const chatCompletion = await openai.chat.completions.create({
    model: "gpt-4o",
    messages: [
      { role: "user", content: "Write a Hello World program in JavaScript" },
    ],
  });

  console.log(chatCompletion.choices[0].message.content);
}

main();

Anthropic SDK Integration

Similarly, for Anthropic models (like the Claude series), you just need to modify the baseURL.

Please note that the Anthropic-compatible `baseURL` is slightly different from OpenAI's; it does not include the `/v1` suffix.

Python

import os
from anthropic import Anthropic

client = Anthropic(
    api_key=os.environ.get("XAI_API_KEY"),
    base_url="https://api.xaixapi.com/",
)

message = client.messages.create(
    model="claude-3-5-sonnet-latest",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": "Explain the concept of 'first principles'",
        }
    ],
)

print(message.content[0].text)

JavaScript / TypeScript

import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic({
  apiKey: process.env.XAI_API_KEY, // Your XAI API Key
  baseURL: "https://api.xaixapi.com/",
});

async function main() {
  const message = await anthropic.messages.create({
    model: "claude-3-5-sonnet-latest",
    max_tokens: 1024,
    messages: [
      {
        role: "user",
        content: "Explain the concept of 'first principles'",
      },
    ],
  });

  console.log(message.content[0].text);
}

main();

Other Clients and Applications

For any third-party client that supports custom OpenAI/Anthropic API addresses, the integration method is similar:

  1. Find the "API Key" or a similar option in the settings and enter your sk-... key.
  2. Find the "API Base URL", "Custom API Domain", or "Endpoint" option and enter https://api.xaixapi.com or https://api.xaixapi.com/v1 (depending on the client's requirements).