fauna-api 1.0.816

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use chrono::{DateTime, Utc};
use futures_util::future::BoxFuture;
use futures_util::stream::BoxStream;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{Map, Value, json};

use super::socket;
use crate::authentification::{CredentialsOrApiKey, PartialApiKey, Profile};
use crate::drive::DriveAuthorization;
use crate::error::Error;
use crate::groups::Group;
use crate::http::{client, ok};
use crate::shared::schema::Schema;

pub use crate::ant::persona::Demographic;
use crate::ant::persona::PartialDemographic;

macro_rules! models {
    ($(#[$meta:meta])* pub enum $name:ident { $($variant:ident = $value:literal,)* }) => {
        $(#[$meta])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
        pub enum $name {
            $(#[serde(rename = $value)] $variant,)*
        }

        impl $name {
            pub(crate) fn as_str(self) -> &'static str {
                match self {
                    $($name::$variant => $value,)*
                }
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(self.as_str())
            }
        }
    };
}

models! {
    /// Text clients.
    pub enum Text {
        Auto = "auto",

        Gpt5_4 = "gpt-5.4",
        Gpt5_4Mini = "gpt-5.4-mini",
        Gpt5_4Nano = "gpt-5.4-nano",
        Gpt5_4Pro = "gpt-5.4-pro",
        Gpt5_5 = "gpt-5.5",
        Gpt5_5Pro = "gpt-5.5-pro",
        Gpt5_6Sol = "gpt-5.6-sol",
        Gpt5_6Terra = "gpt-5.6-terra",
        Gpt5_6Luna = "gpt-5.6-luna",

        ClaudeSonnet4_6 = "claude-sonnet-4-6",
        ClaudeSonnet5 = "claude-sonnet-5",
        ClaudeOpus4_6 = "claude-opus-4-6",
        ClaudeOpus4_7 = "claude-opus-4-7",
        ClaudeOpus4_8 = "claude-opus-4-8",
        ClaudeOpus5 = "claude-opus-5",
        ClaudeFable5 = "claude-fable-5",

        Gemini3_1Pro = "gemini-3.1-pro-preview",
        Gemini3Flash = "gemini-3-flash-preview",
        Gemini3_1FlashLite = "gemini-3.1-flash-lite",
        Gemini3_5Flash = "gemini-3.5-flash",

        Grok4_20Reasoning = "grok-4.20-reasoning-latest",
        Grok4_20NonReasoning = "grok-4.20-non-reasoning-latest",
        Grok4_3 = "grok-4.3-latest",
        Grok4_5 = "grok-4.5",
        Grok4_6 = "grok-4.6",
        GrokCode4_1Fast = "grok-code-fast-1",
    }
}

models! {
    pub enum Image {
        GrokImagineImage = "grok-imagine-image",
        GrokImagineImage2 = "grok-imagine-image-2.0",
        GrokImagineImageQuality = "grok-imagine-image-quality",
        GptImage1_5 = "gpt-image-1.5",
        GptImage1Mini = "gpt-image-1-mini",
    }
}

models! {
    pub enum Video {
        GrokImagineVideo = "grok-imagine-video",
        GrokImagineVideo1_5 = "grok-imagine-video-1.5",

        Sora2 = "sora-2",
        Sora2Pro = "sora-2-pro",
    }
}

models! {
    pub enum Speech {
        Gpt4oMiniTts = "gpt-4o-mini-tts",

        GrokTts = "grok-tts",

        ElevenV3 = "eleven_v3",
        ElevenFlashV2_5 = "eleven_flash_v2_5",
    }
}

models! {
    pub enum Transcription {
        GptTranscribe = "gpt-transcribe",

        GrokVoiceTranscribe2_0 = "grok-voice-transcribe-2.0",

        ScribeV2 = "scribe_v2",
    }
}

models! {
    /// Embedding clients.
    pub enum Embedding {
        TextEmbedding3Small = "text-embedding-3-small",
        TextEmbedding3Large = "text-embedding-3-large",

        GeminiEmbedding001 = "gemini-embedding-001",
        GeminiEmbedding2Preview = "gemini-embedding-2-preview",

        Voyage3 = "voyage-3",
        Voyage3Large = "voyage-3-large",
        Voyage3Lite = "voyage-3-lite",
        VoyageCode3 = "voyage-code-3",
        VoyageFinance2 = "voyage-finance-2",
        VoyageLaw2 = "voyage-law-2",
    }
}

models! {
    pub enum Voice {
        GptRealtime = "gpt-realtime-2",
        GrokVoice = "grok-voice-think-fast-2.0",
        ElevenV3 = "eleven_v3_conversational",
    }
}

models! {
    pub enum Decision {
        Jev1_13 = "jev-1.13.0",
        Jev1_14 = "jev-1.14.0",

        Gpt6Luna = "gpt-6-luna",
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Role {
    User,
    Model,
    System,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct TextPart {
    #[serde(default)]
    pub text: String,
}

/// A body written in HTML, such as an email's. Chat UIs draw it as it is; models read its text.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct HtmlPart {
    #[serde(default)]
    pub html: String,
}

#[derive(Debug, Clone)]
pub struct File {
    pub file: crate::drive::File,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum InvocationStatus {
    /// A NON_BLOCKING call still working; the chat gets the same invocation again, finished.
    Running,
    Success,
    Error,
}

/// A tool call and its result, one part: send a tool's result back on the invocation that
/// called it. A `Running` call's `result` is its started note.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Invocation {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub args: Option<Map<String, Value>>,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<InvocationStatus>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result: Option<String>,
}

/// A reaction to the message at transcript `position`. It travels as its own
/// USER message; chat UIs fold it onto that message instead of drawing a bubble.
/// `on: false` takes the reaction back; the latest one per person, message and
/// emoji wins.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Reaction {
    pub emoji: String,
    pub position: u32,
    pub on: bool,
}

/// One part of a message. On the wire each carries its `type`; a FILE part goes
/// up as a reference (a Drive path or an access code), never its bytes.
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum Part {
    Text(TextPart),
    Html(HtmlPart),
    File(File),
    Invocation(Invocation),
    Reaction(Reaction),
}

pub(crate) fn file_ref(file: &crate::drive::File) -> Value {
    let mut wire = Map::new();
    wire.insert("type".to_string(), Value::from("FILE"));
    wire.insert("name".to_string(), Value::from(file.name()));
    wire.insert(
        "contentType".to_string(),
        Value::from(file.content_type.as_str()),
    );
    match &file.authorization {
        DriveAuthorization::AccessCode { access_code, .. } => {
            wire.insert("accessCode".to_string(), Value::from(access_code.as_str()));
        }
        DriveAuthorization::Path { path, group, .. }
        | DriveAuthorization::Repository { path, group, .. } => {
            wire.insert("path".to_string(), Value::from(path.as_str()));
            if let Some(group) = group {
                wire.insert("group".to_string(), Value::from(group.as_str()));
            }
        }
    }
    Value::Object(wire)
}

fn tagged(kind: &str, value: impl Serialize) -> Value {
    let mut wire = Map::new();
    wire.insert("type".to_string(), Value::from(kind));
    if let Ok(Value::Object(fields)) = serde_json::to_value(value) {
        wire.extend(fields);
    }
    Value::Object(wire)
}

impl Part {
    /// The part as it goes over the wire, FILE parts as references.
    pub(crate) fn wire(&self) -> Value {
        match self {
            Part::Text(part) => tagged("TEXT", part),
            Part::Html(part) => tagged("HTML", part),
            Part::File(part) => file_ref(&part.file),
            Part::Invocation(part) => tagged("INVOCATION", part),
            Part::Reaction(part) => tagged("REACTION", part),
        }
    }

    /// Every part but FILE, which needs the caller's authorization to open.
    pub(crate) fn from_json(json: &Value) -> Option<Part> {
        match json["type"].as_str()? {
            "TEXT" => serde_json::from_value(json.clone()).ok().map(Part::Text),
            "HTML" => serde_json::from_value(json.clone()).ok().map(Part::Html),
            "INVOCATION" => serde_json::from_value(json.clone())
                .ok()
                .map(Part::Invocation),
            "REACTION" => serde_json::from_value(json.clone())
                .ok()
                .map(Part::Reaction),
            _ => None,
        }
    }
}

impl Serialize for Part {
    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        self.wire().serialize(serializer)
    }
}

/// BLOCKING (the default): the reply waits for the result. NON_BLOCKING, in chat rooms: the
/// reply goes on without it. Send the result whenever it's ready (`ChatRoom::send_tool_result`,
/// from any of your devices, even after the reply ended); it lands in the chat as the same
/// invocation, finished, and starts a new reply. Stateless generation refuses it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FunctionBehavior {
    Blocking,
    NonBlocking,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Function {
    pub name: String,
    pub parameters: Schema,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub example: Option<Value>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub behavior: Option<FunctionBehavior>,
}

/// What a tool runs when the model calls it, given the call's arguments.
pub type ToolEvaluate =
    Arc<dyn Fn(Value) -> BoxFuture<'static, crate::Result<String>> + Send + Sync>;

/// The line a tool adds to a prompt, given the call's arguments.
pub type ToolInstruction = Arc<dyn Fn(&Value) -> String + Send + Sync>;

#[derive(Clone)]
pub struct Tool {
    pub function: Function,

    pub evaluate: ToolEvaluate,

    pub instruction: Option<ToolInstruction>,
}

impl fmt::Debug for Tool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Tool")
            .field("function", &self.function)
            .finish_non_exhaustive()
    }
}

/// `Tool[] | Tool` in the TypeScript SDK: a single tool forces it, a list lets
/// the model choose.
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum ToolsOrTool {
    Tools(Vec<Tool>),
    Tool(Tool),
}

/// Who wrote a message: a person, an agent posting with an API key (only its `name`, never
/// its id), an app's own agent (`'MODEL'`, such as an inbox agent), or an outside address
/// such as a phone number or an email. Parrot's own model replies have none; their `model`
/// says which model wrote them.
#[derive(Debug, Clone, PartialEq)]
pub enum Author {
    Profile(Profile),
    ApiKey(PartialApiKey),
    Model,
    Address(String),
}

impl Author {
    pub fn from_json(json: &Value) -> Option<Author> {
        match json {
            Value::String(text) if text == "MODEL" => Some(Author::Model),
            Value::String(text) if !text.is_empty() => Some(Author::Address(text.clone())),
            Value::Object(_) => Profile::from_json(json).map(Author::Profile).or_else(|| {
                json["name"].as_str().map(|name| {
                    Author::ApiKey(PartialApiKey {
                        name: Some(name.to_string()),
                        ..Default::default()
                    })
                })
            }),
            _ => None,
        }
    }
}

impl Serialize for Author {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        match self {
            Author::Profile(profile) => profile.serialize(serializer),
            Author::ApiKey(key) => json!({ "name": key.name }).serialize(serializer),
            Author::Model => serializer.serialize_str("MODEL"),
            Author::Address(address) => serializer.serialize_str(address),
        }
    }
}

impl<'de> Deserialize<'de> for Author {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        let json = Value::deserialize(deserializer)?;
        Author::from_json(&json).ok_or_else(|| serde::de::Error::custom("not an author"))
    }
}

#[derive(Debug, Clone)]
pub struct Content {
    pub parts: Vec<Part>,
    pub role: Role,
    pub created_at: DateTime<Utc>,
    pub author: Option<Author>,
    /// The model that wrote a MODEL turn.
    pub model: Option<Text>,
}

impl Content {
    /// A message off the wire. `file` turns each FILE part into a file; without it FILE
    /// parts are left out, since a file needs a way to be read.
    pub fn from_json(json: &Value, file: Option<&dyn Fn(&Value) -> Part>) -> Content {
        Content {
            parts: json["parts"]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(|part| match (part["type"].as_str(), file) {
                    (Some("FILE"), Some(file)) => Some(file(part)),
                    (Some("FILE"), None) => None,
                    _ => Part::from_json(part),
                })
                .collect(),
            role: serde_json::from_value(json["role"].clone()).unwrap_or(Role::User),
            created_at: crate::tickets::parse_date(&json["createdAt"]).unwrap_or_default(),
            author: Author::from_json(&json["author"]),
            model: serde_json::from_value(json["model"].clone()).ok(),
        }
    }
}

/// `{ promptTokens, completionTokens }` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Usage {
    #[serde(default)]
    pub prompt_tokens: u64,
    #[serde(default)]
    pub completion_tokens: u64,
}

#[derive(Debug, Clone)]
pub struct TextResponse {
    pub content: Content,
    pub usage: Usage,
}

/// `{ promptTokens }` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EmbeddingUsage {
    #[serde(default)]
    pub prompt_tokens: u64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EmbeddingResponse {
    pub embedding: Vec<f64>,
    pub usage: EmbeddingUsage,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum StreamEvent {
    Text {
        #[serde(default)]
        delta: String,
    },
    ToolCall {
        id: String,
        name: String,
        #[serde(default)]
        args: Map<String, Value>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        server: Option<bool>,
    },
    Done {
        #[serde(default)]
        usage: Usage,
    },
    Error {
        message: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        code: Option<String>,
    },
}

fn pcm() -> String {
    "audio/pcm".to_string()
}

fn audio_out<S: Serializer>(delta: &[u8], serializer: S) -> std::result::Result<S::Ok, S::Error> {
    serializer.serialize_str(&STANDARD.encode(delta))
}

/// Audio arrives base64 encoded, or as a list of byte values.
fn audio_in<'de, D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Vec<u8>, D::Error> {
    Ok(socket::audio_delta(&Value::deserialize(deserializer)?))
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum VoiceEvent {
    Audio {
        #[serde(serialize_with = "audio_out", deserialize_with = "audio_in")]
        delta: Vec<u8>,
        #[serde(rename = "contentType", default = "pcm")]
        content_type: String,
    },
    InputTranscript {
        #[serde(default)]
        delta: String,
    },
    OutputTranscript {
        #[serde(default)]
        delta: String,
    },
    ToolCall {
        id: String,
        name: String,
        #[serde(default)]
        args: Map<String, Value>,
    },
    SpeechStarted,
    SpeechStopped,
    Done {
        #[serde(default)]
        usage: Usage,
    },
    Error {
        message: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        code: Option<String>,
    },
}

/// The `options` argument of `generate_text` and `generate_text_sync`. Dropping
/// the returned stream closes the socket, which stops the reply.
#[derive(Debug, Clone, Default)]
pub struct TextOptions {
    pub content: Option<Vec<Content>>,
    pub tools: Option<ToolsOrTool>,
    pub max_tools: Option<u32>,
    pub reasoning: Option<String>,
    pub group: Option<Group>,
}

/// Streaming text generation. A singular Tool forces it; an array lets the model choose.
pub async fn generate_text(
    authorization: &CredentialsOrApiKey,
    model: Text,
    options: TextOptions,
) -> crate::Result<BoxStream<'static, StreamEvent>> {
    socket::stream_text(
        authorization,
        "/generative/text",
        model.as_str(),
        socket::TextOptions {
            content: options.content,
            tools: options.tools,
            max_tools: options.max_tools,
            memories: None,
            reasoning: options.reasoning,
            group: options.group,
        },
    )
    .await
}

/// Synchronous wrapper: buffers the stream and returns the full TextResponse.
pub async fn generate_text_sync(
    authorization: &CredentialsOrApiKey,
    model: Text,
    options: TextOptions,
) -> crate::Result<TextResponse> {
    socket::collect_text(generate_text(authorization, model, options).await?).await
}

/// Embedding (stays HTTP). With `group`, the group pays.
pub async fn generate_embedding(
    authorization: &CredentialsOrApiKey,
    model: Embedding,
    content: &str,
    group: Option<&Group>,
) -> crate::Result<EmbeddingResponse> {
    let mut request = client()
        .post(format!("{}/generative/embed", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let response = request
        .json(&json!({ "model": model, "content": content }))
        .send()
        .await?;
    if !response.status().is_success() {
        return Err(Error::Message(format!(
            "Failed to generate embedding: {}",
            response.status().canonical_reason().unwrap_or_default()
        )));
    }
    Ok(response.json().await?)
}

/// Decision (stays HTTP). Each question lists its options; every option comes back
/// with its probability. A question the model declines is left out. With `group`,
/// the group pays.
pub async fn generate_decision(
    authorization: &CredentialsOrApiKey,
    model: Decision,
    content: &[Content],
    questions: &HashMap<String, Vec<String>>,
    group: Option<&Group>,
) -> crate::Result<HashMap<String, HashMap<String, f64>>> {
    let messages = socket::prepare_messages(authorization, content).await?;
    let mut request = client()
        .post(format!("{}/generative/decision", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let response = request
        .json(&json!({ "model": model, "messages": messages, "questions": questions }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

fn media_extra(fields: Vec<(&str, Option<Value>)>) -> Map<String, Value> {
    fields
        .into_iter()
        .filter_map(|(key, value)| value.map(|value| (key.to_string(), value)))
        .collect()
}

/// The `options` argument of `generate_image`.
#[derive(Debug, Clone, Default)]
pub struct ImageOptions {
    pub content: Option<Vec<Content>>,
    pub size: Option<[u32; 2]>,
    pub group: Option<Group>,
}

/// Image generation.
pub async fn generate_image(
    authorization: &CredentialsOrApiKey,
    model: Image,
    options: ImageOptions,
) -> crate::Result<TextResponse> {
    socket::generate_media(
        authorization,
        "/generative/image",
        model.as_str(),
        options.content,
        options.group,
        media_extra(vec![("size", options.size.map(|size| json!(size)))]),
        "image/png",
    )
    .await
}

/// The `options` argument of `generate_video`.
#[derive(Debug, Clone, Default)]
pub struct VideoOptions {
    pub content: Option<Vec<Content>>,
    pub duration: Option<f64>,
    pub size: Option<[u32; 2]>,
    pub group: Option<Group>,
}

/// Video generation.
pub async fn generate_video(
    authorization: &CredentialsOrApiKey,
    model: Video,
    options: VideoOptions,
) -> crate::Result<TextResponse> {
    socket::generate_media(
        authorization,
        "/generative/video",
        model.as_str(),
        options.content,
        options.group,
        media_extra(vec![
            ("duration", options.duration.map(Value::from)),
            ("size", options.size.map(|size| json!(size))),
        ]),
        "video/mp4",
    )
    .await
}

/// The `options` argument of `generate_speech`.
#[derive(Debug, Clone, Default)]
pub struct SpeechOptions {
    pub content: Option<Vec<Content>>,
    pub voice: Option<Demographic>,
    pub group: Option<Group>,
}

/// Speech generation.
pub async fn generate_speech(
    authorization: &CredentialsOrApiKey,
    model: Speech,
    options: SpeechOptions,
) -> crate::Result<TextResponse> {
    let voice = options.voice.map(serde_json::to_value).transpose()?;
    socket::generate_media(
        authorization,
        "/generative/speech",
        model.as_str(),
        options.content,
        options.group,
        media_extra(vec![("voice", voice)]),
        "audio/mpeg",
    )
    .await
}

/// The `options` argument of `generate_transcription`.
#[derive(Debug, Clone, Default)]
pub struct TranscriptionOptions {
    pub content: Option<Vec<Content>>,
    pub group: Option<Group>,
}

/// Transcription generation.
pub async fn generate_transcription(
    authorization: &CredentialsOrApiKey,
    model: Transcription,
    options: TranscriptionOptions,
) -> crate::Result<TextResponse> {
    socket::generate_media(
        authorization,
        "/generative/transcription",
        model.as_str(),
        options.content,
        options.group,
        Map::new(),
        "application/octet-stream",
    )
    .await
}

/// The `options` argument of `generate_voice` and `generate_voice_sync`. `audio`
/// is PCM16 at 16 kHz. Dropping the returned stream closes the socket.
#[derive(Default)]
pub struct VoiceOptions {
    pub content: Option<Vec<Content>>,
    pub audio: Option<BoxStream<'static, Vec<u8>>>,
    pub notes: Option<BoxStream<'static, String>>,
    pub tools: Option<ToolsOrTool>,
    pub max_tools: Option<u32>,
    pub voice: Option<PartialDemographic>,
    pub group: Option<Group>,
}

/// Streaming voice generation. Each of `notes` tells the model something to act on now.
pub async fn generate_voice(
    authorization: &CredentialsOrApiKey,
    model: Voice,
    options: VoiceOptions,
) -> crate::Result<BoxStream<'static, VoiceEvent>> {
    socket::stream_voice(
        authorization,
        "/generative/voice",
        model.as_str(),
        socket::VoiceOptions {
            content: options.content,
            audio: options.audio,
            notes: options.notes,
            tools: options.tools,
            max_tools: options.max_tools,
            voice: options.voice,
            memories: None,
            group: options.group,
        },
    )
    .await
}

pub async fn generate_voice_sync(
    authorization: &CredentialsOrApiKey,
    model: Voice,
    options: VoiceOptions,
) -> crate::Result<TextResponse> {
    socket::collect_voice(
        authorization,
        generate_voice(authorization, model, options).await?,
    )
    .await
}