kalosm_language_model/openai/
mod.rs1use std::sync::OnceLock;
2
3use thiserror::Error;
4
5mod embedding;
6pub use embedding::*;
7
8mod chat;
9pub use chat::*;
10
11#[derive(Debug, Clone)]
13pub struct OpenAICompatibleClient {
14 reqwest_client: reqwest::Client,
15 base_url: String,
16 api_key: Option<String>,
17 resolved_api_key: OnceLock<String>,
18 organization_id: Option<String>,
19 project_id: Option<String>,
20}
21
22impl Default for OpenAICompatibleClient {
23 fn default() -> Self {
24 Self::new()
25 }
26}
27
28impl OpenAICompatibleClient {
29 pub fn new() -> Self {
31 Self {
32 reqwest_client: reqwest::Client::new(),
33 base_url: "https://api.openai.com/v1/".to_string(),
34 resolved_api_key: OnceLock::new(),
35 api_key: None,
36 organization_id: None,
37 project_id: None,
38 }
39 }
40
41 pub fn with_api_key(mut self, api_key: impl ToString) -> Self {
45 self.api_key = Some(api_key.to_string());
46 self
47 }
48
49 pub fn with_base_url(mut self, base_url: impl ToString) -> Self {
51 self.base_url = base_url.to_string();
52 self
53 }
54
55 pub fn with_organization_id(mut self, organization_id: impl ToString) -> Self {
59 self.organization_id = Some(organization_id.to_string());
60 self
61 }
62
63 pub fn with_project_id(mut self, project_id: impl ToString) -> Self {
67 self.project_id = Some(project_id.to_string());
68 self
69 }
70
71 pub fn with_reqwest_client(mut self, client: reqwest::Client) -> Self {
73 self.reqwest_client = client;
74 self
75 }
76
77 pub fn resolve_api_key(&self) -> Result<String, NoOpenAIAPIKeyError> {
79 if let Some(api_key) = self.resolved_api_key.get() {
80 return Ok(api_key.clone());
81 }
82
83 let open_api_key = match self.api_key.clone() {
84 Some(api_key) => api_key,
85 None => std::env::var("OPENAI_API_KEY").map_err(|_| NoOpenAIAPIKeyError)?,
86 };
87
88 self.resolved_api_key.set(open_api_key.clone()).unwrap();
89
90 Ok(open_api_key)
91 }
92
93 pub(crate) fn base_url(&self) -> &str {
95 self.base_url.trim_end_matches('/')
96 }
97}
98
99#[derive(Debug, Error)]
101#[error("No API key was provided in the [OpenAICompatibleClient] builder or the environment variable `OPENAI_API_KEY` was not set")]
102pub struct NoOpenAIAPIKeyError;