use std::time::Duration;
use rig_core::wasm_compat::WasmBoxedFuture;
use serde_json::Value;
use crate::{Case, EvalError, Evaluator, ExpectedCall, Score, ToolCall, Trial};
mod judge;
pub use judge::{LlmJudge, Verdict};
pub(crate) fn target_failed(name: &str, trial: &Trial) -> Option<Score> {
trial
.error
.as_ref()
.map(|error| Score::fail(name, format!("the target failed: {error}")))
}
fn ready<'a>(score: Result<Score, EvalError>) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
Box::pin(std::future::ready(score))
}
fn ratio(found: usize, total: usize) -> f64 {
if total == 0 {
1.0
} else {
found as f64 / total as f64
}
}
#[derive(Debug, Clone)]
pub struct Contains {
needles: Vec<String>,
ignore_case: bool,
}
pub fn contains(needle: impl Into<String>) -> Contains {
contains_all([needle])
}
pub fn contains_all(needles: impl IntoIterator<Item = impl Into<String>>) -> Contains {
Contains {
needles: needles.into_iter().map(Into::into).collect(),
ignore_case: false,
}
}
impl Contains {
#[must_use]
pub fn ignore_case(mut self) -> Self {
self.ignore_case = true;
self
}
}
impl Evaluator for Contains {
fn name(&self) -> &str {
"contains"
}
fn evaluate<'a>(
&'a self,
_case: &'a Case,
trial: &'a Trial,
) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
if let Some(failed) = target_failed(self.name(), trial) {
return ready(Ok(failed));
}
let fold = |text: &str| {
if self.ignore_case {
text.to_lowercase()
} else {
text.to_owned()
}
};
let output = fold(&trial.output);
let missing: Vec<&str> = self
.needles
.iter()
.filter(|needle| !output.contains(&fold(needle)))
.map(String::as_str)
.collect();
let found = self.needles.len() - missing.len();
let score = Score::new(
self.name(),
ratio(found, self.needles.len()),
missing.is_empty(),
);
ready(Ok(if missing.is_empty() {
score
} else {
score.with_explanation(format!("missing {missing:?}"))
}))
}
}
#[derive(Debug, Clone)]
pub struct Matches(regex::Regex);
pub fn regex(pattern: &str) -> Result<Matches, regex::Error> {
regex::Regex::new(pattern).map(Matches)
}
impl Evaluator for Matches {
fn name(&self) -> &str {
"regex"
}
fn evaluate<'a>(
&'a self,
_case: &'a Case,
trial: &'a Trial,
) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
if let Some(failed) = target_failed(self.name(), trial) {
return ready(Ok(failed));
}
ready(Ok(if self.0.is_match(&trial.output) {
Score::pass(self.name())
} else {
Score::fail(self.name(), format!("does not match {}", self.0.as_str()))
}))
}
}
#[derive(Debug, Clone, Default)]
pub struct Equals {
ignore_case: bool,
skip_without_reference: bool,
}
pub fn equals() -> Equals {
Equals::default()
}
impl Equals {
#[must_use]
pub fn ignore_case(mut self) -> Self {
self.ignore_case = true;
self
}
#[must_use]
pub fn not_applicable_without_reference(mut self) -> Self {
self.skip_without_reference = true;
self
}
}
impl Evaluator for Equals {
fn name(&self) -> &str {
"equals"
}
fn evaluate<'a>(
&'a self,
case: &'a Case,
trial: &'a Trial,
) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
if let Some(failed) = target_failed(self.name(), trial) {
return ready(Ok(failed));
}
let Some(expected) = &case.expected else {
if self.skip_without_reference {
return ready(Ok(Score::not_applicable(
self.name(),
"the case has no expected answer",
)));
}
return ready(Err(EvalError::MissingReference {
case: case.id.clone(),
field: "expected",
}));
};
let (expected, output) = (expected.trim(), trial.output.trim());
let equal = if self.ignore_case {
expected.to_lowercase() == output.to_lowercase()
} else {
expected == output
};
ready(Ok(if equal {
Score::pass(self.name())
} else {
Score::fail(
self.name(),
format!("expected {expected:?}, got {output:?}"),
)
}))
}
}
#[derive(Debug, Clone, Default)]
pub struct Json {
required: Vec<String>,
}
pub fn json() -> Json {
Json::default()
}
impl Json {
#[must_use]
pub fn require(mut self, key: impl Into<String>) -> Self {
self.required.push(key.into());
self
}
}
impl Evaluator for Json {
fn name(&self) -> &str {
"json"
}
fn evaluate<'a>(
&'a self,
_case: &'a Case,
trial: &'a Trial,
) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
if let Some(failed) = target_failed(self.name(), trial) {
return ready(Ok(failed));
}
let value: Value = match serde_json::from_str(trial.output.trim()) {
Ok(value) => value,
Err(error) => return ready(Ok(Score::fail(self.name(), format!("not JSON: {error}")))),
};
if self.required.is_empty() {
return ready(Ok(Score::pass(self.name())));
}
let Some(object) = value.as_object() else {
return ready(Ok(Score::fail(self.name(), "not a JSON object")));
};
let missing: Vec<&str> = self
.required
.iter()
.filter(|key| !object.contains_key(key.as_str()))
.map(String::as_str)
.collect();
ready(Ok(if missing.is_empty() {
Score::pass(self.name())
} else {
Score::fail(self.name(), format!("missing keys {missing:?}"))
}))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TrajectoryMode {
Exact,
InOrder,
AnyOrder,
}
#[derive(Debug, Clone)]
pub struct Trajectory {
mode: TrajectoryMode,
skip_without_reference: bool,
}
pub fn trajectory(mode: TrajectoryMode) -> Trajectory {
Trajectory {
mode,
skip_without_reference: false,
}
}
impl Trajectory {
#[must_use]
pub fn not_applicable_without_reference(mut self) -> Self {
self.skip_without_reference = true;
self
}
}
fn call_matches(expected: &ExpectedCall, actual: &ToolCall) -> bool {
expected.name == actual.name
&& expected
.args
.as_ref()
.is_none_or(|args| match (args, &actual.args) {
(Value::Object(want), Value::Object(got)) => {
want.iter().all(|(key, value)| got.get(key) == Some(value))
}
(want, got) => want == got,
})
}
fn matched(mode: TrajectoryMode, expected: &[ExpectedCall], actual: &[ToolCall]) -> (usize, usize) {
match mode {
TrajectoryMode::Exact => {
let pairs = expected
.iter()
.zip(actual)
.filter(|(want, got)| call_matches(want, got))
.count();
(pairs, expected.len().max(actual.len()))
}
TrajectoryMode::InOrder => {
let mut wanted = expected.iter().peekable();
for call in actual {
wanted.next_if(|want| call_matches(want, call));
}
(expected.len() - wanted.count(), expected.len())
}
TrajectoryMode::AnyOrder => {
let mut free: Vec<&ToolCall> = actual.iter().collect();
let mut found = 0;
let specific = expected.iter().filter(|call| call.args.is_some());
let any = expected.iter().filter(|call| call.args.is_none());
for want in specific.chain(any) {
if let Some(at) = free.iter().position(|got| call_matches(want, got)) {
free.swap_remove(at);
found += 1;
}
}
(found, expected.len())
}
}
}
impl Evaluator for Trajectory {
fn name(&self) -> &str {
"trajectory"
}
fn evaluate<'a>(
&'a self,
case: &'a Case,
trial: &'a Trial,
) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
if let Some(failed) = target_failed(self.name(), trial) {
return ready(Ok(failed));
}
let Some(expected) = &case.trajectory else {
if self.skip_without_reference {
return ready(Ok(Score::not_applicable(
self.name(),
"the case has no trajectory",
)));
}
return ready(Err(EvalError::MissingReference {
case: case.id.clone(),
field: "trajectory",
}));
};
let (found, total) = matched(self.mode, expected, &trial.tool_calls);
let passed = found == total;
let score = Score::new(self.name(), ratio(found, total), passed);
if passed {
return ready(Ok(score));
}
let want: Vec<&str> = expected.iter().map(|call| call.name.as_str()).collect();
let got: Vec<&str> = trial
.tool_calls
.iter()
.map(|call| call.name.as_str())
.collect();
ready(Ok(score.with_explanation(format!(
"expected {want:?} ({:?}), got {got:?}",
self.mode
))))
}
}
#[derive(Debug, Clone, Default)]
pub struct Budget {
output_tokens: Option<u64>,
total_tokens: Option<u64>,
latency: Option<Duration>,
}
pub fn budget() -> Budget {
Budget::default()
}
impl Budget {
#[must_use]
pub fn max_output_tokens(mut self, tokens: u64) -> Self {
self.output_tokens = Some(tokens);
self
}
#[must_use]
pub fn max_total_tokens(mut self, tokens: u64) -> Self {
self.total_tokens = Some(tokens);
self
}
#[must_use]
pub fn max_latency(mut self, latency: Duration) -> Self {
self.latency = Some(latency);
self
}
}
impl Evaluator for Budget {
fn name(&self) -> &str {
"budget"
}
fn evaluate<'a>(
&'a self,
_case: &'a Case,
trial: &'a Trial,
) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
if let Some(failed) = target_failed(self.name(), trial) {
return ready(Ok(failed));
}
let usage = &trial.usage;
let total = usage
.total_tokens
.or(match (usage.input_tokens, usage.output_tokens) {
(None, None) => None,
(input, output) => Some(input.unwrap_or(0) + output.unwrap_or(0)),
});
let mut over = Vec::new();
for (what, limit, used) in [
("output tokens", self.output_tokens, usage.output_tokens),
("total tokens", self.total_tokens, total),
] {
match (limit, used) {
(Some(limit), Some(used)) if used > limit => {
over.push(format!("{what}: {used} > {limit}"));
}
(Some(_), None) => over.push(format!("{what}: not reported")),
_ => {}
}
}
if let Some(limit) = self.latency
&& trial.latency > limit
{
over.push(format!("latency: {:?} > {limit:?}", trial.latency));
}
ready(Ok(if over.is_empty() {
Score::pass(self.name())
} else {
Score::fail(self.name(), over.join("; "))
}))
}
}
#[derive(Debug, Clone, Default)]
pub struct NoError;
pub fn no_error() -> NoError {
NoError
}
impl Evaluator for NoError {
fn name(&self) -> &str {
"no_error"
}
fn evaluate<'a>(
&'a self,
_case: &'a Case,
trial: &'a Trial,
) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
ready(Ok(
target_failed(self.name(), trial).unwrap_or_else(|| Score::pass(self.name()))
))
}
}