use rig_agent::completion::StructuredOutputError;
use rig_core::completion::Usage;
use rig_core::error::BoxError;
use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
use serde::{Deserialize, Serialize};
use crate::{Case, Trial};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Score {
pub evaluator: String,
pub value: f64,
pub passed: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub explanation: Option<String>,
#[serde(default, skip_serializing_if = "is_false")]
pub not_applicable: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage: Option<Usage>,
}
fn is_false(value: &bool) -> bool {
!value
}
impl Score {
pub fn new(evaluator: impl Into<String>, value: f64, passed: bool) -> Self {
Self {
evaluator: evaluator.into(),
value: clamp(value),
passed,
label: None,
explanation: None,
not_applicable: false,
usage: None,
}
}
pub fn not_applicable(evaluator: impl Into<String>, explanation: impl Into<String>) -> Self {
Self {
not_applicable: true,
..Self::new(evaluator, 0.0, false)
.with_label("n/a")
.with_explanation(explanation)
}
}
pub fn pass(evaluator: impl Into<String>) -> Self {
Self::new(evaluator, 1.0, true)
}
pub fn fail(evaluator: impl Into<String>, explanation: impl Into<String>) -> Self {
Self::new(evaluator, 0.0, false).with_explanation(explanation)
}
#[must_use]
pub fn with_label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
#[must_use]
pub fn with_explanation(mut self, explanation: impl Into<String>) -> Self {
self.explanation = Some(explanation.into());
self
}
#[must_use]
pub fn with_usage(mut self, usage: Usage) -> Self {
self.usage = Some(usage);
self
}
}
pub(crate) fn clamp(value: f64) -> f64 {
if value.is_nan() {
0.0
} else {
value.clamp(0.0, 1.0)
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum EvalError {
#[error("case {case:?} has no {field} to compare with")]
MissingReference {
case: String,
field: &'static str,
},
#[error("the judge returned no verdict: {0}")]
Judge(#[from] StructuredOutputError),
#[error(transparent)]
Other(BoxError),
}
pub trait Evaluator: WasmCompatSend + WasmCompatSync {
fn name(&self) -> &str;
fn evaluate<'a>(
&'a self,
case: &'a Case,
trial: &'a Trial,
) -> WasmBoxedFuture<'a, Result<Score, EvalError>>;
fn pass_cutoff(&self) -> Option<f64> {
None
}
fn named(self, name: impl Into<String>) -> Named<Self>
where
Self: Sized,
{
Named {
name: name.into(),
inner: self,
}
}
}
pub struct Named<E> {
name: String,
inner: E,
}
impl<E: Evaluator> Evaluator for Named<E> {
fn name(&self) -> &str {
&self.name
}
fn evaluate<'a>(
&'a self,
case: &'a Case,
trial: &'a Trial,
) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
self.inner.evaluate(case, trial)
}
fn pass_cutoff(&self) -> Option<f64> {
self.inner.pass_cutoff()
}
}