-
Notifications
You must be signed in to change notification settings - Fork 13
/
embeddings.rs
77 lines (66 loc) · 2.42 KB
/
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Get a vector representation of a given input
// that can be easily consumed by machine learning models and algorithms.
// See: https://platform.openai.com/docs/api-reference/embeddings
//! Embeddings API
use serde::{Deserialize, Serialize};
use crate::requests::Requests;
use crate::*;
use super::{Usage, EMBEDDINGS_CREATE};
#[derive(Debug, Serialize, Deserialize)]
pub struct EmbeddingsBody {
/// ID of the model to use. You can use the List models API to see all of your available models,
/// or see our Model overview for descriptions of them.
pub model: String,
/// Input text to get embeddings for, encoded as a string or array of tokens. To get embeddings for multiple inputs in a single request,
/// pass an array of strings or array of token arrays. Each input must not exceed 8192 tokens in length.
pub input: Vec<String>,
/// A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.
#[serde(skip_serializing_if = "Option::is_none")]
pub user: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Embeddings {
pub object: Option<String>,
pub data: Option<Vec<EmbeddingData>>,
pub model: String,
pub usage: Usage,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct EmbeddingData {
pub object: Option<String>,
pub embedding: Option<Vec<f64>>,
pub index: i32,
}
pub trait EmbeddingsApi {
/// Creates an embedding vector representing the input text.
fn embeddings_create(&self, embeddings_body: &EmbeddingsBody) -> ApiResult<Embeddings>;
}
impl EmbeddingsApi for OpenAI {
fn embeddings_create(&self, embeddings_body: &EmbeddingsBody) -> ApiResult<Embeddings> {
let request_body = serde_json::to_value(embeddings_body).unwrap();
let res = self.post(EMBEDDINGS_CREATE, request_body)?;
let embeddings: Embeddings = serde_json::from_value(res.clone()).unwrap();
Ok(embeddings)
}
}
#[cfg(test)]
mod tests {
use crate::{
apis::embeddings::{EmbeddingsApi, EmbeddingsBody},
openai::new_test_openai,
};
#[test]
fn test_embedding_create() {
let openai = new_test_openai();
let body = EmbeddingsBody {
model: "text-embedding-ada-002".to_string(),
input: vec!["The food was delicious and the waiter...".to_string()],
user: None,
};
let rs = openai.embeddings_create(&body);
let embeddings = rs.unwrap().data;
let embedding = embeddings.as_ref().unwrap().get(0).unwrap();
let f = embedding.embedding.as_ref().unwrap();
assert!(!f.is_empty());
}
}