eclipse-core 0.13.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! What one provider call cost, and what the session has cost so far.
//!
//! Two dialects report this, and both are worth reading because they say different things:
//!
//! - **OpenAI** puts `usage: {prompt_tokens, completion_tokens, total_tokens}`, and, when the
//!   server caches a prefix, `usage.prompt_tokens_details.cached_tokens`. It says nothing
//!   about time.
//! - **llama.cpp** adds `timings: {prompt_n, prompt_ms, predicted_n, predicted_ms, cache_n}`
//!   — the prefill cost, the decode cost, and how many prompt tokens were reused from the
//!   KV cache. `prompt_n` counts only the tokens actually processed, so the prompt size is
//!   `prompt_n + cache_n`; that `cache_n` is the number the status line shows, because a
//!   warm cache is the difference between a 1 s and a 20 s turn on a local server.
//!
//! Everything is optional on purpose. A server that reports nothing is normal, and the UI
//! then shows `--` rather than inventing a number.

use serde_json::Value;

/// What one provider call cost.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TurnUsage {
    pub prompt_tokens: Option<u64>,
    pub completion_tokens: Option<u64>,
    pub total_tokens: Option<u64>,
    /// Prompt tokens served from the server's KV/prefix cache (llama.cpp `cache_n`).
    pub cached_tokens: Option<u64>,
    /// Prefill time, when the server distinguishes it.
    pub prompt_ms: Option<u64>,
    /// Decode time.
    pub completion_ms: Option<u64>,
    /// Wall time of the whole call as this process measured it — always present.
    pub latency_ms: u64,
    /// Time to the first streamed character, when the provider streamed at all.
    pub ttft_ms: Option<u64>,
}

fn num(v: &Value, pointer: &str) -> Option<u64> {
    let n = v.pointer(pointer)?;
    if let Some(i) = n.as_u64() {
        Some(i)
    } else {
        n.as_f64()
            .filter(|f| f.is_finite() && *f >= 0.0)
            .map(|f| f.round() as u64)
    }
}

impl TurnUsage {
    /// Read a response body (or a stream's final chunk) plus the wall time we measured.
    pub fn from_body(body: &Value, latency_ms: u64) -> Self {
        let prompt = num(body, "/usage/prompt_tokens");
        let completion = num(body, "/usage/completion_tokens");
        let cached = num(body, "/usage/prompt_tokens_details/cached_tokens");

        // llama.cpp: prompt_n excludes the cached prefix, so the real prompt is their sum.
        let llm_prompt = num(body, "/timings/prompt_n");
        let llm_cached = num(body, "/timings/cache_n");
        let prompt_tokens = match (prompt, llm_prompt, llm_cached) {
            (Some(p), _, _) => Some(p),
            (None, Some(n), Some(c)) => Some(n + c),
            (None, Some(n), None) => Some(n),
            _ => None,
        };
        let total_tokens = num(body, "/usage/total_tokens").or_else(|| {
            match (
                prompt_tokens,
                num(body, "/timings/predicted_n").or(completion),
            ) {
                (Some(p), Some(c)) => Some(p + c),
                _ => None,
            }
        });

        Self {
            prompt_tokens,
            completion_tokens: completion.or_else(|| num(body, "/timings/predicted_n")),
            total_tokens,
            cached_tokens: cached.or(llm_cached),
            prompt_ms: num(body, "/timings/prompt_ms"),
            completion_ms: num(body, "/timings/predicted_ms"),
            latency_ms,
            ttft_ms: None,
        }
    }

    /// Decode speed. Prefers the server's own decode timing (it excludes prefill), else the
    /// whole wall time, which is a floor on the real speed rather than a fake precision.
    pub fn tokens_per_sec(&self) -> Option<f64> {
        let tokens = self.completion_tokens? as f64;
        if let Some(done) = self.completion_ms.filter(|m| *m > 0) {
            return Some(tokens * 1000.0 / done as f64);
        }
        (self.latency_ms > 0).then(|| tokens * 1000.0 / self.latency_ms as f64)
    }

    /// Prefill speed, when the server timed it.
    pub fn prefill_per_sec(&self) -> Option<f64> {
        match (self.prompt_tokens, self.prompt_ms) {
            (Some(tokens), Some(ms)) if ms > 0 => {
                // prompt_n is the prefill; when we only have prompt_n + cache_n, this is the
                // honest upper bound rather than a wrong claim.
                Some(tokens as f64 * 1000.0 / ms as f64)
            }
            _ => None,
        }
    }

    pub fn is_empty(&self) -> bool {
        self.prompt_tokens.is_none() && self.completion_tokens.is_none()
    }
}

/// Running totals for the whole process, so the status line can show more than the last turn.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct UsageTotals {
    pub turns: u64,
    pub prompt_tokens: u64,
    pub completion_tokens: u64,
    pub cached_tokens: u64,
}

impl UsageTotals {
    pub fn add(&mut self, u: &TurnUsage) {
        self.turns += 1;
        self.prompt_tokens += u.prompt_tokens.unwrap_or(0);
        self.completion_tokens += u.completion_tokens.unwrap_or(0);
        self.cached_tokens += u.cached_tokens.unwrap_or(0);
    }

    /// Share of prompt tokens that the server did not have to prefill, 0.0–1.0.
    pub fn cache_ratio(&self) -> Option<f64> {
        (self.prompt_tokens > 0).then(|| self.cached_tokens as f64 / self.prompt_tokens as f64)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn reads_the_openai_shape() {
        let body = json!({"usage": {"prompt_tokens": 1200, "completion_tokens": 55,
                                    "total_tokens": 1255}});
        let u = TurnUsage::from_body(&body, 900);
        assert_eq!(u.prompt_tokens, Some(1200));
        assert_eq!(u.completion_tokens, Some(55));
        assert_eq!(u.total_tokens, Some(1255));
        assert_eq!(u.cached_tokens, None);
        assert_eq!(u.latency_ms, 900);
    }

    #[test]
    fn reads_the_cached_prompt_detail() {
        let body = json!({"usage": {"prompt_tokens": 2000, "completion_tokens": 10,
            "prompt_tokens_details": {"cached_tokens": 1920}}});
        assert_eq!(TurnUsage::from_body(&body, 1).cached_tokens, Some(1920));
    }

    #[test]
    fn reads_llamacpp_timings_and_adds_the_cached_prefix() {
        // prompt_n is what the server actually processed; cache_n was reused on top.
        let body = json!({"timings": {"prompt_n": 300, "prompt_ms": 250.0,
                                      "predicted_n": 40, "predicted_ms": 2000.0,
                                      "cache_n": 1700}});
        let u = TurnUsage::from_body(&body, 2400);
        assert_eq!(u.prompt_tokens, Some(2000), "300 processed + 1700 cached");
        assert_eq!(u.cached_tokens, Some(1700));
        assert_eq!(u.completion_tokens, Some(40));
        assert_eq!(u.total_tokens, Some(2040));
        assert_eq!(u.tokens_per_sec().unwrap().round(), 20.0, "40 tok in 2 s");
    }

    #[test]
    fn timings_win_only_where_usage_is_silent() {
        let body = json!({
            "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
            "timings": {"prompt_n": 1, "predicted_n": 999, "cache_n": 0}
        });
        let u = TurnUsage::from_body(&body, 100);
        assert_eq!(u.prompt_tokens, Some(10));
        assert_eq!(u.completion_tokens, Some(5));
        assert_eq!(u.total_tokens, Some(15));
    }

    #[test]
    fn a_silent_server_reports_nothing_and_says_so() {
        let u = TurnUsage::from_body(&json!({"choices": []}), 500);
        assert!(u.is_empty());
        assert_eq!(u.tokens_per_sec(), None);
        assert_eq!(u.latency_ms, 500);
    }

    #[test]
    fn decode_speed_falls_back_to_wall_time_without_timings() {
        let u = TurnUsage::from_body(&json!({"usage": {"completion_tokens": 50}}), 1000);
        assert_eq!(u.tokens_per_sec().unwrap(), 50.0);
    }

    #[test]
    fn totals_add_up_and_the_cache_ratio_is_honest() {
        let mut t = UsageTotals::default();
        t.add(&TurnUsage::from_body(
            &json!({"timings": {"prompt_n": 100, "cache_n": 900,
                                                        "predicted_n": 10}}),
            1000,
        ));
        t.add(&TurnUsage::from_body(
            &json!({"timings": {"prompt_n": 200, "cache_n": 800,
                                                        "predicted_n": 10}}),
            1000,
        ));
        assert_eq!(t.turns, 2);
        assert_eq!(t.prompt_tokens, 2000);
        assert_eq!(t.cached_tokens, 1700);
        assert_eq!(t.cache_ratio().unwrap(), 0.85);
    }

    #[test]
    fn garbage_fields_do_not_panic_or_go_negative() {
        let body = json!({"usage": {"prompt_tokens": -5, "completion_tokens": "x"}});
        let u = TurnUsage::from_body(&body, 0);
        assert_eq!(u.prompt_tokens, None);
        assert_eq!(u.completion_tokens, None);
    }
}