Skip to main content

openai_oxide/
config.rs

1// Client configuration
2
3use std::env;
4
5const DEFAULT_BASE_URL: &str = "https://api.openai.com/v1";
6const DEFAULT_TIMEOUT_SECS: u64 = 600;
7const DEFAULT_MAX_RETRIES: u32 = 2;
8
9/// Configuration for the OpenAI client.
10#[derive(Debug, Clone)]
11pub struct ClientConfig {
12    pub api_key: String,
13    pub base_url: String,
14    pub organization: Option<String>,
15    pub project: Option<String>,
16    pub timeout_secs: u64,
17    pub max_retries: u32,
18}
19
20impl ClientConfig {
21    /// Create a new config with the given API key.
22    pub fn new(api_key: impl Into<String>) -> Self {
23        Self {
24            api_key: api_key.into(),
25            base_url: DEFAULT_BASE_URL.to_string(),
26            organization: None,
27            project: None,
28            timeout_secs: DEFAULT_TIMEOUT_SECS,
29            max_retries: DEFAULT_MAX_RETRIES,
30        }
31    }
32
33    /// Create config from the `OPENAI_API_KEY` environment variable.
34    pub fn from_env() -> Result<Self, crate::error::OpenAIError> {
35        let api_key = env::var("OPENAI_API_KEY").map_err(|_| {
36            crate::error::OpenAIError::InvalidArgument(
37                "OPENAI_API_KEY environment variable not set".to_string(),
38            )
39        })?;
40        Ok(Self::new(api_key))
41    }
42
43    pub fn base_url(mut self, url: impl Into<String>) -> Self {
44        self.base_url = url.into();
45        self
46    }
47
48    pub fn organization(mut self, org: impl Into<String>) -> Self {
49        self.organization = Some(org.into());
50        self
51    }
52
53    pub fn project(mut self, project: impl Into<String>) -> Self {
54        self.project = Some(project.into());
55        self
56    }
57
58    pub fn timeout_secs(mut self, secs: u64) -> Self {
59        self.timeout_secs = secs;
60        self
61    }
62
63    pub fn max_retries(mut self, retries: u32) -> Self {
64        self.max_retries = retries;
65        self
66    }
67}