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::graph::RunState;
16use crate::human::{Question, answer};
17
18/// Why a node failed: a boxed error, `Send + Sync` except on wasm.
19pub type NodeError = rig_core::error::BoxError;
20
21/// What a node produced.
22#[derive(Debug, Clone, Default)]
23#[non_exhaustive]
24pub struct NodeOutput {
25    /// The text handed to the nodes that follow.
26    pub text: String,
27    /// The model tokens the node spent.
28    pub usage: Usage,
29}
30
31impl NodeOutput {
32    /// An output with no model usage.
33    pub fn new(text: impl Into<String>) -> Self {
34        Self {
35            text: text.into(),
36            usage: Usage::default(),
37        }
38    }
39
40    /// Record the model tokens spent producing it.
41    #[must_use]
42    pub fn with_usage(mut self, usage: Usage) -> Self {
43        self.usage = usage;
44        self
45    }
46}
47
48/// One step of a [`Graph`](crate::Graph): takes the text built from the task
49/// and the outputs before it, and produces text.
50///
51/// Implemented for Rig agents, [`Swarm`](crate::Swarm)s, [`Graph`](crate::Graph)s,
52/// [`human`](crate::human) and, through [`node_fn`], async functions.
53pub trait Node: WasmCompatSend + WasmCompatSync {
54    /// Run the step on `input`. Through `io` it can report the text it
55    /// writes and ask a person, when the graph run is
56    /// [streamed](crate::Graph::stream).
57    fn run<'a>(
58        &'a self,
59        input: String,
60        io: &'a NodeIo<'a>,
61    ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>>;
62}
63
64/// What a node can do while it runs: report text and ask a person (in a
65/// streamed run), and keep its progress (in a checkpointed one).
66pub 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    /// The view of node `node` in a plain run: its text goes nowhere, and
77    /// it cannot ask. Build one to run a node yourself.
78    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    /// The view of node `node` in a streamed run: its text goes to `text`,
90    /// its questions to `question`.
91    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    /// Give an agent node the turn budget its run should have; see
108    /// [`turn_budget`].
109    pub(crate) fn with_turns(mut self, turns: usize) -> Self {
110        self.turns = Some(turns);
111        self
112    }
113
114    /// Give the node the request-scoped state of its run; see [`RunState`].
115    pub(crate) fn with_run_state(mut self, run: RunState) -> Self {
116        self.run = run;
117        self
118    }
119
120    /// The turn budget the node's agent run gets, when the graph sets one.
121    fn turns(&self) -> Option<usize> {
122        self.turns
123    }
124
125    /// The request-scoped state of the run the node is part of: what the
126    /// graph was started with, see [`RunState`]. Empty for a node run by hand.
127    pub fn run_state(&self) -> &RunState {
128        &self.run
129    }
130
131    /// The node's id.
132    pub fn node(&self) -> &str {
133        self.node
134    }
135
136    /// Whether the run is streamed: text is reported and questions asked.
137    pub fn is_streaming(&self) -> bool {
138        self.text.is_some()
139    }
140
141    /// Report text the node wrote; nothing in a plain run.
142    pub fn text(&self, text: &str) {
143        if let Some(sink) = self.text {
144            sink(text);
145        }
146    }
147
148    /// Ask a person `question` about `context`, and wait for the answer.
149    /// Fails in a plain run, where nobody can answer.
150    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    /// Pass on a question from inside the node (a nested swarm's agent).
164    pub(crate) fn forward(&self, question: Question) {
165        if let Some(ask) = self.question {
166            ask(question.via(self.node));
167        }
168    }
169
170    /// Where this run of the node keeps its progress, in a checkpointed run.
171    pub(crate) fn saving(&self) -> Option<&Saving> {
172        self.saving.as_ref()
173    }
174}
175
176impl Node for Agent {
177    /// In a checkpointed run, the agent's tool results go to a journal, so
178    /// a resumed run replays them rather than executing the tools again.
179    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
205/// A node made of an async function; see [`node_fn`].
206pub struct FnNode<F>(F);
207
208/// A node that runs `f`: deterministic steps between agents (parsing,
209/// validation, a lookup, a tool) without a model call.
210///
211/// ```
212/// use rig_multiagent::node_fn;
213/// let shout = node_fn(|input: String| async move { Ok(input.to_uppercase()) });
214/// ```
215pub 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
223/// A node that runs `f` with the request-scoped state of its run: as
224/// [`node_fn`], and `f` also gets the [`RunState`] the graph was started with.
225///
226/// ```
227/// use rig_multiagent::{RunState, node_fn_with_state};
228/// struct Prefix(&'static str);
229/// let tag = node_fn_with_state(|input: String, state: RunState| async move {
230///     let prefix = state.get::<Prefix>().map_or("", |prefix| prefix.0);
231///     Ok(format!("{prefix}{input}"))
232/// });
233/// ```
234pub 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
242/// A node made of an async function that reads the run's state; see
243/// [`node_fn_with_state`].
244pub 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
276/// The turn budget for one run of `agent` under a swarm or graph that sets
277/// `configured` turns per agent: the larger of the two. A run needs a turn
278/// for each tool call whose result the model reads, so an agent's own
279/// `default_max_turns` is kept when it is higher, and raised to `configured`
280/// when it is lower (Rig's default of one turn included).
281pub(crate) fn turn_budget(agent: &Agent, configured: usize) -> usize {
282    agent.run_spec().effective_max_turns().max(configured)
283}
284
285/// Give one agent run its own prompt-cache key, `key` or a fresh one, unless
286/// the agent sets its own. Gateways such as OpenCode Go route a
287/// conversation's calls by it and reuse their prompt cache; without one Rig
288/// sends a fresh id with every call, so no call of a run reuses another's.
289pub(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
301/// A key no other run of any process shares.
302fn 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/// Adds up the usage of every completion an agent run makes, including the
312/// ones the run retried or a hook stopped, which `PromptResponse::usage`
313/// misses when the run ends early.
314#[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}