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.
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.
Synchronous and streaming chat with message builders. Clean API for single-shot and conversational interactions.
Define and use tools in your chat completions. Enable AI to call functions and interact with external systems.
Control reasoning effort levels and enable search capabilities for enhanced AI responses.
Get structured JSON and JSON schema outputs. Perfect for parsing AI responses into typed data structures.
API key and Bearer token support with TLS. Environment variable integration for safe credential management.
Environment variables and programmatic config. Customize timeouts, retries, and connection settings.
Health checks, automatic retries, and keepalive. Robust connection handling for production workloads.
Comprehensive error types with gRPC integration. Clear error messages for debugging and monitoring.
Text-to-image and image-to-image generation with multiple formats. Create stunning visuals from prompts.
Full image and file support for vision models (grok-2-vision, grok-4). Send images via URL or base64 with resolution control.
Generate embeddings for text and images. Perfect for semantic search, similarity, and RAG applications.
Upload, download, list, and delete files. Complete file management with 6 methods and size limits.
Search across document collections with 11 collection management methods. Build powerful knowledge bases.
2-10x faster with connection pooling, HTTP/2, and buffer pooling. 90% reduction in memory allocations.
6 server-side tools: Web search, X/Twitter search, code execution, document search, collections, and MCP integration.
24/24 Chat API parameters including seed, logprobs, parallel tool calls, frequency/presence penalties, and more.
11 critical bugs fixed in v0.5.2: tool calling, reasoning models, multi-turn conversations, and ZDR workflows now fully functional.
Comprehensive unit and integration tests. 8+ detailed examples covering all APIs. Zero placeholder code. Production-ready.
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.

Example: Grok-4 analyzing and describing an image through the SDK in OpenWebUI
go get github.com/ZaguanLabs/xai-sdk-gopackage 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)
}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)
}
}Set your xAI API key as an environment variable:
export XAI_API_KEY=your-api-key-herexai-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
The SDK supports both environment variables and programmatic configuration:
XAI_API_KEY - Your xAI API keyXAI_BASE_URL - Custom API base URL (optional)XAI_TIMEOUT - Request timeout in seconds (optional)client := xai.NewClient(
xai.WithAPIKey("your-api-key"),
xai.WithBaseURL("https://api.x.ai/v1"),
xai.WithTimeout(30 * time.Second),
xai.WithRetries(3),
)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.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.
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.
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.
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.
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.
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.
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%).
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.
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.
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.
Full parity with Python SDK v1.5.0. Continued improvements and alignment with the official xAI Python SDK.
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.
# Clone the repository
git clone https://github.com/ZaguanLabs/xai-sdk-go.git
cd xai-sdk-go
# Build
go build ./...
# Run tests
go test ./...# 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.goContributions 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.