1use std::any::{Any, TypeId};
4use std::collections::HashMap;
5use std::fmt::Write as _;
6use std::sync::Arc;
7use std::time::{Duration, Instant};
8
9use futures::StreamExt;
10use futures::stream::FuturesUnordered;
11use rig_core::completion::Usage;
12use rig_core::wasm_compat::{WasmBoxedFuture, WasmBoxedStream, WasmCompatSend, WasmCompatSync};
13use serde::{Deserialize, Serialize};
14use tracing::Instrument;
15
16use crate::BuildError;
17use crate::checkpoint::{CheckpointError, Checkpoints, Saving};
18use crate::events::{Emit, events};
19use crate::human::{Clock, Question};
20use crate::node::{Node, NodeError, NodeIo, NodeOutput};
21use crate::swarm::DEFAULT_MAX_TURNS;
22
23#[cfg(not(target_family = "wasm"))]
25type Condition = Arc<dyn Fn(&GraphState) -> bool + Send + Sync>;
26#[cfg(target_family = "wasm")]
28type Condition = Arc<dyn Fn(&GraphState) -> bool>;
29
30#[derive(Clone)]
49pub struct Graph {
50 inner: Arc<Inner>,
51}
52
53struct Inner {
54 nodes: Vec<GraphNode>,
55 edges: Vec<Edge>,
56 entries: Vec<usize>,
57 max_node_executions: Option<usize>,
58 max_turns: usize,
59 execution_timeout: Duration,
60 node_timeout: Duration,
61 checkpoints: Option<Checkpoints>,
62}
63
64struct GraphNode {
65 id: String,
66 node: Box<dyn Node>,
67}
68
69struct Edge {
70 from: usize,
71 to: usize,
72 condition: Option<Condition>,
73}
74
75impl Edge {
76 fn holds(&self, state: &GraphState) -> bool {
77 self.condition
78 .as_ref()
79 .is_none_or(|condition| condition(state))
80 }
81}
82
83#[must_use]
85pub struct GraphBuilder {
86 nodes: Vec<(String, Box<dyn Node>)>,
87 edges: Vec<(String, String, Option<Condition>)>,
88 entries: Vec<String>,
89 max_node_executions: Option<usize>,
90 max_turns: usize,
91 execution_timeout: Duration,
92 node_timeout: Duration,
93 checkpoints: Option<Checkpoints>,
94}
95
96impl Graph {
97 pub fn builder() -> GraphBuilder {
99 GraphBuilder {
100 nodes: Vec::new(),
101 edges: Vec::new(),
102 entries: Vec::new(),
103 max_node_executions: None,
104 max_turns: DEFAULT_MAX_TURNS,
105 execution_timeout: Duration::from_secs(15 * 60),
106 node_timeout: Duration::from_secs(5 * 60),
107 checkpoints: None,
108 }
109 }
110}
111
112impl GraphBuilder {
113 pub fn node(mut self, id: impl Into<String>, node: impl Node + 'static) -> Self {
116 self.nodes.push((id.into(), Box::new(node)));
117 self
118 }
119
120 pub fn edge(mut self, from: impl Into<String>, to: impl Into<String>) -> Self {
122 self.edges.push((from.into(), to.into(), None));
123 self
124 }
125
126 pub fn edge_if(
142 mut self,
143 from: impl Into<String>,
144 to: impl Into<String>,
145 condition: impl Fn(&GraphState) -> bool + WasmCompatSend + WasmCompatSync + 'static,
146 ) -> Self {
147 self.edges
148 .push((from.into(), to.into(), Some(Arc::new(condition))));
149 self
150 }
151
152 pub fn entry(mut self, id: impl Into<String>) -> Self {
155 self.entries.push(id.into());
156 self
157 }
158
159 pub fn max_node_executions(mut self, max: usize) -> Self {
162 self.max_node_executions = Some(max);
163 self
164 }
165
166 pub fn max_turns_per_agent(mut self, max_turns: usize) -> Self {
172 self.max_turns = max_turns;
173 self
174 }
175
176 pub fn execution_timeout(mut self, timeout: Duration) -> Self {
178 self.execution_timeout = timeout;
179 self
180 }
181
182 #[doc(alias = "agent_timeout")]
184 pub fn node_timeout(mut self, timeout: Duration) -> Self {
185 self.node_timeout = timeout;
186 self
187 }
188
189 pub fn checkpoints(
193 mut self,
194 store: impl rig_memory::AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
195 ) -> Self {
196 self.checkpoints = Some(Checkpoints::new(store, "graph"));
197 self
198 }
199
200 pub fn build(self) -> Result<Graph, BuildError> {
202 if self.nodes.is_empty() {
203 return Err(BuildError::Empty);
204 }
205 if self.max_turns == 0 {
206 return Err(BuildError::ZeroTurns);
207 }
208 let mut nodes: Vec<GraphNode> = Vec::with_capacity(self.nodes.len());
209 for (id, node) in self.nodes {
210 if nodes.iter().any(|other| other.id == id) {
211 return Err(BuildError::DuplicateName(id));
212 }
213 nodes.push(GraphNode { id, node });
214 }
215 let index = |id: &str| {
216 nodes
217 .iter()
218 .position(|node| node.id == id)
219 .ok_or_else(|| BuildError::UnknownName(id.to_owned()))
220 };
221 let mut edges = Vec::with_capacity(self.edges.len());
222 for (from, to, condition) in self.edges {
223 edges.push(Edge {
224 from: index(&from)?,
225 to: index(&to)?,
226 condition,
227 });
228 }
229 let entries = if self.entries.is_empty() {
230 let starts: Vec<usize> = (0..nodes.len())
231 .filter(|&node| !edges.iter().any(|edge| edge.to == node))
232 .collect();
233 if starts.is_empty() {
234 return Err(BuildError::NoEntry);
235 }
236 starts
237 } else {
238 let mut entries = Vec::new();
239 for id in &self.entries {
240 let entry = index(id)?;
241 if !entries.contains(&entry) {
242 entries.push(entry);
243 }
244 }
245 entries
246 };
247 if self.max_node_executions.is_none() && has_cycle(nodes.len(), &edges) {
248 return Err(BuildError::UnboundedCycle);
249 }
250 Ok(Graph {
251 inner: Arc::new(Inner {
252 nodes,
253 edges,
254 entries,
255 max_node_executions: self.max_node_executions,
256 max_turns: self.max_turns,
257 execution_timeout: self.execution_timeout,
258 node_timeout: self.node_timeout,
259 checkpoints: self.checkpoints,
260 }),
261 })
262 }
263}
264
265fn has_cycle(nodes: usize, edges: &[Edge]) -> bool {
267 let mut incoming = vec![0usize; nodes];
270 for edge in edges {
271 if let Some(count) = incoming.get_mut(edge.to) {
272 *count += 1;
273 }
274 }
275 let mut free: Vec<usize> = incoming
276 .iter()
277 .enumerate()
278 .filter(|(_, count)| **count == 0)
279 .map(|(node, _)| node)
280 .collect();
281 let mut peeled = 0;
282 while let Some(node) = free.pop() {
283 peeled += 1;
284 for edge in edges.iter().filter(|edge| edge.from == node) {
285 if let Some(count) = incoming.get_mut(edge.to) {
286 *count -= 1;
287 if *count == 0 {
288 free.push(edge.to);
289 }
290 }
291 }
292 }
293 peeled < nodes
294}
295
296#[derive(Clone, Default)]
316pub struct RunState {
317 values: Arc<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>,
318}
319
320impl RunState {
321 pub fn new() -> Self {
323 Self::default()
324 }
325
326 #[must_use]
328 pub fn with<T: Any + Send + Sync>(mut self, value: T) -> Self {
329 Arc::make_mut(&mut self.values).insert(TypeId::of::<T>(), Arc::new(value));
330 self
331 }
332
333 pub fn get<T: Any + Send + Sync>(&self) -> Option<&T> {
335 let value: &(dyn Any + Send + Sync) = self.values.get(&TypeId::of::<T>())?.as_ref();
336 value.downcast_ref::<T>()
337 }
338}
339
340impl std::fmt::Debug for RunState {
341 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
343 write!(f, "RunState({} values)", self.values.len())
344 }
345}
346
347impl std::panic::UnwindSafe for RunState {}
353impl std::panic::RefUnwindSafe for RunState {}
354
355#[derive(Debug, Clone, Default, Serialize, Deserialize)]
357pub struct GraphState {
358 task: String,
359 outputs: HashMap<String, String>,
360 runs: HashMap<String, usize>,
361 #[serde(default)]
363 finished: HashMap<String, usize>,
364 order: Vec<String>,
365 #[serde(skip)]
367 run: RunState,
368}
369
370impl GraphState {
371 pub fn task(&self) -> &str {
373 &self.task
374 }
375
376 pub fn run_state(&self) -> &RunState {
378 &self.run
379 }
380
381 pub fn output(&self, id: &str) -> Option<&str> {
383 self.outputs.get(id).map(String::as_str)
384 }
385
386 pub fn runs(&self, id: &str) -> usize {
388 self.runs.get(id).copied().unwrap_or(0)
389 }
390
391 pub fn order(&self) -> &[String] {
393 &self.order
394 }
395}
396
397#[derive(Debug, Clone)]
399#[non_exhaustive]
400pub struct GraphRun {
401 pub state: GraphState,
403 pub last: Vec<String>,
405 pub usage: Usage,
407 pub elapsed: Duration,
409}
410
411impl GraphRun {
412 pub fn output(&self, id: &str) -> Option<&str> {
414 self.state.output(id)
415 }
416
417 pub fn answer(&self) -> String {
420 match self.last.as_slice() {
421 [only] => self.output(only).unwrap_or_default().to_owned(),
422 last => {
423 let mut text = String::new();
424 for id in last {
425 let _ = write!(
426 text,
427 "From {id}:\n{}\n\n",
428 self.output(id).unwrap_or_default()
429 );
430 }
431 text.trim_end().to_owned()
432 }
433 }
434 }
435}
436
437#[derive(Debug, thiserror::Error)]
439#[non_exhaustive]
440pub struct GraphError {
441 pub failures: Vec<GraphFailure>,
443 pub run: GraphRun,
445}
446
447impl std::fmt::Display for GraphError {
448 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
449 match self.failures.as_slice() {
450 [] => f.write_str("the graph run failed"),
451 [only] => only.fmt(f),
452 [first, rest @ ..] => write!(f, "{first} (and {} more failures)", rest.len()),
453 }
454 }
455}
456
457#[derive(Debug)]
459#[non_exhaustive]
460pub enum GraphEvent {
461 Resumed {
464 done: Vec<String>,
466 },
467 NodeStarted {
469 node: String,
471 },
472 Text {
475 node: String,
477 text: String,
479 },
480 NodeFinished {
482 node: String,
484 output: String,
486 },
487 NodeFailed {
489 node: String,
491 error: String,
493 },
494 Question(Question),
497 Finished(Box<Result<GraphRun, GraphError>>),
499}
500
501#[derive(Serialize, Deserialize)]
503struct Saved {
504 finished: bool,
505 state: GraphState,
506 usage: Usage,
507 last: Vec<String>,
508 executions: usize,
509 ready: Vec<String>,
511 #[serde(default)]
513 batch_done: Vec<String>,
514 failed: Vec<String>,
516 active_ms: u64,
517 elapsed_ms: u64,
518}
519
520fn millis(duration: Duration) -> u64 {
521 u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
522}
523
524#[derive(Debug, thiserror::Error)]
526#[non_exhaustive]
527pub enum GraphFailure {
528 #[error("node {node:?} failed: {source}")]
530 Node {
531 node: String,
533 #[source]
535 source: NodeError,
536 },
537 #[error("node {node:?} did not finish in time")]
539 NodeTimeout {
540 node: String,
542 },
543 #[error("checkpoint: {error}")]
545 Checkpoint {
546 #[source]
548 error: CheckpointError,
549 },
550 #[error("the graph ran out of time")]
552 Timeout,
553 #[error("the graph reached its limit of {limit} node runs")]
555 MaxNodeExecutions {
556 limit: usize,
558 },
559}
560
561fn run_span(run_id: Option<&str>) -> tracing::Span {
565 tracing::info_span!(
566 "graph.run",
567 graph.run_id = run_id,
568 graph.node_runs = tracing::field::Empty,
569 graph.usage.input_tokens = tracing::field::Empty,
570 graph.usage.output_tokens = tracing::field::Empty,
571 otel.status_code = tracing::field::Empty,
572 error.type = tracing::field::Empty,
573 )
574}
575
576fn record_outcome(span: &tracing::Span, outcome: &Result<GraphRun, GraphError>) {
578 let run = match outcome {
579 Ok(run) => run,
580 Err(error) => {
581 span.record("otel.status_code", "ERROR");
582 if let Some(failure) = error.failures.first() {
583 span.record("error.type", failure.kind());
584 }
585 &error.run
586 }
587 };
588 span.record("graph.node_runs", run.state.order().len());
589 if let Some(tokens) = run.usage.input_tokens {
590 span.record("graph.usage.input_tokens", tokens);
591 }
592 if let Some(tokens) = run.usage.output_tokens {
593 span.record("graph.usage.output_tokens", tokens);
594 }
595}
596
597fn record_node<T>(span: &tracing::Span, outcome: &Option<Result<T, NodeError>>) {
599 let kind = match outcome {
600 Some(Ok(_)) => return,
601 Some(Err(_)) => "node_failed",
602 None => "timeout",
603 };
604 span.record("otel.status_code", "ERROR");
605 span.record("error.type", kind);
606}
607
608impl GraphFailure {
609 fn kind(&self) -> &'static str {
611 match self {
612 Self::Node { .. } => "node_failed",
613 Self::NodeTimeout { .. } => "node_timeout",
614 Self::Timeout => "timeout",
615 Self::MaxNodeExecutions { .. } => "max_node_executions",
616 Self::Checkpoint { .. } => "checkpoint",
617 }
618 }
619}
620
621impl Graph {
622 pub async fn run(&self, task: impl Into<String>) -> Result<GraphRun, GraphError> {
624 self.run_with_state(task, RunState::default()).await
625 }
626
627 pub async fn run_with_state(
631 &self,
632 task: impl Into<String>,
633 state: RunState,
634 ) -> Result<GraphRun, GraphError> {
635 let span = run_span(None);
636 let outcome = self
637 .run_task(task.into(), None, false, None, state)
638 .instrument(span.clone())
639 .await;
640 record_outcome(&span, &outcome);
641 outcome
642 }
643
644 pub async fn run_as(
657 &self,
658 run_id: &str,
659 task: impl Into<String>,
660 ) -> Result<GraphRun, GraphError> {
661 self.run_as_with_state(run_id, task, RunState::default())
662 .await
663 }
664
665 pub async fn run_as_with_state(
669 &self,
670 run_id: &str,
671 task: impl Into<String>,
672 state: RunState,
673 ) -> Result<GraphRun, GraphError> {
674 let span = run_span(Some(run_id));
675 let outcome = self
676 .run_task(task.into(), self.saving(Some(run_id)), false, None, state)
677 .instrument(span.clone())
678 .await;
679 record_outcome(&span, &outcome);
680 outcome
681 }
682
683 pub fn stream_as<'a>(
687 &'a self,
688 run_id: &'a str,
689 task: impl Into<String>,
690 ) -> WasmBoxedStream<'a, GraphEvent> {
691 self.stream_events(task.into(), Some(run_id), RunState::default())
692 }
693
694 pub fn stream_as_with_state<'a>(
697 &'a self,
698 run_id: &'a str,
699 task: impl Into<String>,
700 state: RunState,
701 ) -> WasmBoxedStream<'a, GraphEvent> {
702 self.stream_events(task.into(), Some(run_id), state)
703 }
704
705 pub fn stream(&self, task: impl Into<String>) -> WasmBoxedStream<'_, GraphEvent> {
711 self.stream_events(task.into(), None, RunState::default())
712 }
713
714 pub fn stream_with_state(
717 &self,
718 task: impl Into<String>,
719 state: RunState,
720 ) -> WasmBoxedStream<'_, GraphEvent> {
721 self.stream_events(task.into(), None, state)
722 }
723
724 fn stream_events<'a>(
725 &'a self,
726 task: String,
727 run_id: Option<&'a str>,
728 state: RunState,
729 ) -> WasmBoxedStream<'a, GraphEvent> {
730 let span = run_span(run_id);
731 events(
732 move |sender| async move {
733 let emit = move |event| {
734 let _ = sender.send(event);
735 };
736 let outcome = self
737 .run_task(task, self.saving(run_id), false, Some(&emit), state)
738 .instrument(span.clone())
739 .await;
740 record_outcome(&span, &outcome);
741 outcome
742 },
743 |outcome| GraphEvent::Finished(Box::new(outcome)),
744 )
745 }
746
747 fn saving(&self, run_id: Option<&str>) -> Option<Saving> {
749 run_id
750 .zip(self.inner.checkpoints.clone())
751 .map(|(id, checkpoints)| Saving::new(checkpoints, id))
752 }
753
754 async fn run_task(
758 &self,
759 task: String,
760 saving: Option<Saving>,
761 nested: bool,
762 emit: Option<Emit<'_, GraphEvent>>,
763 run_state: RunState,
764 ) -> Result<GraphRun, GraphError> {
765 let inner = &*self.inner;
766 let started = Instant::now();
767 let checkpoints = saving
768 .as_ref()
769 .map(|saving| (saving.run_id.as_str(), &saving.checkpoints));
770 let fail = |error: CheckpointError, state: GraphState, before: Duration| GraphError {
771 failures: vec![GraphFailure::Checkpoint { error }],
772 run: GraphRun {
773 state,
774 last: Vec::new(),
775 usage: Usage::default(),
776 elapsed: before + started.elapsed(),
777 },
778 };
779 let index_of = |id: &str| inner.nodes.iter().position(|node| node.id == id);
780 let saved = match checkpoints {
781 Some((id, checkpoints)) => match checkpoints.load::<Saved>(id).await {
782 Ok(Some(saved)) if saved.finished && nested => {
783 return Ok(GraphRun {
784 state: saved.state,
785 last: saved.last,
786 usage: saved.usage,
787 elapsed: Duration::from_millis(saved.elapsed_ms),
788 });
789 }
790 Ok(saved) => saved.filter(|saved| !saved.finished),
791 Err(error) => return Err(fail(error, GraphState::default(), Duration::ZERO)),
792 },
793 None => None,
794 };
795 let mut state;
796 let mut usage;
797 let mut last;
798 let mut executions;
799 let mut ready = Vec::new();
800 let mut carried = Vec::new();
802 let clock;
803 let before;
804 match saved {
805 None => {
806 state = GraphState {
807 task,
808 ..GraphState::default()
809 };
810 state.run = run_state.clone();
811 usage = Usage::default();
812 last = Vec::new();
813 executions = 0;
814 ready = inner.entries.clone();
815 clock = Clock::resumed(Duration::ZERO);
816 before = Duration::ZERO;
817 }
818 Some(saved) => {
819 before = Duration::from_millis(saved.elapsed_ms);
820 for (ids, into) in [
822 (
823 saved.ready.iter().chain(&saved.failed).collect::<Vec<_>>(),
824 &mut ready,
825 ),
826 (saved.batch_done.iter().collect(), &mut carried),
827 ] {
828 for id in ids {
829 let Some(index) = index_of(id) else {
830 let error = CheckpointError::UnknownNode(id.clone());
831 return Err(fail(error, saved.state, before));
832 };
833 if !into.contains(&index) {
834 into.push(index);
835 }
836 }
837 }
838 tracing::info!(done = saved.state.order.len(), "graph run resumed");
839 if let Some(emit) = emit {
840 emit(GraphEvent::Resumed {
841 done: saved.state.order.clone(),
842 });
843 }
844 clock = Clock::resumed(Duration::from_millis(saved.active_ms));
845 state = saved.state;
846 state.run = run_state.clone();
847 usage = saved.usage;
848 last = saved.last;
849 executions = saved.executions;
850 }
851 }
852 let clock = &clock;
853 let mut failures = Vec::new();
854 let names = |indices: &[usize]| -> Vec<String> {
855 indices
856 .iter()
857 .filter_map(|&index| inner.nodes.get(index))
858 .map(|node| node.id.clone())
859 .collect()
860 };
861 let snapshot = |state: &GraphState,
862 usage: &Usage,
863 last: &[String],
864 executions: usize,
865 ready: &[usize],
866 batch_done: &[usize],
867 failures: &[GraphFailure]| Saved {
868 finished: ready.is_empty() && batch_done.is_empty() && failures.is_empty(),
869 state: state.clone(),
870 usage: *usage,
871 last: last.to_vec(),
872 executions,
873 ready: names(ready),
874 batch_done: names(batch_done),
875 failed: failures
876 .iter()
877 .filter_map(|failure| match failure {
878 GraphFailure::Node { node, .. } | GraphFailure::NodeTimeout { node } => {
879 Some(node.clone())
880 }
881 _ => None,
882 })
883 .collect(),
884 active_ms: millis(clock.active()),
885 elapsed_ms: millis(before + started.elapsed()),
886 };
887 'run: while !ready.is_empty() || !carried.is_empty() {
888 let mut finished = std::mem::take(&mut carried);
889 if !ready.is_empty() {
890 if let Some((id, checkpoints)) = checkpoints {
891 let saved = snapshot(
892 &state, &usage, &last, executions, &ready, &finished, &failures,
893 );
894 if let Err(error) = checkpoints.save(id, &saved).await {
895 failures.push(GraphFailure::Checkpoint { error });
896 break 'run;
897 }
898 }
899 if let Some(limit) = inner.max_node_executions
900 && executions + ready.len() > limit
901 {
902 failures.push(GraphFailure::MaxNodeExecutions { limit });
903 break 'run;
904 }
905 let remaining = inner.execution_timeout.saturating_sub(clock.active());
906 if remaining.is_zero() {
907 failures.push(GraphFailure::Timeout);
908 break 'run;
909 }
910 let budget = inner.node_timeout.min(remaining);
911 executions += ready.len();
912 let mut batch: FuturesUnordered<_> = ready
913 .iter()
914 .filter_map(|&index| Some((index, inner.nodes.get(index)?)))
915 .map(|(index, node)| {
916 let input = self.input(index, &state);
917 let part = state.finished.get(&node.id).copied().unwrap_or(0) + 1;
920 let saving = saving
921 .as_ref()
922 .map(|saving| saving.part("node", &node.id, part));
923 let span = tracing::info_span!(
924 "graph.node",
925 graph.node = %node.id,
926 otel.status_code = tracing::field::Empty,
927 error.type = tracing::field::Empty,
928 );
929 let run_state = run_state.clone();
930 async move {
931 let Some(emit) = emit else {
932 let io = NodeIo::quiet(&node.id)
933 .saving_to(saving)
934 .with_turns(inner.max_turns)
935 .with_run_state(run_state.clone());
936 let run = node.node.run(input, &io).instrument(span.clone());
937 let outcome = clock.within(budget, run).await;
938 record_node(&span, &outcome);
939 return (index, node, outcome);
940 };
941 emit(GraphEvent::NodeStarted {
942 node: node.id.clone(),
943 });
944 let on_text = |text: &str| {
945 emit(GraphEvent::Text {
946 node: node.id.clone(),
947 text: text.to_owned(),
948 })
949 };
950 let on_question = |question: Question| {
951 tracing::info!(graph.node = %node.id, "human.question");
954 emit(GraphEvent::Question(question.pausing(clock)))
955 };
956 let io = NodeIo::streaming(&node.id, &on_text, &on_question)
957 .saving_to(saving)
958 .with_turns(inner.max_turns)
959 .with_run_state(run_state.clone());
960 let run = node.node.run(input, &io).instrument(span.clone());
961 let outcome = clock.within(budget, run).await;
962 record_node(&span, &outcome);
963 let id = node.id.clone();
964 emit(match &outcome {
965 Some(Ok(output)) => GraphEvent::NodeFinished {
966 node: id,
967 output: output.text.clone(),
968 },
969 Some(Err(error)) => GraphEvent::NodeFailed {
970 node: id,
971 error: error.to_string(),
972 },
973 None => GraphEvent::NodeFailed {
974 node: id,
975 error: "did not finish in time".to_owned(),
976 },
977 });
978 (index, node, outcome)
979 }
980 })
981 .collect();
982 let mut remaining = ready.clone();
983 while let Some((index, node, outcome)) = batch.next().await {
984 remaining.retain(|&other| other != index);
985 let id = node.id.clone();
986 *state.runs.entry(id.clone()).or_default() += 1;
987 state.order.push(id.clone());
988 match outcome {
989 Some(Ok(output)) => {
990 let NodeOutput {
991 text, usage: spent, ..
992 } = output;
993 usage += spent;
994 *state.finished.entry(id.clone()).or_default() += 1;
995 state.outputs.insert(id, text);
996 finished.push(index);
997 }
998 Some(Err(source)) => {
999 tracing::warn!(graph.node = %id, kind = "node_failed", "graph node failed");
1000 failures.push(GraphFailure::Node { node: id, source });
1001 }
1002 None => failures.push(GraphFailure::NodeTimeout { node: id }),
1003 }
1004 if !remaining.is_empty()
1008 && let Some((id, checkpoints)) = checkpoints
1009 {
1010 let counted = executions - remaining.len();
1011 let saved = snapshot(
1012 &state, &usage, &last, counted, &remaining, &finished, &failures,
1013 );
1014 if checkpoints.save(id, &saved).await.is_err() {
1015 tracing::warn!(
1016 kind = "checkpoint",
1017 "could not save a finished graph node"
1018 );
1019 }
1020 }
1021 }
1022 }
1023 if !finished.is_empty() {
1024 last = names(&finished);
1025 }
1026 ready = Vec::new();
1027 for edge in &inner.edges {
1028 if finished.contains(&edge.from) && !ready.contains(&edge.to) && edge.holds(&state)
1029 {
1030 ready.push(edge.to);
1031 }
1032 }
1033 }
1034 if let Some((id, checkpoints)) = checkpoints
1035 && !failures
1036 .iter()
1037 .any(|failure| matches!(failure, GraphFailure::Checkpoint { .. }))
1038 {
1039 let saved = snapshot(&state, &usage, &last, executions, &[], &[], &failures);
1041 if checkpoints.save(id, &saved).await.is_err() {
1042 tracing::warn!(kind = "checkpoint", "could not save the graph run's end");
1043 }
1044 }
1045 let run = GraphRun {
1046 state,
1047 last,
1048 usage,
1049 elapsed: before + started.elapsed(),
1050 };
1051 if failures.is_empty() {
1052 Ok(run)
1053 } else {
1054 Err(GraphError { failures, run })
1055 }
1056 }
1057
1058 fn input(&self, index: usize, state: &GraphState) -> String {
1060 let inner = &*self.inner;
1061 let mut sources: Vec<(&str, &str)> = Vec::new();
1062 for edge in inner.edges.iter().filter(|edge| edge.to == index) {
1063 let Some(from) = inner.nodes.get(edge.from) else {
1064 continue;
1065 };
1066 let from = from.id.as_str();
1067 if let Some(output) = state.outputs.get(from)
1068 && !sources.iter().any(|(seen, _)| *seen == from)
1069 && edge.holds(state)
1070 {
1071 sources.push((from, output));
1072 }
1073 }
1074 if sources.is_empty() {
1075 return state.task.clone();
1076 }
1077 let mut text = format!(
1078 "Original task: {}\n\nInputs from previous nodes:\n",
1079 state.task
1080 );
1081 for (from, output) in sources {
1082 let _ = write!(text, "\nFrom {from}:\n{output}\n");
1083 }
1084 text.trim_end().to_owned()
1085 }
1086}
1087
1088impl Node for Graph {
1089 fn run<'a>(
1093 &'a self,
1094 input: String,
1095 io: &'a NodeIo<'a>,
1096 ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
1097 Box::pin(async move {
1098 let saving = io.saving().map(|saving| {
1099 let checkpoints = self.inner.checkpoints.clone();
1100 let checkpoints =
1101 checkpoints.unwrap_or_else(|| saving.checkpoints.with_kind("graph"));
1102 Saving::new(checkpoints, saving.run_id.clone())
1103 });
1104 let emit = |event| match event {
1105 GraphEvent::Text { text, .. } => io.text(&text),
1106 GraphEvent::Question(question) => io.forward(question),
1107 _ => {}
1108 };
1109 let emit: Option<Emit<'_, GraphEvent>> = io.is_streaming().then_some(&emit);
1110 let run = self
1111 .run_task(input, saving, true, emit, io.run_state().clone())
1112 .await?;
1113 Ok(NodeOutput::new(run.answer()).with_usage(run.usage))
1114 })
1115 }
1116}