cetai 0.1.1

Typed prompt! expressions and #[ai] functions for natural-language tasks over DeepSeek.
Documentation
//! Runtime configuration: `AiConfig`, the `Thinking` level and environment
//! variable loading. Cetai never reads `.env` files itself.

use std::sync::Arc;

use secrecy::SecretString;

use crate::error::{AiError, Result};
use crate::Transport;

/// Default model name. This is an external fact that may change between
/// cetai releases; override it via `DEEPSEEK_MODEL` or `AiConfig`.
pub const DEFAULT_MODEL: &str = "deepseek-v4-flash";
/// Default DeepSeek API root.
pub const DEFAULT_BASE_URL: &str = "https://api.deepseek.com";

const DEFAULT_HTTP_RETRIES: u32 = 2;
const DEFAULT_REPAIR_RETRIES: u32 = 2;
/// Maximum output length of the current DeepSeek models, in tokens. This is
/// an external fact (see the pricing/models page) and may change between
/// cetai releases; it anchors the automatic `max_tokens` defaults below.
pub(crate) const MODEL_MAX_OUTPUT_TOKENS: u32 = 384_000;

/// Automatic `max_tokens` default per thinking level: 15% / 30% / 60% of
/// [`MODEL_MAX_OUTPUT_TOKENS`]. Thinking consumes output budget for
/// reasoning, so higher levels get larger defaults.
pub(crate) fn default_max_tokens(thinking: Thinking) -> u32 {
    match thinking {
        Thinking::Off => MODEL_MAX_OUTPUT_TOKENS * 15 / 100,
        Thinking::High => MODEL_MAX_OUTPUT_TOKENS * 30 / 100,
        Thinking::Max => MODEL_MAX_OUTPUT_TOKENS * 60 / 100,
    }
}
const DEFAULT_TIMEOUT_SECS: u64 = 900;
const DEFAULT_TEMPERATURE: f32 = 0.3;

/// Maximum accepted value for retry budgets.
pub const MAX_RETRIES: u32 = 10;

/// Reasoning effort for a call.
///
/// Only the common `OFF` / `HIGH` / `MAX` subset is exposed; the wire mapping
/// is defined by the DeepSeek thinking-mode documentation.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Thinking {
    /// Thinking disabled (`thinking.type = "disabled"`).
    #[default]
    Off,
    /// Thinking enabled with `reasoning_effort = "high"`.
    High,
    /// Thinking enabled with `reasoning_effort = "max"`.
    Max,
}

impl Thinking {
    /// `Thinking::Off` as an upper-case associated constant.
    pub const OFF: Self = Self::Off;
    /// `Thinking::High` as an upper-case associated constant.
    pub const HIGH: Self = Self::High;
    /// `Thinking::Max` as an upper-case associated constant.
    pub const MAX: Self = Self::Max;

    /// Wire value of `thinking.type`.
    pub(crate) fn wire_type(self) -> &'static str {
        match self {
            Thinking::Off => "disabled",
            Thinking::High | Thinking::Max => "enabled",
        }
    }

    /// Wire value of `reasoning_effort`, if any.
    pub(crate) fn reasoning_effort(self) -> Option<&'static str> {
        match self {
            Thinking::Off => None,
            Thinking::High => Some("high"),
            Thinking::Max => Some("max"),
        }
    }

    fn parse(text: &str) -> Result<Self> {
        match text {
            "off" => Ok(Thinking::Off),
            "high" => Ok(Thinking::High),
            "max" => Ok(Thinking::Max),
            other => Err(AiError::InvalidConfig(format!(
                "CETAI_THINKING must be one of `off`, `high`, `max`, got `{other}`"
            ))),
        }
    }
}

/// A complete runtime configuration.
///
/// Passed to [`crate::init`], the values are used as-is: no implicit
/// environment merging happens. Build from [`AiConfig::from_env`] first if
/// environment variables should participate.
#[derive(Clone)]
pub struct AiConfig {
    /// DeepSeek API key, stored redacted.
    pub api_key: SecretString,
    /// Model name.
    pub model: String,
    /// API root URL.
    pub base_url: String,
    /// Default thinking level.
    pub thinking: Thinking,
    /// Transient HTTP retries per logical model request.
    pub http_retries: u32,
    /// Model repair rounds after the initial generation.
    pub repair_retries: u32,
    /// Maximum output tokens per generation. `None` selects an automatic
    /// default based on the effective thinking level (15% / 30% / 60% of the
    /// model's maximum output).
    pub max_tokens: Option<u32>,
    /// Timeout of each physical HTTP attempt, in seconds.
    pub timeout_secs: u64,
    /// Sampling temperature for non-thinking mode.
    pub temperature: f32,
    /// HTTP transport used for requests and retry backoff sleeps. Defaults
    /// to the reqwest + tokio implementation when the `reqwest-transport`
    /// feature is enabled; `None` makes calls fail with
    /// [`AiError::InvalidConfig`] until a custom [`Transport`] is installed.
    pub transport: Option<Arc<dyn Transport>>,
}

impl std::fmt::Debug for AiConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AiConfig")
            .field("api_key", &"<redacted>")
            .field("model", &self.model)
            .field("base_url", &self.base_url)
            .field("thinking", &self.thinking)
            .field("http_retries", &self.http_retries)
            .field("repair_retries", &self.repair_retries)
            .field("max_tokens", &self.max_tokens)
            .field("timeout_secs", &self.timeout_secs)
            .field("temperature", &self.temperature)
            .field(
                "transport",
                &self
                    .transport
                    .as_ref()
                    .map_or("<none>", |transport| transport.name()),
            )
            .finish()
    }
}

impl AiConfig {
    /// Creates a configuration with the given API key and built-in defaults
    /// for every other field. Values are validated by [`AiConfig::validate`]
    /// and again before requests are sent.
    pub fn new(api_key: impl Into<String>) -> Self {
        AiConfig {
            api_key: SecretString::from(api_key.into()),
            model: DEFAULT_MODEL.to_string(),
            base_url: DEFAULT_BASE_URL.to_string(),
            thinking: Thinking::default(),
            http_retries: DEFAULT_HTTP_RETRIES,
            repair_retries: DEFAULT_REPAIR_RETRIES,
            max_tokens: None,
            timeout_secs: DEFAULT_TIMEOUT_SECS,
            temperature: DEFAULT_TEMPERATURE,
            transport: default_transport(),
        }
    }

    /// Builds a configuration from process environment variables, layered
    /// over the built-in defaults. Does not read or load `.env` files.
    pub fn from_env() -> Result<Self> {
        let env = |key: &str| std::env::var(key).ok();
        let api_key = env("DEEPSEEK_API_KEY")
            .map(SecretString::from)
            .unwrap_or_default();
        let thinking = match env("CETAI_THINKING") {
            Some(value) => Thinking::parse(&value)?,
            None => Thinking::default(),
        };
        let config = AiConfig {
            api_key,
            model: env("DEEPSEEK_MODEL").unwrap_or_else(|| DEFAULT_MODEL.to_string()),
            base_url: env("DEEPSEEK_BASE_URL").unwrap_or_else(|| DEFAULT_BASE_URL.to_string()),
            thinking,
            http_retries: parse_env_u32("CETAI_HTTP_RETRIES", DEFAULT_HTTP_RETRIES)?,
            repair_retries: parse_env_u32("CETAI_REPAIR_RETRIES", DEFAULT_REPAIR_RETRIES)?,
            max_tokens: parse_env_opt_u32("CETAI_MAX_TOKENS")?,
            timeout_secs: parse_env_u64("CETAI_TIMEOUT_SECS", DEFAULT_TIMEOUT_SECS)?,
            temperature: parse_env_f32("CETAI_TEMPERATURE", DEFAULT_TEMPERATURE)?,
            transport: default_transport(),
        };
        config.validate()?;
        Ok(config)
    }

    /// Validates all values before any request is sent.
    pub fn validate(&self) -> Result<()> {
        use secrecy::ExposeSecret;
        if self.api_key.expose_secret().is_empty() {
            return Err(AiError::MissingApiKey);
        }
        if self.model.trim().is_empty() {
            return Err(AiError::InvalidConfig(
                "model name must not be empty".to_string(),
            ));
        }
        for (key, value) in [
            ("http_retries", self.http_retries),
            ("repair_retries", self.repair_retries),
        ] {
            if value > MAX_RETRIES {
                return Err(AiError::InvalidConfig(format!(
                    "{key} must be in 0..={MAX_RETRIES}, got {value}"
                )));
            }
        }
        if self.max_tokens == Some(0) {
            return Err(AiError::InvalidConfig("max_tokens must be > 0".to_string()));
        }
        if self.timeout_secs == 0 {
            return Err(AiError::InvalidConfig(
                "timeout_secs must be > 0".to_string(),
            ));
        }
        if !self.temperature.is_finite() || !(0.0..=2.0).contains(&self.temperature) {
            return Err(AiError::InvalidConfig(format!(
                "temperature must be a finite number in 0.0..=2.0, got {}",
                self.temperature
            )));
        }
        normalize_base_url(&self.base_url)?;
        Ok(())
    }

    /// Returns the normalized base URL (validated, trailing slashes removed,
    /// existing path preserved).
    pub(crate) fn normalized_base_url(&self) -> Result<String> {
        normalize_base_url(&self.base_url)
    }
}

/// Default transport installed by [`AiConfig::new`] / [`AiConfig::from_env`]:
/// the reqwest + tokio implementation when the `reqwest-transport` feature is
/// enabled, otherwise none.
#[cfg(feature = "reqwest-transport")]
fn default_transport() -> Option<Arc<dyn Transport>> {
    Some(Arc::new(crate::deepseek::ReqwestTransport))
}

#[cfg(not(feature = "reqwest-transport"))]
fn default_transport() -> Option<Arc<dyn Transport>> {
    None
}

fn normalize_base_url(url: &str) -> Result<String> {
    let invalid =
        |reason: &str| AiError::InvalidConfig(format!("invalid base URL `{url}`: {reason}"));
    if !(url.starts_with("http://") || url.starts_with("https://")) {
        return Err(invalid("only http and https are supported"));
    }
    if url.contains(['?', '#']) {
        return Err(invalid("query and fragment are not allowed"));
    }
    Ok(url.trim_end_matches('/').to_string())
}

fn parse_env_u32(key: &str, default: u32) -> Result<u32> {
    parse_env(key, default, |v| v.parse().ok())
}

fn parse_env_opt_u32(key: &str) -> Result<Option<u32>> {
    match std::env::var(key) {
        Ok(value) => value.parse::<u32>().map(Some).map_err(|_| {
            AiError::InvalidConfig(format!("{key} has an invalid numeric value: `{value}`"))
        }),
        Err(_) => Ok(None),
    }
}

fn parse_env_u64(key: &str, default: u64) -> Result<u64> {
    parse_env(key, default, |v| v.parse().ok())
}

fn parse_env_f32(key: &str, default: f32) -> Result<f32> {
    parse_env(key, default, |v| v.parse().ok())
}

fn parse_env<T>(key: &str, default: T, parse: impl Fn(&str) -> Option<T>) -> Result<T> {
    match std::env::var(key) {
        Ok(value) => parse(&value).ok_or_else(|| {
            AiError::InvalidConfig(format!("{key} has an invalid numeric value: `{value}`"))
        }),
        Err(_) => Ok(default),
    }
}