use super::ApiKind;
use crate::{AiOptions, chunk::ResponseError, prelude::*};
use reqwest::{Client, Proxy, header};
use std::time::Duration;
#[derive(Debug, Display, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum EmbeddingSearch {
#[display(fmt = "search_document")]
Document,
#[display(fmt = "search_query")]
Query,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Usage {
pub total_tokens: usize,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EmbeddingsData {
pub object: String,
pub data: Vec<Embedding>,
pub model: String,
pub usage: Usage,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Embedding {
pub object: String,
pub index: usize,
pub embedding: Vec<f32>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Embeddings {
#[serde(skip)]
pub api_version: Option<String>,
#[serde(skip)]
pub api_kind: ApiKind,
#[serde(skip)]
pub api_key: String,
#[serde(skip)]
pub host: Option<String>,
#[serde(skip)]
pub proxy: Option<Proxy>,
#[serde(skip)]
pub timeout: Duration,
pub model: String,
pub input: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub search: Option<EmbeddingSearch>,
}
impl Embeddings {
pub fn new(kind: ApiKind, key: impl Into<String>, model: impl Into<String>) -> Self {
Self {
host: if kind.is_lmstudio() {
Some(str!("http://127.0.0.1:1234"))
} else {
None
},
api_version: if kind.is_anthropic() {
Some(str!("2023-06-01"))
} else {
None
},
api_kind: kind,
api_key: key.into(),
proxy: None,
timeout: Duration::from_secs(30),
model: model.into(),
input: Vec::new(),
search: None,
}
}
pub fn openai(key: impl Into<String>, model: impl Into<String>) -> Self {
Self::new(ApiKind::OpenAI, key, model)
}
pub fn anthropic(key: impl Into<String>, model: impl Into<String>) -> Self {
Self::new(ApiKind::Voyage, key, model)
}
pub fn lmstudio(key: impl Into<String>, model: impl Into<String>) -> Self {
Self::new(ApiKind::LmStudio, key, model)
}
pub fn chatgpt(key: impl Into<String>, model: impl Into<String>) -> Self {
Self::new(ApiKind::ChatGpt, key, model)
}
pub fn cerebras(key: impl Into<String>, model: impl Into<String>) -> Self {
Self::new(ApiKind::Cerebras, key, model)
}
pub fn claude(key: impl Into<String>, model: impl Into<String>) -> Self {
Self::new(ApiKind::Voyage, key, model)
}
pub fn openrouter(key: impl Into<String>, model: impl Into<String>) -> Self {
Self::new(ApiKind::OpenRouter, key, model)
}
pub fn perplexity(key: impl Into<String>, model: impl Into<String>) -> Self {
Self::new(ApiKind::Perplexity, key, model)
}
pub fn voyage(key: impl Into<String>, model: impl Into<String>) -> Self {
Self::new(ApiKind::Voyage, key, model)
}
pub fn google(key: impl Into<String>, model: impl Into<String>) -> Self {
Self::new(ApiKind::Google, key, model)
}
pub fn gemini(key: impl Into<String>, model: impl Into<String>) -> Self {
Self::new(ApiKind::Gemini, key, model)
}
pub fn set_key(&mut self, key: impl Into<String>) {
self.api_key = key.into();
}
pub fn key(mut self, key: impl Into<String>) -> Self {
self.set_key(key);
self
}
pub fn host(mut self, url: impl Into<String>) -> Self {
self.host = Some(url.into());
self
}
pub fn proxy(mut self, proxy: Proxy) -> Self {
self.proxy = Some(proxy);
self
}
pub fn timeout(mut self, dur: Duration) -> Self {
self.timeout = dur;
self
}
pub fn timeout_secs(mut self, secs: u64) -> Self {
self.timeout = Duration::from_secs(secs);
self
}
pub fn timeout_ms(mut self, secs: u64) -> Self {
self.timeout = Duration::from_millis(secs);
self
}
pub fn model(mut self, model: impl Into<String>) -> Self {
self.model = model.into();
self
}
pub fn input(mut self, input: impl Into<String>) -> Self {
self.input.push(input.into());
self
}
pub fn search(mut self, search: EmbeddingSearch) -> Self {
self.search = Some(search);
self
}
pub fn document(self) -> Self {
self.search(EmbeddingSearch::Document)
}
pub fn query(self) -> Self {
self.search(EmbeddingSearch::Query)
}
pub async fn send(&mut self) -> Result<EmbeddingsData> {
let url = if let Some(host) = &self.host {
str!(
"{host}{}{}",
if host.ends_with("/") { "" } else { "/" },
self.api_kind.embeddings_path(&self.model)
)
} else {
str!(
"{}/{}",
self.api_kind.host(),
self.api_kind.embeddings_path(&self.model)
)
};
let mut data = json::to_value(&self).map_err(Error::from)?;
let obj = data.as_object_mut().unwrap();
if self.api_kind.is_google() {
let parts: Vec<JsonValue> = self
.input
.iter()
.map(|text| json!({ "text": text }))
.collect();
*obj = json!({
"content": { "parts": parts }
})
.as_object()
.unwrap()
.clone();
}
let mut client = Client::builder().timeout(self.timeout);
if let Some(proxy) = self.proxy.take() {
client = client.proxy(proxy);
client = client.danger_accept_invalid_certs(true); }
let mut request = client
.build()?
.post(&url)
.header(header::CONTENT_TYPE, "application/json")
.json(&obj);
if self.api_kind.is_google() {
request = request.header("x-goog-api-key", &self.api_key);
} else {
request = request.header(header::AUTHORIZATION, str!("Bearer {}", self.api_key));
}
let response = request.send().await.map_err(Error::from)?;
let output = response.text().await?;
if let Some(e) = ResponseError::from_str(&output) {
return Err(Error::ResponseError(e).into());
}
let embeddings = json::from_str(&output)?;
Ok(embeddings)
}
}
impl TryFrom<AiOptions> for Embeddings {
type Error = DynError;
fn try_from(ops: AiOptions) -> Result<Self> {
let mut this = Self::new(
ops.kind,
if let Some(v) = ops.env_var.as_ref() {
std::env::var(v).unwrap_or_default()
} else {
String::new()
},
ops.model,
);
if let Some(host) = ops.server.as_ref() {
this = this.host(host.to_owned());
}
if let Some(proxy) = ops.proxy.as_ref() {
this = this.proxy(Proxy::all(proxy.to_owned())?);
}
Ok(this)
}
}