fauna-api 1.0.773

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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
use std::sync::Arc;

use serde::de::DeserializeOwned;
use serde_json::{Map, Value, json};

use super::generative::{
    Content, Embedding, Part, Text, TextOptions, TextPart, TextResponse, Tool, generate_embedding,
    generate_text_sync,
};
use crate::authentification::CredentialsOrApiKey;
use crate::error::{Error, Result};
use crate::shared::schema::Schema;

/// `[number | undefined, number | undefined]` in the TypeScript SDK: a lower and
/// an upper bound, either one open.
pub type Bounds = [Option<f64>; 2];

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

fn schema(json: Value) -> Schema {
    serde_json::from_value(json).expect("format schemas are valid")
}

fn stringify(value: &Value) -> String {
    serde_json::to_string(value).unwrap_or_else(|_| "null".to_string())
}

fn evaluate(key: &'static str) -> super::generative::ToolEvaluate {
    Arc::new(move |params: Value| {
        let answer = stringify(&params[key]);
        Box::pin(async move { Ok(answer) })
    })
}

/// Asks `model` with the format's instruction and reads the tool's answer, if any.
async fn ask(
    instruction: &str,
    tool: &Tool,
    authorization: &CredentialsOrApiKey,
    model: Text,
    options: LlmOptions,
) -> Result<(TextResponse, Option<Value>)> {
    let prompt = match &tool.instruction {
        Some(line) => format!("{instruction}\n{}", line(&json!({}))),
        None => instruction.to_string(),
    };

    let mut response = generate_text_sync(
        authorization,
        model,
        TextOptions {
            content: Some(options.content.unwrap_or_default()),
            ..TextOptions::default()
        },
    )
    .await?;
    response
        .content
        .parts
        .push(Part::Text(TextPart { text: prompt }));

    let invocation = response.content.parts.iter().find_map(|part| match part {
        Part::Invocation(invocation) => Some(invocation.clone()),
        _ => None,
    });
    let answer = match invocation {
        Some(invocation) => {
            let args = invocation.args.map(Value::Object).unwrap_or(Value::Null);
            Some(serde_json::from_str((tool.evaluate)(args).await?.as_str())?)
        }
        None => None,
    };
    Ok((response, answer))
}

fn read<T: DeserializeOwned>(answer: Value) -> Option<T> {
    serde_json::from_value(answer).ok()
}

fn unit(vector: &[f64]) -> Vec<f64> {
    if vector.is_empty() {
        return Vec::new();
    }
    let norm_squared: f64 = vector.iter().map(|x| x * x).sum();
    if norm_squared == 0.0 {
        return Vec::new();
    }
    let norm = norm_squared.sqrt();
    vector.iter().map(|x| x / norm).collect()
}

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

/// A question's answer shape. `from_json` returns whichever kind the JSON names.
pub enum Format {
    Numerical(NumericalFormat),
    Vector(VectorFormat),
    Categorical(CategoricalFormat),
    Selection(SelectionFormat),
    Utterance(UtteranceFormat),
}

impl Format {
    pub fn instruction(&self) -> &str {
        match self {
            Format::Numerical(format) => &format.instruction,
            Format::Vector(format) => &format.instruction,
            Format::Categorical(format) => &format.instruction,
            Format::Selection(format) => &format.instruction,
            Format::Utterance(format) => &format.instruction,
        }
    }

    pub fn tool(&self) -> &Tool {
        match self {
            Format::Numerical(format) => &format.tool,
            Format::Vector(format) => &format.tool,
            Format::Categorical(format) => &format.tool,
            Format::Selection(format) => &format.tool,
            Format::Utterance(format) => &format.tool,
        }
    }

    fn tool_mut(&mut self) -> &mut Tool {
        match self {
            Format::Numerical(format) => &mut format.tool,
            Format::Vector(format) => &mut format.tool,
            Format::Categorical(format) => &mut format.tool,
            Format::Selection(format) => &mut format.tool,
            Format::Utterance(format) => &mut format.tool,
        }
    }

    fn kind(&self) -> &'static str {
        match self {
            Format::Numerical(_) => "NumericalFormat",
            Format::Vector(_) => "VectorFormat",
            Format::Categorical(_) => "CategoricalFormat",
            Format::Selection(_) => "SelectionFormat",
            Format::Utterance(_) => "UtteranceFormat",
        }
    }

    /// A fresh format with the same question and no answer.
    #[allow(clippy::should_implement_trait)]
    pub fn clone(&self) -> Format {
        match self {
            Format::Numerical(format) => Format::Numerical(format.clone()),
            Format::Vector(format) => Format::Vector(format.clone()),
            Format::Categorical(format) => Format::Categorical(format.clone()),
            Format::Selection(format) => Format::Selection(format.clone()),
            Format::Utterance(format) => Format::Utterance(format.clone()),
        }
    }

    /// Sets the answer from its JSON; a value of the wrong shape clears it.
    pub fn answer(&mut self, response: Value) {
        match self {
            Format::Numerical(format) => format.response = read(response),
            Format::Vector(format) => format.response = read(response),
            Format::Categorical(format) => format.response = read(response),
            Format::Selection(format) => format.response = read(response),
            Format::Utterance(format) => format.response = read(response),
        }
    }

    pub fn to_json(&self) -> Value {
        match self {
            Format::Numerical(format) => format.to_json(),
            Format::Vector(format) => format.to_json(),
            Format::Categorical(format) => format.to_json(),
            Format::Selection(format) => format.to_json(),
            Format::Utterance(format) => format.to_json(),
        }
    }

    /// Returns a unit-length numerical representation of the format's current
    /// response. Used by the research agent's per-scope rank-dedup matrix to
    /// detect linearly-dependent rows (duplicates). Concatenated across an
    /// entity's atomic fields, the resulting vector is the row's identifier.
    ///
    /// Contract: all implementations return a vector with L2 norm == 1 when
    /// a response is present. If the response is missing or empty, an
    /// implementation may return a zero-length array; callers MUST skip such
    /// fields when concatenating (they correspond to optional / unfilled
    /// fields and are excluded from the rank check).
    pub fn to_vector(&self) -> Vec<f64> {
        match self {
            Format::Numerical(format) => format.to_vector(),
            Format::Vector(format) => format.to_vector(),
            Format::Categorical(format) => format.to_vector(),
            Format::Selection(format) => format.to_vector(),
            Format::Utterance(format) => format.to_vector(),
        }
    }

    pub async fn llm(
        &mut self,
        authorization: &CredentialsOrApiKey,
        model: Text,
        options: LlmOptions,
    ) -> Result<TextResponse> {
        let (response, answer) = ask(
            self.instruction(),
            self.tool(),
            authorization,
            model,
            options,
        )
        .await?;
        if let Some(answer) = answer {
            self.answer(answer);
        }
        Ok(response)
    }

    pub fn get_response(&self) -> Option<Value> {
        match self {
            Format::Numerical(format) => format.get_response().map(Value::from),
            Format::Vector(format) => format.get_response().map(Value::from),
            Format::Categorical(format) => format.get_response().map(Value::from),
            Format::Selection(format) => format.get_response().map(Value::from),
            Format::Utterance(format) => format.get_response().map(Value::from),
        }
    }

    pub fn optional(format: &Format) -> Format {
        let mut clone = format.clone();

        let original = clone.tool().clone();
        let tool = clone.tool_mut();
        if let Schema::Object(parameters) = &mut tool.function.parameters {
            parameters.required = None;
        }
        let instruction = format.tool().instruction.clone();
        tool.instruction = Some(Arc::new(move |params: &Value| {
            let line = instruction
                .as_ref()
                .map(|instruction| instruction(params))
                .unwrap_or_default();
            format!(
                "{line} This is optional. If you would opt out of answering, you may skip the parameters."
            )
        }));
        tool.evaluate = Arc::new(move |params: Value| {
            let original = original.clone();
            Box::pin(async move {
                if params.is_null() {
                    return Ok(stringify(&Value::Null));
                }
                match (original.evaluate)(params).await {
                    Ok(response) => Ok(response),
                    Err(_) => Ok(stringify(&Value::Null)),
                }
            })
        });

        clone
    }

    pub fn calculate_distance(a: &Format, b: &Format) -> Result<f64> {
        match (a, b) {
            (Format::Numerical(a), Format::Numerical(b)) => Ok(NumericalFormat::distance(a, b)),
            (Format::Vector(a), Format::Vector(b)) => Ok(VectorFormat::distance(a, b)),
            (Format::Categorical(a), Format::Categorical(b)) => {
                Ok(CategoricalFormat::distance(a, b))
            }
            (Format::Selection(a), Format::Selection(b)) => Ok(SelectionFormat::distance(a, b)),
            (Format::Utterance(a), Format::Utterance(b)) => UtteranceFormat::distance(a, b),
            _ => Err(Error::Message(format!(
                "Invalid format type: {} and {}",
                a.kind(),
                b.kind()
            ))),
        }
    }

    pub fn from_json(json: &Value) -> Result<Format> {
        let instruction = json["instruction"].as_str().unwrap_or_default();
        let mut format = match json["type"].as_str() {
            Some("numerical") => Format::Numerical(NumericalFormat::new(
                instruction,
                read(json["bounds"].clone()).flatten(),
            )),
            Some("vector") => Format::Vector(VectorFormat::new(
                instruction,
                json["dimension"].as_u64().unwrap_or_default() as usize,
                read(json["bounds"].clone()).flatten(),
            )),
            Some("categorical") => Format::Categorical(CategoricalFormat::new(
                instruction,
                read(json["categories"].clone()).unwrap_or_default(),
            )),
            Some("selection") => Format::Selection(SelectionFormat::new(
                instruction,
                read(json["options"].clone()).unwrap_or_default(),
            )),
            Some("utterance") => {
                Format::Utterance(UtteranceFormat::new(instruction, json["time"].as_f64()))
            }
            kind => {
                return Err(Error::Message(format!(
                    "Invalid format type: {} for format:\n{json}",
                    kind.unwrap_or("undefined")
                )));
            }
        };
        format.answer(json["answer"].clone());
        Ok(format)
    }
}

pub struct NumericalFormat {
    pub instruction: String,
    pub tool: Tool,
    response: Option<f64>,

    pub bounds: Option<Bounds>,
}

impl NumericalFormat {
    pub fn new(instruction: &str, bounds: Option<Bounds>) -> Self {
        NumericalFormat {
            instruction: instruction.to_string(),
            tool: NumericalFormat::tool(None),
            response: None,
            bounds,
        }
    }

    #[allow(clippy::should_implement_trait)]
    pub fn clone(&self) -> Self {
        NumericalFormat::new(&self.instruction, self.bounds)
    }

    pub fn answer(&mut self, response: f64) {
        self.response = Some(response);
    }

    pub async fn llm(
        &mut self,
        authorization: &CredentialsOrApiKey,
        model: Text,
        options: LlmOptions,
    ) -> Result<TextResponse> {
        let (response, answer) =
            ask(&self.instruction, &self.tool, authorization, model, options).await?;
        if let Some(answer) = answer {
            self.response = read(answer);
        }
        Ok(response)
    }

    pub fn get_response(&self) -> Option<f64> {
        let response = self.response?;
        let Some([lower, upper]) = self.bounds else {
            return Some(response);
        };
        let mut formatted = response;
        if let Some(lower) = lower
            && formatted < lower
        {
            formatted = lower;
        }
        if let Some(upper) = upper
            && formatted > upper
        {
            formatted = upper;
        }
        Some(formatted)
    }

    pub fn to_json(&self) -> Value {
        object(vec![
            ("type", Some(Value::from("numerical"))),
            ("instruction", Some(Value::from(self.instruction.as_str()))),
            ("bounds", self.bounds.map(|bounds| json!(bounds))),
            ("answer", self.get_response().map(Value::from)),
        ])
    }

    /// Encode the scalar as a 2-dim unit vector `[x, 1] / sqrt(x²+1)`. Direct
    /// unit-norm on a 1-dim scalar would collapse to just the sign and discard
    /// magnitude; the 2-dim wrap preserves magnitude as the vector's angle so
    /// two identical scalars yield identical unit vectors and different scalars
    /// yield distinguishable directions.
    pub fn to_vector(&self) -> Vec<f64> {
        let Some(x) = self.get_response() else {
            return Vec::new();
        };
        let norm = (x * x + 1.0).sqrt();
        vec![x / norm, 1.0 / norm]
    }

    pub fn compare(a: f64, b: f64) -> f64 {
        const EPSILON: f64 = 1e-8;
        let denom = a.abs().max(b.abs()).max(EPSILON);
        let relative_diff = (a - b).abs() / denom;
        1.0 / (1.0 + relative_diff)
    }

    pub fn distance(a: &NumericalFormat, b: &NumericalFormat) -> f64 {
        match (a.get_response(), b.get_response()) {
            (Some(a), Some(b)) => NumericalFormat::compare(a, b),
            _ => 0.0,
        }
    }

    pub fn tool(bounds: Option<Bounds>) -> Tool {
        Tool {
            function: super::generative::Function {
                name: "return_float".to_string(),
                description: Some("Return a number as a float.".to_string()),
                parameters: schema(json!({
                    "type": "OBJECT",
                    "properties": {
                        "number": { "type": "NUMBER", "description": "The numeric answer." }
                    },
                    "required": ["number"]
                })),
                default: None,
                example: None,
                behavior: None,
            },
            evaluate: evaluate("number"),
            instruction: Some(Arc::new(move |_params: &Value| match bounds {
                Some([Some(lower), Some(upper)]) => format!(
                    "Use the tool \"return_float\" to return your answer as a number on the scale of {lower} to {upper}."
                ),
                Some([Some(lower), None]) => format!(
                    "Use the tool \"return_float\" to return your answer as a number greater than {lower}."
                ),
                Some([None, upper]) => format!(
                    "Use the tool \"return_float\" to return your answer as a number less than {}.",
                    upper.map_or("undefined".to_string(), |upper| upper.to_string())
                ),
                None => {
                    "Use the tool \"return_float\" to return your answer as a number.".to_string()
                }
            })),
        }
    }
}

pub struct VectorFormat {
    pub instruction: String,
    pub tool: Tool,
    response: Option<Vec<f64>>,

    pub dimension: usize,
    pub bounds: Option<Vec<Option<Bounds>>>,
}

impl VectorFormat {
    pub fn new(instruction: &str, dimension: usize, bounds: Option<Vec<Option<Bounds>>>) -> Self {
        VectorFormat {
            instruction: instruction.to_string(),
            tool: VectorFormat::tool(dimension, bounds.clone()),
            response: None,
            dimension,
            bounds,
        }
    }

    #[allow(clippy::should_implement_trait)]
    pub fn clone(&self) -> Self {
        VectorFormat::new(&self.instruction, self.dimension, self.bounds.clone())
    }

    pub fn answer(&mut self, response: Vec<f64>) {
        self.response = Some(response);
    }

    pub async fn llm(
        &mut self,
        authorization: &CredentialsOrApiKey,
        model: Text,
        options: LlmOptions,
    ) -> Result<TextResponse> {
        let (response, answer) =
            ask(&self.instruction, &self.tool, authorization, model, options).await?;
        if let Some(answer) = answer {
            self.response = read(answer);
        }
        Ok(response)
    }

    pub fn get_response(&self) -> Option<Vec<f64>> {
        let response = self.response.as_ref()?;
        let Some(bounds) = &self.bounds else {
            return Some(response.clone());
        };
        Some(
            response
                .iter()
                .enumerate()
                .map(|(index, &number)| {
                    let mut number = number;
                    if let Some(Some([lower, upper])) = bounds.get(index) {
                        if let Some(lower) = lower
                            && number < *lower
                        {
                            number = *lower;
                        }
                        if let Some(upper) = upper
                            && number > *upper
                        {
                            number = *upper;
                        }
                    }
                    number
                })
                .collect(),
        )
    }

    pub fn to_json(&self) -> Value {
        object(vec![
            ("type", Some(Value::from("vector"))),
            ("instruction", Some(Value::from(self.instruction.as_str()))),
            ("dimension", Some(Value::from(self.dimension))),
            ("bounds", self.bounds.as_ref().map(|bounds| json!(bounds))),
            ("answer", self.get_response().map(Value::from)),
        ])
    }

    pub fn to_vector(&self) -> Vec<f64> {
        unit(&self.get_response().unwrap_or_default())
    }

    pub fn distance(a: &VectorFormat, b: &VectorFormat) -> f64 {
        let (Some(vector_a), Some(vector_b)) = (a.get_response(), b.get_response()) else {
            return 0.0;
        };
        let aggregate: f64 = vector_a
            .iter()
            .enumerate()
            .map(|(index, &a)| {
                NumericalFormat::compare(a, vector_b.get(index).copied().unwrap_or(f64::NAN))
            })
            .sum();
        aggregate / vector_a.len() as f64
    }

    pub fn tool(dimension: usize, bounds: Option<Vec<Option<Bounds>>>) -> Tool {
        Tool {
            function: super::generative::Function {
                name: "return_vector".to_string(),
                description: Some(format!("Return a vector of {dimension} numbers.")),
                parameters: schema(json!({
                    "type": "OBJECT",
                    "properties": {
                        "vector": {
                            "type": "ARRAY",
                            "items": { "type": "NUMBER" },
                            "minimum": dimension,
                            "maximum": dimension,
                            "description": format!("A vector of exactly {dimension} numbers.")
                        }
                    },
                    "required": ["vector"]
                })),
                default: None,
                example: None,
                behavior: None,
            },
            evaluate: evaluate("vector"),
            instruction: Some(Arc::new(move |_params: &Value| {
                let Some(bounds) = &bounds else {
                    return format!(
                        "Use the tool \"return_vector\" to return your answer as a numerical vector of dimension {dimension}."
                    );
                };

                let mut lower_bound = String::from("[");
                let mut upper_bound = String::from("[");

                for index in 0..dimension {
                    match bounds.get(index).copied().flatten() {
                        None | Some([None, None]) => {
                            lower_bound.push_str("-infinity");
                            upper_bound.push_str("infinity");
                        }
                        Some([Some(lower), _]) => {
                            lower_bound.push_str(&format!(">{lower}"));
                            upper_bound.push_str("infinity");
                        }
                        Some([None, Some(upper)]) => {
                            lower_bound.push_str("-infinity");
                            upper_bound.push_str(&format!("<{upper}"));
                        }
                    }

                    if index + 1 < dimension {
                        lower_bound.push_str(", ");
                        upper_bound.push_str(", ");
                    }
                }
                lower_bound.push(']');
                upper_bound.push(']');

                format!(
                    "Use the tool \"return_vector\" to return your answer as a numerical vector of dimension {dimension} of scale {lower_bound} to {upper_bound}."
                )
            })),
        }
    }
}

pub struct CategoricalFormat {
    pub instruction: String,
    pub tool: Tool,
    response: Option<String>,

    categories: Vec<String>,
}

impl CategoricalFormat {
    pub fn new(instruction: &str, categories: Vec<String>) -> Self {
        CategoricalFormat {
            instruction: instruction.to_string(),
            tool: CategoricalFormat::tool(&categories),
            response: None,
            categories,
        }
    }

    #[allow(clippy::should_implement_trait)]
    pub fn clone(&self) -> Self {
        CategoricalFormat::new(&self.instruction, self.categories.clone())
    }

    pub fn answer(&mut self, response: String) {
        self.response = Some(response);
    }

    pub async fn llm(
        &mut self,
        authorization: &CredentialsOrApiKey,
        model: Text,
        options: LlmOptions,
    ) -> Result<TextResponse> {
        let (response, answer) =
            ask(&self.instruction, &self.tool, authorization, model, options).await?;
        if let Some(answer) = answer {
            self.response = read(answer);
        }
        Ok(response)
    }

    pub fn get_categories(&self) -> &[String] {
        &self.categories
    }

    pub fn get_response(&self) -> Option<String> {
        match &self.response {
            Some(response) if !response.is_empty() => self
                .categories
                .iter()
                .find(|category| *category == response)
                .cloned(),
            response => response.clone(),
        }
    }

    pub fn to_json(&self) -> Value {
        object(vec![
            ("type", Some(Value::from("categorical"))),
            ("instruction", Some(Value::from(self.instruction.as_str()))),
            ("categories", Some(json!(self.categories))),
            ("answer", self.get_response().map(Value::from)),
        ])
    }

    /// One-hot over the category set, already unit-length.
    pub fn to_vector(&self) -> Vec<f64> {
        let Some(category) = self.get_response() else {
            return Vec::new();
        };
        let Some(index) = self.categories.iter().position(|other| *other == category) else {
            return Vec::new();
        };
        let mut vector = vec![0.0; self.categories.len()];
        vector[index] = 1.0;
        vector
    }

    pub fn distance(a: &CategoricalFormat, b: &CategoricalFormat) -> f64 {
        match (a.get_response(), b.get_response()) {
            (Some(a), Some(b)) if a == b => 1.0,
            _ => 0.0,
        }
    }

    pub fn tool(categories: &[String]) -> Tool {
        let listed = stringify(&json!(categories));
        Tool {
            function: super::generative::Function {
                name: "return_category".to_string(),
                description: Some("Return one of the predefined categories.".to_string()),
                parameters: schema(json!({
                    "type": "OBJECT",
                    "properties": {
                        "category": {
                            "type": "STRING",
                            "enum": categories,
                            "description": "The selected category."
                        }
                    },
                    "required": ["category"]
                })),
                default: None,
                example: None,
                behavior: None,
            },
            evaluate: evaluate("category"),
            instruction: Some(Arc::new(move |_params: &Value| {
                format!(
                    "Use the tool \"return_category\" to return your answer as one of the categories: {listed}."
                )
            })),
        }
    }
}

pub struct SelectionFormat {
    pub instruction: String,
    pub tool: Tool,
    response: Option<Vec<String>>,

    options: Vec<String>,
}

impl SelectionFormat {
    pub fn new(instruction: &str, options: Vec<String>) -> Self {
        SelectionFormat {
            instruction: instruction.to_string(),
            tool: SelectionFormat::tool(&options),
            response: None,
            options,
        }
    }

    #[allow(clippy::should_implement_trait)]
    pub fn clone(&self) -> Self {
        SelectionFormat::new(&self.instruction, self.options.clone())
    }

    pub fn answer(&mut self, response: Vec<String>) {
        self.response = Some(response);
    }

    pub async fn llm(
        &mut self,
        authorization: &CredentialsOrApiKey,
        model: Text,
        options: LlmOptions,
    ) -> Result<TextResponse> {
        let (response, answer) =
            ask(&self.instruction, &self.tool, authorization, model, options).await?;
        if let Some(answer) = answer {
            self.response = read(answer);
        }
        Ok(response)
    }

    pub fn get_options(&self) -> &[String] {
        &self.options
    }

    pub fn get_response(&self) -> Option<Vec<String>> {
        Some(
            self.response
                .iter()
                .flatten()
                .filter(|selection| self.options.contains(selection))
                .cloned()
                .collect(),
        )
    }

    pub fn to_json(&self) -> Value {
        object(vec![
            ("type", Some(Value::from("selection"))),
            ("instruction", Some(Value::from(self.instruction.as_str()))),
            ("options", Some(json!(self.options))),
            ("answer", self.get_response().map(Value::from)),
        ])
    }

    /// Multi-hot scaled by 1/sqrt(count) so the vector is unit-length.
    pub fn to_vector(&self) -> Vec<f64> {
        let selections = self.get_response().unwrap_or_default();
        if selections.is_empty() {
            return Vec::new();
        }
        let mut vector = vec![0.0; self.options.len()];
        let mut count = 0;
        for selection in &selections {
            if let Some(index) = self.options.iter().position(|option| option == selection) {
                vector[index] = 1.0;
                count += 1;
            }
        }
        if count == 0 {
            return Vec::new();
        }
        let scale = 1.0 / (count as f64).sqrt();
        vector.iter().map(|x| x * scale).collect()
    }

    pub fn distance(a: &SelectionFormat, b: &SelectionFormat) -> f64 {
        let selections_a = a.get_response().unwrap_or_default();
        let selections_b = b.get_response().unwrap_or_default();

        if selections_a.is_empty() && selections_b.is_empty() {
            return 1.0;
        }
        if selections_a.is_empty() || selections_b.is_empty() {
            return 0.0;
        }

        let set_a: std::collections::HashSet<&String> = selections_a.iter().collect();
        let set_b: std::collections::HashSet<&String> = selections_b.iter().collect();
        let intersection_size = set_a.intersection(&set_b).count();
        let union_size = set_a.union(&set_b).count();
        intersection_size as f64 / union_size as f64
    }

    pub fn tool(options: &[String]) -> Tool {
        let listed = stringify(&json!(options));
        Tool {
            function: super::generative::Function {
                name: "return_selections".to_string(),
                description: Some("Return one or more selected options.".to_string()),
                parameters: schema(json!({
                    "type": "OBJECT",
                    "properties": {
                        "selections": {
                            "type": "ARRAY",
                            "items": { "type": "STRING", "enum": options },
                            "description": "The selected options."
                        }
                    },
                    "required": ["selections"]
                })),
                default: None,
                example: None,
                behavior: None,
            },
            evaluate: evaluate("selections"),
            instruction: Some(Arc::new(move |_params: &Value| {
                format!(
                    "Use the tool \"return_selections\" to return your answer as a categorical vector of one or more in {listed}"
                )
            })),
        }
    }
}

pub struct UtteranceFormat {
    pub instruction: String,
    pub tool: Tool,
    response: Option<String>,

    pub time: Option<f64>,
    pub embedding: Option<Vec<f64>>,
}

impl UtteranceFormat {
    pub fn new(instruction: &str, time: Option<f64>) -> Self {
        UtteranceFormat {
            instruction: instruction.to_string(),
            tool: UtteranceFormat::tool(None),
            response: None,
            time,
            embedding: None,
        }
    }

    #[allow(clippy::should_implement_trait)]
    pub fn clone(&self) -> Self {
        UtteranceFormat::new(&self.instruction, self.time)
    }

    pub fn answer(&mut self, response: String) {
        self.response = Some(response);
    }

    pub async fn llm(
        &mut self,
        authorization: &CredentialsOrApiKey,
        model: Text,
        options: LlmOptions,
    ) -> Result<TextResponse> {
        let (response, answer) =
            ask(&self.instruction, &self.tool, authorization, model, options).await?;
        if let Some(answer) = answer {
            self.response = read(answer);
        }
        Ok(response)
    }

    pub fn get_response(&self) -> Option<String> {
        self.response.clone()
    }

    pub fn to_json(&self) -> Value {
        object(vec![
            ("type", Some(Value::from("utterance"))),
            ("instruction", Some(Value::from(self.instruction.as_str()))),
            ("time", self.time.map(Value::from)),
            ("answer", self.get_response().map(Value::from)),
        ])
    }

    /// Returns the unit-normalized embedding. The caller MUST have populated
    /// `embedding` first (via `embed()` or the research agent's extraction
    /// pipeline), otherwise this returns an empty vector and the field is
    /// excluded from the rank check. Embedding-less utterances cannot
    /// participate in dedup.
    pub fn to_vector(&self) -> Vec<f64> {
        unit(self.embedding.as_deref().unwrap_or_default())
    }

    pub async fn embed(
        &mut self,
        authorization: &CredentialsOrApiKey,
        model: Embedding,
    ) -> Result<()> {
        let Some(utterance) = self.get_response() else {
            return Err(Error::Message(
                "Cannot embed an utterance format without an answer.".to_string(),
            ));
        };
        let result = generate_embedding(authorization, model, &utterance, None).await?;
        self.embedding = Some(result.embedding);
        Ok(())
    }

    pub fn distance(a: &UtteranceFormat, b: &UtteranceFormat) -> Result<f64> {
        fn linear_cosine_similarity(a: &[f64], b: &[f64]) -> f64 {
            let mut dot_product = 0.0;
            let mut norm_a = 0.0;
            let mut norm_b = 0.0;

            for (index, &x) in a.iter().enumerate() {
                let y = b.get(index).copied().unwrap_or(f64::NAN);
                dot_product += x * y;
                norm_a += x * x;
                norm_b += y * y;
            }

            let norm_a: f64 = f64::sqrt(norm_a);
            let norm_b: f64 = f64::sqrt(norm_b);

            let similarity =
                if norm_a != 0.0 && norm_b != 0.0 && !norm_a.is_nan() && !norm_b.is_nan() {
                    dot_product / (norm_a * norm_b)
                } else {
                    0.0
                };

            1.0 - similarity.clamp(-1.0, 1.0).acos() / std::f64::consts::PI
        }
        match (&a.embedding, &b.embedding) {
            (Some(a), Some(b)) => Ok(linear_cosine_similarity(a, b)),
            _ => Err(Error::Message(
                "Both utterance formats must be embedded before computing distance. Call embed() first."
                    .to_string(),
            )),
        }
    }

    pub fn tool(time: Option<f64>) -> Tool {
        let time = time.filter(|time| *time != 0.0 && !time.is_nan());
        Tool {
            function: super::generative::Function {
                name: "return_text".to_string(),
                description: Some(format!(
                    "Return a free-form text response {}.",
                    time.map_or(String::new(), |time| format!(" within {time} seconds)"))
                )),
                parameters: schema(json!({
                    "type": "OBJECT",
                    "properties": {
                        "content": { "type": "STRING", "description": "The text response." }
                    },
                    "required": ["content"]
                })),
                default: None,
                example: None,
                behavior: None,
            },
            evaluate: evaluate("content"),
            instruction: Some(Arc::new(move |_params: &Value| {
                format!(
                    "Use the tool \"return_text\" to return your answer as a string of {}.",
                    time.map_or("any length".to_string(), |time| format!(
                        "length within {time} seconds"
                    ))
                )
            })),
        }
    }
}