Skip to main content

fauna_api/parrot/
generative.rs

1use std::collections::HashMap;
2use std::fmt;
3use std::sync::Arc;
4
5use base64::Engine;
6use base64::engine::general_purpose::STANDARD;
7use chrono::{DateTime, Utc};
8use futures_util::future::BoxFuture;
9use futures_util::stream::BoxStream;
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11use serde_json::{Map, Value, json};
12
13use super::socket;
14use crate::authentification::{CredentialsOrApiKey, PartialApiKey, Profile};
15use crate::drive::DriveAuthorization;
16use crate::error::Error;
17use crate::groups::Group;
18use crate::http::{client, ok};
19use crate::shared::schema::{ObjectSchema, Schema};
20
21pub use crate::ant::persona::Demographic;
22use crate::ant::persona::PartialDemographic;
23
24macro_rules! models {
25    ($(#[$meta:meta])* pub enum $name:ident { $($variant:ident = $value:literal,)* }) => {
26        $(#[$meta])*
27        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
28        pub enum $name {
29            $(#[serde(rename = $value)] $variant,)*
30        }
31
32        impl $name {
33            pub(crate) fn as_str(self) -> &'static str {
34                match self {
35                    $($name::$variant => $value,)*
36                }
37            }
38        }
39
40        impl fmt::Display for $name {
41            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42                f.write_str(self.as_str())
43            }
44        }
45    };
46}
47
48models! {
49    /// Text clients.
50    pub enum Text {
51        Auto = "auto",
52
53        Gpt5_4 = "gpt-5.4",
54        Gpt5_4Mini = "gpt-5.4-mini",
55        Gpt5_4Nano = "gpt-5.4-nano",
56        Gpt5_4Pro = "gpt-5.4-pro",
57        Gpt5_5 = "gpt-5.5",
58        Gpt5_5Pro = "gpt-5.5-pro",
59        Gpt5_6Sol = "gpt-5.6-sol",
60        Gpt5_6Terra = "gpt-5.6-terra",
61        Gpt5_6Luna = "gpt-5.6-luna",
62        Gpt6Astra = "gpt-6-astra",
63        Gpt6Sol = "gpt-6-sol",
64        Gpt6Luna = "gpt-6-luna",
65        Gpt6_1Sol = "gpt-6.1-sol",
66        Gpt6_1Terra = "gpt-6.1-terra",
67        Gpt6_2Astra = "gpt-6.2-astra",
68        Gpt6_2Sol = "gpt-6.2-sol",
69
70        ClaudeSonnet4_6 = "claude-sonnet-4-6",
71        ClaudeSonnet5 = "claude-sonnet-5",
72        ClaudeOpus4_6 = "claude-opus-4-6",
73        ClaudeOpus4_7 = "claude-opus-4-7",
74        ClaudeOpus4_8 = "claude-opus-4-8",
75        ClaudeOpus5 = "claude-opus-5",
76        ClaudeFable5 = "claude-fable-5",
77        ClaudeFable5_1 = "claude-fable-5-1",
78        ClaudeFable5_2 = "claude-fable-5-2",
79        ClaudeOpus5_5 = "claude-opus-5-5",
80        ClaudeSonnet5_5 = "claude-sonnet-5-5",
81        ClaudeHaiku5_5 = "claude-haiku-5-5",
82
83        Gemini3_1Pro = "gemini-3.1-pro-preview",
84        Gemini4Carbon = "gemini-4-carbon",
85        Gemini4Argon = "gemini-4-argon",
86        Gemini4Neon = "gemini-4-neon",
87        Gemini4Hydrogen = "gemini-4-hydrogen",
88        Gemini3_8Flash = "gemini-3.8-flash",
89        Gemini3_6Flash = "gemini-3.6-flash",
90        Gemini3Flash = "gemini-3-flash-preview",
91        Gemini3_5FlashLite = "gemini-3.5-flash-lite",
92        Gemini3_1FlashLite = "gemini-3.1-flash-lite",
93
94        Grok4_20Reasoning = "grok-4.20-0309-reasoning",
95        Grok4_20NonReasoning = "grok-4.20-0309-non-reasoning",
96        Grok4_3 = "grok-4.3",
97        Grok4_5 = "grok-4.5",
98        Grok4_6 = "grok-4.6",
99        Grok4_7 = "grok-4.7",
100    }
101}
102
103models! {
104    pub enum Image {
105        GrokImagineImage = "grok-imagine-image",
106        GrokImagineImage2 = "grok-imagine-image-2.0",
107        GptImage1_5 = "gpt-image-1.5",
108        GptImage1Mini = "gpt-image-1-mini",
109        GptImage2 = "gpt-image-2",
110        GptImage2_5Flare = "gpt-image-2.5-flare",
111        GptImage2_5Sunburst = "gpt-image-2.5-sunburst",
112        GptImage2_6Flare = "gpt-image-2.6-flare",
113        GptImage2_6Sunburst = "gpt-image-2.6-sunburst",
114    }
115}
116
117models! {
118    pub enum Video {
119        GrokImagineVideo = "grok-imagine-video",
120        GrokImagineVideo1_5 = "grok-imagine-video-1.5",
121        GrokImagineVideo1_5Lite = "grok-imagine-video-1.5-lite",
122
123        Sora2 = "sora-2",
124        Sora2Pro = "sora-2-pro",
125    }
126}
127
128models! {
129    pub enum Speech {
130        GrokTts = "grok-tts",
131
132        ElevenV4 = "eleven_v4",
133        ElevenV4Turbo = "eleven_v4_turbo",
134        ElevenV3 = "eleven_v3",
135        ElevenFlashV2_5 = "eleven_flash_v2_5",
136    }
137}
138
139models! {
140    pub enum Transcription {
141        GptTranscribe = "gpt-transcribe",
142
143        GrokVoiceTranscribe2_0 = "grok-voice-transcribe-2.0",
144
145        ScribeV3 = "scribe_v3",
146        ScribeV2 = "scribe_v2",
147    }
148}
149
150models! {
151    /// Embedding clients.
152    pub enum Embedding {
153        TextEmbedding3Small = "text-embedding-3-small",
154        TextEmbedding3Large = "text-embedding-3-large",
155
156        GeminiEmbedding001 = "gemini-embedding-001",
157        GeminiEmbedding2 = "gemini-embedding-2",
158
159        Voyage4Large = "voyage-4-large",
160        Voyage4 = "voyage-4",
161        Voyage4Lite = "voyage-4-lite",
162        VoyageCode4 = "voyage-code-4",
163        VoyageFinance2 = "voyage-finance-2",
164        VoyageLaw2 = "voyage-law-2",
165    }
166}
167
168models! {
169    pub enum Voice {
170        GptRealtime = "gpt-realtime-2",
171        GptRealtime2_1 = "gpt-realtime-2.1",
172        GptRealtime2_1Mini = "gpt-realtime-2.1-mini",
173        GrokVoice = "grok-voice-3.0",
174        ElevenV3 = "eleven_v3_conversational",
175    }
176}
177
178models! {
179    pub enum Decision {
180        Jev1_13 = "jev-1.13.0",
181        Jev1_14 = "jev-1.14.0",
182
183        Gpt6Luna = "gpt-6-luna",
184    }
185}
186
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
188#[serde(rename_all = "UPPERCASE")]
189pub enum Role {
190    User,
191    Model,
192    System,
193}
194
195#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
196pub struct TextPart {
197    #[serde(default)]
198    pub text: String,
199}
200
201/// A body written in HTML, such as an email's. Chat UIs draw it as it is; models read its text.
202#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
203pub struct HtmlPart {
204    #[serde(default)]
205    pub html: String,
206}
207
208#[derive(Debug, Clone)]
209pub struct File {
210    pub file: crate::drive::File,
211}
212
213#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
214#[serde(rename_all = "lowercase")]
215pub enum InvocationStatus {
216    /// A NON_BLOCKING call still working; the chat gets the same invocation again, finished.
217    Running,
218    Success,
219    Error,
220}
221
222/// The machine room a tool worked in, to watch it.
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
224pub struct ToolSession {
225    pub reference: String,
226}
227
228/// A tool call and its result, one part: send a tool's result back on the invocation that
229/// called it. `Success` carries the `result` object, `Error` why it failed. A `Running` call's
230/// `result` is its started note. A `run_code` call lists the calls its program made in `calls`.
231/// `session` is the machine room a tool worked in, to watch it.
232#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
233pub struct Invocation {
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub id: Option<String>,
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub args: Option<Map<String, Value>>,
238    pub name: String,
239    #[serde(default, skip_serializing_if = "Option::is_none")]
240    pub status: Option<InvocationStatus>,
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub result: Option<Map<String, Value>>,
243    #[serde(default, skip_serializing_if = "Option::is_none")]
244    pub error: Option<String>,
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub calls: Option<Vec<Invocation>>,
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub session: Option<ToolSession>,
249}
250
251/// A reaction to the message at transcript `position`. It travels as its own
252/// USER message; chat UIs fold it onto that message instead of drawing a bubble.
253/// `on: false` takes the reaction back; the latest one per person, message and
254/// emoji wins.
255#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
256pub struct Reaction {
257    pub emoji: String,
258    pub position: u32,
259    pub on: bool,
260}
261
262/// One part of a message. On the wire each carries its `type`; a FILE part goes
263/// up as a reference (a Drive path or an access code), never its bytes.
264#[derive(Debug, Clone)]
265#[allow(clippy::large_enum_variant)]
266pub enum Part {
267    Text(TextPart),
268    Html(HtmlPart),
269    File(File),
270    Invocation(Invocation),
271    Reaction(Reaction),
272}
273
274pub(crate) fn file_ref(file: &crate::drive::File) -> Value {
275    let mut wire = Map::new();
276    wire.insert("type".to_string(), Value::from("FILE"));
277    wire.insert("name".to_string(), Value::from(file.name()));
278    wire.insert(
279        "contentType".to_string(),
280        Value::from(file.content_type.as_str()),
281    );
282    match &file.authorization {
283        DriveAuthorization::AccessCode { access_code, .. } => {
284            wire.insert("accessCode".to_string(), Value::from(access_code.as_str()));
285        }
286        DriveAuthorization::Path { path, group, .. }
287        | DriveAuthorization::Repository { path, group, .. } => {
288            wire.insert("path".to_string(), Value::from(path.as_str()));
289            if let Some(group) = group {
290                wire.insert("group".to_string(), Value::from(group.as_str()));
291            }
292        }
293    }
294    Value::Object(wire)
295}
296
297fn tagged(kind: &str, value: impl Serialize) -> Value {
298    let mut wire = Map::new();
299    wire.insert("type".to_string(), Value::from(kind));
300    if let Ok(Value::Object(fields)) = serde_json::to_value(value) {
301        wire.extend(fields);
302    }
303    Value::Object(wire)
304}
305
306impl Part {
307    /// The part as it goes over the wire, FILE parts as references.
308    pub(crate) fn wire(&self) -> Value {
309        match self {
310            Part::Text(part) => tagged("TEXT", part),
311            Part::Html(part) => tagged("HTML", part),
312            Part::File(part) => file_ref(&part.file),
313            Part::Invocation(part) => tagged("INVOCATION", part),
314            Part::Reaction(part) => tagged("REACTION", part),
315        }
316    }
317
318    /// Every part but FILE, which needs the caller's authorization to open.
319    pub(crate) fn from_json(json: &Value) -> Option<Part> {
320        match json["type"].as_str()? {
321            "TEXT" => serde_json::from_value(json.clone()).ok().map(Part::Text),
322            "HTML" => serde_json::from_value(json.clone()).ok().map(Part::Html),
323            "INVOCATION" => serde_json::from_value(json.clone())
324                .ok()
325                .map(Part::Invocation),
326            "REACTION" => serde_json::from_value(json.clone())
327                .ok()
328                .map(Part::Reaction),
329            _ => None,
330        }
331    }
332}
333
334impl Serialize for Part {
335    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
336        self.wire().serialize(serializer)
337    }
338}
339
340/// BLOCKING (the default): the reply waits for the result. NON_BLOCKING, in chat rooms: the
341/// reply goes on without it. Send the result whenever it's ready (`ChatRoom::send_tool_result`,
342/// from any of your devices, even after the reply ended); it lands in the chat as the same
343/// invocation, finished, and starts a new reply. Stateless generation refuses it.
344#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
345#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
346pub enum FunctionBehavior {
347    Blocking,
348    NonBlocking,
349}
350
351#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
352pub struct Function {
353    /// A JavaScript identifier: programs call it as `tools.{name}(args)`.
354    pub name: String,
355    pub parameters: Schema,
356    /// What it resolves with: always an object.
357    pub returns: ObjectSchema,
358    #[serde(default, skip_serializing_if = "Option::is_none")]
359    pub description: Option<String>,
360
361    #[serde(default, skip_serializing_if = "Option::is_none")]
362    pub default: Option<Value>,
363    #[serde(default, skip_serializing_if = "Option::is_none")]
364    pub example: Option<Value>,
365
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub behavior: Option<FunctionBehavior>,
368}
369
370/// What shows on a running call's chip, as it changes.
371pub type ToolProgress = Arc<dyn Fn(Value) + Send + Sync>;
372
373/// What a tool runs when the model calls it, given the call's arguments and where it reports
374/// progress. It resolves with an object matching `function.returns`, or fails. Stopping a reply
375/// drops the future.
376pub type ToolEvaluate = Arc<
377    dyn Fn(Value, ToolProgress) -> BoxFuture<'static, crate::Result<Map<String, Value>>>
378        + Send
379        + Sync,
380>;
381
382/// A function the model may call, and what runs it.
383#[derive(Clone)]
384pub struct Tool {
385    pub function: Function,
386
387    pub evaluate: ToolEvaluate,
388}
389
390impl fmt::Debug for Tool {
391    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392        f.debug_struct("Tool")
393            .field("function", &self.function)
394            .finish_non_exhaustive()
395    }
396}
397
398/// A tool from its declaration (`parameters` and `returns` valid schemas) and what runs it.
399pub(crate) fn tool(
400    name: &str,
401    description: &str,
402    parameters: Value,
403    returns: Value,
404    evaluate: impl Fn(Value, ToolProgress) -> BoxFuture<'static, crate::Result<Map<String, Value>>>
405    + Send
406    + Sync
407    + 'static,
408) -> Tool {
409    Tool {
410        function: Function {
411            name: name.to_string(),
412            parameters: serde_json::from_value::<Schema>(parameters)
413                .expect("tool schemas are valid"),
414            returns: serde_json::from_value::<ObjectSchema>(returns)
415                .expect("tool returns are valid"),
416            description: Some(description.to_string()),
417            default: None,
418            example: None,
419            behavior: None,
420        },
421        evaluate: Arc::new(evaluate),
422    }
423}
424
425/// How a tool call ended: the tool's result object, or why it failed.
426#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
427#[serde(untagged)]
428pub enum ToolAnswer {
429    Result { result: Map<String, Value> },
430    Error { error: String },
431}
432
433/// The tool a model with tools writes its programs to: a call carries its `{ code }`, the calls
434/// the program made (`calls`) and what it logged.
435pub const RUN_CODE: &str = "run_code";
436
437/// `Tool[] | Tool` in the TypeScript SDK: a single tool forces it, a list lets
438/// the model choose.
439#[derive(Debug, Clone)]
440#[allow(clippy::large_enum_variant)]
441pub enum ToolsOrTool {
442    Tools(Vec<Tool>),
443    Tool(Tool),
444}
445
446/// Who wrote a message: a person, an agent posting with an API key (only its `name`, never
447/// its id), an app's own agent (`'MODEL'`, such as an inbox agent), or an outside address
448/// such as a phone number or an email. Parrot's own model replies have none; their `model`
449/// says which model wrote them.
450#[derive(Debug, Clone, PartialEq)]
451pub enum Author {
452    Profile(Profile),
453    ApiKey(PartialApiKey),
454    Model,
455    Address(String),
456}
457
458impl Author {
459    pub fn from_json(json: &Value) -> Option<Author> {
460        match json {
461            Value::String(text) if text == "MODEL" => Some(Author::Model),
462            Value::String(text) if !text.is_empty() => Some(Author::Address(text.clone())),
463            Value::Object(_) => Profile::from_json(json).map(Author::Profile).or_else(|| {
464                json["name"].as_str().map(|name| {
465                    Author::ApiKey(PartialApiKey {
466                        name: Some(name.to_string()),
467                        ..Default::default()
468                    })
469                })
470            }),
471            _ => None,
472        }
473    }
474}
475
476impl Serialize for Author {
477    fn serialize<S: serde::Serializer>(
478        &self,
479        serializer: S,
480    ) -> std::result::Result<S::Ok, S::Error> {
481        match self {
482            Author::Profile(profile) => profile.serialize(serializer),
483            Author::ApiKey(key) => json!({ "name": key.name }).serialize(serializer),
484            Author::Model => serializer.serialize_str("MODEL"),
485            Author::Address(address) => serializer.serialize_str(address),
486        }
487    }
488}
489
490impl<'de> Deserialize<'de> for Author {
491    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
492        let json = Value::deserialize(deserializer)?;
493        Author::from_json(&json).ok_or_else(|| serde::de::Error::custom("not an author"))
494    }
495}
496
497#[derive(Debug, Clone)]
498pub struct Content {
499    pub parts: Vec<Part>,
500    pub role: Role,
501    pub created_at: DateTime<Utc>,
502    pub author: Option<Author>,
503    /// The model that wrote a MODEL turn.
504    pub model: Option<Text>,
505}
506
507impl Content {
508    /// A message off the wire. `file` turns each FILE part into a file; without it FILE
509    /// parts are left out, since a file needs a way to be read.
510    pub fn from_json(json: &Value, file: Option<&dyn Fn(&Value) -> Part>) -> Content {
511        Content {
512            parts: json["parts"]
513                .as_array()
514                .into_iter()
515                .flatten()
516                .filter_map(|part| match (part["type"].as_str(), file) {
517                    (Some("FILE"), Some(file)) => Some(file(part)),
518                    (Some("FILE"), None) => None,
519                    _ => Part::from_json(part),
520                })
521                .collect(),
522            role: serde_json::from_value(json["role"].clone()).unwrap_or(Role::User),
523            created_at: crate::tickets::parse_date(&json["createdAt"]).unwrap_or_default(),
524            author: Author::from_json(&json["author"]),
525            model: serde_json::from_value(json["model"].clone()).ok(),
526        }
527    }
528}
529
530/// `{ promptTokens, completionTokens }` in the TypeScript SDK.
531#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
532#[serde(rename_all = "camelCase")]
533pub struct Usage {
534    #[serde(default)]
535    pub prompt_tokens: u64,
536    #[serde(default)]
537    pub completion_tokens: u64,
538}
539
540#[derive(Debug, Clone)]
541pub struct TextResponse {
542    pub content: Content,
543    pub usage: Usage,
544}
545
546/// `{ promptTokens }` in the TypeScript SDK.
547#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
548#[serde(rename_all = "camelCase")]
549pub struct EmbeddingUsage {
550    #[serde(default)]
551    pub prompt_tokens: u64,
552}
553
554#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
555pub struct EmbeddingResponse {
556    pub embedding: Vec<f64>,
557    pub usage: EmbeddingUsage,
558}
559
560#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
561#[serde(tag = "event", rename_all = "snake_case")]
562pub enum StreamEvent {
563    Text {
564        #[serde(default)]
565        delta: String,
566    },
567    ToolCall {
568        id: String,
569        name: String,
570        #[serde(default)]
571        args: Map<String, Value>,
572        #[serde(default, skip_serializing_if = "Option::is_none")]
573        server: Option<bool>,
574        /// The `run_code` call whose program made it.
575        #[serde(default, skip_serializing_if = "Option::is_none")]
576        parent: Option<String>,
577    },
578    Done {
579        #[serde(default)]
580        usage: Usage,
581    },
582    Error {
583        message: String,
584        #[serde(default, skip_serializing_if = "Option::is_none")]
585        code: Option<String>,
586    },
587}
588
589fn pcm() -> String {
590    "audio/pcm".to_string()
591}
592
593fn audio_out<S: Serializer>(delta: &[u8], serializer: S) -> std::result::Result<S::Ok, S::Error> {
594    serializer.serialize_str(&STANDARD.encode(delta))
595}
596
597/// Audio arrives base64 encoded, or as a list of byte values.
598fn audio_in<'de, D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Vec<u8>, D::Error> {
599    Ok(socket::audio_delta(&Value::deserialize(deserializer)?))
600}
601
602#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
603#[serde(tag = "event", rename_all = "snake_case")]
604pub enum VoiceEvent {
605    Audio {
606        #[serde(serialize_with = "audio_out", deserialize_with = "audio_in")]
607        delta: Vec<u8>,
608        #[serde(rename = "contentType", default = "pcm")]
609        content_type: String,
610    },
611    InputTranscript {
612        #[serde(default)]
613        delta: String,
614    },
615    OutputTranscript {
616        #[serde(default)]
617        delta: String,
618    },
619    ToolCall {
620        id: String,
621        name: String,
622        #[serde(default)]
623        args: Map<String, Value>,
624    },
625    SpeechStarted,
626    SpeechStopped,
627    Done {
628        #[serde(default)]
629        usage: Usage,
630    },
631    Error {
632        message: String,
633        #[serde(default, skip_serializing_if = "Option::is_none")]
634        code: Option<String>,
635    },
636}
637
638/// The `options` argument of `generate_text` and `generate_text_sync`. Dropping
639/// the returned stream closes the socket, which stops the reply.
640#[derive(Debug, Clone, Default)]
641pub struct TextOptions {
642    pub content: Option<Vec<Content>>,
643    pub tools: Option<ToolsOrTool>,
644    pub max_tools: Option<u32>,
645    pub reasoning: Option<String>,
646    pub group: Option<Group>,
647}
648
649/// Streaming text generation. A singular Tool forces it; an array lets the model choose.
650pub async fn generate_text(
651    authorization: &CredentialsOrApiKey,
652    model: Text,
653    options: TextOptions,
654) -> crate::Result<BoxStream<'static, StreamEvent>> {
655    socket::stream_text(
656        authorization,
657        "/generative/text",
658        model.as_str(),
659        socket::TextOptions {
660            content: options.content,
661            tools: options.tools,
662            max_tools: options.max_tools,
663            memories: None,
664            reasoning: options.reasoning,
665            inbox: None,
666            group: options.group,
667        },
668    )
669    .await
670}
671
672/// Synchronous wrapper: buffers the stream and returns the full TextResponse.
673pub async fn generate_text_sync(
674    authorization: &CredentialsOrApiKey,
675    model: Text,
676    options: TextOptions,
677) -> crate::Result<TextResponse> {
678    socket::collect_text(generate_text(authorization, model, options).await?).await
679}
680
681/// Embedding (stays HTTP). With `group`, the group pays.
682pub async fn generate_embedding(
683    authorization: &CredentialsOrApiKey,
684    model: Embedding,
685    content: &str,
686    group: Option<&Group>,
687) -> crate::Result<EmbeddingResponse> {
688    let mut request = client()
689        .post(format!("{}/generative/embed", super::get_url()))
690        .header(
691            "Authorization",
692            match authorization {
693                CredentialsOrApiKey::Credentials(credentials) => {
694                    format!("Token {}", credentials.token)
695                }
696                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
697            },
698        );
699    if let Some(group) = group {
700        request = request.header("Group", &group.id);
701    }
702    let response = request
703        .json(&json!({ "model": model, "content": content }))
704        .send()
705        .await?;
706    if !response.status().is_success() {
707        return Err(Error::Message(format!(
708            "Failed to generate embedding: {}",
709            response.status().canonical_reason().unwrap_or_default()
710        )));
711    }
712    Ok(response.json().await?)
713}
714
715/// Decision (stays HTTP). Each question lists its options; every option comes back
716/// with its probability. A question the model declines is left out. With `group`,
717/// the group pays.
718pub async fn generate_decision(
719    authorization: &CredentialsOrApiKey,
720    model: Decision,
721    content: &[Content],
722    questions: &HashMap<String, Vec<String>>,
723    group: Option<&Group>,
724) -> crate::Result<HashMap<String, HashMap<String, f64>>> {
725    let messages = socket::prepare_messages(authorization, content).await?;
726    let mut request = client()
727        .post(format!("{}/generative/decision", super::get_url()))
728        .header(
729            "Authorization",
730            match authorization {
731                CredentialsOrApiKey::Credentials(credentials) => {
732                    format!("Token {}", credentials.token)
733                }
734                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
735            },
736        );
737    if let Some(group) = group {
738        request = request.header("Group", &group.id);
739    }
740    let response = request
741        .json(&json!({ "model": model, "messages": messages, "questions": questions }))
742        .send()
743        .await?;
744    Ok(ok(response).await?.json().await?)
745}
746
747fn media_extra(fields: Vec<(&str, Option<Value>)>) -> Map<String, Value> {
748    fields
749        .into_iter()
750        .filter_map(|(key, value)| value.map(|value| (key.to_string(), value)))
751        .collect()
752}
753
754/// The `options` argument of `generate_image`.
755#[derive(Debug, Clone, Default)]
756pub struct ImageOptions {
757    pub content: Option<Vec<Content>>,
758    pub size: Option<[u32; 2]>,
759    pub group: Option<Group>,
760}
761
762/// Image generation.
763pub async fn generate_image(
764    authorization: &CredentialsOrApiKey,
765    model: Image,
766    options: ImageOptions,
767) -> crate::Result<TextResponse> {
768    socket::generate_media(
769        authorization,
770        "/generative/image",
771        model.as_str(),
772        options.content,
773        options.group,
774        media_extra(vec![("size", options.size.map(|size| json!(size)))]),
775        "image/png",
776    )
777    .await
778}
779
780/// The `options` argument of `generate_video`.
781#[derive(Debug, Clone, Default)]
782pub struct VideoOptions {
783    pub content: Option<Vec<Content>>,
784    pub duration: Option<f64>,
785    pub size: Option<[u32; 2]>,
786    pub group: Option<Group>,
787}
788
789/// Video generation.
790pub async fn generate_video(
791    authorization: &CredentialsOrApiKey,
792    model: Video,
793    options: VideoOptions,
794) -> crate::Result<TextResponse> {
795    socket::generate_media(
796        authorization,
797        "/generative/video",
798        model.as_str(),
799        options.content,
800        options.group,
801        media_extra(vec![
802            ("duration", options.duration.map(Value::from)),
803            ("size", options.size.map(|size| json!(size))),
804        ]),
805        "video/mp4",
806    )
807    .await
808}
809
810/// The `options` argument of `generate_speech`.
811#[derive(Debug, Clone, Default)]
812pub struct SpeechOptions {
813    pub content: Option<Vec<Content>>,
814    pub voice: Option<Demographic>,
815    pub group: Option<Group>,
816}
817
818/// Speech generation.
819pub async fn generate_speech(
820    authorization: &CredentialsOrApiKey,
821    model: Speech,
822    options: SpeechOptions,
823) -> crate::Result<TextResponse> {
824    let voice = options.voice.map(serde_json::to_value).transpose()?;
825    socket::generate_media(
826        authorization,
827        "/generative/speech",
828        model.as_str(),
829        options.content,
830        options.group,
831        media_extra(vec![("voice", voice)]),
832        "audio/mpeg",
833    )
834    .await
835}
836
837/// The `options` argument of `generate_transcription`.
838#[derive(Debug, Clone, Default)]
839pub struct TranscriptionOptions {
840    pub content: Option<Vec<Content>>,
841    pub group: Option<Group>,
842}
843
844/// Transcription generation.
845pub async fn generate_transcription(
846    authorization: &CredentialsOrApiKey,
847    model: Transcription,
848    options: TranscriptionOptions,
849) -> crate::Result<TextResponse> {
850    socket::generate_media(
851        authorization,
852        "/generative/transcription",
853        model.as_str(),
854        options.content,
855        options.group,
856        Map::new(),
857        "application/octet-stream",
858    )
859    .await
860}
861
862/// The `options` argument of `generate_voice` and `generate_voice_sync`. `audio`
863/// is PCM16 at 16 kHz. Dropping the returned stream closes the socket.
864#[derive(Default)]
865pub struct VoiceOptions {
866    pub content: Option<Vec<Content>>,
867    pub audio: Option<BoxStream<'static, Vec<u8>>>,
868    pub notes: Option<BoxStream<'static, String>>,
869    pub tools: Option<ToolsOrTool>,
870    pub max_tools: Option<u32>,
871    pub voice: Option<PartialDemographic>,
872    pub group: Option<Group>,
873}
874
875/// Streaming voice generation. Each of `notes` tells the model something to act on now.
876pub async fn generate_voice(
877    authorization: &CredentialsOrApiKey,
878    model: Voice,
879    options: VoiceOptions,
880) -> crate::Result<BoxStream<'static, VoiceEvent>> {
881    socket::stream_voice(
882        authorization,
883        "/generative/voice",
884        model.as_str(),
885        socket::VoiceOptions {
886            content: options.content,
887            audio: options.audio,
888            notes: options.notes,
889            tools: options.tools,
890            max_tools: options.max_tools,
891            voice: options.voice,
892            memories: None,
893            group: options.group,
894        },
895    )
896    .await
897}
898
899pub async fn generate_voice_sync(
900    authorization: &CredentialsOrApiKey,
901    model: Voice,
902    options: VoiceOptions,
903) -> crate::Result<TextResponse> {
904    socket::collect_voice(
905        authorization,
906        generate_voice(authorization, model, options).await?,
907    )
908    .await
909}