# grok_api
[](https://crates.io/crates/grok_api)
[](https://docs.rs/grok_api)
[](https://github.com/microtech/grok-api#license)
[](https://www.buymeacoffee.com/Cobble)
A Rust client library for the **Grok AI API** (xAI). Simple, robust, and production-ready.
## Features
- 🚀 **Easy to use** — Simple async API with builder pattern
- 🔄 **Automatic retries** — Built-in retry logic for transient failures
- 🛡️ **Robust error handling** — Comprehensive error types with detailed messages
- 🌐 **Network resilient** — Optimised for challenging conditions (Starlink, satellite connections)
- 🔧 **Flexible configuration** — Customise timeouts, retries, and more
- 🛠️ **Tool / Function calling** — Full support for function calling and agentic workflows
- 🧠 **Reasoning-aware** — Capability helpers guard against sending unsupported params to reasoning models
- 📦 **Rust 2024 edition** — Built on the latest edition with MSRV 1.85
---
## Quick Start
Add this to your `Cargo.toml`:
```toml
[dependencies]
grok_api = "0.1"
tokio = { version = "1", features = ["full"] }
```
### Simple Example
```rust
use grok_api::{GrokClient, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = GrokClient::new("your-api-key")?;
let response = client
.chat("What is Rust?", None)
.await?;
println!("Response: {}", response);
Ok(())
}
```
### Conversation with History
```rust
use grok_api::{GrokClient, ChatMessage, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = GrokClient::new("your-api-key")?;
let messages = vec![
ChatMessage::system("You are a helpful Rust expert."),
ChatMessage::user("How do I create a Vec?"),
];
let response = client
.chat_with_history(&messages)
.temperature(0.7)
.max_tokens(1000)
.model("grok-4.5") // current flagship
.send()
.await?;
println!("Response: {}", response.content().unwrap_or(""));
println!("Tokens used: {}", response.usage.total_tokens);
Ok(())
}
```
### Advanced Configuration
```rust
use grok_api::{GrokClient, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = GrokClient::builder()
.api_key("your-api-key")
.timeout_secs(60)
.max_retries(5)
.base_url("https://custom-endpoint.com") // optional
.build()?;
// Use client...
Ok(())
}
```
---
## API Key
Get your API key from [x.ai/api](https://x.ai/api).
Set it as an environment variable:
```bash
export GROK_API_KEY="your-api-key-here"
```
Or pass it directly to the client:
```rust
let client = GrokClient::new("your-api-key")?;
```
---
## Available Models
> Last synced with xAI API — **July 9, 2026**
> Call `GET https://api.x.ai/v1/models` with your key to see your account's live list.
> ⚠️ **Retirements effective 2026-05-15 12:00 PT** — the following API strings will stop
> working: `grok-4-1-fast-reasoning`, `grok-4-1-fast-non-reasoning`, `grok-4-0709`,
> `grok-code-fast-1`, `grok-3`, `grok-imagine-image-pro`.
> See the [Migration Guide](#migration-guide-016--017) below.
### 🌟 Grok 4.5 — Current Flagship (500 K token context, July 2026)
| `grok-4.5` | `Model::Grok4_5` | **Recommended for everything** — code, chat, agentic tasks, STEM |
> **Grok 4.5 highlights:**
> - 500,000 token context window
> - Configurable `reasoning_effort`: `"low"` / `"medium"` / `"high"` (default **`high`**)
> - Text + image input; text output
> - $2.00 / 1 M input · $6.00 / 1 M output (doubles for prompts ≥ 200 K tokens)
> - Knowledge cutoff: **February 1, 2026**
> - Aliases: `grok-4.5-latest`, `grok-build-latest`
### ⭐ Grok 4.3 — Previous Flagship (1 M token context)
| `grok-4.3` | `Model::Grok4_3` | Larger context needs (1 M tokens); lower cost than 4.5 |
### 🛠️ Grok Build 0.1 — Agentic Coding (256 K token context)
| `grok-build-0.1` | `Model::GrokBuild0_1` | **Recommended for coding** — agentic coding, tool use, multi-step dev tasks |
> **Grok Build 0.1 highlights:**
> - 256,000 token context window — handles large repos and multi-file work
> - Text + image input; text output; no output-token limit
> - Built-in reasoning (not user-configurable)
> - $1.00 / 1 M input · $2.00 / 1 M output
> - Successor to the retired `grok-code-fast-1`; `parse()` accepts its old aliases
### 🏆 Grok 4.20 — (2 M token context)
| `grok-4.20-0309-reasoning` | `Model::Grok4_20_0309Reasoning` | Complex reasoning, maths, science, multi-step agentic tasks |
| `grok-4.20-non-reasoning` | `Model::Grok4_20NonReasoning` | Fast non-reasoning, high-throughput, lower latency |
| `grok-4.20-0309-non-reasoning` | `Model::Grok4_20_0309NonReasoning` | Dated variant of the 4.20 standard model |
| `grok-4.20-multi-agent-0309` | `Model::Grok4_20MultiAgent0309` | Deep research, complex workflows, multi-agent pipelines |
> **Note:** `Grok4_20_0309Reasoning` / `Grok4_20MultiAgent0309` do **not** support
> `presence_penalty`, `frequency_penalty`, `stop`, or `reasoning_effort`.
> `logprobs` is silently ignored by all Grok 4.20 models.
### 🗄️ Legacy (Grok 3 Mini — still active)
| `grok-3-mini` | `Model::Grok3Mini` | Efficient smaller model; 131 K context; **not** retiring May 2026 |
### 🖼️ Image Generation
| `grok-imagine-image` | `Model::GrokImagineImage` | Standard image generation |
### 🎤 Voice — Real-Time Speech-to-Speech
> Voice models use a **WebSocket** endpoint (`wss://api.x.ai/v1/realtime?model=...`),
> not the chat completions API. They cannot be used with `GrokClient`. Use
> `Model::as_str()` to get the model name for the `?model=` query parameter.
| `grok-voice-think-fast-2.0` | `Model::GrokVoiceThinkFast2_0` | Current flagship voice model |
| `grok-voice-think-fast-1.0` | `Model::GrokVoiceThinkFast1_0` | Previous-gen voice model |
| `grok-voice-latest` | `Model::GrokVoiceLatest` | Rolling alias — pin to versioned name in production |
```rust
// Get the WebSocket URL for the current flagship voice model
let model = Model::GrokVoiceThinkFast2_0;
assert!(model.is_voice_model());
assert!(!model.is_language_model());
let url = format!("wss://api.x.ai/v1/realtime?model={}", model.as_str());
```
---
## Voice API (Real-Time Speech-to-Speech)
The `voice` module provides a full [`VoiceSession`] WebSocket client for the
xAI real-time Speech-to-Speech endpoint (`wss://api.x.ai/v1/realtime`).
Add the required features to your `Cargo.toml`:
```toml
[dependencies]
grok_api = "0.1"
tokio = { version = "1", features = ["full"] }
```
### Quick start
```rust
use grok_api::voice::{VoiceSession, VoiceEvent, AudioFormat};
#[tokio::main]
async fn main() -> grok_api::Result<()> {
let mut session = VoiceSession::builder("your-api-key")
.model("grok-voice-think-fast-2.0")
.instructions("You are a concise voice assistant.")
.server_vad() // auto-detect end-of-speech
.input_format(AudioFormat::pcm(16_000)) // 16 kHz PCM microphone input
.output_format(AudioFormat::pcm(24_000))// 24 kHz PCM speaker output
.build()
.await?;
// --- Send audio from microphone ---
let pcm_chunk_b64 = "AAAA..."; // base64-encoded PCM bytes
session.append_audio(pcm_chunk_b64).await?;
// --- Process events ---
while let Some(event) = session.next_event().await? {
match event {
VoiceEvent::AudioDelta { delta, .. } => {
// stream `delta` (base64 PCM) to your speaker
let _bytes = delta;
}
VoiceEvent::TranscriptDone { transcript, .. } => {
println!("Model said: {}", transcript);
}
VoiceEvent::FunctionCall { name, call_id, arguments } => {
// call your function, then feed result back
let result = format!("{{\"result\": \"42\"}}");
session.send_function_result(call_id, result).await?;
session.request_response().await?;
}
VoiceEvent::Done { usage } => {
println!("Turn complete. Usage: {:?}", usage);
break;
}
VoiceEvent::Error { code, message } => {
eprintln!("API error [{code}]: {message}");
break;
}
_ => {}
}
}
Ok(())
}
```
### Session options
```rust
use grok_api::voice::{VoiceSession, TurnDetection, ReasoningEffort};
let session = VoiceSession::builder("your-api-key")
.model("grok-voice-think-fast-2.0") // or "grok-voice-latest"
.voice("sage") // TTS voice name
.instructions("Respond in French.") // system prompt
// Fine-grained VAD control:
.turn_detection(
TurnDetection::server_vad()
.threshold(0.6)
.silence_duration_ms(400)
.prefix_padding_ms(100)
)
.reasoning_effort(ReasoningEffort::High)
.language_hint("fr") // BCP-47 hint for ASR
.keyterm("Fermat") // boost word recognition
.output_speed(0.9) // slightly slower TTS
.session_resumption() // reconnect replays history
.build()
.await?;
```
### Starlink-aware reconnection
If the WebSocket drops (common on satellite connections), call
`session.reconnect()`. It uses exponential backoff with jitter from the
crate's built-in [`RetryConfig`].
```rust
use grok_api::voice::VoiceSession;
use grok_api::Error;
match session.next_event().await {
Err(Error::ConnectionDropped) => {
eprintln!("Connection dropped (Starlink?), reconnecting…");
session.reconnect().await?; // retries with backoff
}
Ok(event) => { /* handle event */ }
Err(e) => return Err(e),
}
```
---
### 🎥 Video Generation
| `grok-imagine-video` | `Model::GrokImagineVideo` | Video generation |
### 🚨 Deprecated models (retire 2026-05-15)
These variants still compile but emit a **Rust deprecation warning**. Migrate before 2026-05-15.
| `grok-4-1-fast-reasoning` | `Model::Grok4_1FastReasoning` | `Model::Grok4_3` |
| `grok-4-1-fast-non-reasoning` | `Model::Grok4_1FastNonReasoning` | `Model::Grok4_20NonReasoning` |
| `grok-4-0709` | `Model::Grok4_0709` | `Model::Grok4_3` |
| `grok-3` | `Model::Grok3` | `Model::Grok4_3` |
| `grok-code-fast-1` | `Model::GrokCodeFast1` | `Model::Grok4_3` |
| `grok-imagine-image-pro` | `Model::GrokImagineImagePro` | `Model::GrokImagineImage` |
### Recommended models at a glance
| Everyday / chat / CLI default | `grok-4.5` |
| Code generation & agentic coding | `grok-4.5` |
| Large context (> 500 K tokens) | `grok-4.3` (1 M ctx) |
| Maximum reasoning | `grok-4.20-0309-reasoning` |
| Speed + high volume | `grok-4.20-non-reasoning` |
| Agentic / multi-step pipelines | `grok-4.20-multi-agent-0309` |
| Image generation | `grok-imagine-image` |
### Using the `Model` enum
```rust
use grok_api::models::Model;
// Type-safe — no typos
let model = Model::Grok4_5; // current flagship
println!("{}", model.as_str()); // "grok-4.5"
// Guard pure reasoning models against unsupported params
if model.is_reasoning_model() {
// Do NOT set frequency_penalty or presence_penalty
}
// grok-4.5 supports configurable reasoning effort (default = high)
if model.supports_reasoning_effort() {
println!("Can set reasoning_effort = low | medium | high");
}
// Check context window
if let Some(ctx) = model.context_window() {
println!("Context: {} tokens", ctx); // 500_000 for grok-4.5
}
// Check capabilities
println!("Language model: {}", model.is_language_model());
println!("Image model: {}", model.is_image_model());
println!("Video model: {}", model.is_video_model());
println!("Supports logprobs: {}", model.supports_logprobs());
// Parse from a string (e.g. from config / env var)
let m = Model::parse("grok-4.5").expect("unknown model");
// All active (non-deprecated) models
for m in Model::all() {
println!("{}", m);
}
// All models including deprecated ones (for migration tooling)
for m in Model::all_including_deprecated() {
println!("{}", m);
}
```
---
## Error Handling
```rust
use grok_api::{GrokClient, Error};
match client.chat("Hello", None).await {
Ok(response) => println!("Success: {}", response),
Err(Error::Authentication) => eprintln!("Invalid API key"),
Err(Error::RateLimit) => eprintln!("Rate limit exceeded — back off and retry"),
Err(Error::Network(msg)) => eprintln!("Network error: {}", msg),
Err(Error::Timeout(secs)) => eprintln!("Timeout after {} seconds", secs),
Err(e) => eprintln!("Other error: {}", e),
}
```
### Retry Logic
Network errors are automatically retried with exponential backoff:
```rust
let client = GrokClient::builder()
.api_key("your-api-key")
.max_retries(5) // retry up to 5 times
.build()?;
```
Retryable errors include:
- Network timeouts
- Connection failures
- Server errors (5xx)
- Starlink / satellite network drops
---
## Function Calling / Tools
Full support for Grok's function calling and agentic tool use:
```rust
use grok_api::{GrokClient, ChatMessage};
use serde_json::json;
let tools = vec![
json!({
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name"
}
},
"required": ["location"]
}
}
})
];
let messages = vec![
ChatMessage::user("What's the weather in San Francisco?")
];
let response = client
.chat_with_history(&messages)
.model("grok-4.5")
.tools(tools)
.send()
.await?;
if response.has_tool_calls() {
for call in response.tool_calls().unwrap() {
println!("Tool: {}", call.function.name);
println!("Args: {}", call.function.arguments);
// parse args → call your function → feed result back
let result = "Sunny, 18 °C";
messages.push(ChatMessage::tool(result, &call.id));
}
}
```
---
## Starlink Optimisation
The library includes special handling for Starlink and other satellite connections:
- Automatic detection of connection drops
- Exponential backoff with jitter
- Extended timeout handling
```rust
use grok_api::{GrokClient, Error};
let client = GrokClient::builder()
.api_key("your-api-key")
.timeout_secs(60) // longer timeout for satellite latency
.max_retries(5) // more retries for intermittent drops
.build()?;
match client.chat("Hello", None).await {
Ok(response) => println!("Success: {}", response),
Err(e) if e.is_starlink_drop() => {
eprintln!("Starlink connection dropped — all retries exhausted");
}
Err(e) => eprintln!("Error: {}", e),
}
```
---
## Examples
```bash
# Set your API key
export GROK_API_KEY="your-api-key"
# Simple single-turn chat
cargo run --example simple_chat
# Multi-turn conversation
cargo run --example conversation
# Streaming responses
cargo run --example streaming
# Function / tool calling
cargo run --example tools_example
# Video / multimodal
cargo run --example video_chat
```
---
## Cargo Features
| `retry` | ✅ yes | Automatic retry with exponential backoff |
| `starlink` | ❌ no | Extra optimisations for satellite connections |
```toml
[dependencies]
grok_api = { version = "0.1", features = ["starlink"] }
```
---
## Testing
```bash
# Unit + doc tests (no API key needed)
cargo test
# With debug logging
RUST_LOG=debug cargo test
# Clippy
cargo clippy -- -D warnings
```
---
## Minimum Supported Rust Version (MSRV)
This crate requires **Rust 1.85** or later (Rust 2024 edition).
Update your toolchain with:
```bash
rustup update stable
```
---
## Documentation
Full API documentation is available at [docs.rs/grok_api](https://docs.rs/grok_api).
---
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
---
## License
This project is licensed under either of:
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
- MIT License ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
at your option.
---
## Migration Guide: 0.1.6 → 0.1.7
Six models retire on **2026-05-15 12:00 PT**. After that date, the xAI API will
return an error for any request that names a retired model.
### Quick replacement table
| `grok-4-1-fast-reasoning` | `grok-4.3` |
| `grok-4-1-fast-non-reasoning` | `grok-4.20-non-reasoning` |
| `grok-4-0709` | `grok-4.3` |
| `grok-code-fast-1` | `grok-4.3` |
| `grok-3` | `grok-4.3` |
| `grok-imagine-image-pro` | `grok-imagine-image` |
### Rust code migration
```rust
// Before (0.1.6)
let model = Model::Grok4_1FastReasoning; // ⚠️ deprecated in 0.1.7
// After (0.1.7)
let model = Model::Grok4_3; // ✅ new recommended default
```
```rust
// Before (0.1.6)
let model = Model::Grok4_1FastNonReasoning; // ⚠️ deprecated in 0.1.7
// After (0.1.7)
let model = Model::Grok4_20NonReasoning; // ✅ stable 4.20 non-reasoning alias
```
```rust
// Before (0.1.6)
let model = Model::GrokImagineImagePro; // ⚠️ deprecated in 0.1.7
// After (0.1.7)
let model = Model::GrokImagineImage; // ✅ standard image generation
```
> Deprecated variants still **compile** (with a warning) and still **work** until
> 2026-05-15. This gives you time to migrate at your own pace.
---
## Disclaimer
This is an **unofficial** library and is not affiliated with, endorsed by, or sponsored by xAI or X Corp.
---
## Links
- [Crates.io](https://crates.io/crates/grok_api)
- [Documentation](https://docs.rs/grok_api)
- [GitHub Repository](https://github.com/microtech/grok-api)
- [xAI Official Site](https://x.ai)
- [Buy Me a Coffee ☕](https://www.buymeacoffee.com/Cobble)
---
## Changelog
See [CHANGELOG.md](CHANGELOG.md) for full release notes and version history.
---
## Support
For bugs and feature requests, please [open an issue](https://github.com/microtech/grok-api/issues).
---
*Made with ❤️ and Rust — [John McConnell](mailto:john.microtech@gmail.com)*