Skip to main content

Crate cortex_rs_stats

Crate cortex_rs_stats 

Source
Expand description

§relay-stats

license

Usage and cost dashboard from Anthropic/OpenAI org API or local log scraper.

§Overview

relay-stats fetches rolling cost and token usage data from provider APIs (Anthropic, OpenAI) if admin keys are configured, with fallback to scraping local ~/.claude/ session files. It computes per-model costs using cortex.yaml pricing and calculates routing savings by comparing chosen model cost against baseline model cost.

§Usage

Add as a dependency:

[dependencies]
relay-stats = { path = "../relay-stats" }
relay-core = { path = "../relay-core" }
tokio = { version = "1" }

Example:

use cortex_rs_stats::StatsEngine;
use cortex_rs_core::CortexConfig;
use std::path::Path;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let config = CortexConfig::load(Path::new("/Users/me/.cortex/cortex.yaml"))?;
    let engine = StatsEngine::new(config);
    
    // Fetch 7-day summary (tries provider API, falls back to log scraper)
    let summary = engine.fetch_summary(7).await?;
    println!("Total cost: ${:.2}", summary.total_cost_usd);
    println!("Routing savings: ${:.2}", summary.routing_savings_usd);
    println!("Source: {:?}", summary.source);
    
    for model_usage in &summary.by_model {
        println!("{}: {} tokens, ${:.2}", model_usage.model, model_usage.input_tokens, model_usage.cost_usd);
    }
    
    Ok(())
}

§Public API

  • StatsEngine::new(config) - initialize from CortexConfig
  • StatsEngine::fetch_summary(days) - fetch rolling usage (async)
  • UsageSummary - contains by_model vec, total_cost_usd, routing_savings_usd, source
  • ModelUsage - per-model breakdown with token counts and cost
  • StatsSource - enum: ProviderApi, LocalLogScraper, or Unavailable

§Dependencies

  • relay-core - config, database, types
  • rusqlite - query routing decisions for savings
  • tokio / reqwest - async HTTP for provider APIs
  • chrono - date range calculations
  • keyring - OS keychain access for provider admin keys

§Part of Relay

relay-stats is one of six MIT-licensed pillar crates. It tracks usage alongside relay-memory (tiered storage), relay-notes (wikilinks), relay-router (task classification), and relay-miner (pattern mining). Three architecture crates (relay-mcp, relay-daemon, relay-cli) assemble all pillars into the MCP server.

See the workspace README and LICENSING.md for details.

§License

MIT. See LICENSE.

Structs§

ModelUsage
StatsEngine
TokenCounts
UsageSummary

Enums§

StatsSource

Functions§

scrape_claude_logs
Scan ~/.claude/ JSONL session files for usage data within days. Returns map of model → TokenCounts (input/output/cache_creation/cache_read).