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/// What one target run produced.
51#[derive(Debug, Clone, Default, PartialEq)]
52#[non_exhaustive]
53pub struct TargetOutput {
54    /// The answer.
55    pub output: String,
56    /// The tool calls, in order.
57    pub tool_calls: Vec<ToolCall>,
58    /// The model tokens spent.
59    pub usage: Usage,
60    /// The session the run belongs to, for evaluators that read its traces.
61    pub session_id: Option<String>,
62}
63
64impl TargetOutput {
65    /// An answer with no tool calls or usage.
66    pub fn new(output: impl Into<String>) -> Self {
67        Self {
68            output: output.into(),
69            ..Self::default()
70        }
71    }
72
73    /// Record the tool calls made.
74    #[must_use]
75    pub fn with_tool_calls(mut self, tool_calls: Vec<ToolCall>) -> Self {
76        self.tool_calls = tool_calls;
77        self
78    }
79
80    /// Record the model tokens spent.
81    #[must_use]
82    pub fn with_usage(mut self, usage: Usage) -> Self {
83        self.usage = usage;
84        self
85    }
86
87    /// Record the session the run belongs to.
88    #[must_use]
89    pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
90        self.session_id = Some(session_id.into());
91        self
92    }
93}
94
95impl From<String> for TargetOutput {
96    fn from(output: String) -> Self {
97        Self::new(output)
98    }
99}
100
101impl From<&str> for TargetOutput {
102    fn from(output: &str) -> Self {
103        Self::new(output)
104    }
105}
106
107/// Something to evaluate: runs a case's input and reports what it did.
108pub trait Target: WasmCompatSend + WasmCompatSync {
109    /// Run `case`.
110    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>>;
111}
112
113impl Target for Agent {
114    /// Prompts the agent with the case's input. The tool calls are the ones
115    /// in the run's transcript; the usage is the run's total.
116    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
117        Box::pin(async move {
118            let response = self.prompt(case.input.clone()).run().await?;
119            let tool_calls = response
120                .messages
121                .iter()
122                .filter_map(|message| match message {
123                    Message::Assistant(turn) => Some(turn),
124                    _ => None,
125                })
126                .flat_map(|turn| turn.tool_calls().map(ToolCall::from))
127                .collect();
128            Ok(TargetOutput::new(response.output())
129                .with_tool_calls(tool_calls)
130                .with_usage(response.usage))
131        })
132    }
133}
134
135/// A target made of an async function; see [`target_fn`].
136pub struct FnTarget<F>(F);
137
138/// A target that runs `f` on each case: a wrapper around an agent pipeline,
139/// a remote service, or a stub. `f` returns a [`TargetOutput`] or anything
140/// that converts into one (a `String`).
141///
142/// ```
143/// use rig_evals::{Case, TargetError, target_fn};
144/// let echo = target_fn(|case: Case| async move { Ok::<_, TargetError>(case.input) });
145/// ```
146pub fn target_fn<F, Fut, O>(f: F) -> FnTarget<F>
147where
148    F: Fn(Case) -> Fut + WasmCompatSend + WasmCompatSync,
149    Fut: Future<Output = Result<O, TargetError>> + WasmCompatSend + 'static,
150    O: Into<TargetOutput>,
151{
152    FnTarget(f)
153}
154
155impl<F, Fut, O> Target for FnTarget<F>
156where
157    F: Fn(Case) -> Fut + WasmCompatSend + WasmCompatSync,
158    Fut: Future<Output = Result<O, TargetError>> + WasmCompatSend + 'static,
159    O: Into<TargetOutput>,
160{
161    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
162        let future = (self.0)(case.clone());
163        Box::pin(async move { future.await.map(Into::into) })
164    }
165}
166
167/// A rig-multiagent node (a swarm, a graph, an agent) as a target; see
168/// [`node_target`].
169#[cfg(feature = "multiagent")]
170pub struct NodeTarget<N>(N);
171
172/// Evaluate a rig-multiagent [`Node`](rig_multiagent::Node): its answer and
173/// usage. Nodes do not report their tool calls, so trials have none.
174#[cfg(feature = "multiagent")]
175pub fn node_target<N: rig_multiagent::Node>(node: N) -> NodeTarget<N> {
176    NodeTarget(node)
177}
178
179#[cfg(feature = "multiagent")]
180impl<N: rig_multiagent::Node> Target for NodeTarget<N> {
181    fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
182        Box::pin(async move {
183            let io = rig_multiagent::NodeIo::quiet(&case.id);
184            let output = self.0.run(case.input.clone(), &io).await?;
185            Ok(TargetOutput::new(output.text).with_usage(output.usage))
186        })
187    }
188}