1use std::future::Future;
4use std::sync::{Arc, Mutex, PoisonError};
5
6use rig_agent::Agent;
7use rig_agent::AgentRunner;
8use rig_agent::agent::{AgentHook, HookContext, OutcomeAction, OutcomeEvent};
9use rig_core::completion::GenerationOptions;
10use rig_core::completion::Usage;
11use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
12
13use crate::checkpoint::{Journal, Saving};
14use crate::events::{Emit, EmitText, stream_agent};
15use crate::human::{Question, answer};
16
17pub type NodeError = rig_core::error::BoxError;
19
20#[derive(Debug, Clone, Default)]
22#[non_exhaustive]
23pub struct NodeOutput {
24 pub text: String,
26 pub usage: Usage,
28}
29
30impl NodeOutput {
31 pub fn new(text: impl Into<String>) -> Self {
33 Self {
34 text: text.into(),
35 usage: Usage::default(),
36 }
37 }
38
39 #[must_use]
41 pub fn with_usage(mut self, usage: Usage) -> Self {
42 self.usage = usage;
43 self
44 }
45}
46
47pub trait Node: WasmCompatSend + WasmCompatSync {
53 fn run<'a>(
57 &'a self,
58 input: String,
59 io: &'a NodeIo<'a>,
60 ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>>;
61}
62
63pub struct NodeIo<'a> {
66 node: &'a str,
67 text: Option<EmitText<'a>>,
68 question: Option<Emit<'a, Question>>,
69 saving: Option<Saving>,
70 turns: Option<usize>,
71}
72
73impl<'a> NodeIo<'a> {
74 pub fn quiet(node: &'a str) -> Self {
77 Self {
78 node,
79 text: None,
80 question: None,
81 saving: None,
82 turns: None,
83 }
84 }
85
86 pub fn streaming(node: &'a str, text: EmitText<'a>, question: Emit<'a, Question>) -> Self {
89 Self {
90 node,
91 text: Some(text),
92 question: Some(question),
93 saving: None,
94 turns: None,
95 }
96 }
97
98 pub(crate) fn saving_to(mut self, saving: Option<Saving>) -> Self {
99 self.saving = saving;
100 self
101 }
102
103 pub(crate) fn with_turns(mut self, turns: usize) -> Self {
106 self.turns = Some(turns);
107 self
108 }
109
110 fn turns(&self) -> Option<usize> {
112 self.turns
113 }
114
115 pub fn node(&self) -> &str {
117 self.node
118 }
119
120 pub fn is_streaming(&self) -> bool {
122 self.text.is_some()
123 }
124
125 pub fn text(&self, text: &str) {
127 if let Some(sink) = self.text {
128 sink(text);
129 }
130 }
131
132 pub async fn ask(
135 &self,
136 question: impl Into<String>,
137 context: impl Into<String>,
138 ) -> Result<String, NodeError> {
139 let Some(ask) = self.question else {
140 return Err("this node asks a person: run the graph with stream()".into());
141 };
142 let (question, reply) = Question::new(self.node, question, context);
143 ask(question);
144 answer(reply).await
145 }
146
147 pub(crate) fn forward(&self, question: Question) {
149 if let Some(ask) = self.question {
150 ask(question.via(self.node));
151 }
152 }
153
154 pub(crate) fn saving(&self) -> Option<&Saving> {
156 self.saving.as_ref()
157 }
158}
159
160impl Node for Agent {
161 fn run<'a>(
164 &'a self,
165 input: String,
166 io: &'a NodeIo<'a>,
167 ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
168 Box::pin(async move {
169 let meter = Meter::default();
170 let key = io.saving().map(|saving| saving.run_id.clone());
171 let mut runner = in_conversation(self.prompt(input), self, key);
172 if let Some(turns) = io.turns() {
173 runner = runner.max_turns(turn_budget(self, turns));
174 }
175 runner = runner.add_hook(meter.clone());
176 if let Some(saving) = io.saving() {
177 runner = runner.add_hook(Journal::open(saving.kind("journal")).await?);
178 }
179 let response = if io.is_streaming() {
180 stream_agent(runner, &|text: &str| io.text(text)).await?
181 } else {
182 runner.run().await?
183 };
184 Ok(NodeOutput::new(response.output()).with_usage(meter.total()))
185 })
186 }
187}
188
189pub struct FnNode<F>(F);
191
192pub fn node_fn<F, Fut>(f: F) -> FnNode<F>
200where
201 F: Fn(String) -> Fut + WasmCompatSend + WasmCompatSync,
202 Fut: Future<Output = Result<String, NodeError>> + WasmCompatSend + 'static,
203{
204 FnNode(f)
205}
206
207impl<F, Fut> Node for FnNode<F>
208where
209 F: Fn(String) -> Fut + WasmCompatSend + WasmCompatSync,
210 Fut: Future<Output = Result<String, NodeError>> + WasmCompatSend + 'static,
211{
212 fn run<'a>(
213 &'a self,
214 input: String,
215 _io: &'a NodeIo<'a>,
216 ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
217 let future = (self.0)(input);
218 Box::pin(async move { Ok(NodeOutput::new(future.await?)) })
219 }
220}
221
222pub(crate) fn turn_budget(agent: &Agent, configured: usize) -> usize {
228 agent.run_spec().effective_max_turns().max(configured)
229}
230
231pub(crate) fn in_conversation(
236 runner: AgentRunner,
237 agent: &Agent,
238 key: Option<String>,
239) -> AgentRunner {
240 if agent.run_spec().options.cache_key.is_some() {
241 return runner;
242 }
243 let key = key.unwrap_or_else(fresh_key);
244 runner.options(GenerationOptions::default().cache_key(key))
245}
246
247fn fresh_key() -> String {
249 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
250 let started = std::time::SystemTime::now()
251 .duration_since(std::time::UNIX_EPOCH)
252 .map_or(0, |since| since.as_nanos());
253 let run = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
254 format!("rig-multiagent-{}-{started:x}-{run}", std::process::id())
255}
256
257#[derive(Clone, Default)]
261pub(crate) struct Meter(Arc<Mutex<Usage>>);
262
263impl Meter {
264 pub(crate) fn total(&self) -> Usage {
265 *self.0.lock().unwrap_or_else(PoisonError::into_inner)
266 }
267}
268
269impl AgentHook for Meter {
270 async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
271 if let Some(completion) = event.completion() {
272 *self.0.lock().unwrap_or_else(PoisonError::into_inner) += completion.usage;
273 }
274 OutcomeAction::proceed()
275 }
276}