groqai 0.1.4

A modern, type-safe Rust SDK for the Groq AI API with enterprise-grade features
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
use crate::error::GroqError;
use crate::models::{
    ChatCompletionChunk, ChatCompletionRequest, ChatCompletionResponse,
    ModelListResponse, FileObject, FileListResponse, FileDeleteResponse,
    BatchObject, BatchListResponse, AudioTranscriptionResponse, AudioTranslationResponse,
    AudioTranscriptionRequest, AudioTranslationRequest, Tool, ToolChoice, ChatMessage,
};
use futures::TryStreamExt;
use futures::stream::Stream;
use reqwest::Client;
use std::pin::Pin;

#[derive(Debug)]
/// A client for interacting with the Groq API.
/// 
/// This client provides methods for chat completions, file operations,
/// batch processing, and audio operations.
/// 
/// # Examples
/// 
/// ```rust,no_run
/// use groqai::GroqClient;
/// 
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let client = GroqClient::new("gsk_your_api_key_here".to_string())?;
///     
///     // Use the client...
///     Ok(())
/// }
/// ```
pub struct GroqClient {
    base_url: String,
    api_key: String,
    client: Client,
}

impl GroqClient {
    /// Create a new GroqClient with the provided API key.
    /// 
    /// # Arguments
    /// 
    /// * `api_key` - Your Groq API key. Must start with "gsk_".
    /// 
    /// # Returns
    /// 
    /// Returns a `Result` containing the client if successful, or an error if the API key is invalid.
    /// 
    /// # Errors
    /// 
    /// * `InvalidApiKey` - If the API key is empty or has an invalid format.
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// use groqai::GroqClient;
    /// 
    /// let client = GroqClient::new("gsk_your_api_key_here".to_string())?;
    /// # Ok::<(), groqai::GroqError>(())
    /// ```
    pub fn new(api_key: String) -> Result<Self, GroqError> {
        if api_key.trim().is_empty() {
            return Err(GroqError::InvalidApiKey("API key cannot be empty".to_string()));
        }
        
        // Basic validation: API key should start with "gsk_" for Groq
        if !api_key.starts_with("gsk_") {
            return Err(GroqError::InvalidApiKey("Invalid API key format. Groq API keys should start with 'gsk_'".to_string()));
        }

        let client = Client::new();
        let base_url = "https://api.groq.com/openai/v1".to_string();
        Ok(GroqClient {
            base_url,
            api_key,
            client,
        })
    }

    /// Create a new GroqClient from the `GROQ_API_KEY` environment variable.
    /// 
    /// # Returns
    /// 
    /// Returns a `Result` containing the client if successful, or an error if the environment variable is not set or invalid.
    /// 
    /// # Errors
    /// 
    /// * `InvalidApiKey` - If the `GROQ_API_KEY` environment variable is not set or contains an invalid API key.
    /// 
    /// # Examples
    /// 
    /// ```bash
    /// # Set environment variable
    /// export GROQ_API_KEY="gsk_your_api_key_here"
    /// ```
    /// 
    /// ```rust
    /// use groqai::GroqClient;
    /// 
    /// let client = GroqClient::from_env()?;
    /// # Ok::<(), groqai::GroqError>(())
    /// ```
    pub fn from_env() -> Result<Self, GroqError> {
        let api_key = std::env::var("GROQ_API_KEY")
            .map_err(|_| GroqError::InvalidApiKey("GROQ_API_KEY environment variable not set".to_string()))?;
        
        Self::new(api_key)
    }

    /// Chat completions
    pub async fn chat_completions(
        &self,
        request: ChatCompletionRequest,
    ) -> Result<ChatCompletionResponse, GroqError> {
        let url = format!("{}/chat/completions", self.base_url);
        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .json(&request)
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(GroqError::api_error(status, text));
        }

        let chat_response: ChatCompletionResponse = response.json().await?;
        Ok(chat_response)
    }

    /// Streaming chat completions
    pub async fn stream_chat_completions(
        &self,
        request: ChatCompletionRequest,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<ChatCompletionChunk, GroqError>> + Send>>, GroqError>
    {
        let url = format!("{}/chat/completions", self.base_url);
        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .json(&request)
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(GroqError::api_error(status, text));
        }

        let bytes_stream = response.bytes_stream().map_err(GroqError::from);

        let stream = bytes_stream.try_filter_map(|chunk| async move {
            let chunk_str = match String::from_utf8(chunk.to_vec()) {
                Ok(s) => s,
                Err(_) => return Err(GroqError::StreamParsing("Invalid UTF-8 in stream chunk".to_string())),
            };

            // Process SSE format data
            let lines: Vec<&str> = chunk_str.lines().collect();

            for line in lines {
                let line = line.trim();
                if line.is_empty() || line == "data: [DONE]" {
                    continue;
                }

                if line.starts_with("data: ") {
                    let json_str = line.trim_start_matches("data: ");
                    if json_str == "[DONE]" {
                        continue;
                    }

                    // Skip empty data lines
                    if json_str.trim().is_empty() {
                        continue;
                    }

                    match serde_json::from_str::<ChatCompletionChunk>(json_str) {
                        Ok(chunk) => return Ok(Some(chunk)),
                        Err(e) => {
                            // Log the invalid JSON for debugging but don't fail the entire stream
                            eprintln!("Failed to parse chunk JSON: {} from line: {}", e, json_str);
                            continue;
                        }
                    }
                }
            }

            Ok(None)
        });

        Ok(Box::pin(stream))
    }

    /// Get available models list
    pub async fn get_models(&self) -> Result<ModelListResponse, GroqError> {
        let url = format!("{}/models", self.base_url);
        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(GroqError::api_error(status, text));
        }
        let models: ModelListResponse = response.json().await?;
        Ok(models)
    }

    /// Upload file
    pub async fn upload_file(&self, file_path: &str, purpose: &str) -> Result<FileObject, GroqError> {
        let url = format!("{}/files", self.base_url);
        let form = reqwest::multipart::Form::new()
            .text("purpose", purpose.to_string())
            .part(
                "file",
                reqwest::multipart::Part::file(file_path)
                    .await
                    .map_err(|e| GroqError::Multipart(e.to_string()))?,
            );
        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .multipart(form)
            .send()
            .await?;
        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(GroqError::api_error(status, text));
        }
        let file_object: FileObject = response.json().await?;
        Ok(file_object)
    }

    /// List all files
    pub async fn list_files(&self) -> Result<FileListResponse, GroqError> {
        let url = format!("{}/files", self.base_url);
        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .send()
            .await?;
        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(GroqError::api_error(status, text));
        }
        let file_list: FileListResponse = response.json().await?;
        Ok(file_list)
    }

    /// Delete file
    pub async fn delete_file(&self, file_id: &str) -> Result<FileDeleteResponse, GroqError> {
        let url = format!("{}/files/{}", self.base_url, file_id);
        let response = self
            .client
            .delete(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .send()
            .await?;
        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(GroqError::api_error(status, text));
        }
        let delete_response: FileDeleteResponse = response.json().await?;
        Ok(delete_response)
    }

    /// Get file information
    pub async fn retrieve_file(&self, file_id: &str) -> Result<FileObject, GroqError> {
        let url = format!("{}/files/{}", self.base_url, file_id);
        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .send()
            .await?;
        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(GroqError::api_error(status, text));
        }
        let file_object: FileObject = response.json().await?;
        Ok(file_object)
    }

    /// Download file content
    pub async fn download_file(&self, file_id: &str) -> Result<bytes::Bytes, GroqError> {
        let url = format!("{}/files/{}/content", self.base_url, file_id);
        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .send()
            .await?;
        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(GroqError::api_error(status, text));
        }
        Ok(response.bytes().await?)
    }

    /// Create batch job
    pub async fn create_batch(
        &self,
        input_file_id: &str,
        completion_window: &str,
    ) -> Result<BatchObject, GroqError> {
        let url = format!("{}/batches", self.base_url);
        let body = serde_json::json!({
            "input_file_id": input_file_id,
            "endpoint": "/v1/chat/completions",
            "completion_window": completion_window
        });
        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .json(&body)
            .send()
            .await?;
        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(GroqError::api_error(status, text));
        }
        let batch_object: BatchObject = response.json().await?;
        Ok(batch_object)
    }

    /// Retrieve batch job
    pub async fn retrieve_batch(&self, batch_id: &str) -> Result<BatchObject, GroqError> {
        let url = format!("{}/batches/{}", self.base_url, batch_id);
        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .send()
            .await?;
        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(GroqError::api_error(status, text));
        }
        let batch_object: BatchObject = response.json().await?;
        Ok(batch_object)
    }

    /// Cancel batch job
    pub async fn cancel_batch(&self, batch_id: &str) -> Result<BatchObject, GroqError> {
        let url = format!("{}/batches/{}/cancel", self.base_url, batch_id);
        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .send()
            .await?;
        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(GroqError::api_error(status, text));
        }
        let batch_object: BatchObject = response.json().await?;
        Ok(batch_object)
    }

    /// List all batch jobs
    pub async fn list_batches(&self) -> Result<BatchListResponse, GroqError> {
        let url = format!("{}/batches", self.base_url);
        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .send()
            .await?;
        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(GroqError::api_error(status, text));
        }
        let batch_list: BatchListResponse = response.json().await?;
        Ok(batch_list)
    }

    /// Audio transcription
    pub async fn audio_transcription(
        &self,
        request: AudioTranscriptionRequest,
        file_path: &str,
    ) -> Result<AudioTranscriptionResponse, GroqError> {
        let url = format!("{}/audio/transcriptions", self.base_url);
        let mut form = reqwest::multipart::Form::new()
            .text("model", request.model)
            .part(
                "file",
                reqwest::multipart::Part::file(file_path)
                    .await
                    .map_err(|e| GroqError::Multipart(e.to_string()))?,
            );
        
        if let Some(lang) = request.language {
            form = form.text("language", lang);
        }
        if let Some(p) = request.prompt {
            form = form.text("prompt", p);
        }
        if let Some(fmt) = request.response_format {
            form = form.text("response_format", fmt);
        }
        if let Some(temp) = request.temperature {
            form = form.text("temperature", temp.to_string());
        }
        if let Some(gran) = request.timestamp_granularities {
            for g in gran {
                form = form.text("timestamp_granularities[]", g);
            }
        }
        
        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .multipart(form)
            .send()
            .await?;
        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(GroqError::api_error(status, text));
        }
        let transcription: AudioTranscriptionResponse = response.json().await?;
        Ok(transcription)
    }

    /// Audio translation
    pub async fn audio_translation(
        &self,
        request: AudioTranslationRequest,
        file_path: &str,
    ) -> Result<AudioTranslationResponse, GroqError> {
        let url = format!("{}/audio/translations", self.base_url);
        let mut form = reqwest::multipart::Form::new()
            .text("model", request.model)
            .part(
                "file",
                reqwest::multipart::Part::file(file_path)
                    .await
                    .map_err(|e| GroqError::Multipart(e.to_string()))?,
            );
        
        if let Some(p) = request.prompt {
            form = form.text("prompt", p);
        }
        if let Some(fmt) = request.response_format {
            form = form.text("response_format", fmt);
        }
        if let Some(temp) = request.temperature {
            form = form.text("temperature", temp.to_string());
        }
        if let Some(lang) = request.language {
            form = form.text("language", lang);
        }
        
        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .multipart(form)
            .send()
            .await?;
        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(GroqError::api_error(status, text));
        }
        let translation: AudioTranslationResponse = response.json().await?;
        Ok(translation)
    }

    /// Audio speech synthesis
    pub async fn audio_speech(
        &self,
        model: &str,
        input: &str,
        voice: &str,
        response_format: Option<&str>,
        sample_rate: Option<u32>,
        speed: Option<f32>,
    ) -> Result<bytes::Bytes, GroqError> {
        let url = format!("{}/audio/speech", self.base_url);
        let mut body = serde_json::json!({
            "model": model,
            "input": input,
            "voice": voice
        });
        if let Some(fmt) = response_format {
            body["response_format"] = serde_json::json!(fmt);
        }
        if let Some(rate) = sample_rate {
            body["sample_rate"] = serde_json::json!(rate);
        }
        if let Some(s) = speed {
            body["speed"] = serde_json::json!(s);
        }
        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .json(&body)
            .send()
            .await?;
        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(GroqError::api_error(status, text));
        }
        Ok(response.bytes().await?)
    }

    /// Helper method to create a tool call request
    pub fn create_tool_call_request(
        &self,
        messages: Vec<ChatMessage>,
        model: &str,
        tools: Vec<Tool>,
        tool_choice: Option<ToolChoice>,
    ) -> ChatCompletionRequest {
        ChatCompletionRequest {
            messages,
            model: model.to_string(),
            tools: Some(tools),
            tool_choice,
            ..Default::default()
        }
    }

    /// Helper method to handle tool calls in chat completion
    pub async fn chat_with_tools(
        &self,
        messages: Vec<ChatMessage>,
        model: &str,
        tools: Vec<Tool>,
        tool_choice: Option<ToolChoice>,
    ) -> Result<ChatCompletionResponse, GroqError> {
        let request = self.create_tool_call_request(messages, model, tools, tool_choice);
        self.chat_completions(request).await
    }
}