use super::ApiKind;
use crate::{AiOptions, error::ResponseError, prelude::*};
use reqwest::{Client, Proxy, header};
use std::time::Duration;
#[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 server: Option<String>,
#[serde(skip)]
pub proxy: Option<Proxy>,
#[serde(skip)]
pub timeout: Duration,
pub model: String,
pub input: Vec<String>,
}
impl Embeddings {
pub fn new(kind: ApiKind, key: impl Into<String>, model: impl Into<String>) -> Self {
Self {
server: if kind == ApiKind::LmStudio {
Some(str!("http://127.0.0.1:1234"))
} else {
None
},
api_version: if kind.is_anthropic_standart() {
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(),
}
}
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 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 set_server(&mut self, url: impl Into<String>) {
self.server = Some(url.into());
}
pub fn server(mut self, url: impl Into<String>) -> Self {
self.set_server(url);
self
}
pub fn set_proxy(&mut self, proxy: Proxy) {
self.proxy = Some(proxy);
}
pub fn proxy(mut self, proxy: Proxy) -> Self {
self.set_proxy(proxy);
self
}
pub fn set_timeout(&mut self, dur: Duration) {
self.timeout = dur;
}
pub fn timeout(mut self, dur: Duration) -> Self {
self.set_timeout(dur);
self
}
pub fn set_timeout_secs(&mut self, secs: u64) {
self.timeout = Duration::from_secs(secs);
}
pub fn timeout_secs(mut self, secs: u64) -> Self {
self.set_timeout_secs(secs);
self
}
pub fn set_timeout_ms(&mut self, secs: u64) {
self.timeout = Duration::from_millis(secs);
}
pub fn timeout_ms(mut self, secs: u64) -> Self {
self.set_timeout_ms(secs);
self
}
pub fn set_model(&mut self, model: impl Into<String>) {
self.model = model.into();
}
pub fn model(mut self, model: impl Into<String>) -> Self {
self.set_model(model);
self
}
pub fn add_input(&mut self, input: impl Into<String>) {
self.input.push(input.into());
}
pub fn input(mut self, input: impl Into<String>) -> Self {
self.add_input(input);
self
}
pub async fn send(&mut self) -> Result<EmbeddingsData> {
let url = if let Some(url) = &self.server {
self.api_kind.custom_embeddings_url(url)
} else {
self.api_kind.embeddings_url()
};
let mut data = json::to_value(&self).map_err(Error::from)?;
let obj = data.as_object_mut().unwrap();
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 response = client
.build()?
.post(&url)
.header(header::CONTENT_TYPE, "application/json")
.header(header::AUTHORIZATION, &self.api_key)
.json(&obj)
.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.set_server(host.to_owned());
}
if let Some(proxy) = ops.proxy.as_ref() {
this.set_proxy(Proxy::all(proxy.to_owned())?);
}
Ok(this)
}
}