1use rig_agent::completion::StructuredOutputError;
4use rig_core::error::BoxError;
5use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
6use serde::{Deserialize, Serialize};
7
8use crate::{Case, Trial};
9
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12#[non_exhaustive]
13pub struct Score {
14 pub evaluator: String,
17 pub value: f64,
19 pub passed: bool,
21 #[serde(default, skip_serializing_if = "Option::is_none")]
24 pub label: Option<String>,
25 #[serde(default, skip_serializing_if = "Option::is_none")]
27 pub explanation: Option<String>,
28}
29
30impl Score {
31 pub fn new(evaluator: impl Into<String>, value: f64, passed: bool) -> Self {
33 Self {
34 evaluator: evaluator.into(),
35 value: clamp(value),
36 passed,
37 label: None,
38 explanation: None,
39 }
40 }
41
42 pub fn pass(evaluator: impl Into<String>) -> Self {
44 Self::new(evaluator, 1.0, true)
45 }
46
47 pub fn fail(evaluator: impl Into<String>, explanation: impl Into<String>) -> Self {
49 Self::new(evaluator, 0.0, false).with_explanation(explanation)
50 }
51
52 #[must_use]
54 pub fn with_label(mut self, label: impl Into<String>) -> Self {
55 self.label = Some(label.into());
56 self
57 }
58
59 #[must_use]
61 pub fn with_explanation(mut self, explanation: impl Into<String>) -> Self {
62 self.explanation = Some(explanation.into());
63 self
64 }
65}
66
67pub(crate) fn clamp(value: f64) -> f64 {
69 if value.is_nan() {
70 0.0
71 } else {
72 value.clamp(0.0, 1.0)
73 }
74}
75
76#[derive(Debug, thiserror::Error)]
79#[non_exhaustive]
80pub enum EvalError {
81 #[error("case {case:?} has no {field} to compare with")]
83 MissingReference {
84 case: String,
86 field: &'static str,
88 },
89 #[error("the judge returned no verdict: {0}")]
91 Judge(#[from] StructuredOutputError),
92 #[error(transparent)]
94 Other(BoxError),
95}
96
97pub trait Evaluator: WasmCompatSend + WasmCompatSync {
99 fn name(&self) -> &str;
102
103 fn evaluate<'a>(
106 &'a self,
107 case: &'a Case,
108 trial: &'a Trial,
109 ) -> WasmBoxedFuture<'a, Result<Score, EvalError>>;
110
111 fn named(self, name: impl Into<String>) -> Named<Self>
114 where
115 Self: Sized,
116 {
117 Named {
118 name: name.into(),
119 inner: self,
120 }
121 }
122}
123
124pub struct Named<E> {
126 name: String,
127 inner: E,
128}
129
130impl<E: Evaluator> Evaluator for Named<E> {
131 fn name(&self) -> &str {
132 &self.name
133 }
134
135 fn evaluate<'a>(
136 &'a self,
137 case: &'a Case,
138 trial: &'a Trial,
139 ) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
140 self.inner.evaluate(case, trial)
141 }
142}