mastermind_cli/api/
mod.rs

1use crate::configs::config::Config;
2use dotenv::dotenv;
3use std::env;
4
5mod chat_completions;
6mod models;
7
8pub struct Instance {
9    client: reqwest::Client,
10    base_url: String,
11    api_key: String,
12}
13
14impl Instance {
15    pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
16        let config = Config::new()?;
17        dotenv().ok();
18
19        let base_url =
20            Self::read_from_env_or_config_file("OPENAI_API_BASE_URL", config.get_base_url())?;
21
22        let base_url = if !base_url.ends_with('/') {
23            format!("{base_url}/")
24        } else {
25            base_url
26        };
27
28        let api_key = Self::read_from_env_or_config_file("API_KEY", config.get_api_key())?;
29
30        Ok(Self {
31            client: reqwest::Client::new(),
32            base_url,
33            api_key,
34        })
35    }
36
37    fn read_from_env_or_config_file(
38        envvar: &str,
39        config_value: Option<&str>,
40    ) -> Result<String, Box<dyn std::error::Error>> {
41        match env::var(envvar) {
42            Ok(key) => Ok(key),
43            Err(_) => {
44                if let Some(config_key) = config_value {
45                    Ok(config_key.to_string())
46                } else {
47                    Err(format!(
48                        "Could not find environment variable '{envvar}' or any related configuration\nPlease check you config file"
49                    )
50                        .into())
51                }
52            }
53        }
54    }
55}
56
57#[cfg(test)]
58impl Instance {
59    pub(crate) fn set_base_url(&mut self, base_url: String) {
60        self.base_url = base_url;
61    }
62}
63
64#[cfg(test)]
65impl Default for Instance {
66    fn default() -> Self {
67        Self {
68            client: reqwest::Client::new(),
69            base_url: "".to_string(),
70            api_key: "".to_string(),
71        }
72    }
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78
79    #[test]
80    fn test_new() {
81        env::set_var("OPENAI_API_BASE_URL", "abc");
82        env::set_var("API_KEY", "def");
83
84        let api_instance = Instance::new().unwrap();
85        assert_eq!(api_instance.base_url, "abc/");
86        assert_eq!(api_instance.api_key, "def");
87    }
88
89    #[test]
90    fn test_default() {
91        let api_instance = Instance::default();
92        assert_eq!(api_instance.base_url, "");
93        assert_eq!(api_instance.api_key, "");
94    }
95}