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    turns: Option<usize>,
71}
72
73impl<'a> NodeIo<'a> {
74    /// The view of node `node` in a plain run: its text goes nowhere, and
75    /// it cannot ask. Build one to run a node yourself.
76    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    /// The view of node `node` in a streamed run: its text goes to `text`,
87    /// its questions to `question`.
88    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    /// Give an agent node the turn budget its run should have; see
104    /// [`turn_budget`].
105    pub(crate) fn with_turns(mut self, turns: usize) -> Self {
106        self.turns = Some(turns);
107        self
108    }
109
110    /// The turn budget the node's agent run gets, when the graph sets one.
111    fn turns(&self) -> Option<usize> {
112        self.turns
113    }
114
115    /// The node's id.
116    pub fn node(&self) -> &str {
117        self.node
118    }
119
120    /// Whether the run is streamed: text is reported and questions asked.
121    pub fn is_streaming(&self) -> bool {
122        self.text.is_some()
123    }
124
125    /// Report text the node wrote; nothing in a plain run.
126    pub fn text(&self, text: &str) {
127        if let Some(sink) = self.text {
128            sink(text);
129        }
130    }
131
132    /// Ask a person `question` about `context`, and wait for the answer.
133    /// Fails in a plain run, where nobody can answer.
134    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    /// Pass on a question from inside the node (a nested swarm's agent).
148    pub(crate) fn forward(&self, question: Question) {
149        if let Some(ask) = self.question {
150            ask(question.via(self.node));
151        }
152    }
153
154    /// Where this run of the node keeps its progress, in a checkpointed run.
155    pub(crate) fn saving(&self) -> Option<&Saving> {
156        self.saving.as_ref()
157    }
158}
159
160impl Node for Agent {
161    /// In a checkpointed run, the agent's tool results go to a journal, so
162    /// a resumed run replays them rather than executing the tools again.
163    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
189/// A node made of an async function; see [`node_fn`].
190pub struct FnNode<F>(F);
191
192/// A node that runs `f`: deterministic steps between agents (parsing,
193/// validation, a lookup, a tool) without a model call.
194///
195/// ```
196/// use rig_multiagent::node_fn;
197/// let shout = node_fn(|input: String| async move { Ok(input.to_uppercase()) });
198/// ```
199pub 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
222/// The turn budget for one run of `agent` under a swarm or graph that sets
223/// `configured` turns per agent: the larger of the two. A run needs a turn
224/// for each tool call whose result the model reads, so an agent's own
225/// `default_max_turns` is kept when it is higher, and raised to `configured`
226/// when it is lower (Rig's default of one turn included).
227pub(crate) fn turn_budget(agent: &Agent, configured: usize) -> usize {
228    agent.run_spec().effective_max_turns().max(configured)
229}
230
231/// Give one agent run its own prompt-cache key, `key` or a fresh one, unless
232/// the agent sets its own. Gateways such as OpenCode Go route a
233/// conversation's calls by it and reuse their prompt cache; without one Rig
234/// sends a fresh id with every call, so no call of a run reuses another's.
235pub(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
247/// A key no other run of any process shares.
248fn 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/// Adds up the usage of every completion an agent run makes, including the
258/// ones the run retried or a hook stopped, which `PromptResponse::usage`
259/// misses when the run ends early.
260#[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}