1use 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
16pub type TargetError = rig_core::error::BoxError;
18
19#[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 pub(crate) static TRIAL_DEADLINE: Option<Deadline>;
33}
34
35pub(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
43pub(crate) fn timeout_message(limit: Duration) -> String {
45 format!("timed out after {}s", limit.as_secs_f64())
46}
47
48const MAX_RESULT_BYTES: usize = 4096;
51
52#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55#[non_exhaustive]
56pub struct ToolCall {
57 pub name: String,
59 pub args: Value,
62 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub result: Option<String>,
67}
68
69impl ToolCall {
70 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 #[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
98fn 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
155fn 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
182#[non_exhaustive]
183pub struct Turn {
184 pub input: String,
186 pub output: String,
188}
189
190impl Turn {
191 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#[derive(Debug, Clone, Default, PartialEq)]
202#[non_exhaustive]
203pub struct TargetOutput {
204 pub output: String,
206 pub tool_calls: Vec<ToolCall>,
208 pub usage: Usage,
210 pub session_id: Option<String>,
212 pub transcript: Vec<Turn>,
214}
215
216impl TargetOutput {
217 pub fn new(output: impl Into<String>) -> Self {
219 Self {
220 output: output.into(),
221 ..Self::default()
222 }
223 }
224
225 #[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 #[must_use]
234 pub fn with_usage(mut self, usage: Usage) -> Self {
235 self.usage = usage;
236 self
237 }
238
239 #[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 #[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
266pub trait Target: WasmCompatSend + WasmCompatSync {
268 fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>>;
270}
271
272impl Target for Agent {
273 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 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 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#[derive(Debug)]
325#[non_exhaustive]
326pub struct TurnFailed {
327 pub turn: usize,
329 pub partial: TargetOutput,
331 cause: TargetError,
332}
333
334impl TurnFailed {
335 pub(crate) fn new(turn: usize, partial: TargetOutput, cause: TargetError) -> Self {
337 Self {
338 turn,
339 partial,
340 cause,
341 }
342 }
343
344 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
358pub(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
373pub struct FnTarget<F>(F);
375
376pub 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#[cfg(feature = "multiagent")]
408pub struct NodeTarget<N>(N);
409
410#[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}