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::graph::RunState;
16use crate::human::{Question, answer};
17
18pub type NodeError = rig_core::error::BoxError;
20
21#[derive(Debug, Clone, Default)]
23#[non_exhaustive]
24pub struct NodeOutput {
25 pub text: String,
27 pub usage: Usage,
29}
30
31impl NodeOutput {
32 pub fn new(text: impl Into<String>) -> Self {
34 Self {
35 text: text.into(),
36 usage: Usage::default(),
37 }
38 }
39
40 #[must_use]
42 pub fn with_usage(mut self, usage: Usage) -> Self {
43 self.usage = usage;
44 self
45 }
46}
47
48pub trait Node: WasmCompatSend + WasmCompatSync {
54 fn run<'a>(
58 &'a self,
59 input: String,
60 io: &'a NodeIo<'a>,
61 ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>>;
62}
63
64pub struct NodeIo<'a> {
67 node: &'a str,
68 text: Option<EmitText<'a>>,
69 question: Option<Emit<'a, Question>>,
70 saving: Option<Saving>,
71 turns: Option<usize>,
72 run: RunState,
73}
74
75impl<'a> NodeIo<'a> {
76 pub fn quiet(node: &'a str) -> Self {
79 Self {
80 node,
81 text: None,
82 question: None,
83 saving: None,
84 turns: None,
85 run: RunState::default(),
86 }
87 }
88
89 pub fn streaming(node: &'a str, text: EmitText<'a>, question: Emit<'a, Question>) -> Self {
92 Self {
93 node,
94 text: Some(text),
95 question: Some(question),
96 saving: None,
97 turns: None,
98 run: RunState::default(),
99 }
100 }
101
102 pub(crate) fn saving_to(mut self, saving: Option<Saving>) -> Self {
103 self.saving = saving;
104 self
105 }
106
107 pub(crate) fn with_turns(mut self, turns: usize) -> Self {
110 self.turns = Some(turns);
111 self
112 }
113
114 pub(crate) fn with_run_state(mut self, run: RunState) -> Self {
116 self.run = run;
117 self
118 }
119
120 fn turns(&self) -> Option<usize> {
122 self.turns
123 }
124
125 pub fn run_state(&self) -> &RunState {
128 &self.run
129 }
130
131 pub fn node(&self) -> &str {
133 self.node
134 }
135
136 pub fn is_streaming(&self) -> bool {
138 self.text.is_some()
139 }
140
141 pub fn text(&self, text: &str) {
143 if let Some(sink) = self.text {
144 sink(text);
145 }
146 }
147
148 pub async fn ask(
151 &self,
152 question: impl Into<String>,
153 context: impl Into<String>,
154 ) -> Result<String, NodeError> {
155 let Some(ask) = self.question else {
156 return Err("this node asks a person: run the graph with stream()".into());
157 };
158 let (question, reply) = Question::new(self.node, question, context);
159 ask(question);
160 answer(reply).await
161 }
162
163 pub(crate) fn forward(&self, question: Question) {
165 if let Some(ask) = self.question {
166 ask(question.via(self.node));
167 }
168 }
169
170 pub(crate) fn saving(&self) -> Option<&Saving> {
172 self.saving.as_ref()
173 }
174}
175
176impl Node for Agent {
177 fn run<'a>(
180 &'a self,
181 input: String,
182 io: &'a NodeIo<'a>,
183 ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
184 Box::pin(async move {
185 let meter = Meter::default();
186 let key = io.saving().map(|saving| saving.run_id.clone());
187 let mut runner = in_conversation(self.prompt(input), self, key);
188 if let Some(turns) = io.turns() {
189 runner = runner.max_turns(turn_budget(self, turns));
190 }
191 runner = runner.add_hook(meter.clone());
192 if let Some(saving) = io.saving() {
193 runner = runner.add_hook(Journal::open(saving.kind("journal")).await?);
194 }
195 let response = if io.is_streaming() {
196 stream_agent(runner, &|text: &str| io.text(text)).await?
197 } else {
198 runner.run().await?
199 };
200 Ok(NodeOutput::new(response.output()).with_usage(meter.total()))
201 })
202 }
203}
204
205pub struct FnNode<F>(F);
207
208pub fn node_fn<F, Fut>(f: F) -> FnNode<F>
216where
217 F: Fn(String) -> Fut + WasmCompatSend + WasmCompatSync,
218 Fut: Future<Output = Result<String, NodeError>> + WasmCompatSend + 'static,
219{
220 FnNode(f)
221}
222
223pub fn node_fn_with_state<F, Fut>(f: F) -> StateFnNode<F>
235where
236 F: Fn(String, RunState) -> Fut + WasmCompatSend + WasmCompatSync,
237 Fut: Future<Output = Result<String, NodeError>> + WasmCompatSend + 'static,
238{
239 StateFnNode(f)
240}
241
242pub struct StateFnNode<F>(F);
245
246impl<F, Fut> Node for StateFnNode<F>
247where
248 F: Fn(String, RunState) -> Fut + WasmCompatSend + WasmCompatSync,
249 Fut: Future<Output = Result<String, NodeError>> + WasmCompatSend + 'static,
250{
251 fn run<'a>(
252 &'a self,
253 input: String,
254 io: &'a NodeIo<'a>,
255 ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
256 let future = (self.0)(input, io.run_state().clone());
257 Box::pin(async move { Ok(NodeOutput::new(future.await?)) })
258 }
259}
260
261impl<F, Fut> Node for FnNode<F>
262where
263 F: Fn(String) -> Fut + WasmCompatSend + WasmCompatSync,
264 Fut: Future<Output = Result<String, NodeError>> + WasmCompatSend + 'static,
265{
266 fn run<'a>(
267 &'a self,
268 input: String,
269 _io: &'a NodeIo<'a>,
270 ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
271 let future = (self.0)(input);
272 Box::pin(async move { Ok(NodeOutput::new(future.await?)) })
273 }
274}
275
276pub(crate) fn turn_budget(agent: &Agent, configured: usize) -> usize {
282 agent.run_spec().effective_max_turns().max(configured)
283}
284
285pub(crate) fn in_conversation(
290 runner: AgentRunner,
291 agent: &Agent,
292 key: Option<String>,
293) -> AgentRunner {
294 if agent.run_spec().options.cache_key.is_some() {
295 return runner;
296 }
297 let key = key.unwrap_or_else(fresh_key);
298 runner.options(GenerationOptions::default().cache_key(key))
299}
300
301fn fresh_key() -> String {
303 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
304 let started = std::time::SystemTime::now()
305 .duration_since(std::time::UNIX_EPOCH)
306 .map_or(0, |since| since.as_nanos());
307 let run = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
308 format!("rig-multiagent-{}-{started:x}-{run}", std::process::id())
309}
310
311#[derive(Clone, Default)]
315pub(crate) struct Meter(Arc<Mutex<Usage>>);
316
317impl Meter {
318 pub(crate) fn total(&self) -> Usage {
319 *self.0.lock().unwrap_or_else(PoisonError::into_inner)
320 }
321}
322
323impl AgentHook for Meter {
324 async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
325 if let Some(completion) = event.completion() {
326 *self.0.lock().unwrap_or_else(PoisonError::into_inner) += completion.usage;
327 }
328 OutcomeAction::proceed()
329 }
330}