Skip to main content

rig_evals/
target.rs

1//! What an experiment evaluates: Rig agents, async functions and, with the
2//! `multiagent` feature, swarms and graphs.
3
4use std::future::Future;
5
6use rig_agent::Agent;
7use rig_core::completion::Usage;
8use rig_core::message::Message;
9use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12
13use crate::Case;
14
15/// Why a target run failed: a boxed error, `Send + Sync` except on wasm.
16pub type TargetError = rig_core::error::BoxError;
17
18/// A tool call the target made.
19#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
20#[non_exhaustive]
21pub struct ToolCall {
22    /// The tool's name.
23    pub name: String,
24    /// The arguments; a string when the model sent arguments that were not a
25    /// JSON object.
26    pub args: Value,
27}
28
29impl ToolCall {
30    /// A call to `name` with `args`.
31    pub fn new(name: impl Into<String>, args: Value) -> Self {
32        Self {
33            name: name.into(),
34            args,
35        }
36    }
37}
38
39impl From<&rig_core::message::ToolCall> for ToolCall {
40    fn from(call: &rig_core::message::ToolCall) -> Self {
41        let function = &call.function;
42        let args = match &function.invalid_arguments {
43            Some(raw) => Value::String(raw.clone()),
44            None => Value::Object(function.arguments.clone()),
45        };
46        Self::new(function.name.as_str(), args)
47    }
48}
49
50/// One user turn of a multi-turn run and the answer it got.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52#[non_exhaustive]
53pub struct Turn {
54    /// The user's message.
55    pub input: String,
56    /// The target's answer to it.
57    pub output: String,
58}
59
60impl Turn {
61    /// A turn of `input` answered by `output`.
62    pub fn new(input: impl Into<String>, output: impl Into<String>) -> Self {
63        Self {
64            input: input.into(),
65            output: output.into(),
66        }
67    }
68}
69
70/// What one target run produced.
71#[derive(Debug, Clone, Default, PartialEq)]
72#[non_exhaustive]
73pub struct TargetOutput {
74    /// The answer: to the last turn of a multi-turn case.
75    pub output: String,
76    /// The tool calls, in order, over all turns.
77    pub tool_calls: Vec<ToolCall>,
78    /// The model tokens spent, over all turns.
79    pub usage: Usage,
80    /// The session the run belongs to, for evaluators that read its traces.
81    pub session_id: Option<String>,
82    /// Each turn and its answer, in order; empty for a single-turn run.
83    pub transcript: Vec<Turn>,
84}
85
86impl TargetOutput {
87    /// An answer with no tool calls or usage.
88    pub fn new(output: impl Into<String>) -> Self {
89        Self {
90            output: output.into(),
91            ..Self::default()
92        }
93    }
94
95    /// Record the tool calls made.
96    #[must_use]
97    pub fn with_tool_calls(mut self, tool_calls: Vec<ToolCall>) -> Self {
98        self.tool_calls = tool_calls;
99        self
100    }
101
102    /// Record the model tokens spent.
103    #[must_use]
104    pub fn with_usage(mut self, usage: Usage) -> Self {
105        self.usage = usage;
106        self
107    }
108
109    /// Record the session the run belongs to.
110    #[must_use]
111    pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
112        self.session_id = Some(session_id.into());
113        self
114    }
115
116    /// Record the turns of a multi-turn run.
117    #[must_use]
118    pub fn with_transcript(mut self, transcript: Vec<Turn>) -> Self {
119        self.transcript = transcript;
120        self
121    }
122}
123
124impl From<String> for TargetOutput {
125    fn from(output: String) -> Self {
126        Self::new(output)
127    }
128}
129
130impl From<&str> for TargetOutput {
131    fn from(output: &str) -> Self {
132        Self::new(output)
133    }
134}
135
136/// Something to evaluate: runs a case's input and reports what it did.
137pub trait Target: WasmCompatSend + WasmCompatSync {
138    /// Run `case`.
139    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>>;
140}
141
142impl Target for Agent {
143    /// Prompts the agent with the case's input, or with each of its turns in
144    /// order on one conversation (the agent keeps the history between
145    /// turns). The tool calls are the ones in the runs' transcripts; the
146    /// usage is the total over the turns. A multi-turn case that fails part
147    /// way is a [`TurnFailed`] holding the turns that completed.
148    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
149        Box::pin(async move {
150            let multi = !case.turns.is_empty();
151            // A multi-turn case carries its own history, starting empty, so
152            // it does not pick up the agent's memory store; a single-turn
153            // case runs as before.
154            let mut history: Vec<Message> = Vec::new();
155            let mut output = TargetOutput::default();
156            for (number, input) in case.prompts().into_iter().enumerate() {
157                let mut run = self.prompt(input.to_owned());
158                if multi {
159                    run = run.history(history.iter().cloned());
160                }
161                let response = match run.run().await {
162                    Ok(response) => response,
163                    Err(error) => {
164                        return Err(turn_error(multi, number + 1, output, error.into()));
165                    }
166                };
167                output.tool_calls.extend(
168                    response
169                        .messages
170                        .iter()
171                        .filter_map(|message| match message {
172                            Message::Assistant(turn) => Some(turn),
173                            _ => None,
174                        })
175                        .flat_map(|turn| turn.tool_calls().map(ToolCall::from)),
176                );
177                output.usage += response.usage;
178                let answer = response.output();
179                output.transcript.push(Turn::new(input, answer.clone()));
180                output.output = answer;
181                history.extend(response.messages);
182            }
183            if !multi {
184                output.transcript.clear();
185            }
186            Ok(output)
187        })
188    }
189}
190
191/// A multi-turn run that failed at one of its turns. The error of the turn
192/// is prefixed `turn <n>:`; the completed turns, their tool calls and usage
193/// (and the session id, if any) are kept in [`partial`](Self::partial), and
194/// the experiment puts them in the failed trial.
195#[derive(Debug)]
196#[non_exhaustive]
197pub struct TurnFailed {
198    /// The turn that failed, from 1.
199    pub turn: usize,
200    /// What the run had before it failed.
201    pub partial: TargetOutput,
202    cause: TargetError,
203}
204
205impl TurnFailed {
206    /// Turn `turn` failed with `cause`, after the turns in `partial`.
207    pub(crate) fn new(turn: usize, partial: TargetOutput, cause: TargetError) -> Self {
208        Self {
209            turn,
210            partial,
211            cause,
212        }
213    }
214
215    /// The error of the turn.
216    pub fn cause(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
217        self.cause.as_ref()
218    }
219}
220
221impl std::fmt::Display for TurnFailed {
222    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223        write!(f, "turn {}: {}", self.turn, self.cause)
224    }
225}
226
227impl std::error::Error for TurnFailed {}
228
229/// The error of turn `turn` of a run, with what the run had before it. A
230/// single-turn run keeps its error as it is.
231pub(crate) fn turn_error(
232    multi: bool,
233    turn: usize,
234    partial: TargetOutput,
235    cause: TargetError,
236) -> TargetError {
237    if multi {
238        Box::new(TurnFailed::new(turn, partial, cause))
239    } else {
240        cause
241    }
242}
243
244/// A target made of an async function; see [`target_fn`].
245pub struct FnTarget<F>(F);
246
247/// A target that runs `f` on each case: a wrapper around an agent pipeline,
248/// a remote service, or a stub. `f` returns a [`TargetOutput`] or anything
249/// that converts into one (a `String`).
250///
251/// ```
252/// use rig_evals::{Case, TargetError, target_fn};
253/// let echo = target_fn(|case: Case| async move { Ok::<_, TargetError>(case.input) });
254/// ```
255pub fn target_fn<F, Fut, O>(f: F) -> FnTarget<F>
256where
257    F: Fn(Case) -> Fut + WasmCompatSend + WasmCompatSync,
258    Fut: Future<Output = Result<O, TargetError>> + WasmCompatSend + 'static,
259    O: Into<TargetOutput>,
260{
261    FnTarget(f)
262}
263
264impl<F, Fut, O> Target for FnTarget<F>
265where
266    F: Fn(Case) -> Fut + WasmCompatSend + WasmCompatSync,
267    Fut: Future<Output = Result<O, TargetError>> + WasmCompatSend + 'static,
268    O: Into<TargetOutput>,
269{
270    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
271        let future = (self.0)(case.clone());
272        Box::pin(async move { future.await.map(Into::into) })
273    }
274}
275
276/// A rig-multiagent node (a swarm, a graph, an agent) as a target; see
277/// [`node_target`].
278#[cfg(feature = "multiagent")]
279pub struct NodeTarget<N>(N);
280
281/// Evaluate a rig-multiagent [`Node`](rig_multiagent::Node): its answer and
282/// usage. Nodes do not report their tool calls, so trials have none.
283#[cfg(feature = "multiagent")]
284pub fn node_target<N: rig_multiagent::Node>(node: N) -> NodeTarget<N> {
285    NodeTarget(node)
286}
287
288#[cfg(feature = "multiagent")]
289impl<N: rig_multiagent::Node> Target for NodeTarget<N> {
290    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
291        Box::pin(async move {
292            let io = rig_multiagent::NodeIo::quiet(&case.id);
293            let turns = case.prompts();
294            let [prompt] = turns.as_slice() else {
295                return Err(
296                    "a node target runs single-turn cases only; its nodes keep no conversation"
297                        .into(),
298                );
299            };
300            let output = self.0.run((*prompt).to_owned(), &io).await?;
301            Ok(TargetOutput::new(output.text).with_usage(output.usage))
302        })
303    }
304}