rig-evals 0.47.3

Evaluations for Rig agents: datasets of cases, built-in and LLM-judge evaluators, repetitions and pass-rate thresholds, JSON, JUnit and Markdown reports, OpenTelemetry GenAI evaluation events.
Documentation
//! What an experiment evaluates: Rig agents, async functions and, with the
//! `multiagent` feature, swarms and graphs.

use std::future::Future;

use rig_agent::Agent;
use rig_core::completion::Usage;
use rig_core::message::Message;
use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::Case;

/// Why a target run failed: a boxed error, `Send + Sync` except on wasm.
pub type TargetError = rig_core::error::BoxError;

/// A tool call the target made.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ToolCall {
    /// The tool's name.
    pub name: String,
    /// The arguments; a string when the model sent arguments that were not a
    /// JSON object.
    pub args: Value,
}

impl ToolCall {
    /// A call to `name` with `args`.
    pub fn new(name: impl Into<String>, args: Value) -> Self {
        Self {
            name: name.into(),
            args,
        }
    }
}

impl From<&rig_core::message::ToolCall> for ToolCall {
    fn from(call: &rig_core::message::ToolCall) -> Self {
        let function = &call.function;
        let args = match &function.invalid_arguments {
            Some(raw) => Value::String(raw.clone()),
            None => Value::Object(function.arguments.clone()),
        };
        Self::new(function.name.as_str(), args)
    }
}

/// One user turn of a multi-turn run and the answer it got.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Turn {
    /// The user's message.
    pub input: String,
    /// The target's answer to it.
    pub output: String,
}

impl Turn {
    /// A turn of `input` answered by `output`.
    pub fn new(input: impl Into<String>, output: impl Into<String>) -> Self {
        Self {
            input: input.into(),
            output: output.into(),
        }
    }
}

/// What one target run produced.
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct TargetOutput {
    /// The answer: to the last turn of a multi-turn case.
    pub output: String,
    /// The tool calls, in order, over all turns.
    pub tool_calls: Vec<ToolCall>,
    /// The model tokens spent, over all turns.
    pub usage: Usage,
    /// The session the run belongs to, for evaluators that read its traces.
    pub session_id: Option<String>,
    /// Each turn and its answer, in order; empty for a single-turn run.
    pub transcript: Vec<Turn>,
}

impl TargetOutput {
    /// An answer with no tool calls or usage.
    pub fn new(output: impl Into<String>) -> Self {
        Self {
            output: output.into(),
            ..Self::default()
        }
    }

    /// Record the tool calls made.
    #[must_use]
    pub fn with_tool_calls(mut self, tool_calls: Vec<ToolCall>) -> Self {
        self.tool_calls = tool_calls;
        self
    }

    /// Record the model tokens spent.
    #[must_use]
    pub fn with_usage(mut self, usage: Usage) -> Self {
        self.usage = usage;
        self
    }

    /// Record the session the run belongs to.
    #[must_use]
    pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
        self.session_id = Some(session_id.into());
        self
    }

    /// Record the turns of a multi-turn run.
    #[must_use]
    pub fn with_transcript(mut self, transcript: Vec<Turn>) -> Self {
        self.transcript = transcript;
        self
    }
}

impl From<String> for TargetOutput {
    fn from(output: String) -> Self {
        Self::new(output)
    }
}

impl From<&str> for TargetOutput {
    fn from(output: &str) -> Self {
        Self::new(output)
    }
}

/// Something to evaluate: runs a case's input and reports what it did.
pub trait Target: WasmCompatSend + WasmCompatSync {
    /// Run `case`.
    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>>;
}

impl Target for Agent {
    /// Prompts the agent with the case's input, or with each of its turns in
    /// order on one conversation (the agent keeps the history between
    /// turns). The tool calls are the ones in the runs' transcripts; the
    /// usage is the total over the turns. A multi-turn case that fails part
    /// way is a [`TurnFailed`] holding the turns that completed.
    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
        Box::pin(async move {
            let multi = !case.turns.is_empty();
            // A multi-turn case carries its own history, starting empty, so
            // it does not pick up the agent's memory store; a single-turn
            // case runs as before.
            let mut history: Vec<Message> = Vec::new();
            let mut output = TargetOutput::default();
            for (number, input) in case.prompts().into_iter().enumerate() {
                let mut run = self.prompt(input.to_owned());
                if multi {
                    run = run.history(history.iter().cloned());
                }
                let response = match run.run().await {
                    Ok(response) => response,
                    Err(error) => {
                        return Err(turn_error(multi, number + 1, output, error.into()));
                    }
                };
                output.tool_calls.extend(
                    response
                        .messages
                        .iter()
                        .filter_map(|message| match message {
                            Message::Assistant(turn) => Some(turn),
                            _ => None,
                        })
                        .flat_map(|turn| turn.tool_calls().map(ToolCall::from)),
                );
                output.usage += response.usage;
                let answer = response.output();
                output.transcript.push(Turn::new(input, answer.clone()));
                output.output = answer;
                history.extend(response.messages);
            }
            if !multi {
                output.transcript.clear();
            }
            Ok(output)
        })
    }
}

/// A multi-turn run that failed at one of its turns. The error of the turn
/// is prefixed `turn <n>:`; the completed turns, their tool calls and usage
/// (and the session id, if any) are kept in [`partial`](Self::partial), and
/// the experiment puts them in the failed trial.
#[derive(Debug)]
#[non_exhaustive]
pub struct TurnFailed {
    /// The turn that failed, from 1.
    pub turn: usize,
    /// What the run had before it failed.
    pub partial: TargetOutput,
    cause: TargetError,
}

impl TurnFailed {
    /// Turn `turn` failed with `cause`, after the turns in `partial`.
    pub(crate) fn new(turn: usize, partial: TargetOutput, cause: TargetError) -> Self {
        Self {
            turn,
            partial,
            cause,
        }
    }

    /// The error of the turn.
    pub fn cause(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
        self.cause.as_ref()
    }
}

impl std::fmt::Display for TurnFailed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "turn {}: {}", self.turn, self.cause)
    }
}

impl std::error::Error for TurnFailed {}

/// The error of turn `turn` of a run, with what the run had before it. A
/// single-turn run keeps its error as it is.
pub(crate) fn turn_error(
    multi: bool,
    turn: usize,
    partial: TargetOutput,
    cause: TargetError,
) -> TargetError {
    if multi {
        Box::new(TurnFailed::new(turn, partial, cause))
    } else {
        cause
    }
}

/// A target made of an async function; see [`target_fn`].
pub struct FnTarget<F>(F);

/// A target that runs `f` on each case: a wrapper around an agent pipeline,
/// a remote service, or a stub. `f` returns a [`TargetOutput`] or anything
/// that converts into one (a `String`).
///
/// ```
/// use rig_evals::{Case, TargetError, target_fn};
/// let echo = target_fn(|case: Case| async move { Ok::<_, TargetError>(case.input) });
/// ```
pub fn target_fn<F, Fut, O>(f: F) -> FnTarget<F>
where
    F: Fn(Case) -> Fut + WasmCompatSend + WasmCompatSync,
    Fut: Future<Output = Result<O, TargetError>> + WasmCompatSend + 'static,
    O: Into<TargetOutput>,
{
    FnTarget(f)
}

impl<F, Fut, O> Target for FnTarget<F>
where
    F: Fn(Case) -> Fut + WasmCompatSend + WasmCompatSync,
    Fut: Future<Output = Result<O, TargetError>> + WasmCompatSend + 'static,
    O: Into<TargetOutput>,
{
    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
        let future = (self.0)(case.clone());
        Box::pin(async move { future.await.map(Into::into) })
    }
}

/// A rig-multiagent node (a swarm, a graph, an agent) as a target; see
/// [`node_target`].
#[cfg(feature = "multiagent")]
pub struct NodeTarget<N>(N);

/// Evaluate a rig-multiagent [`Node`](rig_multiagent::Node): its answer and
/// usage. Nodes do not report their tool calls, so trials have none.
#[cfg(feature = "multiagent")]
pub fn node_target<N: rig_multiagent::Node>(node: N) -> NodeTarget<N> {
    NodeTarget(node)
}

#[cfg(feature = "multiagent")]
impl<N: rig_multiagent::Node> Target for NodeTarget<N> {
    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
        Box::pin(async move {
            let io = rig_multiagent::NodeIo::quiet(&case.id);
            let turns = case.prompts();
            let [prompt] = turns.as_slice() else {
                return Err(
                    "a node target runs single-turn cases only; its nodes keep no conversation"
                        .into(),
                );
            };
            let output = self.0.run((*prompt).to_owned(), &io).await?;
            Ok(TargetOutput::new(output.text).with_usage(output.usage))
        })
    }
}