kind_openai/endpoints/
embeddings.rs

1use bon::Builder;
2use reqwest::Method;
3use serde::{Deserialize, Serialize};
4
5use super::OpenAIRequestProvider;
6
7/// The model used to create text embeddings.
8#[derive(Serialize, Debug, Clone, Copy)]
9pub enum EmbeddingsModel {
10    #[serde(rename = "text-embedding-3-large")]
11    TextEmbedding3Large,
12}
13
14/// A text embeddings creation request.
15///
16/// Construct with `Embeddings::model`
17#[derive(Serialize, Debug, Clone, Builder)]
18#[builder(start_fn = model)]
19pub struct Embeddings<'a> {
20    #[builder(start_fn)]
21    model: EmbeddingsModel,
22    input: &'a str,
23}
24
25impl OpenAIRequestProvider for Embeddings<'_> {
26    type Response = EmbeddingsResponse;
27
28    const METHOD: reqwest::Method = Method::POST;
29
30    fn path_with_leading_slash() -> String {
31        "/embeddings".to_string()
32    }
33}
34
35impl super::private::Sealed for Embeddings<'_> {}
36
37#[derive(Deserialize)]
38pub struct EmbeddingsResponse {
39    data: Vec<EmbeddingsData>,
40}
41
42impl EmbeddingsResponse {
43    /// Consumes the response and gives the embeddings.
44    pub fn embedding(self) -> Vec<f32> {
45        self.data
46            .into_iter()
47            .next()
48            .map(|d| d.embedding)
49            .unwrap_or_default()
50    }
51
52    /// Gives a reference to the generated embeddings.
53    pub fn embedding_ref(&self) -> &[f32] {
54        &self.data[0].embedding
55    }
56}
57
58#[derive(Deserialize)]
59struct EmbeddingsData {
60    embedding: Vec<f32>,
61}