1use 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
15pub type TargetError = rig_core::error::BoxError;
17
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
20#[non_exhaustive]
21pub struct ToolCall {
22 pub name: String,
24 pub args: Value,
27}
28
29impl ToolCall {
30 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52#[non_exhaustive]
53pub struct Turn {
54 pub input: String,
56 pub output: String,
58}
59
60impl Turn {
61 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#[derive(Debug, Clone, Default, PartialEq)]
72#[non_exhaustive]
73pub struct TargetOutput {
74 pub output: String,
76 pub tool_calls: Vec<ToolCall>,
78 pub usage: Usage,
80 pub session_id: Option<String>,
82 pub transcript: Vec<Turn>,
84}
85
86impl TargetOutput {
87 pub fn new(output: impl Into<String>) -> Self {
89 Self {
90 output: output.into(),
91 ..Self::default()
92 }
93 }
94
95 #[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 #[must_use]
104 pub fn with_usage(mut self, usage: Usage) -> Self {
105 self.usage = usage;
106 self
107 }
108
109 #[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 #[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
136pub trait Target: WasmCompatSend + WasmCompatSync {
138 fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>>;
140}
141
142impl Target for Agent {
143 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 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#[derive(Debug)]
196#[non_exhaustive]
197pub struct TurnFailed {
198 pub turn: usize,
200 pub partial: TargetOutput,
202 cause: TargetError,
203}
204
205impl TurnFailed {
206 pub(crate) fn new(turn: usize, partial: TargetOutput, cause: TargetError) -> Self {
208 Self {
209 turn,
210 partial,
211 cause,
212 }
213 }
214
215 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
229pub(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
244pub struct FnTarget<F>(F);
246
247pub 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#[cfg(feature = "multiagent")]
279pub struct NodeTarget<N>(N);
280
281#[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}