Skip to main content

rig_multiagent/
human.rs

1//! Asking a person: questions, the node that asks one, and the run clock that
2//! stops while a person thinks.
3
4use std::future::Future;
5use std::sync::{Arc, Mutex, PoisonError};
6use std::time::{Duration, Instant};
7
8use rig_core::wasm_compat::WasmBoxedFuture;
9use tokio::sync::oneshot;
10
11use crate::node::{Node, NodeError, NodeIo, NodeOutput};
12
13/// A question for a person, reported by a streamed run. The part of the run
14/// that asked waits until it is [answered](Self::answer); time spent waiting
15/// does not count against the run's timeouts. Dropping it unanswered tells
16/// the asker that nobody answered.
17pub struct Question {
18    from: String,
19    question: String,
20    context: String,
21    reply: oneshot::Sender<String>,
22    /// Stops the run clocks of every level the question passed through,
23    /// until it is answered or dropped.
24    _paused: Vec<Pause>,
25}
26
27impl std::fmt::Debug for Question {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        f.debug_struct("Question")
30            .field("from", &self.from)
31            .field("question", &self.question)
32            .field("context", &self.context)
33            .finish_non_exhaustive()
34    }
35}
36
37impl Question {
38    pub(crate) fn new(
39        from: impl Into<String>,
40        question: impl Into<String>,
41        context: impl Into<String>,
42    ) -> (Self, oneshot::Receiver<String>) {
43        let (reply, answer) = oneshot::channel();
44        let question = Self {
45            from: from.into(),
46            question: question.into(),
47            context: context.into(),
48            reply,
49            _paused: Vec::new(),
50        };
51        (question, answer)
52    }
53
54    /// Who asks: a graph node or swarm agent, with the nodes it sits in
55    /// before it (`review/approve`, `team/planner`).
56    pub fn from(&self) -> &str {
57        &self.from
58    }
59
60    /// The question.
61    pub fn question(&self) -> &str {
62        &self.question
63    }
64
65    /// What the question is about: for a [`human`] node, its input (the
66    /// work to approve, say). Empty when the asker gave none.
67    pub fn context(&self) -> &str {
68        &self.context
69    }
70
71    /// Answer it; the run carries on.
72    pub fn answer(self, answer: impl Into<String>) {
73        // The asker may be gone (its run stopped); nobody to tell then.
74        let _ = self.reply.send(answer.into());
75    }
76
77    /// The same question, stopping `clock` until it is answered.
78    pub(crate) fn pausing(mut self, clock: &Clock) -> Self {
79        self._paused.push(clock.pause());
80        self
81    }
82
83    /// The same question, as seen from the node `node` it came out of.
84    pub(crate) fn via(mut self, node: &str) -> Self {
85        self.from = format!("{node}/{}", self.from);
86        self
87    }
88}
89
90/// Wait for the answer to a question the asker sent.
91pub(crate) async fn answer(answer: oneshot::Receiver<String>) -> Result<String, NodeError> {
92    answer
93        .await
94        .map_err(|_| "the question was dismissed without an answer".into())
95}
96
97/// A graph node that asks a person; see [`human`].
98pub struct HumanNode {
99    question: String,
100}
101
102/// A graph node that asks a person `question`, with its input as the
103/// question's [context](Question::context), and outputs their answer.
104///
105/// Only a [streamed](crate::Graph::stream) run can ask; a plain run fails at
106/// this node. To gate work on an answer, put the condition on the edges into
107/// the gated node, from the human node and from the work:
108///
109/// ```
110/// use rig_multiagent::{Graph, GraphState, human, node_fn};
111/// # let build = node_fn(|_: String| async { Ok("release notes".to_owned()) });
112/// # let deploy = node_fn(|input: String| async move { Ok(input) });
113/// let approved = |state: &GraphState| state.output("approve") == Some("yes");
114/// let graph = Graph::builder()
115///     .node("build", build)
116///     .node("approve", human("Deploy this release? (yes/no)"))
117///     .node("deploy", deploy)
118///     .edge("build", "approve")
119///     .edge_if("approve", "deploy", approved)
120///     .edge_if("build", "deploy", approved) // so deploy gets the build too
121///     .build()?;
122/// # Ok::<(), rig_multiagent::BuildError>(())
123/// ```
124pub fn human(question: impl Into<String>) -> HumanNode {
125    HumanNode {
126        question: question.into(),
127    }
128}
129
130impl Node for HumanNode {
131    fn run<'a>(
132        &'a self,
133        input: String,
134        io: &'a NodeIo<'a>,
135    ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
136        Box::pin(async move { Ok(NodeOutput::new(io.ask(&self.question, input).await?)) })
137    }
138}
139
140/// A run's clock: time that counts against its timeouts, which stops while
141/// any question of the run waits for a person.
142#[derive(Clone)]
143pub(crate) struct Clock(Arc<Mutex<ClockState>>);
144
145struct ClockState {
146    /// Counted time from before a restart.
147    offset: Duration,
148    started: Instant,
149    paused_total: Duration,
150    paused_since: Option<Instant>,
151    pauses: usize,
152}
153
154impl Clock {
155    /// A clock that has already counted `offset`, for a resumed run.
156    pub(crate) fn resumed(offset: Duration) -> Self {
157        Self(Arc::new(Mutex::new(ClockState {
158            offset,
159            started: Instant::now(),
160            paused_total: Duration::ZERO,
161            paused_since: None,
162            pauses: 0,
163        })))
164    }
165
166    fn state(&self) -> std::sync::MutexGuard<'_, ClockState> {
167        self.0.lock().unwrap_or_else(PoisonError::into_inner)
168    }
169
170    /// The time that counts so far.
171    pub(crate) fn active(&self) -> Duration {
172        let state = self.state();
173        let now = Instant::now();
174        let paused = state.paused_total
175            + state
176                .paused_since
177                .map_or(Duration::ZERO, |since| now - since);
178        state.offset + (now - state.started).saturating_sub(paused)
179    }
180
181    fn is_paused(&self) -> bool {
182        self.state().pauses > 0
183    }
184
185    fn pause(&self) -> Pause {
186        let mut state = self.state();
187        state.pauses += 1;
188        if state.pauses == 1 {
189            state.paused_since = Some(Instant::now());
190        }
191        Pause(self.clone())
192    }
193
194    /// `future`'s output, or `None` once it has used `budget` of counted time.
195    pub(crate) async fn within<F: Future>(&self, budget: Duration, future: F) -> Option<F::Output> {
196        let start = self.active();
197        let mut future = std::pin::pin!(future);
198        loop {
199            let left = budget.saturating_sub(self.active().saturating_sub(start));
200            let paused = self.is_paused();
201            if left.is_zero() && !paused {
202                return None;
203            }
204            // While paused the counted time stands still: check back later.
205            let wait = if paused {
206                left.max(Duration::from_secs(1))
207            } else {
208                left
209            };
210            tokio::select! {
211                output = &mut future => return Some(output),
212                () = tokio::time::sleep(wait) => {}
213            }
214        }
215    }
216}
217
218/// Holds a clock stopped; dropping it restarts the clock once no other
219/// pause holds it.
220pub(crate) struct Pause(Clock);
221
222impl Drop for Pause {
223    fn drop(&mut self) {
224        let mut state = self.0.state();
225        state.pauses -= 1;
226        if state.pauses == 0
227            && let Some(since) = state.paused_since.take()
228        {
229            state.paused_total += since.elapsed();
230        }
231    }
232}