Skip to content

The platform for continuously improving AI agents.

7.6 KB
Raw Blame
use std::collections::{BTreeMap, HashMap};

use serde::{Deserialize, Serialize};
use trace_types::SpanRecord;

use crate::evidence;

/// Below this a judge's score earns a written reason.
pub const REASON_BELOW: f64 = 0.75;
/// Below this a span is considered failing.
pub const FAIL_BELOW: f64 = 0.5;
/// Maximum judging passes per span or trajectory before recording an error metric.
pub const MAX_ATTEMPTS: u32 = 3;
/// Maximum spans loaded for one trace.
pub const TRACE_SPAN_CAP: usize = 2_000;
/// Jev rejects requests whose state + question exceeds ~31k UTF-8 bytes.
pub const JEV_STATE_LIMIT: usize = 30_000;
/// Cap on per-span expectation judge calls.
pub const MAX_EXPECTATIONS: usize = 64;
/// Maximum concurrent span evaluations inside a batch.
pub const MAX_CONCURRENT_SPANS: usize = 64;
/// Process-wide cap on concurrent Jev / explanation HTTP calls.
pub const MAX_CONCURRENT_JUDGES: usize = 32;
/// Stale claim expiry (10 minutes), matching Python `CLAIM_TTL`.
pub const CLAIM_TTL_MS: i64 = 10 * 60 * 1_000;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EvalRowType {
    Deterministic,
    Llm,
}

impl EvalRowType {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Deterministic => "deterministic",
            Self::Llm => "llm",
        }
    }

    pub fn parse(raw: &str) -> Option<Self> {
        match raw.trim().to_ascii_lowercase().as_str() {
            "deterministic" => Some(Self::Deterministic),
            "llm" => Some(Self::Llm),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JudgeOption {
    pub label: String,
    pub score: f64,
}

/// Mirrors `overbae.models.EvalMatrix` (plus optional benchmark `judge_options`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EvalMatrixRow {
    pub id: Option<String>,
    pub project_id: String,
    pub capability_id: Option<String>,
    pub name: String,
    pub row_type: EvalRowType,
    pub source: String,
    pub span_type: String,
    pub span_name: String,
    pub enabled: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub judge_options: Option<Vec<JudgeOption>>,
}

impl EvalMatrixRow {
    pub fn deterministic(project_id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: None,
            project_id: project_id.into(),
            capability_id: None,
            name: name.into(),
            row_type: EvalRowType::Deterministic,
            source: String::new(),
            span_type: String::new(),
            span_name: String::new(),
            enabled: true,
            judge_options: None,
        }
    }

    pub fn llm(
        project_id: impl Into<String>,
        name: impl Into<String>,
        expectation: impl Into<String>,
    ) -> Self {
        Self {
            id: None,
            project_id: project_id.into(),
            capability_id: None,
            name: name.into(),
            row_type: EvalRowType::Llm,
            source: expectation.into(),
            span_type: String::new(),
            span_name: String::new(),
            enabled: true,
            judge_options: None,
        }
    }

    pub fn is_unscoped(&self) -> bool {
        self.span_type.is_empty() && self.span_name.is_empty()
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Metric {
    pub expectation: String,
    pub score: Option<f64>,
    pub verdict: String,
    pub reason: String,
    pub error: String,
}

impl Metric {
    pub fn scored(
        expectation: impl Into<String>,
        score: f64,
        verdict: impl Into<String>,
        reason: impl Into<String>,
    ) -> Self {
        Self {
            expectation: expectation.into(),
            score: Some(score),
            verdict: verdict.into(),
            reason: reason.into(),
            error: String::new(),
        }
    }

    pub fn abstained(expectation: impl Into<String>, reason: impl Into<String>) -> Self {
        Self {
            expectation: expectation.into(),
            score: None,
            verdict: "abstain".to_string(),
            reason: reason.into(),
            error: String::new(),
        }
    }

    pub fn errored(expectation: impl Into<String>, error: impl Into<String>) -> Self {
        Self {
            expectation: expectation.into(),
            score: None,
            verdict: String::new(),
            reason: String::new(),
            error: error.into(),
        }
    }

    pub fn into_span_metric(self, row_type: EvalRowType) -> SpanMetric {
        SpanMetric {
            row_type: row_type.as_str().to_string(),
            expectation: self.expectation,
            score: self.score,
            verdict: self.verdict,
            reason: self.reason,
            error: self.error,
        }
    }
}

/// Wire shape stored inside `span_evals.metrics` / `eval_scores.metrics`,
/// matching Python `Metric.as_dict(row_type)`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpanMetric {
    #[serde(rename = "type")]
    pub row_type: String,
    pub expectation: String,
    pub score: Option<f64>,
    pub verdict: String,
    pub reason: String,
    pub error: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpanEvalState {
    pub span_id: String,
    pub trace_id: String,
    pub version: u32,
    pub intent: String,
    pub fingerprint: String,
    /// `true` once the span has a final evaluation (even if `score` is `None`).
    pub has_score: bool,
    pub score: Option<f64>,
    pub metrics: BTreeMap<String, SpanMetric>,
    pub partial: BTreeMap<String, SpanMetric>,
    pub attempts: u32,
    pub error: String,
}

impl SpanEvalState {
    pub fn empty(span_id: impl Into<String>, trace_id: impl Into<String>) -> Self {
        Self {
            span_id: span_id.into(),
            trace_id: trace_id.into(),
            version: 0,
            intent: String::new(),
            fingerprint: String::new(),
            has_score: false,
            score: None,
            metrics: BTreeMap::new(),
            partial: BTreeMap::new(),
            attempts: 0,
            error: String::new(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TrajectoryEvalState {
    pub trace_id: String,
    pub root_span_id: String,
    pub span_count: usize,
    pub has_trajectory: bool,
    pub score: Option<f64>,
    pub passed: Option<bool>,
    pub metrics: BTreeMap<String, Metric>,
    pub attempts: u32,
}

/// `None` when nothing was scored (every metric abstained or errored).
pub fn mean_of<I>(scores: I) -> Option<f64>
where
    I: IntoIterator<Item = Option<f64>>,
{
    let mut sum = 0.0;
    let mut count = 0usize;
    for score in scores.into_iter().flatten() {
        if score.is_finite() {
            sum += score;
            count += 1;
        }
    }
    if count == 0 {
        None
    } else {
        Some(sum / count as f64)
    }
}

pub fn is_failing(score: Option<f64>) -> bool {
    score.is_some_and(|s| s < FAIL_BELOW)
}

/// The trace root, or the topmost span of a capability: the span that carries its answer.
pub fn answers_for_capability(span: &SpanRecord, trace: &HashMap<String, SpanRecord>) -> bool {
    if evidence::is_root(span) {
        return true;
    }
    let Some(cap_id) = evidence::capability_id(span) else {
        return false;
    };
    let Some(parent_id) = span.parent_span_id.as_deref().filter(|s| !s.is_empty()) else {
        return true;
    };
    match trace.get(parent_id) {
        None => true,
        Some(parent) => evidence::capability_id(parent).as_deref() != Some(cap_id.as_str()),
    }
}