kind_openai/endpoints/
embeddings.rs

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
use bon::Builder;
use reqwest::Method;
use serde::{Deserialize, Serialize};

use super::OpenAIRequestProvider;

/// The model used to create text embeddings.
#[derive(Serialize, Debug, Clone, Copy)]
pub enum EmbeddingsModel {
    #[serde(rename = "text-embedding-3-large")]
    TextEmbedding3Large,
}

/// A text embeddings creation request.
///
/// Construct with `Embeddings::model`
#[derive(Serialize, Debug, Clone, Builder)]
#[builder(start_fn = model)]
pub struct Embeddings<'a> {
    #[builder(start_fn)]
    model: EmbeddingsModel,
    input: &'a str,
}

impl OpenAIRequestProvider for Embeddings<'_> {
    type Response = EmbeddingsResponse;

    const METHOD: reqwest::Method = Method::POST;

    fn path_with_leading_slash() -> String {
        "/embeddings".to_string()
    }
}

impl super::private::Sealed for Embeddings<'_> {}

#[derive(Deserialize)]
pub struct EmbeddingsResponse {
    data: Vec<EmbeddingsData>,
}

impl EmbeddingsResponse {
    /// Consumes the response and gives the embeddings.
    pub fn embedding(self) -> Vec<f32> {
        self.data
            .into_iter()
            .next()
            .map(|d| d.embedding)
            .unwrap_or_default()
    }

    /// Gives a reference to the generated embeddings.
    pub fn embedding_ref(&self) -> &[f32] {
        &self.data[0].embedding
    }
}

#[derive(Deserialize)]
struct EmbeddingsData {
    embedding: Vec<f32>,
}