1use std::fmt::Write as _;
4use std::sync::{Arc, Mutex};
5
6use rig_agent::Agent;
7use rig_agent::agent::{AgentHook, HookContext, ModelTurnAction, ModelTurnFinished};
8use rig_core::completion::{FinishReason, Usage};
9use rig_core::wasm_compat::WasmBoxedFuture;
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12
13use super::{ready, target_failed};
14use crate::{Case, EvalError, Evaluator, Score, Trial};
15
16#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
18pub struct Verdict {
19 pub score: f64,
21 pub reasoning: String,
23}
24
25pub struct LlmJudge {
36 agent: Agent,
37 name: &'static str,
38 rubric: String,
39 threshold: f64,
40}
41
42const HELPFULNESS: &str = "\
44Score how helpful the answer is to the user's input, from 0 to 1.
45- 1: directly and fully does what the user asked, is accurate as far as you can tell, and is clear enough to act on.
46- 0.5: does part of what was asked, or is correct but vague, padded or missing a step the user needs.
47- 0: ignores the request, is wrong, or is empty. An empty or refused answer scores 0 unless refusing is correct for the input.
48Do not reward length or tone on their own.";
49
50const FAITHFULNESS: &str = "\
52Score whether the answer is faithful to the evidence, from 0 to 1. The evidence is the user's input, the transcript, the tool calls the agent made with the results they returned (when recorded), the expected answer and the assertions. Leave out of the score any claim whose only source is a tool result that is not recorded or was cut short; score the remaining claims.
53- 1: every factual claim in the answer is supported by the evidence.
54- 0.5: most claims are supported, but one claim is unsupported or only partly supported.
55- 0: the answer contradicts the evidence, or most of its factual claims are unsupported by it.
56Do not penalize an answer for leaving things out. An empty or refused answer scores 0 unless refusing is correct for the input.";
57
58const GOAL_SUCCESS: &str = "\
60Score whether the agent achieved the user's goal across the whole conversation, from 0 to 1. The input turns are the user's messages in order, and the transcript holds each turn with the agent's answer. Judge the state at the end of the conversation, using every turn: a goal met early and undone later is not met.
61- 1: by the last turn the user's goal is met, without the user having to repeat or correct themselves.
62- 0.5: the goal is partly met, or met only after the user corrected the agent or asked again.
63- 0: the goal is not met, the agent went off track or gave up, or the answer is empty or refused when refusing is wrong.
64A single-turn case is judged the same way, on its one turn.";
65
66impl LlmJudge {
67 pub fn new(agent: Agent, rubric: impl Into<String>) -> Self {
76 Self::named("llm_judge", agent, rubric)
77 }
78
79 fn named(name: &'static str, agent: Agent, rubric: impl Into<String>) -> Self {
80 Self {
81 agent,
82 name,
83 rubric: rubric.into(),
84 threshold: 0.5,
85 }
86 }
87
88 pub fn helpfulness(agent: Agent) -> Self {
92 Self::named("helpfulness", agent, HELPFULNESS)
93 }
94
95 pub fn faithfulness(agent: Agent) -> Self {
100 Self::named("faithfulness", agent, FAITHFULNESS)
101 }
102
103 pub fn goal_success(agent: Agent) -> Self {
107 Self::named("goal_success", agent, GOAL_SUCCESS)
108 }
109
110 #[must_use]
112 pub fn threshold(mut self, threshold: f64) -> Self {
113 self.threshold = threshold;
114 self
115 }
116
117 fn prompt(&self, case: &Case, trial: &Trial) -> String {
119 let mut prompt = format!(
120 "You grade the answer of an AI agent.\n\nRubric:\n{}\n\n",
121 self.rubric
122 );
123 let prompts = case.prompts();
124 if let [input] = prompts.as_slice() {
125 let _ = write!(prompt, "Input:\n{input}\n");
126 } else {
127 prompt.push_str("Input turns, sent in order on one conversation:\n");
128 for (number, input) in prompts.iter().enumerate() {
129 let _ = writeln!(prompt, "{}. {input}", number + 1);
130 }
131 }
132 if let Some(expected) = &case.expected {
133 let _ = write!(prompt, "\nExpected answer:\n{expected}\n");
134 }
135 if !case.assertions.is_empty() {
136 prompt.push_str("\nThe answer must satisfy:\n");
137 for assertion in &case.assertions {
138 let _ = writeln!(prompt, "- {assertion}");
139 }
140 }
141 if !trial.transcript.is_empty() {
142 prompt.push_str("\nTranscript:\n");
143 for turn in &trial.transcript {
144 let _ = write!(prompt, "User: {}\nAgent: {}\n", turn.input, turn.output);
145 }
146 }
147 if !trial.tool_calls.is_empty() {
148 prompt.push_str("\nTool calls the agent made:\n");
149 for call in &trial.tool_calls {
150 let _ = writeln!(prompt, "- {}({})", call.name, call.args);
151 if let Some(result) = &call.result {
152 let _ = writeln!(prompt, " Result: {}", result.replace('\n', "\n "));
153 }
154 }
155 }
156 let _ = write!(
157 prompt,
158 "\nAnswer to grade:\n{}\n\nScore it from 0 (fails the rubric) to 1 (fully meets it), and give your reasoning.",
159 trial.output
160 );
161 prompt
162 }
163}
164
165#[derive(Debug, Clone, Default)]
168struct Watch {
169 cut_off: Option<Option<u64>>,
171 usage: Usage,
173}
174
175impl Watch {
176 fn observe(
177 &mut self,
178 finish_reason: Option<&FinishReason>,
179 max_tokens: Option<u64>,
180 usage: Usage,
181 ) {
182 self.cut_off = matches!(finish_reason, Some(FinishReason::Length)).then_some(max_tokens);
183 self.usage += usage;
184 }
185}
186
187struct Observe(Arc<Mutex<Watch>>);
189
190impl AgentHook for Observe {
191 async fn on_model_turn_finished(
192 &self,
193 _ctx: &HookContext,
194 event: ModelTurnFinished<'_>,
195 ) -> ModelTurnAction {
196 if let Ok(mut watch) = self.0.lock() {
197 watch.observe(event.finish_reason, event.max_tokens, event.usage);
198 }
199 ModelTurnAction::Continue
200 }
201}
202
203impl Evaluator for LlmJudge {
204 fn name(&self) -> &str {
205 self.name
206 }
207
208 fn pass_cutoff(&self) -> Option<f64> {
209 Some(self.threshold)
210 }
211
212 fn evaluate<'a>(
213 &'a self,
214 case: &'a Case,
215 trial: &'a Trial,
216 ) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
217 if let Some(failed) = target_failed(self.name(), trial) {
218 return ready(Ok(failed));
219 }
220 let watch = Arc::new(Mutex::new(Watch::default()));
221 let run = self
222 .agent
223 .prompt_typed::<Verdict>(self.prompt(case, trial))
224 .add_hook(Observe(Arc::clone(&watch)));
225 Box::pin(async move {
226 match run.await {
227 Ok(response) => {
228 let verdict = response.output;
229 let score = Score::new(self.name(), verdict.score, false);
230 let passed = score.value >= self.threshold;
231 Ok(Score { passed, ..score }
232 .with_explanation(verdict.reasoning)
233 .with_usage(response.usage))
234 }
235 Err(error) => {
236 let watch = watch.lock().map(|watch| watch.clone()).unwrap_or_default();
240 let message = match watch.cut_off {
241 Some(max_tokens) => format!(
242 "the judge returned no verdict: the reply was truncated at max_tokens{}",
243 max_tokens.map(|n| format!(" ({n})")).unwrap_or_default()
244 ),
245 None => format!("the judge returned no verdict: {error}"),
246 };
247 Ok(Score::fail(self.name(), message)
248 .with_label("error")
249 .with_usage(watch.usage))
250 }
251 }
252 })
253 }
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259
260 #[test]
261 fn the_cut_off_is_the_last_turns_and_the_usage_adds_up() {
262 let usage = |n| {
263 Usage::new()
264 .input_tokens(n)
265 .output_tokens(n)
266 .total_tokens(2 * n)
267 };
268 let mut watch = Watch::default();
269 watch.observe(Some(&FinishReason::Length), Some(64), usage(1));
270 assert_eq!(watch.cut_off, Some(Some(64)));
271
272 watch.observe(Some(&FinishReason::Stop), Some(64), usage(2));
273 assert_eq!(watch.cut_off, None, "a later stop clears an earlier length");
274
275 watch.observe(Some(&FinishReason::Length), None, usage(3));
276 assert_eq!(watch.cut_off, Some(None), "a length without a cap");
277 assert_eq!(watch.usage.total_tokens, Some(12));
278 }
279}