Skip to main content

rig_multiagent/
node.rs

1//! What a graph runs: agents, swarms, graphs and plain async functions.
2
3use 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
17/// Why a node failed: a boxed error, `Send + Sync` except on wasm.
18pub type NodeError = rig_core::error::BoxError;
19
20/// What a node produced.
21#[derive(Debug, Clone, Default)]
22#[non_exhaustive]
23pub struct NodeOutput {
24    /// The text handed to the nodes that follow.
25    pub text: String,
26    /// The model tokens the node spent.
27    pub usage: Usage,
28}
29
30impl NodeOutput {
31    /// An output with no model usage.
32    pub fn new(text: impl Into<String>) -> Self {
33        Self {
34            text: text.into(),
35            usage: Usage::default(),
36        }
37    }
38
39    /// Record the model tokens spent producing it.
40    #[must_use]
41    pub fn with_usage(mut self, usage: Usage) -> Self {
42        self.usage = usage;
43        self
44    }
45}
46
47/// One step of a [`Graph`](crate::Graph): takes the text built from the task
48/// and the outputs before it, and produces text.
49///
50/// Implemented for Rig agents, [`Swarm`](crate::Swarm)s, [`Graph`](crate::Graph)s,
51/// [`human`](crate::human) and, through [`node_fn`], async functions.
52pub trait Node: WasmCompatSend + WasmCompatSync {
53    /// Run the step on `input`. Through `io` it can report the text it
54    /// writes and ask a person, when the graph run is
55    /// [streamed](crate::Graph::stream).
56    fn run<'a>(
57        &'a self,
58        input: String,
59        io: &'a NodeIo<'a>,
60    ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>>;
61}
62
63/// What a node can do while it runs: report text and ask a person (in a
64/// streamed run), and keep its progress (in a checkpointed one).
65pub 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    /// The view of node `node` in a plain run: its text goes nowhere, and
74    /// it cannot ask. Build one to run a node yourself.
75    pub fn quiet(node: &'a str) -> Self {
76        Self {
77            node,
78            text: None,
79            question: None,
80            saving: None,
81        }
82    }
83
84    /// The view of node `node` in a streamed run: its text goes to `text`,
85    /// its questions to `question`.
86    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    /// The node's id.
101    pub fn node(&self) -> &str {
102        self.node
103    }
104
105    /// Whether the run is streamed: text is reported and questions asked.
106    pub fn is_streaming(&self) -> bool {
107        self.text.is_some()
108    }
109
110    /// Report text the node wrote; nothing in a plain run.
111    pub fn text(&self, text: &str) {
112        if let Some(sink) = self.text {
113            sink(text);
114        }
115    }
116
117    /// Ask a person `question` about `context`, and wait for the answer.
118    /// Fails in a plain run, where nobody can answer.
119    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    /// Pass on a question from inside the node (a nested swarm's agent).
133    pub(crate) fn forward(&self, question: Question) {
134        if let Some(ask) = self.question {
135            ask(question.via(self.node));
136        }
137    }
138
139    /// Where this run of the node keeps its progress, in a checkpointed run.
140    pub(crate) fn saving(&self) -> Option<&Saving> {
141        self.saving.as_ref()
142    }
143}
144
145impl Node for Agent {
146    /// In a checkpointed run, the agent's tool results go to a journal, so
147    /// a resumed run replays them rather than executing the tools again.
148    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
171/// A node made of an async function; see [`node_fn`].
172pub struct FnNode<F>(F);
173
174/// A node that runs `f`: deterministic steps between agents (parsing,
175/// validation, a lookup, a tool) without a model call.
176///
177/// ```
178/// use rig_multiagent::node_fn;
179/// let shout = node_fn(|input: String| async move { Ok(input.to_uppercase()) });
180/// ```
181pub 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
204/// Give one agent run its own prompt-cache key, `key` or a fresh one, unless
205/// the agent sets its own. Gateways such as OpenCode Go route a
206/// conversation's calls by it and reuse their prompt cache; without one Rig
207/// sends a fresh id with every call, so no call of a run reuses another's.
208pub(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
220/// A key no other run of any process shares.
221fn 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/// Adds up the usage of every completion an agent run makes, including the
231/// ones the run retried or a hook stopped, which `PromptResponse::usage`
232/// misses when the run ends early.
233#[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}