use std::future::Future;
use std::sync::{Arc, Mutex, PoisonError};
use rig_agent::Agent;
use rig_agent::AgentRunner;
use rig_agent::agent::{AgentHook, HookContext, OutcomeAction, OutcomeEvent};
use rig_core::completion::GenerationOptions;
use rig_core::completion::Usage;
use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
use crate::checkpoint::{Journal, Saving};
use crate::events::{Emit, EmitText, stream_agent};
use crate::human::{Question, answer};
pub type NodeError = rig_core::error::BoxError;
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct NodeOutput {
pub text: String,
pub usage: Usage,
}
impl NodeOutput {
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
usage: Usage::default(),
}
}
#[must_use]
pub fn with_usage(mut self, usage: Usage) -> Self {
self.usage = usage;
self
}
}
pub trait Node: WasmCompatSend + WasmCompatSync {
fn run<'a>(
&'a self,
input: String,
io: &'a NodeIo<'a>,
) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>>;
}
pub struct NodeIo<'a> {
node: &'a str,
text: Option<EmitText<'a>>,
question: Option<Emit<'a, Question>>,
saving: Option<Saving>,
turns: Option<usize>,
}
impl<'a> NodeIo<'a> {
pub fn quiet(node: &'a str) -> Self {
Self {
node,
text: None,
question: None,
saving: None,
turns: None,
}
}
pub fn streaming(node: &'a str, text: EmitText<'a>, question: Emit<'a, Question>) -> Self {
Self {
node,
text: Some(text),
question: Some(question),
saving: None,
turns: None,
}
}
pub(crate) fn saving_to(mut self, saving: Option<Saving>) -> Self {
self.saving = saving;
self
}
pub(crate) fn with_turns(mut self, turns: usize) -> Self {
self.turns = Some(turns);
self
}
fn turns(&self) -> Option<usize> {
self.turns
}
pub fn node(&self) -> &str {
self.node
}
pub fn is_streaming(&self) -> bool {
self.text.is_some()
}
pub fn text(&self, text: &str) {
if let Some(sink) = self.text {
sink(text);
}
}
pub async fn ask(
&self,
question: impl Into<String>,
context: impl Into<String>,
) -> Result<String, NodeError> {
let Some(ask) = self.question else {
return Err("this node asks a person: run the graph with stream()".into());
};
let (question, reply) = Question::new(self.node, question, context);
ask(question);
answer(reply).await
}
pub(crate) fn forward(&self, question: Question) {
if let Some(ask) = self.question {
ask(question.via(self.node));
}
}
pub(crate) fn saving(&self) -> Option<&Saving> {
self.saving.as_ref()
}
}
impl Node for Agent {
fn run<'a>(
&'a self,
input: String,
io: &'a NodeIo<'a>,
) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
Box::pin(async move {
let meter = Meter::default();
let key = io.saving().map(|saving| saving.run_id.clone());
let mut runner = in_conversation(self.prompt(input), self, key);
if let Some(turns) = io.turns() {
runner = runner.max_turns(turn_budget(self, turns));
}
runner = runner.add_hook(meter.clone());
if let Some(saving) = io.saving() {
runner = runner.add_hook(Journal::open(saving.kind("journal")).await?);
}
let response = if io.is_streaming() {
stream_agent(runner, &|text: &str| io.text(text)).await?
} else {
runner.run().await?
};
Ok(NodeOutput::new(response.output()).with_usage(meter.total()))
})
}
}
pub struct FnNode<F>(F);
pub fn node_fn<F, Fut>(f: F) -> FnNode<F>
where
F: Fn(String) -> Fut + WasmCompatSend + WasmCompatSync,
Fut: Future<Output = Result<String, NodeError>> + WasmCompatSend + 'static,
{
FnNode(f)
}
impl<F, Fut> Node for FnNode<F>
where
F: Fn(String) -> Fut + WasmCompatSend + WasmCompatSync,
Fut: Future<Output = Result<String, NodeError>> + WasmCompatSend + 'static,
{
fn run<'a>(
&'a self,
input: String,
_io: &'a NodeIo<'a>,
) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
let future = (self.0)(input);
Box::pin(async move { Ok(NodeOutput::new(future.await?)) })
}
}
pub(crate) fn turn_budget(agent: &Agent, configured: usize) -> usize {
agent.run_spec().effective_max_turns().max(configured)
}
pub(crate) fn in_conversation(
runner: AgentRunner,
agent: &Agent,
key: Option<String>,
) -> AgentRunner {
if agent.run_spec().options.cache_key.is_some() {
return runner;
}
let key = key.unwrap_or_else(fresh_key);
runner.options(GenerationOptions::default().cache_key(key))
}
fn fresh_key() -> String {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let started = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |since| since.as_nanos());
let run = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
format!("rig-multiagent-{}-{started:x}-{run}", std::process::id())
}
#[derive(Clone, Default)]
pub(crate) struct Meter(Arc<Mutex<Usage>>);
impl Meter {
pub(crate) fn total(&self) -> Usage {
*self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl AgentHook for Meter {
async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
if let Some(completion) = event.completion() {
*self.0.lock().unwrap_or_else(PoisonError::into_inner) += completion.usage;
}
OutcomeAction::proceed()
}
}