rusty_openai/openai_api/embeddings.rs
1use crate::{error_handling::OpenAIResult, openai::OpenAI};
2use serde::Serialize;
3use serde_json::Value;
4
5/// [`EmbeddingsApi`] struct to interact with the embeddings endpoint of the API.
6pub struct EmbeddingsApi<'a>(pub(crate) &'a OpenAI<'a>);
7
8#[derive(Serialize)]
9struct AssistantRequest<'a> {
10 /// The input text for which to create embeddings.
11 input: &'a str,
12
13 /// Embedding model to use
14 model: &'a str,
15
16 /// Optional encoding format
17 #[serde(skip_serializing_if = "Option::is_none")]
18 encoding_format: Option<&'a str>,
19
20 /// Optional number of dimensions
21 #[serde(skip_serializing_if = "Option::is_none")]
22 dimensions: Option<u64>,
23
24 /// Optional user ID
25 #[serde(skip_serializing_if = "Option::is_none")]
26 user: Option<&'a str>,
27}
28
29impl<'a> EmbeddingsApi<'a> {
30 /// Create an embedding using the provided parameters.
31 ///
32 /// # Arguments
33 ///
34 /// * `input` - The input text for which to create embeddings.
35 /// * `model` - The name of the model to use for creating embeddings.
36 /// * `encoding_format` - Optional encoding format.
37 /// * `dimensions` - Optional number of dimensions for the embeddings.
38 /// * `user` - Optional user ID.
39 ///
40 /// # Returns
41 ///
42 /// A Result containing the JSON response as [`serde_json::Value`] on success, or an [`OpenAIError`][crate::error_handling::OpenAIError] on failure.
43 pub async fn create(
44 &self,
45 input: &str,
46 model: &str, // Embedding model to use
47 encoding_format: Option<&str>, // Optional encoding format
48 dimensions: Option<u64>, // Optional number of dimensions
49 user: Option<&str>, // Optional user ID
50 ) -> OpenAIResult<Value> {
51 // Initialize a JSON object to build the request body.
52 let body = AssistantRequest {
53 input,
54 model,
55 encoding_format,
56 dimensions,
57 user,
58 };
59
60 // Send a POST request to the embeddings endpoint with the request body.
61 self.0.post_json("/embeddings", &body).await
62 }
63}