replicate_rs/
config.rs

1//! Utilities for high level configuration for Replicate clients.
2//!
3use crate::errors::{ReplicateError, ReplicateResult};
4use crate::{api_key, base_url};
5use anyhow::anyhow;
6
7/// Config for Replicate Client
8#[derive(Clone, Debug)]
9pub struct ReplicateConfig {
10    /// [API token](https://replicate.com/account/api-tokens) for replicate
11    api_key: Option<&'static str>,
12    /// Endpoint url
13    base_url: String,
14}
15
16impl Default for ReplicateConfig {
17    fn default() -> Self {
18        ReplicateConfig {
19            api_key: None,
20            base_url: base_url().to_string(),
21        }
22    }
23}
24
25impl ReplicateConfig {
26    /// Create a default config, inherits api_key from REPLICATE_API_KEY environment variable
27    pub fn new() -> anyhow::Result<Self> {
28        let api_key = api_key()?;
29        let base_url = base_url().to_string();
30        anyhow::Ok(ReplicateConfig {
31            api_key: Some(api_key),
32            base_url,
33        })
34    }
35
36    #[cfg(test)]
37    pub fn test(base_url: String) -> anyhow::Result<Self> {
38        anyhow::Ok(ReplicateConfig {
39            api_key: Some("test-api-key"),
40            base_url,
41        })
42    }
43
44    pub(crate) fn get_api_key(&self) -> ReplicateResult<&'static str> {
45        self.api_key.ok_or(ReplicateError::MissingCredentials(
46            "REPLICATE_API_KEY not provided in environment variable".to_string(),
47        ))
48    }
49
50    pub(crate) fn get_base_url(&self) -> String {
51        self.base_url.clone()
52    }
53}