1use std::collections::HashMap;
4use std::fmt::Write as _;
5use std::sync::Arc;
6use std::time::{Duration, Instant};
7
8use futures::StreamExt;
9use futures::stream::FuturesUnordered;
10use rig_core::completion::Usage;
11use rig_core::wasm_compat::{WasmBoxedFuture, WasmBoxedStream, WasmCompatSend, WasmCompatSync};
12use serde::{Deserialize, Serialize};
13use tracing::Instrument;
14
15use crate::BuildError;
16use crate::checkpoint::{CheckpointError, Checkpoints, Saving};
17use crate::events::{Emit, events};
18use crate::human::{Clock, Question};
19use crate::node::{Node, NodeError, NodeIo, NodeOutput};
20use crate::swarm::DEFAULT_MAX_TURNS;
21
22#[cfg(not(target_family = "wasm"))]
24type Condition = Arc<dyn Fn(&GraphState) -> bool + Send + Sync>;
25#[cfg(target_family = "wasm")]
27type Condition = Arc<dyn Fn(&GraphState) -> bool>;
28
29#[derive(Clone)]
48pub struct Graph {
49 inner: Arc<Inner>,
50}
51
52struct Inner {
53 nodes: Vec<GraphNode>,
54 edges: Vec<Edge>,
55 entries: Vec<usize>,
56 max_node_executions: Option<usize>,
57 max_turns: usize,
58 execution_timeout: Duration,
59 node_timeout: Duration,
60 checkpoints: Option<Checkpoints>,
61}
62
63struct GraphNode {
64 id: String,
65 node: Box<dyn Node>,
66}
67
68struct Edge {
69 from: usize,
70 to: usize,
71 condition: Option<Condition>,
72}
73
74impl Edge {
75 fn holds(&self, state: &GraphState) -> bool {
76 self.condition
77 .as_ref()
78 .is_none_or(|condition| condition(state))
79 }
80}
81
82#[must_use]
84pub struct GraphBuilder {
85 nodes: Vec<(String, Box<dyn Node>)>,
86 edges: Vec<(String, String, Option<Condition>)>,
87 entries: Vec<String>,
88 max_node_executions: Option<usize>,
89 max_turns: usize,
90 execution_timeout: Duration,
91 node_timeout: Duration,
92 checkpoints: Option<Checkpoints>,
93}
94
95impl Graph {
96 pub fn builder() -> GraphBuilder {
98 GraphBuilder {
99 nodes: Vec::new(),
100 edges: Vec::new(),
101 entries: Vec::new(),
102 max_node_executions: None,
103 max_turns: DEFAULT_MAX_TURNS,
104 execution_timeout: Duration::from_secs(15 * 60),
105 node_timeout: Duration::from_secs(5 * 60),
106 checkpoints: None,
107 }
108 }
109}
110
111impl GraphBuilder {
112 pub fn node(mut self, id: impl Into<String>, node: impl Node + 'static) -> Self {
115 self.nodes.push((id.into(), Box::new(node)));
116 self
117 }
118
119 pub fn edge(mut self, from: impl Into<String>, to: impl Into<String>) -> Self {
121 self.edges.push((from.into(), to.into(), None));
122 self
123 }
124
125 pub fn edge_if(
141 mut self,
142 from: impl Into<String>,
143 to: impl Into<String>,
144 condition: impl Fn(&GraphState) -> bool + WasmCompatSend + WasmCompatSync + 'static,
145 ) -> Self {
146 self.edges
147 .push((from.into(), to.into(), Some(Arc::new(condition))));
148 self
149 }
150
151 pub fn entry(mut self, id: impl Into<String>) -> Self {
154 self.entries.push(id.into());
155 self
156 }
157
158 pub fn max_node_executions(mut self, max: usize) -> Self {
161 self.max_node_executions = Some(max);
162 self
163 }
164
165 pub fn max_turns_per_agent(mut self, max_turns: usize) -> Self {
171 self.max_turns = max_turns;
172 self
173 }
174
175 pub fn execution_timeout(mut self, timeout: Duration) -> Self {
177 self.execution_timeout = timeout;
178 self
179 }
180
181 pub fn node_timeout(mut self, timeout: Duration) -> Self {
183 self.node_timeout = timeout;
184 self
185 }
186
187 pub fn checkpoints(
191 mut self,
192 store: impl rig_memory::AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
193 ) -> Self {
194 self.checkpoints = Some(Checkpoints::new(store, "graph"));
195 self
196 }
197
198 pub fn build(self) -> Result<Graph, BuildError> {
200 if self.nodes.is_empty() {
201 return Err(BuildError::Empty);
202 }
203 if self.max_turns == 0 {
204 return Err(BuildError::ZeroTurns);
205 }
206 let mut nodes: Vec<GraphNode> = Vec::with_capacity(self.nodes.len());
207 for (id, node) in self.nodes {
208 if nodes.iter().any(|other| other.id == id) {
209 return Err(BuildError::DuplicateName(id));
210 }
211 nodes.push(GraphNode { id, node });
212 }
213 let index = |id: &str| {
214 nodes
215 .iter()
216 .position(|node| node.id == id)
217 .ok_or_else(|| BuildError::UnknownName(id.to_owned()))
218 };
219 let mut edges = Vec::with_capacity(self.edges.len());
220 for (from, to, condition) in self.edges {
221 edges.push(Edge {
222 from: index(&from)?,
223 to: index(&to)?,
224 condition,
225 });
226 }
227 let entries = if self.entries.is_empty() {
228 let starts: Vec<usize> = (0..nodes.len())
229 .filter(|&node| !edges.iter().any(|edge| edge.to == node))
230 .collect();
231 if starts.is_empty() {
232 return Err(BuildError::NoEntry);
233 }
234 starts
235 } else {
236 let mut entries = Vec::new();
237 for id in &self.entries {
238 let entry = index(id)?;
239 if !entries.contains(&entry) {
240 entries.push(entry);
241 }
242 }
243 entries
244 };
245 if self.max_node_executions.is_none() && has_cycle(nodes.len(), &edges) {
246 return Err(BuildError::UnboundedCycle);
247 }
248 Ok(Graph {
249 inner: Arc::new(Inner {
250 nodes,
251 edges,
252 entries,
253 max_node_executions: self.max_node_executions,
254 max_turns: self.max_turns,
255 execution_timeout: self.execution_timeout,
256 node_timeout: self.node_timeout,
257 checkpoints: self.checkpoints,
258 }),
259 })
260 }
261}
262
263fn has_cycle(nodes: usize, edges: &[Edge]) -> bool {
265 let mut incoming = vec![0usize; nodes];
268 for edge in edges {
269 if let Some(count) = incoming.get_mut(edge.to) {
270 *count += 1;
271 }
272 }
273 let mut free: Vec<usize> = incoming
274 .iter()
275 .enumerate()
276 .filter(|(_, count)| **count == 0)
277 .map(|(node, _)| node)
278 .collect();
279 let mut peeled = 0;
280 while let Some(node) = free.pop() {
281 peeled += 1;
282 for edge in edges.iter().filter(|edge| edge.from == node) {
283 if let Some(count) = incoming.get_mut(edge.to) {
284 *count -= 1;
285 if *count == 0 {
286 free.push(edge.to);
287 }
288 }
289 }
290 }
291 peeled < nodes
292}
293
294#[derive(Debug, Clone, Default, Serialize, Deserialize)]
296pub struct GraphState {
297 task: String,
298 outputs: HashMap<String, String>,
299 runs: HashMap<String, usize>,
300 #[serde(default)]
302 finished: HashMap<String, usize>,
303 order: Vec<String>,
304}
305
306impl GraphState {
307 pub fn task(&self) -> &str {
309 &self.task
310 }
311
312 pub fn output(&self, id: &str) -> Option<&str> {
314 self.outputs.get(id).map(String::as_str)
315 }
316
317 pub fn runs(&self, id: &str) -> usize {
319 self.runs.get(id).copied().unwrap_or(0)
320 }
321
322 pub fn order(&self) -> &[String] {
324 &self.order
325 }
326}
327
328#[derive(Debug, Clone)]
330#[non_exhaustive]
331pub struct GraphRun {
332 pub state: GraphState,
334 pub last: Vec<String>,
336 pub usage: Usage,
338 pub elapsed: Duration,
340}
341
342impl GraphRun {
343 pub fn output(&self, id: &str) -> Option<&str> {
345 self.state.output(id)
346 }
347
348 pub fn answer(&self) -> String {
351 match self.last.as_slice() {
352 [only] => self.output(only).unwrap_or_default().to_owned(),
353 last => {
354 let mut text = String::new();
355 for id in last {
356 let _ = write!(
357 text,
358 "From {id}:\n{}\n\n",
359 self.output(id).unwrap_or_default()
360 );
361 }
362 text.trim_end().to_owned()
363 }
364 }
365 }
366}
367
368#[derive(Debug, thiserror::Error)]
370#[non_exhaustive]
371pub struct GraphError {
372 pub failures: Vec<GraphFailure>,
374 pub run: GraphRun,
376}
377
378impl std::fmt::Display for GraphError {
379 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
380 match self.failures.as_slice() {
381 [] => f.write_str("the graph run failed"),
382 [only] => only.fmt(f),
383 [first, rest @ ..] => write!(f, "{first} (and {} more failures)", rest.len()),
384 }
385 }
386}
387
388#[derive(Debug)]
390#[non_exhaustive]
391pub enum GraphEvent {
392 Resumed {
395 done: Vec<String>,
397 },
398 NodeStarted {
400 node: String,
402 },
403 Text {
406 node: String,
408 text: String,
410 },
411 NodeFinished {
413 node: String,
415 output: String,
417 },
418 NodeFailed {
420 node: String,
422 error: String,
424 },
425 Question(Question),
428 Finished(Box<Result<GraphRun, GraphError>>),
430}
431
432#[derive(Serialize, Deserialize)]
434struct Saved {
435 finished: bool,
436 state: GraphState,
437 usage: Usage,
438 last: Vec<String>,
439 executions: usize,
440 ready: Vec<String>,
442 #[serde(default)]
444 batch_done: Vec<String>,
445 failed: Vec<String>,
447 active_ms: u64,
448 elapsed_ms: u64,
449}
450
451fn millis(duration: Duration) -> u64 {
452 u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
453}
454
455#[derive(Debug, thiserror::Error)]
457#[non_exhaustive]
458pub enum GraphFailure {
459 #[error("node {node:?} failed: {source}")]
461 Node {
462 node: String,
464 #[source]
466 source: NodeError,
467 },
468 #[error("node {node:?} did not finish in time")]
470 NodeTimeout {
471 node: String,
473 },
474 #[error("checkpoint: {error}")]
476 Checkpoint {
477 #[source]
479 error: CheckpointError,
480 },
481 #[error("the graph ran out of time")]
483 Timeout,
484 #[error("the graph reached its limit of {limit} node runs")]
486 MaxNodeExecutions {
487 limit: usize,
489 },
490}
491
492fn run_span(run_id: Option<&str>) -> tracing::Span {
496 tracing::info_span!(
497 "graph.run",
498 graph.run_id = run_id,
499 graph.node_runs = tracing::field::Empty,
500 graph.usage.input_tokens = tracing::field::Empty,
501 graph.usage.output_tokens = tracing::field::Empty,
502 otel.status_code = tracing::field::Empty,
503 error.type = tracing::field::Empty,
504 )
505}
506
507fn record_outcome(span: &tracing::Span, outcome: &Result<GraphRun, GraphError>) {
509 let run = match outcome {
510 Ok(run) => run,
511 Err(error) => {
512 span.record("otel.status_code", "ERROR");
513 if let Some(failure) = error.failures.first() {
514 span.record("error.type", failure.kind());
515 }
516 &error.run
517 }
518 };
519 span.record("graph.node_runs", run.state.order().len());
520 if let Some(tokens) = run.usage.input_tokens {
521 span.record("graph.usage.input_tokens", tokens);
522 }
523 if let Some(tokens) = run.usage.output_tokens {
524 span.record("graph.usage.output_tokens", tokens);
525 }
526}
527
528fn record_node<T>(span: &tracing::Span, outcome: &Option<Result<T, NodeError>>) {
530 let kind = match outcome {
531 Some(Ok(_)) => return,
532 Some(Err(_)) => "node_failed",
533 None => "timeout",
534 };
535 span.record("otel.status_code", "ERROR");
536 span.record("error.type", kind);
537}
538
539impl GraphFailure {
540 fn kind(&self) -> &'static str {
542 match self {
543 Self::Node { .. } => "node_failed",
544 Self::NodeTimeout { .. } => "node_timeout",
545 Self::Timeout => "timeout",
546 Self::MaxNodeExecutions { .. } => "max_node_executions",
547 Self::Checkpoint { .. } => "checkpoint",
548 }
549 }
550}
551
552impl Graph {
553 pub async fn run(&self, task: impl Into<String>) -> Result<GraphRun, GraphError> {
555 let span = run_span(None);
556 let outcome = self
557 .run_task(task.into(), None, false, None)
558 .instrument(span.clone())
559 .await;
560 record_outcome(&span, &outcome);
561 outcome
562 }
563
564 pub async fn run_as(
577 &self,
578 run_id: &str,
579 task: impl Into<String>,
580 ) -> Result<GraphRun, GraphError> {
581 let span = run_span(Some(run_id));
582 let outcome = self
583 .run_task(task.into(), self.saving(Some(run_id)), false, None)
584 .instrument(span.clone())
585 .await;
586 record_outcome(&span, &outcome);
587 outcome
588 }
589
590 pub fn stream_as<'a>(
594 &'a self,
595 run_id: &'a str,
596 task: impl Into<String>,
597 ) -> WasmBoxedStream<'a, GraphEvent> {
598 self.stream_events(task.into(), Some(run_id))
599 }
600
601 pub fn stream(&self, task: impl Into<String>) -> WasmBoxedStream<'_, GraphEvent> {
607 self.stream_events(task.into(), None)
608 }
609
610 fn stream_events<'a>(
611 &'a self,
612 task: String,
613 run_id: Option<&'a str>,
614 ) -> WasmBoxedStream<'a, GraphEvent> {
615 let span = run_span(run_id);
616 events(
617 move |sender| async move {
618 let emit = move |event| {
619 let _ = sender.send(event);
620 };
621 let outcome = self
622 .run_task(task, self.saving(run_id), false, Some(&emit))
623 .instrument(span.clone())
624 .await;
625 record_outcome(&span, &outcome);
626 outcome
627 },
628 |outcome| GraphEvent::Finished(Box::new(outcome)),
629 )
630 }
631
632 fn saving(&self, run_id: Option<&str>) -> Option<Saving> {
634 run_id
635 .zip(self.inner.checkpoints.clone())
636 .map(|(id, checkpoints)| Saving::new(checkpoints, id))
637 }
638
639 async fn run_task(
643 &self,
644 task: String,
645 saving: Option<Saving>,
646 nested: bool,
647 emit: Option<Emit<'_, GraphEvent>>,
648 ) -> Result<GraphRun, GraphError> {
649 let inner = &*self.inner;
650 let started = Instant::now();
651 let checkpoints = saving
652 .as_ref()
653 .map(|saving| (saving.run_id.as_str(), &saving.checkpoints));
654 let fail = |error: CheckpointError, state: GraphState, before: Duration| GraphError {
655 failures: vec![GraphFailure::Checkpoint { error }],
656 run: GraphRun {
657 state,
658 last: Vec::new(),
659 usage: Usage::default(),
660 elapsed: before + started.elapsed(),
661 },
662 };
663 let index_of = |id: &str| inner.nodes.iter().position(|node| node.id == id);
664 let saved = match checkpoints {
665 Some((id, checkpoints)) => match checkpoints.load::<Saved>(id).await {
666 Ok(Some(saved)) if saved.finished && nested => {
667 return Ok(GraphRun {
668 state: saved.state,
669 last: saved.last,
670 usage: saved.usage,
671 elapsed: Duration::from_millis(saved.elapsed_ms),
672 });
673 }
674 Ok(saved) => saved.filter(|saved| !saved.finished),
675 Err(error) => return Err(fail(error, GraphState::default(), Duration::ZERO)),
676 },
677 None => None,
678 };
679 let mut state;
680 let mut usage;
681 let mut last;
682 let mut executions;
683 let mut ready = Vec::new();
684 let mut carried = Vec::new();
686 let clock;
687 let before;
688 match saved {
689 None => {
690 state = GraphState {
691 task,
692 ..GraphState::default()
693 };
694 usage = Usage::default();
695 last = Vec::new();
696 executions = 0;
697 ready = inner.entries.clone();
698 clock = Clock::resumed(Duration::ZERO);
699 before = Duration::ZERO;
700 }
701 Some(saved) => {
702 before = Duration::from_millis(saved.elapsed_ms);
703 for (ids, into) in [
705 (
706 saved.ready.iter().chain(&saved.failed).collect::<Vec<_>>(),
707 &mut ready,
708 ),
709 (saved.batch_done.iter().collect(), &mut carried),
710 ] {
711 for id in ids {
712 let Some(index) = index_of(id) else {
713 let error = CheckpointError::UnknownNode(id.clone());
714 return Err(fail(error, saved.state, before));
715 };
716 if !into.contains(&index) {
717 into.push(index);
718 }
719 }
720 }
721 tracing::info!(done = saved.state.order.len(), "graph run resumed");
722 if let Some(emit) = emit {
723 emit(GraphEvent::Resumed {
724 done: saved.state.order.clone(),
725 });
726 }
727 clock = Clock::resumed(Duration::from_millis(saved.active_ms));
728 state = saved.state;
729 usage = saved.usage;
730 last = saved.last;
731 executions = saved.executions;
732 }
733 }
734 let clock = &clock;
735 let mut failures = Vec::new();
736 let names = |indices: &[usize]| -> Vec<String> {
737 indices
738 .iter()
739 .filter_map(|&index| inner.nodes.get(index))
740 .map(|node| node.id.clone())
741 .collect()
742 };
743 let snapshot = |state: &GraphState,
744 usage: &Usage,
745 last: &[String],
746 executions: usize,
747 ready: &[usize],
748 batch_done: &[usize],
749 failures: &[GraphFailure]| Saved {
750 finished: ready.is_empty() && batch_done.is_empty() && failures.is_empty(),
751 state: state.clone(),
752 usage: *usage,
753 last: last.to_vec(),
754 executions,
755 ready: names(ready),
756 batch_done: names(batch_done),
757 failed: failures
758 .iter()
759 .filter_map(|failure| match failure {
760 GraphFailure::Node { node, .. } | GraphFailure::NodeTimeout { node } => {
761 Some(node.clone())
762 }
763 _ => None,
764 })
765 .collect(),
766 active_ms: millis(clock.active()),
767 elapsed_ms: millis(before + started.elapsed()),
768 };
769 'run: while !ready.is_empty() || !carried.is_empty() {
770 let mut finished = std::mem::take(&mut carried);
771 if !ready.is_empty() {
772 if let Some((id, checkpoints)) = checkpoints {
773 let saved = snapshot(
774 &state, &usage, &last, executions, &ready, &finished, &failures,
775 );
776 if let Err(error) = checkpoints.save(id, &saved).await {
777 failures.push(GraphFailure::Checkpoint { error });
778 break 'run;
779 }
780 }
781 if let Some(limit) = inner.max_node_executions
782 && executions + ready.len() > limit
783 {
784 failures.push(GraphFailure::MaxNodeExecutions { limit });
785 break 'run;
786 }
787 let remaining = inner.execution_timeout.saturating_sub(clock.active());
788 if remaining.is_zero() {
789 failures.push(GraphFailure::Timeout);
790 break 'run;
791 }
792 let budget = inner.node_timeout.min(remaining);
793 executions += ready.len();
794 let mut batch: FuturesUnordered<_> = ready
795 .iter()
796 .filter_map(|&index| Some((index, inner.nodes.get(index)?)))
797 .map(|(index, node)| {
798 let input = self.input(index, &state);
799 let part = state.finished.get(&node.id).copied().unwrap_or(0) + 1;
802 let saving = saving
803 .as_ref()
804 .map(|saving| saving.part("node", &node.id, part));
805 let span = tracing::info_span!(
806 "graph.node",
807 graph.node = %node.id,
808 otel.status_code = tracing::field::Empty,
809 error.type = tracing::field::Empty,
810 );
811 async move {
812 let Some(emit) = emit else {
813 let io = NodeIo::quiet(&node.id)
814 .saving_to(saving)
815 .with_turns(inner.max_turns);
816 let run = node.node.run(input, &io).instrument(span.clone());
817 let outcome = clock.within(budget, run).await;
818 record_node(&span, &outcome);
819 return (index, node, outcome);
820 };
821 emit(GraphEvent::NodeStarted {
822 node: node.id.clone(),
823 });
824 let on_text = |text: &str| {
825 emit(GraphEvent::Text {
826 node: node.id.clone(),
827 text: text.to_owned(),
828 })
829 };
830 let on_question = |question: Question| {
831 tracing::info!(graph.node = %node.id, "human.question");
834 emit(GraphEvent::Question(question.pausing(clock)))
835 };
836 let io = NodeIo::streaming(&node.id, &on_text, &on_question)
837 .saving_to(saving)
838 .with_turns(inner.max_turns);
839 let run = node.node.run(input, &io).instrument(span.clone());
840 let outcome = clock.within(budget, run).await;
841 record_node(&span, &outcome);
842 let id = node.id.clone();
843 emit(match &outcome {
844 Some(Ok(output)) => GraphEvent::NodeFinished {
845 node: id,
846 output: output.text.clone(),
847 },
848 Some(Err(error)) => GraphEvent::NodeFailed {
849 node: id,
850 error: error.to_string(),
851 },
852 None => GraphEvent::NodeFailed {
853 node: id,
854 error: "did not finish in time".to_owned(),
855 },
856 });
857 (index, node, outcome)
858 }
859 })
860 .collect();
861 let mut remaining = ready.clone();
862 while let Some((index, node, outcome)) = batch.next().await {
863 remaining.retain(|&other| other != index);
864 let id = node.id.clone();
865 *state.runs.entry(id.clone()).or_default() += 1;
866 state.order.push(id.clone());
867 match outcome {
868 Some(Ok(output)) => {
869 let NodeOutput {
870 text, usage: spent, ..
871 } = output;
872 usage += spent;
873 *state.finished.entry(id.clone()).or_default() += 1;
874 state.outputs.insert(id, text);
875 finished.push(index);
876 }
877 Some(Err(source)) => {
878 tracing::warn!(graph.node = %id, error = %source, "graph node failed");
879 failures.push(GraphFailure::Node { node: id, source });
880 }
881 None => failures.push(GraphFailure::NodeTimeout { node: id }),
882 }
883 if !remaining.is_empty()
887 && let Some((id, checkpoints)) = checkpoints
888 {
889 let counted = executions - remaining.len();
890 let saved = snapshot(
891 &state, &usage, &last, counted, &remaining, &finished, &failures,
892 );
893 if let Err(error) = checkpoints.save(id, &saved).await {
894 tracing::warn!(%error, "could not save a finished graph node");
895 }
896 }
897 }
898 }
899 if !finished.is_empty() {
900 last = names(&finished);
901 }
902 ready = Vec::new();
903 for edge in &inner.edges {
904 if finished.contains(&edge.from) && !ready.contains(&edge.to) && edge.holds(&state)
905 {
906 ready.push(edge.to);
907 }
908 }
909 }
910 if let Some((id, checkpoints)) = checkpoints
911 && !failures
912 .iter()
913 .any(|failure| matches!(failure, GraphFailure::Checkpoint { .. }))
914 {
915 let saved = snapshot(&state, &usage, &last, executions, &[], &[], &failures);
917 if let Err(error) = checkpoints.save(id, &saved).await {
918 tracing::warn!(%error, "could not save the graph run's end");
919 }
920 }
921 let run = GraphRun {
922 state,
923 last,
924 usage,
925 elapsed: before + started.elapsed(),
926 };
927 if failures.is_empty() {
928 Ok(run)
929 } else {
930 Err(GraphError { failures, run })
931 }
932 }
933
934 fn input(&self, index: usize, state: &GraphState) -> String {
936 let inner = &*self.inner;
937 let mut sources: Vec<(&str, &str)> = Vec::new();
938 for edge in inner.edges.iter().filter(|edge| edge.to == index) {
939 let Some(from) = inner.nodes.get(edge.from) else {
940 continue;
941 };
942 let from = from.id.as_str();
943 if let Some(output) = state.outputs.get(from)
944 && !sources.iter().any(|(seen, _)| *seen == from)
945 && edge.holds(state)
946 {
947 sources.push((from, output));
948 }
949 }
950 if sources.is_empty() {
951 return state.task.clone();
952 }
953 let mut text = format!(
954 "Original task: {}\n\nInputs from previous nodes:\n",
955 state.task
956 );
957 for (from, output) in sources {
958 let _ = write!(text, "\nFrom {from}:\n{output}\n");
959 }
960 text.trim_end().to_owned()
961 }
962}
963
964impl Node for Graph {
965 fn run<'a>(
969 &'a self,
970 input: String,
971 io: &'a NodeIo<'a>,
972 ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
973 Box::pin(async move {
974 let saving = io.saving().map(|saving| {
975 let checkpoints = self.inner.checkpoints.clone();
976 let checkpoints =
977 checkpoints.unwrap_or_else(|| saving.checkpoints.with_kind("graph"));
978 Saving::new(checkpoints, saving.run_id.clone())
979 });
980 let emit = |event| match event {
981 GraphEvent::Text { text, .. } => io.text(&text),
982 GraphEvent::Question(question) => io.forward(question),
983 _ => {}
984 };
985 let emit: Option<Emit<'_, GraphEvent>> = io.is_streaming().then_some(&emit);
986 let run = self.run_task(input, saving, true, emit).await?;
987 Ok(NodeOutput::new(run.answer()).with_usage(run.usage))
988 })
989 }
990}