groqu 0.1.3

Groq API wrapper. One of the worst lmfao
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
/// Groq models. Model definitions are generated by AI because... yeah. Elon ma.
/// But don't worry, I still home-made those `impl`'s.

use std::{ marker::PhantomData, ops::Index };

use ijson::{ ijson, IValue };
use serde::{ Deserialize, Serialize };
use base64::{ engine::general_purpose, Engine as _ };

#[derive(Debug, Clone, Default, Serialize)]
pub struct ChatCompletionRequest {
    /// ID of the model to use
    pub model: IValue,
    /// A list of messages comprising the conversation so far
    pub messages: IValue,
    /// What sampling temperature to use, between 0 and 2
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    /// An alternative to sampling with temperature, called nucleus sampling
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,
    /// How many chat completion choices to generate for each input message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub n: Option<u32>,
    /// Up to 4 sequences where the API will stop generating further tokens
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop: Option<StopSequence>,
    /// The maximum number of tokens that can be generated in the chat completion
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_completion_tokens: Option<u32>,
    /// Number between -2.0 and 2.0 affecting frequency penalty
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frequency_penalty: Option<f32>,
    /// Number between -2.0 and 2.0 affecting presence penalty
    #[serde(skip_serializing_if = "Option::is_none")]
    pub presence_penalty: Option<f32>,
    /// Specifies how to output reasoning tokens
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_format: Option<String>,
    /// An object specifying the format that the model must output
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_format: Option<ResponseFormat>,
    /// For deterministic sampling
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seed: Option<u64>,
    /// A unique identifier representing your end-user
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
}

impl<'a> ChatCompletionRequest {
    pub fn builder() -> _ChatCompletionRequestBuilder<'a> {
        _ChatCompletionRequestBuilder {
            ph: Default::default(),
            rq: ChatCompletionRequest::default(),
        }
    }
}

#[derive(Debug)]
pub struct _ChatCompletionRequestBuilder<'a> {
    ph: PhantomData<&'a ()>,
    rq: ChatCompletionRequest,
}

impl _ChatCompletionRequestBuilder<'_> {
    /// ID of the model to use
    pub fn model<K: AsRef<str>>(mut self, name: K) -> Self {
        self.rq.model = IValue::from(name.as_ref());
        self
    }

    /// A list of messages comprising the conversation so far
    pub fn messages(mut self, messages: &[ChatMessage]) -> Self {
        self.rq.messages = ijson!(messages);
        self
    }

    /// What sampling temperature to use, between 0 and 2
    pub fn temperature(mut self, tmp: f32) -> Self {
        self.rq.temperature = Some(tmp);
        self
    }

    /// An alternative to sampling with temperature, called nucleus sampling
    pub fn top_p(mut self, p: f32) -> Self {
        self.rq.top_p = Some(p);
        self
    }

    /// How many chat completion choices to generate for each input message
    pub fn n(mut self, x: u32) -> Self {
        self.rq.n = Some(x);
        self
    }

    /// Up to 4 sequences where the API will stop generating further tokens
    pub fn stop(mut self, seq: StopSequence) -> Self {
        self.rq.stop = Some(seq);
        self
    }

    /// Up to 4 sequences where the API will stop generating further tokens
    ///
    /// This method targets a single token.
    pub fn stop_single(mut self, token: String) -> Self {
        self.rq.stop = Some(StopSequence::Single(token));
        self
    }

    /// Up to 4 sequences where the API will stop generating further tokens
    ///
    /// This method targets multiple tokens.
    pub fn stop_multiple(mut self, tokens: Vec<String>) -> Self {
        self.rq.stop = Some(StopSequence::Multiple(tokens));
        self
    }

    /// The maximum number of tokens that can be generated in the chat completion
    pub fn max_completion_tokens(mut self, n: u32) -> Self {
        self.rq.max_completion_tokens = Some(n);
        self
    }

    /// Number between -2.0 and 2.0 affecting frequency penalty
    pub fn frequency_penalty(mut self, x: f32) -> Self {
        self.rq.frequency_penalty = Some(x);
        self
    }

    /// Number between -2.0 and 2.0 affecting presence penalty
    pub fn presence_penalty(mut self, x: f32) -> Self {
        self.rq.presence_penalty = Some(x);
        self
    }

    /// Specifies how to output reasoning tokens
    ///
    /// See https://console.groq.com/docs/api-reference#chat-create
    pub fn reasoning_format(mut self, fmt: String) -> Self {
        self.rq.reasoning_format = Some(fmt);
        self
    }

    /// Type of the format that the model must output
    ///
    /// You do not need to pass an object here.
    /// See https://console.groq.com/docs/api-reference#chat-create
    pub fn response_format(mut self, fmt: String) -> Self {
        self.rq.response_format = Some(ResponseFormat { r#type: fmt });
        self
    }

    /// For deterministic sampling
    pub fn seed(mut self, x: u64) -> Self {
        self.rq.seed = Some(x);
        self
    }

    /// A unique identifier representing your end-user
    pub fn user(mut self, id: String) -> Self {
        self.rq.user = Some(id);
        self
    }

    /// Builds the request
    ///
    /// **You must use this** in order to build a request object.
    pub fn build(self) -> ChatCompletionRequest {
        self.rq
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatMessage {
    /// The role of the message author
    pub role: ChatRole,
    /// The content of the message
    pub content: ContentType,
    /// Optional name for the message author
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

macro_rules! messagerole {
    ($name:ident, $e:expr) => {
        pub fn $name(content: impl Into<ContentType>, name: Option<String>) -> Self {
            Self { role: $e, content: content.into(), name }
        }
    };
}

impl ChatMessage {
    messagerole!(system, ChatRole::System);
    messagerole!(assistant, ChatRole::Assistant);
    messagerole!(user, ChatRole::User);
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ContentType {
    /// Text content type.
    Text(String),
    /// Array of content parts.
    Parts(Vec<ContentPart>),
}

impl ContentType {
    /// Creates a new instance, pure text only.
    pub fn text(x: String) -> Self {
        Self::Text(x)
    }

    /// Creates a part with text and image.
    pub fn text_and_image<T: Into<ContentPart>>(a: T, b: T) -> Self {
        Self::Parts(vec![a.into(), b.into()])
    }

    /// Used for constructed instances. Gets the text if this is a text part.
    pub fn get_text(self) -> String {
        match self {
            Self::Text(t) => t,
            _ => panic!("Expected text"),
        }
    }

    /// Used for constructed instances. Gets the text as a referenced str.
    pub fn get_text_as_str(&self) -> &str {
        match self {
            Self::Text(t) => t,
            _ => panic!("Expected text"),
        }
    }
}

impl From<String> for ContentType {
    fn from(value: String) -> Self {
        Self::Text(value)
    }
}

impl From<&str> for ContentType {
    fn from(value: &str) -> Self {
        Self::Text(value.to_string())
    }
}

impl<T: Into<ContentPart>> From<(T, T)> for ContentType {
    fn from((a, b): (T, T)) -> Self {
        Self::Parts(vec![a.into(), b.into()])
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ContentPart {
    /// A text content part.
    /// This can be paired with a `ContentPart::Image`.
    Text {
        r#type: String,
        /// The text.
        text: String,
    },
    /// An image content part. Requires an [`ImageUrl`] object.
    Image {
        r#type: String,
        /// The image.
        image_url: ImageUrl,
    },
}

impl ContentPart {
    /// Creates a text content part.
    pub fn text(text: String) -> Self {
        Self::Text {
            r#type: String::from("text"),
            text,
        }
    }

    /// Creates an image content part.
    ///
    /// This method is not recommended, if you're lazy like me.
    pub fn image(image_url: ImageUrl) -> Self {
        Self::Image { r#type: String::from("image_url"), image_url }
    }

    /// Creates an image content part from an image URL.
    pub fn image_url(url: String) -> Self {
        Self::Image { r#type: String::from("image_url"), image_url: ImageUrl::new_string(url) }
    }

    /// Creates an image content part from bytes of a PNG.
    pub fn image_png(image: &[u8]) -> Self {
        Self::Image { r#type: String::from("image_url"), image_url: ImageUrl::new_png(image) }
    }

    /// Creates an image content part from bytes of any content type.
    ///
    /// For instance, for a PNG, you could pass `"image/png"` to the `dt` parameter.
    pub fn image_any<K: AsRef<str>>(dt: K, image: &[u8]) -> Self {
        Self::Image { r#type: String::from("image_url"), image_url: ImageUrl::new_any(dt, image) }
    }

    /// Creates an image content part directly from a `String`.
    pub fn image_string(url_s: String) -> Self {
        Self::Image { r#type: String::from("image_url"), image_url: ImageUrl::new_string(url_s) }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageUrl {
    pub url: String,
}

impl ImageUrl {
    /// Image URL from a PNG.
    pub fn new_png(image: &[u8]) -> Self {
        Self {
            url: format!("data:image/png;base64,{}", general_purpose::STANDARD.encode(image)),
        }
    }

    /// Image URL from any data type.
    ///
    /// For instance, for a PNG, you could pass `"image/png"` to the `dt` parameter.
    pub fn new_any<K: AsRef<str>>(dt: K, image: &[u8]) -> Self {
        Self {
            url: format!("data:{};base64,{}", dt.as_ref(), general_purpose::STANDARD.encode(image)),
        }
    }

    /// ...or you could do it manually, of course.
    ///
    /// I'm not sure if external URLs are supported.
    pub fn new_string(url: String) -> Self {
        Self { url }
    }
}

/// Represents a chat role.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ChatRole {
    System,
    Assistant,
    User,
}

/// Represents a stop sequence.
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum StopSequence {
    Single(String),
    Multiple(Vec<String>),
}

impl From<String> for StopSequence {
    fn from(value: String) -> Self {
        Self::Single(value)
    }
}

impl From<&[String]> for StopSequence {
    fn from(value: &[String]) -> Self {
        Self::Multiple(value.to_vec())
    }
}

impl From<Vec<String>> for StopSequence {
    fn from(value: Vec<String>) -> Self {
        Self::Multiple(value)
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct ResponseFormat {
    /// The type of response format
    pub r#type: String,
}

#[derive(Debug, Clone, Deserialize, Default)]
pub struct ChatCompletionResponse {
    /// The list of completion choices
    pub choices: Option<Vec<ChatCompletionChoice>>,
}

impl ChatCompletionResponse {
    /// Get the last choice. This is the most commonly used one.
    pub fn get_choice(self) -> ChatCompletionChoice {
        let mut choices = self.get_choices();
        choices.pop().unwrap()
    }

    /// Get all the choices.
    pub fn get_choices(self) -> Vec<ChatCompletionChoice> {
        self.choices.unwrap()
    }
}

impl<K: AsRef<str>> Index<K> for ChatCompletionResponse {
    type Output = Vec<ChatCompletionChoice>;
    fn index(&self, index: K) -> &Self::Output {
        assert_eq!(index.as_ref(), "choices");
        if let Some(item) = &self.choices {
            item
        } else {
            panic!("Key error: choices")
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct ChatCompletionChoice {
    /// The index of this completion choice
    pub index: usize,
    /// The message produced by the model
    pub message: ChatMessage,
    /// The reason the model stopped generating tokens
    pub finish_reason: String,
}