alith_interface/llms/api/
config.rs1use reqwest::header::HeaderMap;
2use secrecy::SecretString;
3
4#[derive(Clone, Debug)]
5pub struct ApiConfig {
6 pub host: String,
7 pub port: Option<String>,
8 pub api_key: Option<SecretString>,
9 pub api_key_env_var: String,
10}
11
12impl ApiConfig {
13 pub(crate) fn load_api_key(&mut self) -> crate::Result<SecretString> {
14 if let Some(api_key) = self.api_key.as_ref() {
15 crate::trace!("Using api_key from parameter");
16 return Ok(api_key.to_owned());
17 }
18 crate::trace!("api_key not set. Attempting to load from .env");
19 dotenvy::dotenv().ok();
20
21 match dotenvy::var(&self.api_key_env_var) {
22 Ok(api_key) => {
23 crate::trace!("Successfully loaded api_key from .env");
24 Ok(api_key.into())
25 }
26 Err(_) => {
27 crate::trace!(
28 "{} not found in dotenv, nor was it set manually",
29 self.api_key_env_var
30 );
31 crate::bail!("Failed to load api_key from parameter or .env")
32 }
33 }
34 }
35}
36
37pub trait LLMApiConfigTrait {
38 fn api_base_config_mut(&mut self) -> &mut ApiConfig;
39
40 fn api_config(&self) -> &ApiConfig;
41
42 fn with_api_host<S: AsRef<str>>(mut self, host: S) -> Self
43 where
44 Self: Sized,
45 {
46 self.api_base_config_mut().host = host.as_ref().to_string();
47 self
48 }
49
50 fn with_api_port<S: AsRef<str>>(mut self, port: S) -> Self
51 where
52 Self: Sized,
53 {
54 self.api_base_config_mut().port = Some(port.as_ref().to_string());
55 self
56 }
57
58 fn with_api_key<S: Into<String>>(mut self, api_key: S) -> Self
59 where
60 Self: Sized,
61 {
62 self.api_base_config_mut().api_key = Some(SecretString::from(api_key.into()));
63 self
64 }
65
66 fn with_api_key_env_var<S: Into<String>>(mut self, api_key_env_var: S) -> Self
68 where
69 Self: Sized,
70 {
71 self.api_base_config_mut().api_key_env_var = api_key_env_var.into();
72 self
73 }
74}
75
76pub trait ApiConfigTrait {
77 fn headers(&self) -> HeaderMap;
78
79 fn url(&self, path: &str) -> String;
80
81 fn api_key(&self) -> &Option<SecretString>;
82}