fauna-api 1.0.861

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
use std::collections::HashMap;
use std::ops::Deref;

use serde::de::DeserializeOwned;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;

use super::generative::{Decision, Embedding, Image, Speech, Text, Transcription, Video, Voice};
use crate::authentification::CredentialsOrApiKey;
use crate::error::Result;
use crate::http::{client, encode, ok};

/// One provider's settings in a garden.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProviderConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub system_prompt: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f64>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Garden {
    #[serde(default)]
    pub providers: HashMap<String, ProviderConfig>,
    #[serde(default)]
    pub memories: u32,
}

/// `Partial<Garden>` in the TypeScript SDK.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct PartialGarden {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub providers: Option<HashMap<String, ProviderConfig>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memories: Option<u32>,
}

/// `Partial<Garden> & { provider?, providerConfig? }` in the TypeScript SDK.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GardenUpdate {
    #[serde(flatten)]
    pub garden: PartialGarden,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_config: Option<ProviderConfig>,
}

impl Deref for GardenUpdate {
    type Target = PartialGarden;
    fn deref(&self) -> &PartialGarden {
        &self.garden
    }
}

/// `Text | Embedding | Image | Video | Speech | Transcription | Voice | Decision`
/// in the TypeScript SDK: any Parrot model.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(untagged)]
pub enum TextOrEmbeddingOrImageOrVideoOrSpeechOrTranscriptionOrVoiceOrDecision {
    Text(Text),
    Embedding(Embedding),
    Image(Image),
    Video(Video),
    Speech(Speech),
    Transcription(Transcription),
    Voice(Voice),
    Decision(Decision),
}

impl TextOrEmbeddingOrImageOrVideoOrSpeechOrTranscriptionOrVoiceOrDecision {
    fn as_str(self) -> &'static str {
        match self {
            Self::Text(model) => model.as_str(),
            Self::Embedding(model) => model.as_str(),
            Self::Image(model) => model.as_str(),
            Self::Video(model) => model.as_str(),
            Self::Speech(model) => model.as_str(),
            Self::Transcription(model) => model.as_str(),
            Self::Voice(model) => model.as_str(),
            Self::Decision(model) => model.as_str(),
        }
    }
}

macro_rules! any_model {
    ($($variant:ident),*) => {
        $(
            impl From<$variant> for TextOrEmbeddingOrImageOrVideoOrSpeechOrTranscriptionOrVoiceOrDecision {
                fn from(model: $variant) -> Self {
                    Self::$variant(model)
                }
            }
        )*
    };
}

any_model!(
    Text,
    Embedding,
    Image,
    Video,
    Speech,
    Transcription,
    Voice,
    Decision
);

/// `{ inputPer1M?, outputPer1M?, perUnit?, unit? }` in the TypeScript SDK.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Price {
    #[serde(
        default,
        rename = "inputPer1M",
        skip_serializing_if = "Option::is_none"
    )]
    pub input_per_1m: Option<f64>,
    #[serde(
        default,
        rename = "outputPer1M",
        skip_serializing_if = "Option::is_none"
    )]
    pub output_per_1m: Option<f64>,
    #[serde(default, rename = "perUnit", skip_serializing_if = "Option::is_none")]
    pub per_unit: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unit: Option<String>,
}

pub async fn get_price(
    model: impl Into<TextOrEmbeddingOrImageOrVideoOrSpeechOrTranscriptionOrVoiceOrDecision>,
) -> Result<Price> {
    let response = client()
        .get(format!(
            "{}/routing/price/{}",
            super::get_url(),
            encode(model.into().as_str())
        ))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

pub async fn get_dimensions(model: Embedding) -> Result<u32> {
    let response = client()
        .get(format!(
            "{}/routing/dimensions/{}",
            super::get_url(),
            encode(model.as_str())
        ))
        .send()
        .await?;
    let text = ok(response).await?.text().await?;
    Ok(text.trim().parse::<f64>().unwrap_or(f64::NAN) as u32)
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CatalogModel {
    pub model: String,
    pub name: String,
    pub provider: String,
    #[serde(rename = "baseURL")]
    pub base_url: String,
    pub icon: String,
    #[serde(
        default,
        rename = "inputPer1M",
        skip_serializing_if = "Option::is_none"
    )]
    pub input_per_1m: Option<f64>,
    #[serde(
        default,
        rename = "outputPer1M",
        skip_serializing_if = "Option::is_none"
    )]
    pub output_per_1m: Option<f64>,
    #[serde(
        default,
        rename = "cachedInputPer1M",
        skip_serializing_if = "Option::is_none"
    )]
    pub cached_input_per_1m: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub per_unit: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unit: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dimensions: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<Vec<String>>,
    /// Decision models: image input and the limits the model accepts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub images: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_questions: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_options: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input_context_window: Option<u64>,
}

/// Every model Parrot offers, by family.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Catalog {
    #[serde(default)]
    pub text: Vec<CatalogModel>,
    #[serde(default)]
    pub embedding: Vec<CatalogModel>,
    #[serde(default)]
    pub image: Vec<CatalogModel>,
    #[serde(default)]
    pub video: Vec<CatalogModel>,
    #[serde(default)]
    pub speech: Vec<CatalogModel>,
    #[serde(default)]
    pub transcription: Vec<CatalogModel>,
    #[serde(default)]
    pub voice: Vec<CatalogModel>,
    #[serde(default)]
    pub decision: Vec<CatalogModel>,
}

pub async fn get_all() -> Result<Catalog> {
    let response = client()
        .get(format!("{}/routing/all", super::get_url()))
        .header("Content-Type", "application/json")
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// A model id this SDK knows; one it doesn't reads as unset.
fn known<'de, D: Deserializer<'de>, T: DeserializeOwned>(
    deserializer: D,
) -> std::result::Result<Option<T>, D::Error> {
    Ok(serde_json::from_value(Value::deserialize(deserializer)?).ok())
}

/// `{ model, reasoning? }` in the TypeScript SDK.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LastTextModel {
    pub model: Text,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<String>,
}

/// The model the caller starts from in each kind: the one they last picked in a model picker,
/// else the kind's default. A model this SDK doesn't know reads as `None`. As the argument of
/// `set_last_used_models`, the kinds to record.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct LastUsedModels {
    #[serde(
        default,
        deserialize_with = "known",
        skip_serializing_if = "Option::is_none"
    )]
    pub text: Option<LastTextModel>,
    #[serde(
        default,
        deserialize_with = "known",
        skip_serializing_if = "Option::is_none"
    )]
    pub embedding: Option<Embedding>,
    #[serde(
        default,
        deserialize_with = "known",
        skip_serializing_if = "Option::is_none"
    )]
    pub image: Option<Image>,
    #[serde(
        default,
        deserialize_with = "known",
        skip_serializing_if = "Option::is_none"
    )]
    pub video: Option<Video>,
    #[serde(
        default,
        deserialize_with = "known",
        skip_serializing_if = "Option::is_none"
    )]
    pub speech: Option<Speech>,
    #[serde(
        default,
        deserialize_with = "known",
        skip_serializing_if = "Option::is_none"
    )]
    pub transcription: Option<Transcription>,
    #[serde(
        default,
        deserialize_with = "known",
        skip_serializing_if = "Option::is_none"
    )]
    pub voice: Option<Voice>,
    #[serde(
        default,
        deserialize_with = "known",
        skip_serializing_if = "Option::is_none"
    )]
    pub decision: Option<Decision>,
}

/// The model you start from in each kind: the one you last picked in a model picker, else the
/// kind's default (the cheapest Google model, else the cheapest). Generating never changes it;
/// `set_last_used_models` does.
pub async fn get_last_used_models(authorization: &CredentialsOrApiKey) -> Result<LastUsedModels> {
    let response = client()
        .get(format!("{}/routing/last", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// Records the models you picked. Each kind given replaces that kind; a text model replaces its
/// reasoning too, clearing it when none is given. A model outside its kind, or a reasoning the
/// model doesn't take, is refused.
pub async fn set_last_used_models(
    authorization: &CredentialsOrApiKey,
    models: &LastUsedModels,
) -> Result<()> {
    let response = client()
        .put(format!("{}/routing/last", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(models)
        .send()
        .await?;
    ok(response).await?;
    Ok(())
}

/// `{ input, output }` in the TypeScript SDK: text tokens spent.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct TokenCost {
    #[serde(default)]
    pub input: f64,
    #[serde(default)]
    pub output: f64,
}

/// `{ cost }` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct Cost {
    #[serde(default)]
    pub cost: f64,
}

/// The caller's usage by family: `(model, day, spend)` rows.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ModelUsage {
    #[serde(default)]
    pub text: Vec<(String, String, TokenCost)>,
    #[serde(default)]
    pub embedding: Vec<(String, String, Cost)>,
    #[serde(default)]
    pub image: Vec<(String, String, Cost)>,
    #[serde(default)]
    pub video: Vec<(String, String, Cost)>,
    #[serde(default)]
    pub speech: Vec<(String, String, Cost)>,
    #[serde(default)]
    pub transcription: Vec<(String, String, Cost)>,
    #[serde(default)]
    pub voice: Vec<(String, String, Cost)>,
    #[serde(default)]
    pub decision: Vec<(String, String, Cost)>,
}

pub async fn get_usage(authorization: &CredentialsOrApiKey) -> Result<ModelUsage> {
    let response = client()
        .get(format!("{}/routing/usage", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

pub async fn get_garden(authorization: &CredentialsOrApiKey) -> Result<Garden> {
    let response = client()
        .get(format!("{}/routing/garden", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

pub async fn set_garden(authorization: &CredentialsOrApiKey, update: &GardenUpdate) -> Result<()> {
    let response = client()
        .put(format!("{}/routing/garden", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(update)
        .send()
        .await?;
    ok(response).await?;
    Ok(())
}