1use serde::{Deserialize, Serialize};
6
7use crate::vision::VisionCriteria;
8
9#[derive(Debug, Clone, Default, Serialize, Deserialize)]
11pub struct EvaluationCriteria {
12 #[serde(default)]
15 pub tool_trajectory_score: Option<f64>,
16
17 #[serde(default)]
19 pub tool_trajectory_config: Option<ToolTrajectoryConfig>,
20
21 #[serde(default)]
24 pub response_similarity: Option<f64>,
25
26 #[serde(default)]
28 pub response_match_config: Option<ResponseMatchConfig>,
29
30 #[serde(default)]
33 pub semantic_match_score: Option<f64>,
34
35 #[serde(default)]
37 pub semantic_match_config: Option<SemanticMatchConfig>,
38
39 #[serde(default)]
42 pub rubric_quality_score: Option<f64>,
43
44 #[serde(default)]
46 pub rubric_config: Option<RubricConfig>,
47
48 #[serde(default)]
51 pub safety_score: Option<f64>,
52
53 #[serde(default)]
56 pub hallucination_score: Option<f64>,
57
58 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub vision: Option<VisionCriteria>,
63
64 #[serde(default)]
70 pub custom: Vec<CustomCriterion>,
71}
72
73impl EvaluationCriteria {
74 pub fn exact_tools() -> Self {
76 Self {
77 tool_trajectory_score: Some(1.0),
78 tool_trajectory_config: Some(ToolTrajectoryConfig {
79 strict_order: true,
80 strict_args: true,
81 }),
82 ..Default::default()
83 }
84 }
85
86 pub fn semantic_match(threshold: f64) -> Self {
88 Self { semantic_match_score: Some(threshold), ..Default::default() }
89 }
90
91 pub fn response_similarity(threshold: f64) -> Self {
93 Self { response_similarity: Some(threshold), ..Default::default() }
94 }
95
96 pub fn with_tool_trajectory(mut self, threshold: f64) -> Self {
98 self.tool_trajectory_score = Some(threshold);
99 self
100 }
101
102 pub fn with_response_similarity(mut self, threshold: f64) -> Self {
104 self.response_similarity = Some(threshold);
105 self
106 }
107
108 pub fn with_semantic_match(mut self, threshold: f64) -> Self {
110 self.semantic_match_score = Some(threshold);
111 self
112 }
113
114 pub fn with_rubrics(mut self, threshold: f64, rubrics: Vec<Rubric>) -> Self {
116 self.rubric_quality_score = Some(threshold);
117 self.rubric_config = Some(RubricConfig { rubrics });
118 self
119 }
120
121 pub fn with_vision(mut self, vision: VisionCriteria) -> Self {
137 self.vision = Some(vision);
138 self
139 }
140
141 pub fn has_criteria(&self) -> bool {
165 self.tool_trajectory_score.is_some()
166 || self.response_similarity.is_some()
167 || self.semantic_match_score.is_some()
168 || self.rubric_quality_score.is_some()
169 || self.safety_score.is_some()
170 || self.hallucination_score.is_some()
171 || self.vision.as_ref().is_some_and(VisionCriteria::has_thresholds)
172 }
173}
174
175#[derive(Debug, Clone, Serialize, Deserialize)]
177pub struct ToolTrajectoryConfig {
178 #[serde(default = "default_true")]
183 pub strict_order: bool,
184 #[serde(default)]
193 pub strict_args: bool,
194}
195
196impl Default for ToolTrajectoryConfig {
197 fn default() -> Self {
198 Self { strict_order: true, strict_args: false }
199 }
200}
201
202#[derive(Debug, Clone, Serialize, Deserialize)]
204pub struct ResponseMatchConfig {
205 #[serde(default)]
207 pub algorithm: SimilarityAlgorithm,
208 #[serde(default = "default_true")]
210 pub normalize: bool,
211 #[serde(default = "default_true")]
213 pub ignore_case: bool,
214 #[serde(default)]
216 pub ignore_punctuation: bool,
217}
218
219impl Default for ResponseMatchConfig {
220 fn default() -> Self {
221 Self {
222 algorithm: SimilarityAlgorithm::default(),
223 normalize: true,
224 ignore_case: true,
225 ignore_punctuation: false,
226 }
227 }
228}
229
230#[derive(Debug, Clone, Default, Serialize, Deserialize)]
232#[serde(rename_all = "snake_case")]
233pub enum SimilarityAlgorithm {
234 Exact,
236 Contains,
238 Levenshtein,
240 #[default]
242 Jaccard,
243 Rouge1,
245 Rouge2,
247 RougeL,
249}
250
251#[derive(Debug, Clone, Serialize, Deserialize)]
253pub struct SemanticMatchConfig {
254 #[serde(default = "default_judge_model")]
256 pub judge_model: String,
257 pub custom_prompt: Option<String>,
263}
264
265impl Default for SemanticMatchConfig {
266 fn default() -> Self {
267 Self { judge_model: default_judge_model(), custom_prompt: None }
268 }
269}
270
271fn default_judge_model() -> String {
272 "gemini-3.8-flash".to_string()
273}
274
275#[derive(Debug, Clone, Default, Serialize, Deserialize)]
277pub struct RubricConfig {
278 pub rubrics: Vec<Rubric>,
280}
281
282impl RubricConfig {
283 pub fn from_criteria<I, S>(criteria: I) -> Self
294 where
295 I: IntoIterator<Item = S>,
296 S: AsRef<str>,
297 {
298 let rubrics = criteria
299 .into_iter()
300 .map(|criterion| criterion.as_ref().trim().to_string())
301 .filter(|criterion| !criterion.is_empty())
302 .map(|criterion| Rubric::new(&criterion, &criterion))
303 .collect();
304 Self { rubrics }
305 }
306
307 pub fn from_markdown(text: &str) -> Self {
328 let mut items: Vec<String> = Vec::new();
329 let mut in_item = false;
330 for line in text.lines() {
331 let trimmed = line.trim();
332 if trimmed.is_empty() || trimmed.starts_with('#') {
333 in_item = false;
334 continue;
335 }
336 let indented = line.starts_with([' ', '\t']);
337 if let Some(item) = list_item(trimmed).filter(|_| !(indented && in_item)) {
338 items.push(item.to_string());
339 in_item = true;
340 } else if indented
341 && in_item
342 && let Some(current) = items.last_mut()
343 {
344 current.push(' ');
345 current.push_str(list_item(trimmed).unwrap_or(trimmed));
346 } else {
347 in_item = false;
348 }
349 }
350 if items.is_empty() {
351 let mut paragraph = String::new();
352 for line in text.lines().map(str::trim) {
353 if line.is_empty() || line.starts_with('#') {
354 items.extend((!paragraph.is_empty()).then(|| std::mem::take(&mut paragraph)));
355 } else {
356 if !paragraph.is_empty() {
357 paragraph.push(' ');
358 }
359 paragraph.push_str(line);
360 }
361 }
362 items.extend((!paragraph.is_empty()).then_some(paragraph));
363 }
364 Self::from_criteria(items)
365 }
366}
367
368fn list_item(line: &str) -> Option<&str> {
370 let rest = if let Some(rest) = line
371 .strip_prefix("- ")
372 .or_else(|| line.strip_prefix("* "))
373 .or_else(|| line.strip_prefix("+ "))
374 {
375 rest
376 } else {
377 let digits = line.bytes().take_while(u8::is_ascii_digit).count();
378 let marker =
379 line[digits..].strip_prefix(". ").or_else(|| line[digits..].strip_prefix(") "));
380 match marker {
381 Some(rest) if digits > 0 => rest,
382 _ => return None,
383 }
384 };
385 let rest = rest.trim_start();
386 let rest = ["[ ] ", "[x] ", "[X] "]
387 .iter()
388 .find_map(|checkbox| rest.strip_prefix(checkbox))
389 .unwrap_or(rest);
390 Some(rest.trim())
391}
392
393#[derive(Debug, Clone, Serialize, Deserialize)]
395pub struct Rubric {
396 pub name: String,
398 pub description: String,
400 #[serde(default = "default_weight")]
402 pub weight: f64,
403 #[serde(default)]
405 pub levels: Vec<RubricLevel>,
406}
407
408impl Rubric {
409 pub fn new(name: &str, description: &str) -> Self {
411 Self {
412 name: name.to_string(),
413 description: description.to_string(),
414 weight: 1.0,
415 levels: vec![],
416 }
417 }
418
419 pub fn with_weight(mut self, weight: f64) -> Self {
421 self.weight = weight;
422 self
423 }
424
425 pub fn with_levels(mut self, levels: Vec<RubricLevel>) -> Self {
427 self.levels = levels;
428 self
429 }
430}
431
432#[derive(Debug, Clone, Serialize, Deserialize)]
434pub struct RubricLevel {
435 pub score: f64,
437 pub description: String,
439}
440
441#[derive(Debug, Clone, Serialize, Deserialize)]
443pub struct CustomCriterion {
444 pub name: String,
446 pub description: String,
448 pub threshold: f64,
450 #[serde(default)]
452 pub config: serde_json::Value,
453}
454
455fn default_true() -> bool {
456 true
457}
458
459fn default_weight() -> f64 {
460 1.0
461}
462
463#[cfg(test)]
464mod tests {
465 use super::*;
466
467 #[test]
468 fn test_criteria_builder() {
469 let criteria = EvaluationCriteria::exact_tools()
470 .with_response_similarity(0.8)
471 .with_semantic_match(0.9);
472
473 assert_eq!(criteria.tool_trajectory_score, Some(1.0));
474 assert_eq!(criteria.response_similarity, Some(0.8));
475 assert_eq!(criteria.semantic_match_score, Some(0.9));
476 assert!(criteria.has_criteria());
477 }
478
479 #[test]
480 fn test_rubric_creation() {
481 let rubric = Rubric::new("Accuracy", "Response is factually correct")
482 .with_weight(0.7)
483 .with_levels(vec![
484 RubricLevel { score: 1.0, description: "Completely accurate".to_string() },
485 RubricLevel { score: 0.5, description: "Partially accurate".to_string() },
486 RubricLevel { score: 0.0, description: "Inaccurate".to_string() },
487 ]);
488
489 assert_eq!(rubric.name, "Accuracy");
490 assert_eq!(rubric.weight, 0.7);
491 assert_eq!(rubric.levels.len(), 3);
492 }
493
494 #[test]
495 fn test_default_criteria() {
496 let criteria = EvaluationCriteria::default();
497 assert!(!criteria.has_criteria());
498 }
499
500 #[test]
501 fn custom_criteria_alone_are_not_criteria() {
502 let criteria = EvaluationCriteria {
503 custom: vec![CustomCriterion {
504 name: "tone".to_string(),
505 description: "friendly".to_string(),
506 threshold: 0.5,
507 config: serde_json::Value::Null,
508 }],
509 ..Default::default()
510 };
511 assert!(!criteria.has_criteria());
512 }
513}