claude-cost 0.1.0

Calculate Claude API call cost from a usage block. Cache-aware (cache_creation, cache_read), supports Anthropic API and AWS Bedrock model IDs, BYO pricing override. No SDK dependency.
Documentation
//! Token usage block.

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Four-field token usage as returned by Anthropic API and Bedrock Converse.
///
/// Field names match Anthropic's API; the `From` impls in this crate map
/// Bedrock Converse's camelCase names (`cacheReadInputTokens`,
/// `cacheWriteInputTokens` -> `cache_creation_input_tokens`) onto these.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct Usage {
    /// Tokens in the input prompt that were not cached.
    pub input_tokens: u64,
    /// Tokens in the model output.
    pub output_tokens: u64,
    /// Tokens written to the prompt cache on this request (cache miss).
    pub cache_creation_input_tokens: u64,
    /// Tokens served from the prompt cache (cache hit).
    pub cache_read_input_tokens: u64,
}

impl Usage {
    /// True when the request hit the prompt cache.
    pub fn cache_hit(&self) -> bool {
        self.cache_read_input_tokens > 0
    }

    /// Total tokens billed (input + output + cache_creation + cache_read).
    pub fn total_tokens(&self) -> u64 {
        self.input_tokens
            + self.output_tokens
            + self.cache_creation_input_tokens
            + self.cache_read_input_tokens
    }

    /// Build a Usage from Bedrock Converse's camelCase JSON shape.
    ///
    /// The `inputTokens` field on Bedrock includes only fresh input (cache
    /// fields are reported separately), so we map them 1:1.
    pub fn from_bedrock_converse(
        input_tokens: u64,
        output_tokens: u64,
        cache_read_input_tokens: u64,
        cache_write_input_tokens: u64,
    ) -> Self {
        Self {
            input_tokens,
            output_tokens,
            cache_creation_input_tokens: cache_write_input_tokens,
            cache_read_input_tokens,
        }
    }
}