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, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Turn {
pub input: String,
pub output: String,
}
impl Turn {
pub fn new(input: impl Into<String>, output: impl Into<String>) -> Self {
Self {
input: input.into(),
output: output.into(),
}
}
}
#[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>,
pub transcript: Vec<Turn>,
}
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
}
#[must_use]
pub fn with_transcript(mut self, transcript: Vec<Turn>) -> Self {
self.transcript = transcript;
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 multi = !case.turns.is_empty();
let mut history: Vec<Message> = Vec::new();
let mut output = TargetOutput::default();
for (number, input) in case.prompts().into_iter().enumerate() {
let mut run = self.prompt(input.to_owned());
if multi {
run = run.history(history.iter().cloned());
}
let response = match run.run().await {
Ok(response) => response,
Err(error) => {
return Err(turn_error(multi, number + 1, output, error.into()));
}
};
output.tool_calls.extend(
response
.messages
.iter()
.filter_map(|message| match message {
Message::Assistant(turn) => Some(turn),
_ => None,
})
.flat_map(|turn| turn.tool_calls().map(ToolCall::from)),
);
output.usage += response.usage;
let answer = response.output();
output.transcript.push(Turn::new(input, answer.clone()));
output.output = answer;
history.extend(response.messages);
}
if !multi {
output.transcript.clear();
}
Ok(output)
})
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct TurnFailed {
pub turn: usize,
pub partial: TargetOutput,
cause: TargetError,
}
impl TurnFailed {
pub(crate) fn new(turn: usize, partial: TargetOutput, cause: TargetError) -> Self {
Self {
turn,
partial,
cause,
}
}
pub fn cause(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
self.cause.as_ref()
}
}
impl std::fmt::Display for TurnFailed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "turn {}: {}", self.turn, self.cause)
}
}
impl std::error::Error for TurnFailed {}
pub(crate) fn turn_error(
multi: bool,
turn: usize,
partial: TargetOutput,
cause: TargetError,
) -> TargetError {
if multi {
Box::new(TurnFailed::new(turn, partial, cause))
} else {
cause
}
}
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 turns = case.prompts();
let [prompt] = turns.as_slice() else {
return Err(
"a node target runs single-turn cases only; its nodes keep no conversation"
.into(),
);
};
let output = self.0.run((*prompt).to_owned(), &io).await?;
Ok(TargetOutput::new(output.text).with_usage(output.usage))
})
}
}