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, Default, PartialEq)]
52#[non_exhaustive]
53pub struct TargetOutput {
54 pub output: String,
56 pub tool_calls: Vec<ToolCall>,
58 pub usage: Usage,
60 pub session_id: Option<String>,
62}
63
64impl TargetOutput {
65 pub fn new(output: impl Into<String>) -> Self {
67 Self {
68 output: output.into(),
69 ..Self::default()
70 }
71 }
72
73 #[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 #[must_use]
82 pub fn with_usage(mut self, usage: Usage) -> Self {
83 self.usage = usage;
84 self
85 }
86
87 #[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
107pub trait Target: WasmCompatSend + WasmCompatSync {
109 fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>>;
111}
112
113impl Target for Agent {
114 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
135pub struct FnTarget<F>(F);
137
138pub 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#[cfg(feature = "multiagent")]
170pub struct NodeTarget<N>(N);
171
172#[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}