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}
71
72impl<'a> NodeIo<'a> {
73 pub fn quiet(node: &'a str) -> Self {
76 Self {
77 node,
78 text: None,
79 question: None,
80 saving: None,
81 }
82 }
83
84 pub fn streaming(node: &'a str, text: EmitText<'a>, question: Emit<'a, Question>) -> Self {
87 Self {
88 node,
89 text: Some(text),
90 question: Some(question),
91 saving: None,
92 }
93 }
94
95 pub(crate) fn saving_to(mut self, saving: Option<Saving>) -> Self {
96 self.saving = saving;
97 self
98 }
99
100 pub fn node(&self) -> &str {
102 self.node
103 }
104
105 pub fn is_streaming(&self) -> bool {
107 self.text.is_some()
108 }
109
110 pub fn text(&self, text: &str) {
112 if let Some(sink) = self.text {
113 sink(text);
114 }
115 }
116
117 pub async fn ask(
120 &self,
121 question: impl Into<String>,
122 context: impl Into<String>,
123 ) -> Result<String, NodeError> {
124 let Some(ask) = self.question else {
125 return Err("this node asks a person: run the graph with stream()".into());
126 };
127 let (question, reply) = Question::new(self.node, question, context);
128 ask(question);
129 answer(reply).await
130 }
131
132 pub(crate) fn forward(&self, question: Question) {
134 if let Some(ask) = self.question {
135 ask(question.via(self.node));
136 }
137 }
138
139 pub(crate) fn saving(&self) -> Option<&Saving> {
141 self.saving.as_ref()
142 }
143}
144
145impl Node for Agent {
146 fn run<'a>(
149 &'a self,
150 input: String,
151 io: &'a NodeIo<'a>,
152 ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
153 Box::pin(async move {
154 let meter = Meter::default();
155 let key = io.saving().map(|saving| saving.run_id.clone());
156 let mut runner = in_conversation(self.prompt(input), self, key);
157 runner = runner.add_hook(meter.clone());
158 if let Some(saving) = io.saving() {
159 runner = runner.add_hook(Journal::open(saving.kind("journal")).await?);
160 }
161 let response = if io.is_streaming() {
162 stream_agent(runner, &|text: &str| io.text(text)).await?
163 } else {
164 runner.run().await?
165 };
166 Ok(NodeOutput::new(response.output()).with_usage(meter.total()))
167 })
168 }
169}
170
171pub struct FnNode<F>(F);
173
174pub fn node_fn<F, Fut>(f: F) -> FnNode<F>
182where
183 F: Fn(String) -> Fut + WasmCompatSend + WasmCompatSync,
184 Fut: Future<Output = Result<String, NodeError>> + WasmCompatSend + 'static,
185{
186 FnNode(f)
187}
188
189impl<F, Fut> Node for FnNode<F>
190where
191 F: Fn(String) -> Fut + WasmCompatSend + WasmCompatSync,
192 Fut: Future<Output = Result<String, NodeError>> + WasmCompatSend + 'static,
193{
194 fn run<'a>(
195 &'a self,
196 input: String,
197 _io: &'a NodeIo<'a>,
198 ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
199 let future = (self.0)(input);
200 Box::pin(async move { Ok(NodeOutput::new(future.await?)) })
201 }
202}
203
204pub(crate) fn in_conversation(
209 runner: AgentRunner,
210 agent: &Agent,
211 key: Option<String>,
212) -> AgentRunner {
213 if agent.run_spec().options.cache_key.is_some() {
214 return runner;
215 }
216 let key = key.unwrap_or_else(fresh_key);
217 runner.options(GenerationOptions::default().cache_key(key))
218}
219
220fn fresh_key() -> String {
222 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
223 let started = std::time::SystemTime::now()
224 .duration_since(std::time::UNIX_EPOCH)
225 .map_or(0, |since| since.as_nanos());
226 let run = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
227 format!("rig-multiagent-{}-{started:x}-{run}", std::process::id())
228}
229
230#[derive(Clone, Default)]
234pub(crate) struct Meter(Arc<Mutex<Usage>>);
235
236impl Meter {
237 pub(crate) fn total(&self) -> Usage {
238 *self.0.lock().unwrap_or_else(PoisonError::into_inner)
239 }
240}
241
242impl AgentHook for Meter {
243 async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
244 if let Some(completion) = event.completion() {
245 *self.0.lock().unwrap_or_else(PoisonError::into_inner) += completion.usage;
246 }
247 OutcomeAction::proceed()
248 }
249}