xai-grpc-client
Unofficial Rust client for xAI's Grok API with full gRPC support.
Features
- ๐ Async/await API - Built on tokio and tonic for high performance
- ๐ Type-safe - Strongly typed request builders with compile-time guarantees
- ๐ก Streaming support - Real-time response streaming with tokio-stream
- ๐ง Tool calling - Function calling with 7 tool types (function, web search, X search, MCP, etc.)
- ๐ผ๏ธ Multimodal - Text and image inputs for vision capabilities
- ๐ง Advanced features - Log probabilities, reasoning traces, deferred completions
- ๐ Model discovery - List available models with pricing and capabilities
- ๐ข Embeddings - Generate vector representations from text and images
- ๐ค Tokenization - Count tokens for cost estimation and prompt optimization
- ๐ API key management - Check API key status and permissions
- ๐จ Image generation - Create images from text prompts
- ๐ Document search - RAG support with collection search
- ๐ Secure by default - Uses
secrecycrate to protect API keys in memory - โ Complete - 100% coverage of Grok API (19/19 RPCs)
- ๐งช Well-tested - 98 unit tests covering all core modules
Installation
Add this to your Cargo.toml:
[]
= "0.4"
= { = "1", = ["full"] }
= "0.1"
TLS Configuration
The crate provides flexible TLS configuration through feature flags for root certificate selection:
Default (webpki-roots - recommended for containers):
[]
= "0.4"
Using native system roots (recommended for development):
[]
= { = "0.4", = ["tls-native-roots"], = false }
Using both root stores (if unsure):
[]
= { = "0.4", = ["tls-roots"], = false }
Available features:
tls-webpki-roots(default) - Uses Mozilla's root certificates (works in containers/distroless)tls-native-roots- Uses the system's native certificate storetls-roots- Enables both root stores simultaneously
Advanced: Custom TLS Configuration
For advanced use cases (custom CA certificates, proxies, custom timeouts), use the with_channel() constructor:
use ;
use SecretString;
use Duration;
// Load custom CA certificate
let ca_cert = read?;
let ca = from_pem;
// Configure TLS with custom CA
let tls_config = new
.ca_certificate
.domain_name;
// Build custom channel
let channel = from_static
.timeout
.tls_config?
.connect
.await?;
// Create client with custom channel
let api_key = from;
let client = with_channel;
See the custom_tls example for more details.
Quick Start
use ;
async
Set your API key:
Examples
Streaming Chat
Stream responses in real-time:
use ;
use StreamExt;
async
Tool Calling (Function Calling)
Enable the model to call functions:
use ;
use json;
async
Multimodal (Vision)
Send images with your prompts:
use ;
async
Web Search
Enable web search for up-to-date information:
use ;
async
Model Listing
List available models and get pricing information:
use GrokClient;
async
Embeddings
Generate vector embeddings from text or images:
use ;
async
Tokenization
Count tokens before making requests for cost estimation:
use ;
async
API Key Information
Check your API key status and permissions:
use GrokClient;
async
Advanced: Deferred Completions
For long-running tasks, start a deferred completion and poll for results:
use ;
use Duration;
async
CompletionOptions (for trait abstraction)
Use CompletionOptions to create reusable configurations:
use ;
async
API Coverage
This library implements 100% (19/19) of the xAI Grok API services! ๐
โ Fully Implemented Services
Chat Service (6/6 RPCs)
- โ GetCompletion - Blocking chat completions
- โ GetCompletionChunk - Streaming chat completions
- โ StartDeferredCompletion - Async completion handling
- โ GetDeferredCompletion - Poll deferred completions
- โ GetStoredCompletion - Retrieve stored completions
- โ DeleteStoredCompletion - Delete stored completions
Models Service (6/6 RPCs)
- โ ListLanguageModels - List all language models
- โ GetLanguageModel - Get language model details
- โ ListEmbeddingModels - List all embedding models
- โ GetEmbeddingModel - Get embedding model details
- โ ListImageGenerationModels - List image generation models
- โ GetImageGenerationModel - Get image model details
Embeddings Service (1/1 RPCs)
- โ Embed - Generate embeddings from text/images
Tokenize Service (1/1 RPCs)
- โ TokenizeText - Count tokens for cost estimation
Auth Service (1/1 RPCs)
- โ GetApiKeyInfo - Get API key status and permissions
Sample Service (2/2 RPCs)
- โ SampleText - Simpler text completion API
- โ SampleTextStreaming - Streaming text sampling
Image Service (1/1 RPCs)
- โ GenerateImage - Generate images from text prompts
Documents Service (1/1 RPCs)
- โ Search - Search documents/collections for RAG
Feature Summary
- โ Chat & Completions: Complete - All chat methods including streaming, deferred, and stored
- โ Embeddings: Complete - Text and image embedding generation
- โ Models: Complete - Full model discovery for language, embedding, and image models
- โ Tokenization: Complete - Token counting for all models
- โ Auth: Complete - API key information and validation
- โ Image Generation: Complete - Text-to-image and image-to-image generation
- โ Document Search: Complete - RAG with collection-based search
- โ Sample API: Complete - Alternative simple text completion interface
- โ Tool Calling: 7 tool types (function, web search, X search, MCP, collections, documents, code execution)
- โ Multimodal: Text and image inputs for vision models
- โ Advanced Features: Log probabilities, reasoning effort, JSON output, stop sequences, seed
Error Handling
The library provides comprehensive error handling with retry logic:
use ;
async
Configuration
From Environment Variable
let client = from_env.await?;
Requires GROK_API_KEY environment variable.
Manual Configuration
use ;
use SecretString;
use Duration;
let config = GrokConfig ;
let client = new.await?;
Available Models
grok-2-1212- Latest Grok 2 (December 2024)grok-2-vision-1212- Grok 2 with vision capabilitiesgrok-beta- Beta model with experimental features
Check xAI's documentation for the latest model list.
Testing
Run the test suite:
# Unit tests (no API key required)
# Integration tests (requires GROK_API_KEY)
# Run specific test
The library includes 77 comprehensive unit tests covering:
- Request building and validation
- Response parsing
- Error handling and retry logic
- Tool configuration
- Multimodal messages
- Model information and pricing
- Embedding generation
- Tokenization
- API key management
Examples
See the examples/ directory for more complete examples:
# Simple chat
# Streaming
# Tool calling
# Multimodal
# Model listing
# Embeddings
# Tokenization
# Custom TLS configuration
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Development Setup
# Clone the repository with submodules
# Or if you already cloned without --recursive:
Note: This project uses a Git submodule for proto definitions. The xai-proto submodule must be initialized before building.
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Disclaimer
This is an unofficial client library and is not affiliated with or endorsed by xAI. Use at your own risk.
Links
Changelog
See CHANGELOG.md for release history.