grok_api 0.1.71

Rust client library for the Grok AI API (xAI)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Main client implementation for the Grok API

use crate::error::{Error, Result};
use crate::models::{ChatMessage, ChatRequest, ChatResponse, Model};
use crate::retry::{RetryConfig, retry_async};
use reqwest::{Client, ClientBuilder};
use serde_json::Value;
use std::time::Duration;
use tracing::{debug, info, warn};

/// Base URL for the Grok API
const DEFAULT_BASE_URL: &str = "https://api.x.ai";

/// Default timeout in seconds
const DEFAULT_TIMEOUT_SECS: u64 = 30;

/// Default model (grok-4.3 — new flagship, replaces retired grok-4-1-fast-reasoning)
const DEFAULT_MODEL: &str = "grok-4.3";

/// Main client for interacting with the Grok API
#[derive(Clone, Debug)]
pub struct GrokClient {
    client: Client,
    api_key: String,
    base_url: String,
    retry_config: RetryConfig,
}

impl GrokClient {
    /// Create a new Grok client with the given API key
    ///
    /// # Example
    ///
    /// ```no_run
    /// use grok_api::{GrokClient, Result};
    ///
    /// # async fn example() -> Result<()> {
    /// let client = GrokClient::new("your-api-key")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(api_key: impl Into<String>) -> Result<Self> {
        Self::builder().api_key(api_key).build()
    }

    /// Create a new builder for configuring the client
    ///
    /// # Example
    ///
    /// ```no_run
    /// use grok_api::{GrokClient, Result};
    ///
    /// # async fn example() -> Result<()> {
    /// let client = GrokClient::builder()
    ///     .api_key("your-api-key")
    ///     .timeout_secs(60)
    ///     .max_retries(5)
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn builder() -> GrokClientBuilder {
        GrokClientBuilder::default()
    }

    /// Send a simple chat message
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use grok_api::{GrokClient, Result};
    /// # async fn example() -> Result<()> {
    /// # let client = GrokClient::new("key")?;
    /// let response = client.chat("What is Rust?", None).await?;
    /// println!("Response: {}", response);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn chat(&self, message: impl Into<String>, model: Option<&str>) -> Result<String> {
        let message_text: String = message.into();
        let messages = vec![ChatMessage::user(message_text)];
        let response: ChatResponse = self
            .chat_with_history(&messages)
            .model(model.unwrap_or(DEFAULT_MODEL))
            .send()
            .await?;

        Ok(response.content().unwrap_or("").to_string())
    }

    /// Create a chat request builder with message history
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use grok_api::{GrokClient, ChatMessage, Result};
    /// # async fn example() -> Result<()> {
    /// # let client = GrokClient::new("key")?;
    /// let messages = vec![
    ///     ChatMessage::system("You are a helpful assistant"),
    ///     ChatMessage::user("Hello!"),
    /// ];
    ///
    /// let response = client
    ///     .chat_with_history(&messages)
    ///     .temperature(0.7)
    ///     .max_tokens(1000)
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn chat_with_history(&self, messages: &[ChatMessage]) -> ChatRequestBuilder {
        ChatRequestBuilder::new(self.clone(), messages.to_vec())
    }

    /// List available models
    pub async fn list_models(&self) -> Result<Vec<String>> {
        let url = format!("{}/v1/models", self.base_url);

        let result = retry_async(&self.retry_config, || async {
            let response = self
                .client
                .get(&url)
                .bearer_auth(&self.api_key)
                .send()
                .await
                .map_err(Error::from_reqwest)?;

            if !response.status().is_success() {
                let status = response.status().as_u16();
                let body = response.text().await.unwrap_or_default();
                return Err(Error::Http {
                    status,
                    message: body,
                });
            }

            let json: Value = response.json().await.map_err(Error::from_reqwest)?;

            if let Some(data) = json.get("data").and_then(|d| d.as_array()) {
                let models = data
                    .iter()
                    .filter_map(|m| m.get("id")?.as_str())
                    .map(String::from)
                    .collect();
                Ok(models)
            } else {
                // Fallback to known models
                Ok(Model::all().iter().map(|m: &Model| m.to_string()).collect())
            }
        })
        .await?;

        Ok(result)
    }

    /// Test connection to the API
    pub async fn test_connection(&self) -> Result<()> {
        info!("Testing connection to Grok API");
        let _ = self.chat("Hello", Some("grok-4.3")).await?;
        info!("Connection test successful");
        Ok(())
    }

    /// Internal method to send a chat completion request
    async fn send_chat_request(&self, request: ChatRequest) -> Result<ChatResponse> {
        let url = format!("{}/v1/chat/completions", self.base_url);

        debug!("Sending chat request to {}", url);
        debug!(
            "Model: {}, Messages: {}",
            request.model,
            request.messages.len()
        );

        let result = retry_async(&self.retry_config, || async {
            let response = self
                .client
                .post(&url)
                .bearer_auth(&self.api_key)
                .json(&request)
                .send()
                .await
                .map_err(Error::from_reqwest)?;

            let status = response.status();
            if !status.is_success() {
                let status_code = status.as_u16();
                let body = response.text().await.unwrap_or_default();

                warn!("API request failed: {} - {}", status_code, body);

                return Err(match status_code {
                    401 => Error::Authentication,
                    429 => Error::RateLimit,
                    404 => Error::ModelNotFound(request.model.clone()),
                    400 => Error::InvalidRequest(body),
                    500..=599 => Error::ServerError(body),
                    _ => Error::Http {
                        status: status_code,
                        message: body,
                    },
                });
            }

            let response_text = response.text().await.map_err(Error::from_reqwest)?;
            debug!("Response received: {} bytes", response_text.len());

            let chat_response: ChatResponse =
                serde_json::from_str(&response_text).map_err(|e| {
                    warn!("Failed to parse response: {}", e);
                    Error::Json(e)
                })?;

            info!(
                "Chat completion successful - Model: {}, Tokens: {}",
                chat_response.model, chat_response.usage.total_tokens
            );

            Ok(chat_response)
        })
        .await?;

        Ok(result)
    }
}

/// Builder for configuring a GrokClient
#[derive(Default)]
pub struct GrokClientBuilder {
    api_key: Option<String>,
    base_url: Option<String>,
    timeout_secs: Option<u64>,
    max_retries: Option<u32>,
    retry_config: Option<RetryConfig>,
}

impl GrokClientBuilder {
    /// Set the API key
    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.api_key = Some(key.into());
        self
    }

    /// Set a custom base URL (for testing or proxies)
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Set request timeout in seconds
    pub fn timeout_secs(mut self, timeout: u64) -> Self {
        self.timeout_secs = Some(timeout);
        self
    }

    /// Set maximum number of retry attempts
    pub fn max_retries(mut self, retries: u32) -> Self {
        self.max_retries = Some(retries);
        self
    }

    /// Set a custom retry configuration
    pub fn retry_config(mut self, config: RetryConfig) -> Self {
        self.retry_config = Some(config);
        self
    }

    /// Build the GrokClient
    pub fn build(self) -> Result<GrokClient> {
        let api_key = self.api_key.ok_or(Error::EmptyApiKey)?;

        if api_key.is_empty() {
            return Err(Error::EmptyApiKey);
        }

        let timeout = self.timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS);
        let client = ClientBuilder::new()
            .timeout(Duration::from_secs(timeout))
            .connect_timeout(Duration::from_secs(10))
            .tcp_keepalive(Duration::from_secs(30))
            .user_agent(format!("grok_api/{}", env!("CARGO_PKG_VERSION")))
            .build()
            .map_err(Error::from_reqwest)?;

        let retry_config = self
            .retry_config
            .unwrap_or_else(|| RetryConfig::new(self.max_retries.unwrap_or(3)));

        Ok(GrokClient {
            client,
            api_key,
            base_url: self
                .base_url
                .unwrap_or_else(|| DEFAULT_BASE_URL.to_string()),
            retry_config,
        })
    }
}

/// Builder for creating chat requests
pub struct ChatRequestBuilder {
    client: GrokClient,
    messages: Vec<ChatMessage>,
    model: Option<String>,
    temperature: Option<f32>,
    max_tokens: Option<u32>,
    tools: Option<Vec<Value>>,
    top_p: Option<f32>,
    reasoning_effort: Option<String>,
}

impl ChatRequestBuilder {
    fn new(client: GrokClient, messages: Vec<ChatMessage>) -> Self {
        Self {
            client,
            messages,
            model: None,
            temperature: None,
            max_tokens: None,
            tools: None,
            top_p: None,
            reasoning_effort: None,
        }
    }

    /// Set the model to use
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Set the sampling temperature (0.0 to 2.0)
    pub fn temperature(mut self, temp: f32) -> Self {
        self.temperature = Some(temp.clamp(0.0, 2.0));
        self
    }

    /// Set maximum tokens to generate
    pub fn max_tokens(mut self, tokens: u32) -> Self {
        self.max_tokens = Some(tokens);
        self
    }

    /// Set tools/functions available to the model
    pub fn tools(mut self, tools: Vec<Value>) -> Self {
        self.tools = Some(tools);
        self
    }

    /// Set top-p sampling parameter
    pub fn top_p(mut self, p: f32) -> Self {
        self.top_p = Some(p.clamp(0.0, 1.0));
        self
    }

    /// Set the reasoning effort level for thinking-capable models.
    /// Valid values: `"low"`, `"medium"`, `"high"`.
    /// Has no effect on models that do not support reasoning (field is
    /// silently omitted from the request if not set).
    pub fn reasoning_effort(mut self, effort: impl Into<String>) -> Self {
        self.reasoning_effort = Some(effort.into());
        self
    }

    /// Send the chat request
    pub async fn send(self) -> Result<ChatResponse> {
        let request = ChatRequest {
            model: self.model.unwrap_or_else(|| DEFAULT_MODEL.to_string()),
            messages: self.messages,
            temperature: self.temperature,
            max_tokens: self.max_tokens,
            stream: Some(false),
            tools: self.tools,
            top_p: self.top_p,
            frequency_penalty: None,
            presence_penalty: None,
            reasoning_effort: self.reasoning_effort,
        };

        self.client.send_chat_request(request).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_client_builder() {
        let client = GrokClient::builder()
            .api_key("test-key")
            .timeout_secs(60)
            .max_retries(5)
            .build();

        assert!(client.is_ok());
        let client = client.unwrap();
        assert_eq!(client.api_key, "test-key");
    }

    #[test]
    fn test_empty_api_key_error() {
        let result = GrokClient::new("");
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::EmptyApiKey));
    }

    #[test]
    fn test_builder_missing_api_key() {
        let result = GrokClient::builder().timeout_secs(30).build();
        assert!(result.is_err());
    }
}