Production ReadySDK • Go • v0.2.1

xAI SDK for Go

The unofficial Go SDK for xAI provides a first-class, idiomatic Go interface to xAI's powerful AI capabilities. This SDK enables Go developers to integrate chat completions, streaming responses, and upcoming features like file operations, image generation, and more.

Production Ready: v0.2.1 - Hotfix release with 100% proto alignment to xAI Python SDK v1.4.0. Verified and running in production on Zaguán. All 14 proto files aligned (108 messages, 18 enums). Chat API fully functional and tested.

Why xAI SDK for Go?

xAI's Grok models offer powerful AI capabilities, but integrating them into Go applications requires careful handling of HTTP requests, streaming responses, and error management.

xAI SDK for Go provides a clean, idiomatic Go interface that handles all the complexity for you. Focus on building your application while the SDK manages authentication, connection pooling, retries, and streaming.

✓ Production Verified: This SDK is actively used in production on Zaguán, handling real-world workloads with proven reliability.

Features

Chat Completions

Synchronous and streaming chat with message builders. Clean API for single-shot and conversational interactions.

Function Calling

Define and use tools in your chat completions. Enable AI to call functions and interact with external systems.

Reasoning & Search

Control reasoning effort levels and enable search capabilities for enhanced AI responses.

Structured Outputs

Get structured JSON and JSON schema outputs. Perfect for parsing AI responses into typed data structures.

Secure Authentication

API key and Bearer token support with TLS. Environment variable integration for safe credential management.

Flexible Configuration

Environment variables and programmatic config. Customize timeouts, retries, and connection settings.

Connection Management

Health checks, automatic retries, and keepalive. Robust connection handling for production workloads.

Error Handling

Comprehensive error types with gRPC integration. Clear error messages for debugging and monitoring.

Well Tested

Comprehensive test coverage for all components. Reliable and production-ready code.

Quick Start

Installation

go get github.com/ZaguanLabs/xai-sdk-go

Basic Usage

package main

import (
    "context"
    "fmt"
    "log"
    
    "github.com/ZaguanLabs/xai-sdk-go/pkg/xai"
)

func main() {
    // Create client with API key from environment
    client := xai.NewClient()
    
    // Create a chat completion
    resp, err := client.Chat.Create(context.Background(), &xai.ChatRequest{
        Model: "grok-beta",
        Messages: []xai.Message{
            {Role: "user", Content: "What is the meaning of life?"},
        },
    })
    
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Println(resp.Choices[0].Message.Content)
}

Streaming Usage

package main

import (
    "context"
    "fmt"
    "log"
    
    "github.com/ZaguanLabs/xai-sdk-go/pkg/xai"
)

func main() {
    client := xai.NewClient()
    
    stream, err := client.Chat.CreateStream(context.Background(), &xai.ChatRequest{
        Model: "grok-beta",
        Messages: []xai.Message{
            {Role: "user", Content: "Tell me a story"},
        },
        Stream: true,
    })
    
    if err != nil {
        log.Fatal(err)
    }
    defer stream.Close()
    
    // Process streaming chunks
    for {
        chunk, err := stream.Recv()
        if err != nil {
            break
        }
        fmt.Print(chunk.Choices[0].Delta.Content)
    }
}

Environment Setup

Set your xAI API key as an environment variable:

export XAI_API_KEY=your-api-key-here

Project Structure

xai-sdk-go/
├── pkg/
│   └── xai/
│       ├── client.go          # Main client implementation
│       ├── chat.go            # Chat completions API
│       ├── stream.go          # Streaming support
│       ├── config.go          # Configuration management
│       ├── errors.go          # Error types and handling
│       └── types.go           # Request/response types
├── examples/
│   ├── basic/                 # Basic usage examples
│   ├── streaming/             # Streaming examples
│   └── advanced/              # Advanced features
├── go.mod
└── README.md

Configuration

The SDK supports both environment variables and programmatic configuration:

Environment Variables

  • XAI_API_KEY - Your xAI API key
  • XAI_BASE_URL - Custom API base URL (optional)
  • XAI_TIMEOUT - Request timeout in seconds (optional)

Programmatic Configuration

client := xai.NewClient(
    xai.WithAPIKey("your-api-key"),
    xai.WithBaseURL("https://api.x.ai/v1"),
    xai.WithTimeout(30 * time.Second),
    xai.WithRetries(3),
)

Roadmap

v0.1.x Series

Foundation through v0.1.6 - Core infrastructure, proto definitions, configuration, client, authentication, chat completions with function calling and structured outputs. Production-verified on Zaguán.

v0.2.x Series (Current - Production Ready)

v0.2.0-v0.2.1 - 100% proto alignment with xAI Python SDK v1.4.0. All 14 proto files aligned (108 messages, 18 enums). New proto files: deferred, documents, embed, sample, types, shared, usage. Complete chat proto with all 37 messages. Embed API wrapper added.

v0.2.x Continued

SDK wrapper implementations: Deferred completions API, Documents search API, Updated files and collections wrappers

v0.3.0 Additional Features

Image generation API, Tokenization API, Enhanced error handling, Integration tests

Development

Prerequisites

  • Go 1.21 or later
  • xAI API key

Building

# Clone the repository
git clone https://github.com/ZaguanLabs/xai-sdk-go.git
cd xai-sdk-go

# Build
go build ./...

# Run tests
go test ./...

Running Examples

# Set your API key
export XAI_API_KEY=your-api-key-here

# Run basic example
go run examples/basic/main.go

# Run streaming example
go run examples/streaming/main.go

Contributing

Contributions are welcome! Whether it's bug reports, feature requests, or pull requests, we appreciate all forms of contribution.

Apache 2.0 Licensed - The xAI SDK for Go is free and open source software. You're welcome to use, modify, and distribute it for any purpose.

Ready to Build with xAI?

Check out the repository for full documentation, examples, and API reference.