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;
5use std::time::Duration;
6
7use rig_agent::Agent;
8use rig_core::completion::Usage;
9use rig_core::message::{Message, ToolResultContent, UserContent};
10use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13
14use crate::Case;
15
16/// Why a target run failed: a boxed error, `Send + Sync` except on wasm.
17pub type TargetError = rig_core::error::BoxError;
18
19/// When a trial ends and the limit it was set from, for the target run of an
20/// experiment with a [`trial_timeout`](crate::Experiment::trial_timeout).
21#[derive(Debug, Clone, Copy)]
22pub(crate) struct Deadline {
23    pub(crate) at: tokio::time::Instant,
24    pub(crate) limit: Duration,
25}
26
27tokio::task_local! {
28    /// The deadline of the trial whose target run this is, `None` when the
29    /// trial has no timeout. An agent target stops each turn at it, so a
30    /// timed-out run keeps its completed turns. Every target run sets it, so
31    /// a run nested in another never inherits the outer deadline.
32    pub(crate) static TRIAL_DEADLINE: Option<Deadline>;
33}
34
35/// The deadline `limit` from now, or `None` when that overflows the clock
36/// (such as `Duration::MAX`): such a limit is no limit.
37pub(crate) fn deadline_in(limit: Duration) -> Option<Deadline> {
38    tokio::time::Instant::now()
39        .checked_add(limit)
40        .map(|at| Deadline { at, limit })
41}
42
43/// The explanation of a call that outlived `limit`.
44pub(crate) fn timeout_message(limit: Duration) -> String {
45    format!("timed out after {}s", limit.as_secs_f64())
46}
47
48/// The longest tool result kept, in bytes; a longer one is cut at a char
49/// boundary and marked `[truncated]`.
50const MAX_RESULT_BYTES: usize = 4096;
51
52/// A tool call the target made, and the result the tool returned when the
53/// target recorded it.
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55#[non_exhaustive]
56pub struct ToolCall {
57    /// The tool's name.
58    pub name: String,
59    /// The arguments; a string when the model sent arguments that were not a
60    /// JSON object.
61    pub args: Value,
62    /// What the tool returned: its text parts (JSON as its JSON text, images
63    /// as a placeholder) joined by newlines, cut to 4 KiB. `None` when the
64    /// target did not record a result.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub result: Option<String>,
67}
68
69impl ToolCall {
70    /// A call to `name` with `args`, with no result.
71    pub fn new(name: impl Into<String>, args: Value) -> Self {
72        Self {
73            name: name.into(),
74            args,
75            result: None,
76        }
77    }
78
79    /// Record the result the tool returned.
80    #[must_use]
81    pub fn with_result(mut self, result: impl Into<String>) -> Self {
82        self.result = Some(result.into());
83        self
84    }
85}
86
87impl From<&rig_core::message::ToolCall> for ToolCall {
88    fn from(call: &rig_core::message::ToolCall) -> Self {
89        let function = &call.function;
90        let args = match &function.invalid_arguments {
91            Some(raw) => Value::String(raw.clone()),
92            None => Value::Object(function.arguments.clone()),
93        };
94        Self::new(function.name.as_str(), args)
95    }
96}
97
98/// The tool calls of one run's messages, in order, each with the result its
99/// tool returned. A result is matched to its call by id. A call with no
100/// provider id (rig issued a local one) takes the next unmatched result whose
101/// id belongs to no call of the run, so it never takes a later call's result.
102fn tool_calls_of(messages: &[Message]) -> Vec<ToolCall> {
103    let mut results: Vec<(String, Option<String>)> = messages
104        .iter()
105        .filter_map(|message| match message {
106            Message::User { content } => Some(content),
107            _ => None,
108        })
109        .flatten()
110        .filter_map(|part| match part {
111            UserContent::ToolResult(result) => Some((
112                result.call.wire().into_owned(),
113                Some(render_result(&result.content)),
114            )),
115            _ => None,
116        })
117        .collect();
118    let calls: Vec<&rig_core::message::ToolCall> = messages
119        .iter()
120        .filter_map(|message| match message {
121            Message::Assistant(turn) => Some(turn),
122            _ => None,
123        })
124        .flat_map(|turn| turn.tool_calls())
125        .collect();
126    let call_ids: Vec<String> = calls
127        .iter()
128        .map(|call| call.id.wire().into_owned())
129        .collect();
130    calls
131        .into_iter()
132        .map(|call| {
133            let id = call.id.wire();
134            let slot = results
135                .iter()
136                .position(|(result_id, text)| text.is_some() && result_id == id.as_ref())
137                .or_else(|| {
138                    call.id.is_local().then(|| {
139                        results.iter().position(|(result_id, text)| {
140                            text.is_some() && !call_ids.contains(result_id)
141                        })
142                    })?
143                });
144            let tool = ToolCall::from(call);
145            let text =
146                slot.and_then(|slot| results.get_mut(slot).and_then(|(_, text)| text.take()));
147            match text {
148                Some(text) => tool.with_result(text),
149                None => tool,
150            }
151        })
152        .collect()
153}
154
155/// The text of a tool result's parts, joined by newlines and cut to
156/// [`MAX_RESULT_BYTES`].
157fn render_result(content: &[ToolResultContent]) -> String {
158    let text = content
159        .iter()
160        .map(|part| match part {
161            ToolResultContent::Text(text) => text.text.clone(),
162            ToolResultContent::Json { value } => value.to_string(),
163            ToolResultContent::Image(_) => "[image]".to_owned(),
164        })
165        .collect::<Vec<_>>()
166        .join("\n");
167    if text.len() <= MAX_RESULT_BYTES {
168        return text;
169    }
170    let mut end = MAX_RESULT_BYTES;
171    while !text.is_char_boundary(end) {
172        end -= 1;
173    }
174    let mut cut = text;
175    cut.truncate(end);
176    cut.push_str(" [truncated]");
177    cut
178}
179
180/// One user turn of a multi-turn run and the answer it got.
181#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
182#[non_exhaustive]
183pub struct Turn {
184    /// The user's message.
185    pub input: String,
186    /// The target's answer to it.
187    pub output: String,
188}
189
190impl Turn {
191    /// A turn of `input` answered by `output`.
192    pub fn new(input: impl Into<String>, output: impl Into<String>) -> Self {
193        Self {
194            input: input.into(),
195            output: output.into(),
196        }
197    }
198}
199
200/// What one target run produced.
201#[derive(Debug, Clone, Default, PartialEq)]
202#[non_exhaustive]
203pub struct TargetOutput {
204    /// The answer: to the last turn of a multi-turn case.
205    pub output: String,
206    /// The tool calls, in order, over all turns.
207    pub tool_calls: Vec<ToolCall>,
208    /// The model tokens spent, over all turns.
209    pub usage: Usage,
210    /// The session the run belongs to, for evaluators that read its traces.
211    pub session_id: Option<String>,
212    /// Each turn and its answer, in order; empty for a single-turn run.
213    pub transcript: Vec<Turn>,
214}
215
216impl TargetOutput {
217    /// An answer with no tool calls or usage.
218    pub fn new(output: impl Into<String>) -> Self {
219        Self {
220            output: output.into(),
221            ..Self::default()
222        }
223    }
224
225    /// Record the tool calls made.
226    #[must_use]
227    pub fn with_tool_calls(mut self, tool_calls: Vec<ToolCall>) -> Self {
228        self.tool_calls = tool_calls;
229        self
230    }
231
232    /// Record the model tokens spent.
233    #[must_use]
234    pub fn with_usage(mut self, usage: Usage) -> Self {
235        self.usage = usage;
236        self
237    }
238
239    /// Record the session the run belongs to.
240    #[must_use]
241    pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
242        self.session_id = Some(session_id.into());
243        self
244    }
245
246    /// Record the turns of a multi-turn run.
247    #[must_use]
248    pub fn with_transcript(mut self, transcript: Vec<Turn>) -> Self {
249        self.transcript = transcript;
250        self
251    }
252}
253
254impl From<String> for TargetOutput {
255    fn from(output: String) -> Self {
256        Self::new(output)
257    }
258}
259
260impl From<&str> for TargetOutput {
261    fn from(output: &str) -> Self {
262        Self::new(output)
263    }
264}
265
266/// Something to evaluate: runs a case's input and reports what it did.
267pub trait Target: WasmCompatSend + WasmCompatSync {
268    /// Run `case`.
269    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>>;
270}
271
272impl Target for Agent {
273    /// Prompts the agent with the case's input, or with each of its turns in
274    /// order on one conversation (the agent keeps the history between
275    /// turns). The tool calls are the ones in the runs' transcripts, each with
276    /// the result its tool returned; the usage is the total over the turns. A multi-turn case that fails part
277    /// way is a [`TurnFailed`] holding the turns that completed.
278    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
279        Box::pin(async move {
280            let multi = !case.turns.is_empty();
281            let deadline = TRIAL_DEADLINE.try_with(|deadline| *deadline).ok().flatten();
282            // A multi-turn case carries its own history, starting empty, so
283            // it does not pick up the agent's memory store; a single-turn
284            // case runs as before.
285            let mut history: Vec<Message> = Vec::new();
286            let mut output = TargetOutput::default();
287            for (number, input) in case.prompts().into_iter().enumerate() {
288                let mut run = self.prompt(input.to_owned());
289                if multi {
290                    run = run.history(history.iter().cloned());
291                }
292                // Under a trial deadline the turn stops at it, while the
293                // completed turns are still in hand.
294                let outcome: Result<_, TargetError> = match deadline {
295                    Some(deadline) => match tokio::time::timeout_at(deadline.at, run.run()).await {
296                        Ok(result) => result.map_err(Into::into),
297                        Err(_) => Err(timeout_message(deadline.limit).into()),
298                    },
299                    None => run.run().await.map_err(Into::into),
300                };
301                let response = match outcome {
302                    Ok(response) => response,
303                    Err(error) => return Err(turn_error(multi, number + 1, output, error)),
304                };
305                output.tool_calls.extend(tool_calls_of(&response.messages));
306                output.usage += response.usage;
307                let answer = response.output();
308                output.transcript.push(Turn::new(input, answer.clone()));
309                output.output = answer;
310                history.extend(response.messages);
311            }
312            if !multi {
313                output.transcript.clear();
314            }
315            Ok(output)
316        })
317    }
318}
319
320/// A multi-turn run that failed at one of its turns. The error of the turn
321/// is prefixed `turn <n>:`; the completed turns, their tool calls and usage
322/// (and the session id, if any) are kept in [`partial`](Self::partial), and
323/// the experiment puts them in the failed trial.
324#[derive(Debug)]
325#[non_exhaustive]
326pub struct TurnFailed {
327    /// The turn that failed, from 1.
328    pub turn: usize,
329    /// What the run had before it failed.
330    pub partial: TargetOutput,
331    cause: TargetError,
332}
333
334impl TurnFailed {
335    /// Turn `turn` failed with `cause`, after the turns in `partial`.
336    pub(crate) fn new(turn: usize, partial: TargetOutput, cause: TargetError) -> Self {
337        Self {
338            turn,
339            partial,
340            cause,
341        }
342    }
343
344    /// The error of the turn.
345    pub fn cause(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
346        self.cause.as_ref()
347    }
348}
349
350impl std::fmt::Display for TurnFailed {
351    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352        write!(f, "turn {}: {}", self.turn, self.cause)
353    }
354}
355
356impl std::error::Error for TurnFailed {}
357
358/// The error of turn `turn` of a run, with what the run had before it. A
359/// single-turn run keeps its error as it is.
360pub(crate) fn turn_error(
361    multi: bool,
362    turn: usize,
363    partial: TargetOutput,
364    cause: TargetError,
365) -> TargetError {
366    if multi {
367        Box::new(TurnFailed::new(turn, partial, cause))
368    } else {
369        cause
370    }
371}
372
373/// A target made of an async function; see [`target_fn`].
374pub struct FnTarget<F>(F);
375
376/// A target that runs `f` on each case: a wrapper around an agent pipeline,
377/// a remote service, or a stub. `f` returns a [`TargetOutput`] or anything
378/// that converts into one (a `String`).
379///
380/// ```
381/// use rig_evals::{Case, TargetError, target_fn};
382/// let echo = target_fn(|case: Case| async move { Ok::<_, TargetError>(case.input) });
383/// ```
384pub fn target_fn<F, Fut, O>(f: F) -> FnTarget<F>
385where
386    F: Fn(Case) -> Fut + WasmCompatSend + WasmCompatSync,
387    Fut: Future<Output = Result<O, TargetError>> + WasmCompatSend + 'static,
388    O: Into<TargetOutput>,
389{
390    FnTarget(f)
391}
392
393impl<F, Fut, O> Target for FnTarget<F>
394where
395    F: Fn(Case) -> Fut + WasmCompatSend + WasmCompatSync,
396    Fut: Future<Output = Result<O, TargetError>> + WasmCompatSend + 'static,
397    O: Into<TargetOutput>,
398{
399    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
400        let future = (self.0)(case.clone());
401        Box::pin(async move { future.await.map(Into::into) })
402    }
403}
404
405/// A rig-multiagent node (a swarm, a graph, an agent) as a target; see
406/// [`node_target`].
407#[cfg(feature = "multiagent")]
408pub struct NodeTarget<N>(N);
409
410/// Evaluate a rig-multiagent [`Node`](rig_multiagent::Node): its answer and
411/// usage. Nodes do not report their tool calls, so trials have none.
412#[cfg(feature = "multiagent")]
413pub fn node_target<N: rig_multiagent::Node>(node: N) -> NodeTarget<N> {
414    NodeTarget(node)
415}
416
417#[cfg(feature = "multiagent")]
418impl<N: rig_multiagent::Node> Target for NodeTarget<N> {
419    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
420        Box::pin(async move {
421            let io = rig_multiagent::NodeIo::quiet(&case.id);
422            let turns = case.prompts();
423            let [prompt] = turns.as_slice() else {
424                return Err(
425                    "a node target runs single-turn cases only; its nodes keep no conversation"
426                        .into(),
427                );
428            };
429            let output = self.0.run((*prompt).to_owned(), &io).await?;
430            Ok(TargetOutput::new(output.text).with_usage(output.usage))
431        })
432    }
433}
434
435#[cfg(test)]
436mod tests {
437    use rig_core::message::{AssistantContent, Text};
438    use rig_core::message::{
439        AssistantMessage, CallId, LocalCallId, ToolFunction, ToolName, ToolResultContent,
440        UserContent,
441    };
442
443    use super::*;
444
445    #[test]
446    fn a_local_id_call_does_not_take_a_later_provider_call_result() {
447        let call = |id: CallId, name: &str| {
448            AssistantContent::ToolCall(rig_core::message::ToolCall::new(
449                id,
450                ToolFunction::new(ToolName::new(name).expect("name"), serde_json::json!({})),
451            ))
452        };
453        let messages = [
454            Message::Assistant(AssistantMessage::new(vec![
455                call(CallId::Local(LocalCallId::new()), "first"),
456                call(CallId::from_wire("p2"), "second"),
457            ])),
458            Message::User {
459                content: vec![UserContent::tool_result(
460                    CallId::from_wire("p2"),
461                    ToolName::new("second").expect("name"),
462                    vec![ToolResultContent::Text(Text::new("B"))],
463                )],
464            },
465        ];
466        let results: Vec<Option<String>> = tool_calls_of(&messages)
467            .into_iter()
468            .map(|call| call.result)
469            .collect();
470        assert_eq!(results, [None, Some("B".to_owned())]);
471    }
472}