Skip to main content

kalosm_language_model/openai/
mod.rs

1use std::sync::OnceLock;
2
3use thiserror::Error;
4
5mod embedding;
6pub use embedding::*;
7
8mod chat;
9pub use chat::*;
10
11/// A client for making requests to an OpenAI compatible API.
12#[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    /// Create a new client.
30    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    /// Sets the API key for the builder. (defaults to the environment variable `OPENAI_API_KEY`)
42    ///
43    /// The API key can be accessed from the OpenAI dashboard [here](https://platform.openai.com/settings/organization/api-keys).
44    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    /// Set the base URL of the API. (defaults to `https://api.openai.com/v1/`)
50    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    /// Set the organization ID for the builder.
56    ///
57    /// The organization ID can be accessed from the OpenAI dashboard [here](https://platform.openai.com/settings/organization/general).
58    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    /// Set the project ID for the builder.
64    ///
65    /// The project ID can be accessed from the OpenAI dashboard [here](https://platform.openai.com/settings/organization/projects).
66    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    /// Set the reqwest client for the builder.
72    pub fn with_reqwest_client(mut self, client: reqwest::Client) -> Self {
73        self.reqwest_client = client;
74        self
75    }
76
77    /// Resolve the openai API key from the environment variable `OPENAI_API_KEY` or the provided api key.
78    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    /// Get the base URL for the OpenAI API.
94    pub(crate) fn base_url(&self) -> &str {
95        self.base_url.trim_end_matches('/')
96    }
97}
98
99/// An error that can occur when building a remote OpenAI model without an API key.
100#[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;