cetai 0.1.1

Typed prompt! expressions and #[ai] functions for natural-language tasks over DeepSeek.
Documentation
//! Error type for all expected runtime failures.
//!
//! `Display` and `Debug` never include API keys, full inputs or full model
//! outputs: only statuses, request IDs, short summaries and content
//! length/hash fingerprints.

use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;

/// Result alias used by every cetai operation.
pub type Result<T> = std::result::Result<T, AiError>;

/// Errors returned by `prompt!` / `#[ai]` calls and configuration.
#[derive(Debug, thiserror::Error)]
pub enum AiError {
    /// No DeepSeek API key was provided by `AiConfig` or the environment.
    #[error("missing DeepSeek API key: set DEEPSEEK_API_KEY or provide one via AiConfig")]
    MissingApiKey,

    /// A configuration value is invalid, or `init` was called twice.
    #[error("invalid configuration: {0}")]
    InvalidConfig(String),

    /// An input parameter could not be serialized to JSON.
    #[error("failed to serialize an input parameter to JSON: {0}")]
    InputSerialization(String),

    /// No valid example could be generated for the return schema; no API
    /// request was sent.
    #[error("unsupported output schema: {0}")]
    UnsupportedSchema(String),

    /// Connection, transport or per-attempt timeout failure.
    #[error("http error after {attempts} attempt(s): {summary}")]
    Http {
        /// Number of physical HTTP attempts made.
        attempts: u32,
        /// Short redacted summary of the transport failure.
        summary: String,
    },

    /// DeepSeek returned a non-success status or an abnormal response.
    #[error("api error (status: {status:?}, request id: {request_id:?}): {summary}")]
    Api {
        /// HTTP status code, if a response was received.
        status: Option<u16>,
        /// DeepSeek request ID header, when present.
        request_id: Option<String>,
        /// Short redacted summary of the failure.
        summary: String,
    },

    /// A successful response carried no usable content.
    #[error("empty model content (request id: {request_id:?})")]
    EmptyContent {
        /// DeepSeek request ID header, when present.
        request_id: Option<String>,
    },

    /// The model content was not valid JSON.
    #[error(
        "model output is not valid JSON (request id: {request_id:?}, {content_len} bytes, hash {content_hash:#x}): {summary}"
    )]
    JsonParse {
        /// DeepSeek request ID header, when present.
        request_id: Option<String>,
        /// Byte length of the model output.
        content_len: usize,
        /// Non-cryptographic fingerprint of the model output.
        content_hash: u64,
        /// Short redacted summary of the parse failure.
        summary: String,
    },

    /// The model output did not conform to the output envelope schema.
    #[error(
        "model output failed schema validation (request id: {request_id:?}, {content_len} bytes, hash {content_hash:#x}): {summary}"
    )]
    SchemaValidation {
        /// DeepSeek request ID header, when present.
        request_id: Option<String>,
        /// Byte length of the model output.
        content_len: usize,
        /// Non-cryptographic fingerprint of the model output.
        content_hash: u64,
        /// Short redacted summary of the validation failure.
        summary: String,
    },

    /// The output passed schema validation but could not be deserialized into
    /// the target type `T`.
    #[error(
        "model output passed schema validation but failed deserialization ({content_len} bytes, hash {content_hash:#x}): {summary}"
    )]
    OutputDeserialization {
        /// Byte length of the model output.
        content_len: usize,
        /// Non-cryptographic fingerprint of the model output.
        content_hash: u64,
        /// Short redacted summary of the deserialization failure.
        summary: String,
    },
}

/// Computes a stable-enough fingerprint of model output for debugging without
/// revealing the content itself.
pub(crate) fn content_fingerprint(content: &str) -> u64 {
    let mut hasher = DefaultHasher::new();
    hasher.write(content.as_bytes());
    hasher.finish()
}

/// Truncates a (possibly model- or server-provided) message to a bounded
/// single-line summary so errors stay compact and redacted.
pub(crate) fn summarize(message: &str, max_chars: usize) -> String {
    let flattened: String = message.split_whitespace().collect::<Vec<_>>().join(" ");
    let mut out: String = flattened.chars().take(max_chars).collect();
    if flattened.chars().count() > max_chars {
        out.push('…');
    }
    out
}