Production ReadySDK • Go • v0.10.0

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, embeddings, file operations, image generation, document search, and more with 100% API coverage.

v0.10.0 Released - Python SDK v1.5.0 Parity! Full parity with Python SDK v1.5.0. Requires Go 1.24+ due to gRPC v1.76.0 dependency.

In Production: This SDK is actively used in production on Zaguán. Successfully tested with Qwen-Code using the grok-code-fast-1 model for real-world AI-powered development workflows.

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.

Image Generation

Text-to-image and image-to-image generation with multiple formats. Create stunning visuals from prompts.

Vision Model Support

Full image and file support for vision models (grok-2-vision, grok-4). Send images via URL or base64 with resolution control.

Embeddings

Generate embeddings for text and images. Perfect for semantic search, similarity, and RAG applications.

File Operations

Upload, download, list, and delete files. Complete file management with 6 methods and size limits.

Document Search

Search across document collections with 11 collection management methods. Build powerful knowledge bases.

High Performance

2-10x faster with connection pooling, HTTP/2, and buffer pooling. 90% reduction in memory allocations.

Server-Side Tools

6 server-side tools: Web search, X/Twitter search, code execution, document search, collections, and MCP integration.

Complete Parameters

24/24 Chat API parameters including seed, logprobs, parallel tool calls, frequency/presence penalties, and more.

Critical Fixes

11 critical bugs fixed in v0.5.2: tool calling, reasoning models, multi-turn conversations, and ZDR workflows now fully functional.

Well Tested

Comprehensive unit and integration tests. 8+ detailed examples covering all APIs. Zero placeholder code. Production-ready.

Vision Models in Action

The SDK provides full support for xAI's vision models like grok-2-vision and grok-4. Send images via URL or base64 encoding, control resolution settings, and get detailed image analysis.

Grok-4 successfully describing an image in OpenWebUI

Example: Grok-4 analyzing and describing an image through the SDK in OpenWebUI

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

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.3.0 - Complete API Coverage

100% API coverage with all 11 xAI APIs (28+ methods). REST client foundation with connection pooling, HTTP/2, and buffer pooling. New APIs: Image Generation, Embeddings, Files, Collections, Document Search, Deferred Completions, Auth, Tokenizer, Sample. 2-10x performance improvements, 8 comprehensive examples, 15+ integration tests, security audit completed with all P0-P1 issues resolved.

v0.4.0 - Complete Parameter Coverage

100% Chat API parameter coverage (24/24 parameters). Added 13 missing parameters: TopP, Stop, Frequency/Presence Penalties, Seed, Logprobs, TopLogprobs, N, User, ParallelToolCalls, PreviousResponseID, StoreMessages, UseEncryptedContent. Centralized version management. New examples for advanced parameters and features.

v0.5.0 - Complete Tool Support

100% tool type coverage (7/7 tools). Added 6 server-side tools: WebSearch (domain filtering, image understanding), XSearch (handle/date filtering, video understanding), CodeExecution, CollectionsSearch, DocumentSearch, MCP (authorization, custom headers). Complete feature parity with Python SDK for tools. New comprehensive server-side tools example and documentation.

v0.5.2 - Critical Bug Fixes

Fixed 11 critical bugs preventing tool calling, reasoning models, and multi-turn conversations from working. Implemented Response.ToolCalls(), Chunk.ToolCalls(), Message accessors/setters for tool calls/reasoning/encrypted content, Request.AppendResponse() for multi-turn conversations. Removed all placeholder code. 100% feature parity with Python SDK achieved. 13 new tests added.

v0.5.3 - 100% Proto Field Coverage

Achieved 100% proto field coverage (64/64 fields). Added image/file support for vision models (grok-2-vision, grok-4), citations, system fingerprint, request settings, debug output with cache stats, log probabilities, strict schema validation, advanced search sources (web, news, X, RSS). Fixed critical image/file bug and Chunk.Usage(). 25 new tests, 6 new documentation files. Complete parity with Python SDK.

v0.6.0 - Critical Bug Fixes & Quality

Fixed critical JSON parsing panic and example compilation errors. Achieved 45.8% test coverage (+15.1pp) with comprehensive unit tests for 9 packages. Security hardened (gosec scan clean), migrated to non-deprecated gRPC APIs, enhanced error handling. All quality checks passing (go vet, staticcheck, race detector). Test coverage by package: auth (90.0%), documents (90.0%), sample (90.9%), image (89.3%), tokenizer (88.2%), deferred (87.0%), embed (83.6%), collections (76.9%), models (24.4%).

v0.7.0 - Code Quality & API Improvements

Improved code quality with reduced cyclomatic complexity across configuration and error handling. API naming improvements following Go best practices (image.ImageInput → image.Input, chat.ChatServiceClient → chat.ServiceClient). New features: tool call status tracking for server-side execution lifecycle, batch file upload with concurrent processing (default 50 concurrent uploads). Enhanced metadata with SDK version tracking. Requires Go 1.24+ due to gRPC v1.76.0. All quality checks passing with comprehensive test coverage for new features.

v0.8.0 - Official Proto Integration

Integrated official xAI protobuf definitions from xai-proto repository. Enhanced type safety with proper optional field handling using pointer types and oneof discriminated unions. New proto files for Files and Collections API service definitions. Backward compatible with no breaking changes for users. 200+ tests updated and passing with new proto structures. SDK now matches xAI's official API specifications exactly.

v0.9.0 - Python SDK v1.4.1 Parity

Full parity with Python SDK v1.4.1. New features: IncludeOption type for response customization, InlineCitation types (Web, X, Collections) for tracking citation sources, ToolCallType for distinguishing between different tool call types. Requires Go 1.24+ due to gRPC v1.76.0 dependency.

v0.10.0 - Python SDK v1.5.0 Parity (Current)

Full parity with Python SDK v1.5.0. Continued improvements and alignment with the official xAI Python SDK.

Future Plans

v1.0.0 with 80%+ test coverage and complete documentation. Community feedback and improvements, bug fixes and enhancements, additional features based on user requests, continued optimization and refinement.

Development

Prerequisites

  • Go 1.24 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.