use std::future::Future;
use rig_agent::Agent;
use rig_core::completion::Usage;
use rig_core::message::Message;
use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::Case;
pub type TargetError = rig_core::error::BoxError;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ToolCall {
pub name: String,
pub args: Value,
}
impl ToolCall {
pub fn new(name: impl Into<String>, args: Value) -> Self {
Self {
name: name.into(),
args,
}
}
}
impl From<&rig_core::message::ToolCall> for ToolCall {
fn from(call: &rig_core::message::ToolCall) -> Self {
let function = &call.function;
let args = match &function.invalid_arguments {
Some(raw) => Value::String(raw.clone()),
None => Value::Object(function.arguments.clone()),
};
Self::new(function.name.as_str(), args)
}
}
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct TargetOutput {
pub output: String,
pub tool_calls: Vec<ToolCall>,
pub usage: Usage,
pub session_id: Option<String>,
}
impl TargetOutput {
pub fn new(output: impl Into<String>) -> Self {
Self {
output: output.into(),
..Self::default()
}
}
#[must_use]
pub fn with_tool_calls(mut self, tool_calls: Vec<ToolCall>) -> Self {
self.tool_calls = tool_calls;
self
}
#[must_use]
pub fn with_usage(mut self, usage: Usage) -> Self {
self.usage = usage;
self
}
#[must_use]
pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
self.session_id = Some(session_id.into());
self
}
}
impl From<String> for TargetOutput {
fn from(output: String) -> Self {
Self::new(output)
}
}
impl From<&str> for TargetOutput {
fn from(output: &str) -> Self {
Self::new(output)
}
}
pub trait Target: WasmCompatSend + WasmCompatSync {
fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>>;
}
impl Target for Agent {
fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
Box::pin(async move {
let response = self.prompt(case.input.clone()).run().await?;
let tool_calls = response
.messages
.iter()
.filter_map(|message| match message {
Message::Assistant(turn) => Some(turn),
_ => None,
})
.flat_map(|turn| turn.tool_calls().map(ToolCall::from))
.collect();
Ok(TargetOutput::new(response.output())
.with_tool_calls(tool_calls)
.with_usage(response.usage))
})
}
}
pub struct FnTarget<F>(F);
pub fn target_fn<F, Fut, O>(f: F) -> FnTarget<F>
where
F: Fn(Case) -> Fut + WasmCompatSend + WasmCompatSync,
Fut: Future<Output = Result<O, TargetError>> + WasmCompatSend + 'static,
O: Into<TargetOutput>,
{
FnTarget(f)
}
impl<F, Fut, O> Target for FnTarget<F>
where
F: Fn(Case) -> Fut + WasmCompatSend + WasmCompatSync,
Fut: Future<Output = Result<O, TargetError>> + WasmCompatSend + 'static,
O: Into<TargetOutput>,
{
fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
let future = (self.0)(case.clone());
Box::pin(async move { future.await.map(Into::into) })
}
}
#[cfg(feature = "multiagent")]
pub struct NodeTarget<N>(N);
#[cfg(feature = "multiagent")]
pub fn node_target<N: rig_multiagent::Node>(node: N) -> NodeTarget<N> {
NodeTarget(node)
}
#[cfg(feature = "multiagent")]
impl<N: rig_multiagent::Node> Target for NodeTarget<N> {
fn run<'a>(&'a self, case: &'a Case) -> WasmBoxedFuture<'a, Result<TargetOutput, TargetError>> {
Box::pin(async move {
let io = rig_multiagent::NodeIo::quiet(&case.id);
let output = self.0.run(case.input.clone(), &io).await?;
Ok(TargetOutput::new(output.text).with_usage(output.usage))
})
}
}