grok_api 0.1.1

Rust client library for the Grok AI API (xAI)
Documentation
# grok_api


[![Crates.io](https://img.shields.io/crates/v/grok_api.svg)](https://crates.io/crates/grok_api)
[![Documentation](https://docs.rs/grok_api/badge.svg)](https://docs.rs/grok_api)
[![License](https://img.shields.io/crates/l/grok_api.svg)](https://github.com/microtech/grok-api#license)
[![Cobble](https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png)](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** - Optimized for challenging conditions (Starlink, satellite connections)
- 🔧 **Flexible configuration** - Customize timeouts, retries, and more
- 📊 **Rate limiting** - Client-side rate limit tracking (optional)
- 🛠️ **Tool/Function calling** - Full support for function calling and tools

## 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-3")
        .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](https://x.ai).

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


- `grok-3` - Latest flagship model (default)
- `grok-3-mini` - Efficient smaller model
- `grok-2-latest` - Previous generation
- `grok-2` - Stable previous generation
- `grok-beta` - Experimental features
- `grok-vision-beta` - Vision capabilities

```rust
// Use a specific model
let response = client.chat("Hello", Some("grok-3-mini")).await?;

// Or with the builder
let response = client
    .chat_with_history(&messages)
    .model("grok-3")
    .send()
    .await?;
```

## Error Handling


The library provides comprehensive error types:

```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"),
    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


The library supports Grok's function calling feature:

```rust
use grok_api::{GrokClient, ChatMessage};
use serde_json::json;

let tools = vec![
    json!({
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather",
            "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)
    .tools(tools)
    .send()
    .await?;

if response.has_tool_calls() {
    for tool_call in response.tool_calls().unwrap() {
        println!("Tool: {}", tool_call.function.name);
        println!("Args: {}", tool_call.function.arguments);
    }
}
```

## Starlink Optimization


The library includes special handling for Starlink and other satellite connections:

- Automatic detection of connection drops
- Exponential backoff with jitter
- Extended timeout handling
- Connection pooling and keep-alive

```rust
use grok_api::{GrokClient, Error};

let client = GrokClient::builder()
    .api_key("your-api-key")
    .timeout_secs(60)      // Longer timeout for satellite
    .max_retries(5)        // More retries for drops
    .build()?;

match client.chat("Hello", None).await {
    Ok(response) => println!("Success: {}", response),
    Err(e) if e.is_starlink_drop() => {
        eprintln!("Starlink connection dropped, already retried");
    }
    Err(e) => eprintln!("Error: {}", e),
}
```

## Examples


Run the examples:

```bash
# Set your API key

export GROK_API_KEY="your-api-key"

# Simple chat

cargo run --example simple_chat

# Multi-turn conversation

cargo run --example conversation

# Streaming (placeholder for future feature)

cargo run --example streaming
```

## Features


### Default Features


- `retry` - Automatic retry logic (enabled by default)

### Optional Features


- `starlink` - Additional optimizations for Starlink connections

```toml
[dependencies]
grok_api = { version = "0.1", features = ["starlink"] }
```

## Testing


```bash
# Run tests

cargo test

# Run tests with logging

RUST_LOG=debug cargo test

# Run integration tests (requires API key)

GROK_API_KEY="your-key" cargo test --test integration
```

## Minimum Supported Rust Version (MSRV)


This crate requires **Rust 1.70** or later.

## 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.

## 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

## Changelog


See [CHANGELOG.md](CHANGELOG.md) for 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**