use std::collections::BTreeMap;
use std::future::Future;
use std::pin::Pin;
use futures::stream::{self, StreamExt};
use serde::{Deserialize, Serialize};
use crate::error::{Error, Result};
use crate::report::MetricReport;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelBehaviorTask {
pub id: String,
pub prompt: String,
#[serde(default)]
pub must_contain: Vec<String>,
#[serde(default)]
pub must_not_contain: Vec<String>,
#[serde(default)]
pub require_json: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_output_tokens: Option<u64>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub metadata: BTreeMap<String, String>,
}
impl ModelBehaviorTask {
pub fn new(id: impl Into<String>, prompt: impl Into<String>) -> Self {
Self {
id: id.into(),
prompt: prompt.into(),
must_contain: Vec::new(),
must_not_contain: Vec::new(),
require_json: false,
max_output_tokens: None,
metadata: BTreeMap::new(),
}
}
#[must_use]
pub fn must_contain(mut self, term: impl Into<String>) -> Self {
self.must_contain.push(term.into());
self
}
#[must_use]
pub fn must_not_contain(mut self, term: impl Into<String>) -> Self {
self.must_not_contain.push(term.into());
self
}
#[must_use]
pub fn requiring_json(mut self) -> Self {
self.require_json = true;
self
}
#[must_use]
pub fn with_max_output_tokens(mut self, max: u64) -> Self {
self.max_output_tokens = Some(max);
self
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ModelBehaviorTaskSet {
pub id: String,
pub tasks: Vec<ModelBehaviorTask>,
}
impl ModelBehaviorTaskSet {
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
tasks: Vec::new(),
}
}
pub fn push(&mut self, task: ModelBehaviorTask) {
self.tasks.push(task);
}
#[must_use]
pub fn len(&self) -> usize {
self.tasks.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.tasks.is_empty()
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ModelObservation {
pub output: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub input_tokens: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub output_tokens: Option<u64>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub metadata: BTreeMap<String, String>,
}
pub trait ModelRunner: Send + Sync {
fn run<'a>(
&'a self,
task: &'a ModelBehaviorTask,
) -> Pin<Box<dyn Future<Output = Result<ModelObservation>> + Send + 'a>>;
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelBehaviorResult {
pub task_id: String,
pub score: f64,
pub passed: bool,
pub observation: ModelObservation,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelBehaviorReport {
pub suite_id: String,
pub n_tasks: usize,
pub mean_score: f64,
pub results: Vec<ModelBehaviorResult>,
}
impl ModelBehaviorReport {
#[must_use]
pub fn metric_report(&self) -> MetricReport {
MetricReport::from_per_query(
"model.behavior".to_string(),
self.results
.iter()
.map(|result| (result.task_id.clone(), result.score))
.collect(),
)
}
}
pub struct ModelBehaviorHarness<R: ModelRunner> {
runner: R,
concurrency: usize,
}
impl<R: ModelRunner> ModelBehaviorHarness<R> {
pub fn new(runner: R) -> Self {
Self {
runner,
concurrency: 1,
}
}
#[must_use]
pub fn with_concurrency(mut self, concurrency: usize) -> Self {
self.concurrency = concurrency.max(1);
self
}
pub async fn run(&self, tasks: &ModelBehaviorTaskSet) -> Result<ModelBehaviorReport> {
if tasks.is_empty() {
return Err(Error::Config("model behavior task set is empty".into()));
}
let rows = stream::iter(tasks.tasks.iter().map(|task| async move {
let observation = self.runner.run(task).await?;
Ok::<_, Error>(grade_model_task(task, observation))
}))
.buffer_unordered(self.concurrency)
.collect::<Vec<_>>()
.await;
let mut results = Vec::with_capacity(rows.len());
for row in rows {
results.push(row?);
}
results.sort_by(|a, b| a.task_id.cmp(&b.task_id));
let mean_score = if results.is_empty() {
0.0
} else {
results.iter().map(|result| result.score).sum::<f64>() / results.len() as f64
};
Ok(ModelBehaviorReport {
suite_id: tasks.id.clone(),
n_tasks: tasks.len(),
mean_score,
results,
})
}
}
fn grade_model_task(
task: &ModelBehaviorTask,
observation: ModelObservation,
) -> ModelBehaviorResult {
let output_lower = observation.output.to_lowercase();
let mut checks = 0usize;
let mut passed = 0usize;
let mut notes = Vec::new();
for term in &task.must_contain {
checks = checks.saturating_add(1);
if output_lower.contains(&term.to_lowercase()) {
passed = passed.saturating_add(1);
} else {
notes.push(format!("missing required term `{term}`"));
}
}
for term in &task.must_not_contain {
checks = checks.saturating_add(1);
if output_lower.contains(&term.to_lowercase()) {
notes.push(format!("found forbidden term `{term}`"));
} else {
passed = passed.saturating_add(1);
}
}
if task.require_json {
checks = checks.saturating_add(1);
if serde_json::from_str::<serde_json::Value>(&observation.output).is_ok() {
passed = passed.saturating_add(1);
} else {
notes.push("output was not valid JSON".to_string());
}
}
if let Some(max) = task.max_output_tokens {
checks = checks.saturating_add(1);
match observation.output_tokens {
Some(tokens) if tokens <= max => {
passed = passed.saturating_add(1);
}
Some(tokens) => notes.push(format!("output tokens {tokens} exceeded max {max}")),
None => notes.push("runner did not report output tokens".to_string()),
}
}
let score = if checks == 0 {
1.0
} else {
passed as f64 / checks as f64
};
ModelBehaviorResult {
task_id: task.id.clone(),
score,
passed: (score - 1.0).abs() < f64::EPSILON,
observation,
notes,
}
}