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};
20
21#[cfg(not(target_family = "wasm"))]
23type Condition = Arc<dyn Fn(&GraphState) -> bool + Send + Sync>;
24#[cfg(target_family = "wasm")]
26type Condition = Arc<dyn Fn(&GraphState) -> bool>;
27
28#[derive(Clone)]
47pub struct Graph {
48 inner: Arc<Inner>,
49}
50
51struct Inner {
52 nodes: Vec<GraphNode>,
53 edges: Vec<Edge>,
54 entries: Vec<usize>,
55 max_node_executions: Option<usize>,
56 execution_timeout: Duration,
57 node_timeout: Duration,
58 checkpoints: Option<Checkpoints>,
59}
60
61struct GraphNode {
62 id: String,
63 node: Box<dyn Node>,
64}
65
66struct Edge {
67 from: usize,
68 to: usize,
69 condition: Option<Condition>,
70}
71
72impl Edge {
73 fn holds(&self, state: &GraphState) -> bool {
74 self.condition
75 .as_ref()
76 .is_none_or(|condition| condition(state))
77 }
78}
79
80#[must_use]
82pub struct GraphBuilder {
83 nodes: Vec<(String, Box<dyn Node>)>,
84 edges: Vec<(String, String, Option<Condition>)>,
85 entries: Vec<String>,
86 max_node_executions: Option<usize>,
87 execution_timeout: Duration,
88 node_timeout: Duration,
89 checkpoints: Option<Checkpoints>,
90}
91
92impl Graph {
93 pub fn builder() -> GraphBuilder {
95 GraphBuilder {
96 nodes: Vec::new(),
97 edges: Vec::new(),
98 entries: Vec::new(),
99 max_node_executions: None,
100 execution_timeout: Duration::from_secs(15 * 60),
101 node_timeout: Duration::from_secs(5 * 60),
102 checkpoints: None,
103 }
104 }
105}
106
107impl GraphBuilder {
108 pub fn node(mut self, id: impl Into<String>, node: impl Node + 'static) -> Self {
111 self.nodes.push((id.into(), Box::new(node)));
112 self
113 }
114
115 pub fn edge(mut self, from: impl Into<String>, to: impl Into<String>) -> Self {
117 self.edges.push((from.into(), to.into(), None));
118 self
119 }
120
121 pub fn edge_if(
137 mut self,
138 from: impl Into<String>,
139 to: impl Into<String>,
140 condition: impl Fn(&GraphState) -> bool + WasmCompatSend + WasmCompatSync + 'static,
141 ) -> Self {
142 self.edges
143 .push((from.into(), to.into(), Some(Arc::new(condition))));
144 self
145 }
146
147 pub fn entry(mut self, id: impl Into<String>) -> Self {
150 self.entries.push(id.into());
151 self
152 }
153
154 pub fn max_node_executions(mut self, max: usize) -> Self {
157 self.max_node_executions = Some(max);
158 self
159 }
160
161 pub fn execution_timeout(mut self, timeout: Duration) -> Self {
163 self.execution_timeout = timeout;
164 self
165 }
166
167 pub fn node_timeout(mut self, timeout: Duration) -> Self {
169 self.node_timeout = timeout;
170 self
171 }
172
173 pub fn checkpoints(
177 mut self,
178 store: impl rig_memory::AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
179 ) -> Self {
180 self.checkpoints = Some(Checkpoints::new(store, "graph"));
181 self
182 }
183
184 pub fn build(self) -> Result<Graph, BuildError> {
186 if self.nodes.is_empty() {
187 return Err(BuildError::Empty);
188 }
189 let mut nodes: Vec<GraphNode> = Vec::with_capacity(self.nodes.len());
190 for (id, node) in self.nodes {
191 if nodes.iter().any(|other| other.id == id) {
192 return Err(BuildError::DuplicateName(id));
193 }
194 nodes.push(GraphNode { id, node });
195 }
196 let index = |id: &str| {
197 nodes
198 .iter()
199 .position(|node| node.id == id)
200 .ok_or_else(|| BuildError::UnknownName(id.to_owned()))
201 };
202 let mut edges = Vec::with_capacity(self.edges.len());
203 for (from, to, condition) in self.edges {
204 edges.push(Edge {
205 from: index(&from)?,
206 to: index(&to)?,
207 condition,
208 });
209 }
210 let entries = if self.entries.is_empty() {
211 let starts: Vec<usize> = (0..nodes.len())
212 .filter(|&node| !edges.iter().any(|edge| edge.to == node))
213 .collect();
214 if starts.is_empty() {
215 return Err(BuildError::NoEntry);
216 }
217 starts
218 } else {
219 let mut entries = Vec::new();
220 for id in &self.entries {
221 let entry = index(id)?;
222 if !entries.contains(&entry) {
223 entries.push(entry);
224 }
225 }
226 entries
227 };
228 if self.max_node_executions.is_none() && has_cycle(nodes.len(), &edges) {
229 return Err(BuildError::UnboundedCycle);
230 }
231 Ok(Graph {
232 inner: Arc::new(Inner {
233 nodes,
234 edges,
235 entries,
236 max_node_executions: self.max_node_executions,
237 execution_timeout: self.execution_timeout,
238 node_timeout: self.node_timeout,
239 checkpoints: self.checkpoints,
240 }),
241 })
242 }
243}
244
245fn has_cycle(nodes: usize, edges: &[Edge]) -> bool {
247 let mut incoming = vec![0usize; nodes];
250 for edge in edges {
251 if let Some(count) = incoming.get_mut(edge.to) {
252 *count += 1;
253 }
254 }
255 let mut free: Vec<usize> = incoming
256 .iter()
257 .enumerate()
258 .filter(|(_, count)| **count == 0)
259 .map(|(node, _)| node)
260 .collect();
261 let mut peeled = 0;
262 while let Some(node) = free.pop() {
263 peeled += 1;
264 for edge in edges.iter().filter(|edge| edge.from == node) {
265 if let Some(count) = incoming.get_mut(edge.to) {
266 *count -= 1;
267 if *count == 0 {
268 free.push(edge.to);
269 }
270 }
271 }
272 }
273 peeled < nodes
274}
275
276#[derive(Debug, Clone, Default, Serialize, Deserialize)]
278pub struct GraphState {
279 task: String,
280 outputs: HashMap<String, String>,
281 runs: HashMap<String, usize>,
282 #[serde(default)]
284 finished: HashMap<String, usize>,
285 order: Vec<String>,
286}
287
288impl GraphState {
289 pub fn task(&self) -> &str {
291 &self.task
292 }
293
294 pub fn output(&self, id: &str) -> Option<&str> {
296 self.outputs.get(id).map(String::as_str)
297 }
298
299 pub fn runs(&self, id: &str) -> usize {
301 self.runs.get(id).copied().unwrap_or(0)
302 }
303
304 pub fn order(&self) -> &[String] {
306 &self.order
307 }
308}
309
310#[derive(Debug, Clone)]
312#[non_exhaustive]
313pub struct GraphRun {
314 pub state: GraphState,
316 pub last: Vec<String>,
318 pub usage: Usage,
320 pub elapsed: Duration,
322}
323
324impl GraphRun {
325 pub fn output(&self, id: &str) -> Option<&str> {
327 self.state.output(id)
328 }
329
330 pub fn answer(&self) -> String {
333 match self.last.as_slice() {
334 [only] => self.output(only).unwrap_or_default().to_owned(),
335 last => {
336 let mut text = String::new();
337 for id in last {
338 let _ = write!(
339 text,
340 "From {id}:\n{}\n\n",
341 self.output(id).unwrap_or_default()
342 );
343 }
344 text.trim_end().to_owned()
345 }
346 }
347 }
348}
349
350#[derive(Debug, thiserror::Error)]
352#[non_exhaustive]
353pub struct GraphError {
354 pub failures: Vec<GraphFailure>,
356 pub run: GraphRun,
358}
359
360impl std::fmt::Display for GraphError {
361 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
362 match self.failures.as_slice() {
363 [] => f.write_str("the graph run failed"),
364 [only] => only.fmt(f),
365 [first, rest @ ..] => write!(f, "{first} (and {} more failures)", rest.len()),
366 }
367 }
368}
369
370#[derive(Debug)]
372#[non_exhaustive]
373pub enum GraphEvent {
374 Resumed {
377 done: Vec<String>,
379 },
380 NodeStarted {
382 node: String,
384 },
385 Text {
388 node: String,
390 text: String,
392 },
393 NodeFinished {
395 node: String,
397 output: String,
399 },
400 NodeFailed {
402 node: String,
404 error: String,
406 },
407 Question(Question),
410 Finished(Box<Result<GraphRun, GraphError>>),
412}
413
414#[derive(Serialize, Deserialize)]
416struct Saved {
417 finished: bool,
418 state: GraphState,
419 usage: Usage,
420 last: Vec<String>,
421 executions: usize,
422 ready: Vec<String>,
424 #[serde(default)]
426 batch_done: Vec<String>,
427 failed: Vec<String>,
429 active_ms: u64,
430 elapsed_ms: u64,
431}
432
433fn millis(duration: Duration) -> u64 {
434 u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
435}
436
437#[derive(Debug, thiserror::Error)]
439#[non_exhaustive]
440pub enum GraphFailure {
441 #[error("node {node:?} failed: {source}")]
443 Node {
444 node: String,
446 #[source]
448 source: NodeError,
449 },
450 #[error("node {node:?} did not finish in time")]
452 NodeTimeout {
453 node: String,
455 },
456 #[error("checkpoint: {error}")]
458 Checkpoint {
459 #[source]
461 error: CheckpointError,
462 },
463 #[error("the graph ran out of time")]
465 Timeout,
466 #[error("the graph reached its limit of {limit} node runs")]
468 MaxNodeExecutions {
469 limit: usize,
471 },
472}
473
474fn run_span(run_id: Option<&str>) -> tracing::Span {
478 tracing::info_span!(
479 "graph.run",
480 graph.run_id = run_id,
481 graph.node_runs = tracing::field::Empty,
482 graph.usage.input_tokens = tracing::field::Empty,
483 graph.usage.output_tokens = tracing::field::Empty,
484 otel.status_code = tracing::field::Empty,
485 error.type = tracing::field::Empty,
486 )
487}
488
489fn record_outcome(span: &tracing::Span, outcome: &Result<GraphRun, GraphError>) {
491 let run = match outcome {
492 Ok(run) => run,
493 Err(error) => {
494 span.record("otel.status_code", "ERROR");
495 if let Some(failure) = error.failures.first() {
496 span.record("error.type", failure.kind());
497 }
498 &error.run
499 }
500 };
501 span.record("graph.node_runs", run.state.order().len());
502 if let Some(tokens) = run.usage.input_tokens {
503 span.record("graph.usage.input_tokens", tokens);
504 }
505 if let Some(tokens) = run.usage.output_tokens {
506 span.record("graph.usage.output_tokens", tokens);
507 }
508}
509
510fn record_node<T>(span: &tracing::Span, outcome: &Option<Result<T, NodeError>>) {
512 let kind = match outcome {
513 Some(Ok(_)) => return,
514 Some(Err(_)) => "node_failed",
515 None => "timeout",
516 };
517 span.record("otel.status_code", "ERROR");
518 span.record("error.type", kind);
519}
520
521impl GraphFailure {
522 fn kind(&self) -> &'static str {
524 match self {
525 Self::Node { .. } => "node_failed",
526 Self::NodeTimeout { .. } => "node_timeout",
527 Self::Timeout => "timeout",
528 Self::MaxNodeExecutions { .. } => "max_node_executions",
529 Self::Checkpoint { .. } => "checkpoint",
530 }
531 }
532}
533
534impl Graph {
535 pub async fn run(&self, task: impl Into<String>) -> Result<GraphRun, GraphError> {
537 let span = run_span(None);
538 let outcome = self
539 .run_task(task.into(), None, false, None)
540 .instrument(span.clone())
541 .await;
542 record_outcome(&span, &outcome);
543 outcome
544 }
545
546 pub async fn run_as(
559 &self,
560 run_id: &str,
561 task: impl Into<String>,
562 ) -> Result<GraphRun, GraphError> {
563 let span = run_span(Some(run_id));
564 let outcome = self
565 .run_task(task.into(), self.saving(Some(run_id)), false, None)
566 .instrument(span.clone())
567 .await;
568 record_outcome(&span, &outcome);
569 outcome
570 }
571
572 pub fn stream_as<'a>(
576 &'a self,
577 run_id: &'a str,
578 task: impl Into<String>,
579 ) -> WasmBoxedStream<'a, GraphEvent> {
580 self.stream_events(task.into(), Some(run_id))
581 }
582
583 pub fn stream(&self, task: impl Into<String>) -> WasmBoxedStream<'_, GraphEvent> {
589 self.stream_events(task.into(), None)
590 }
591
592 fn stream_events<'a>(
593 &'a self,
594 task: String,
595 run_id: Option<&'a str>,
596 ) -> WasmBoxedStream<'a, GraphEvent> {
597 let span = run_span(run_id);
598 events(
599 move |sender| async move {
600 let emit = move |event| {
601 let _ = sender.send(event);
602 };
603 let outcome = self
604 .run_task(task, self.saving(run_id), false, Some(&emit))
605 .instrument(span.clone())
606 .await;
607 record_outcome(&span, &outcome);
608 outcome
609 },
610 |outcome| GraphEvent::Finished(Box::new(outcome)),
611 )
612 }
613
614 fn saving(&self, run_id: Option<&str>) -> Option<Saving> {
616 run_id
617 .zip(self.inner.checkpoints.clone())
618 .map(|(id, checkpoints)| Saving::new(checkpoints, id))
619 }
620
621 async fn run_task(
625 &self,
626 task: String,
627 saving: Option<Saving>,
628 nested: bool,
629 emit: Option<Emit<'_, GraphEvent>>,
630 ) -> Result<GraphRun, GraphError> {
631 let inner = &*self.inner;
632 let started = Instant::now();
633 let checkpoints = saving
634 .as_ref()
635 .map(|saving| (saving.run_id.as_str(), &saving.checkpoints));
636 let fail = |error: CheckpointError, state: GraphState, before: Duration| GraphError {
637 failures: vec![GraphFailure::Checkpoint { error }],
638 run: GraphRun {
639 state,
640 last: Vec::new(),
641 usage: Usage::default(),
642 elapsed: before + started.elapsed(),
643 },
644 };
645 let index_of = |id: &str| inner.nodes.iter().position(|node| node.id == id);
646 let saved = match checkpoints {
647 Some((id, checkpoints)) => match checkpoints.load::<Saved>(id).await {
648 Ok(Some(saved)) if saved.finished && nested => {
649 return Ok(GraphRun {
650 state: saved.state,
651 last: saved.last,
652 usage: saved.usage,
653 elapsed: Duration::from_millis(saved.elapsed_ms),
654 });
655 }
656 Ok(saved) => saved.filter(|saved| !saved.finished),
657 Err(error) => return Err(fail(error, GraphState::default(), Duration::ZERO)),
658 },
659 None => None,
660 };
661 let mut state;
662 let mut usage;
663 let mut last;
664 let mut executions;
665 let mut ready = Vec::new();
666 let mut carried = Vec::new();
668 let clock;
669 let before;
670 match saved {
671 None => {
672 state = GraphState {
673 task,
674 ..GraphState::default()
675 };
676 usage = Usage::default();
677 last = Vec::new();
678 executions = 0;
679 ready = inner.entries.clone();
680 clock = Clock::resumed(Duration::ZERO);
681 before = Duration::ZERO;
682 }
683 Some(saved) => {
684 before = Duration::from_millis(saved.elapsed_ms);
685 for (ids, into) in [
687 (
688 saved.ready.iter().chain(&saved.failed).collect::<Vec<_>>(),
689 &mut ready,
690 ),
691 (saved.batch_done.iter().collect(), &mut carried),
692 ] {
693 for id in ids {
694 let Some(index) = index_of(id) else {
695 let error = CheckpointError::UnknownNode(id.clone());
696 return Err(fail(error, saved.state, before));
697 };
698 if !into.contains(&index) {
699 into.push(index);
700 }
701 }
702 }
703 tracing::info!(done = saved.state.order.len(), "graph run resumed");
704 if let Some(emit) = emit {
705 emit(GraphEvent::Resumed {
706 done: saved.state.order.clone(),
707 });
708 }
709 clock = Clock::resumed(Duration::from_millis(saved.active_ms));
710 state = saved.state;
711 usage = saved.usage;
712 last = saved.last;
713 executions = saved.executions;
714 }
715 }
716 let clock = &clock;
717 let mut failures = Vec::new();
718 let names = |indices: &[usize]| -> Vec<String> {
719 indices
720 .iter()
721 .filter_map(|&index| inner.nodes.get(index))
722 .map(|node| node.id.clone())
723 .collect()
724 };
725 let snapshot = |state: &GraphState,
726 usage: &Usage,
727 last: &[String],
728 executions: usize,
729 ready: &[usize],
730 batch_done: &[usize],
731 failures: &[GraphFailure]| Saved {
732 finished: ready.is_empty() && batch_done.is_empty() && failures.is_empty(),
733 state: state.clone(),
734 usage: *usage,
735 last: last.to_vec(),
736 executions,
737 ready: names(ready),
738 batch_done: names(batch_done),
739 failed: failures
740 .iter()
741 .filter_map(|failure| match failure {
742 GraphFailure::Node { node, .. } | GraphFailure::NodeTimeout { node } => {
743 Some(node.clone())
744 }
745 _ => None,
746 })
747 .collect(),
748 active_ms: millis(clock.active()),
749 elapsed_ms: millis(before + started.elapsed()),
750 };
751 'run: while !ready.is_empty() || !carried.is_empty() {
752 let mut finished = std::mem::take(&mut carried);
753 if !ready.is_empty() {
754 if let Some((id, checkpoints)) = checkpoints {
755 let saved = snapshot(
756 &state, &usage, &last, executions, &ready, &finished, &failures,
757 );
758 if let Err(error) = checkpoints.save(id, &saved).await {
759 failures.push(GraphFailure::Checkpoint { error });
760 break 'run;
761 }
762 }
763 if let Some(limit) = inner.max_node_executions
764 && executions + ready.len() > limit
765 {
766 failures.push(GraphFailure::MaxNodeExecutions { limit });
767 break 'run;
768 }
769 let remaining = inner.execution_timeout.saturating_sub(clock.active());
770 if remaining.is_zero() {
771 failures.push(GraphFailure::Timeout);
772 break 'run;
773 }
774 let budget = inner.node_timeout.min(remaining);
775 executions += ready.len();
776 let mut batch: FuturesUnordered<_> = ready
777 .iter()
778 .filter_map(|&index| Some((index, inner.nodes.get(index)?)))
779 .map(|(index, node)| {
780 let input = self.input(index, &state);
781 let part = state.finished.get(&node.id).copied().unwrap_or(0) + 1;
784 let saving = saving
785 .as_ref()
786 .map(|saving| saving.part("node", &node.id, part));
787 let span = tracing::info_span!(
788 "graph.node",
789 graph.node = %node.id,
790 otel.status_code = tracing::field::Empty,
791 error.type = tracing::field::Empty,
792 );
793 async move {
794 let Some(emit) = emit else {
795 let io = NodeIo::quiet(&node.id).saving_to(saving);
796 let run = node.node.run(input, &io).instrument(span.clone());
797 let outcome = clock.within(budget, run).await;
798 record_node(&span, &outcome);
799 return (index, node, outcome);
800 };
801 emit(GraphEvent::NodeStarted {
802 node: node.id.clone(),
803 });
804 let on_text = |text: &str| {
805 emit(GraphEvent::Text {
806 node: node.id.clone(),
807 text: text.to_owned(),
808 })
809 };
810 let on_question = |question: Question| {
811 tracing::info!(graph.node = %node.id, "human.question");
814 emit(GraphEvent::Question(question.pausing(clock)))
815 };
816 let io = NodeIo::streaming(&node.id, &on_text, &on_question)
817 .saving_to(saving);
818 let run = node.node.run(input, &io).instrument(span.clone());
819 let outcome = clock.within(budget, run).await;
820 record_node(&span, &outcome);
821 let id = node.id.clone();
822 emit(match &outcome {
823 Some(Ok(output)) => GraphEvent::NodeFinished {
824 node: id,
825 output: output.text.clone(),
826 },
827 Some(Err(error)) => GraphEvent::NodeFailed {
828 node: id,
829 error: error.to_string(),
830 },
831 None => GraphEvent::NodeFailed {
832 node: id,
833 error: "did not finish in time".to_owned(),
834 },
835 });
836 (index, node, outcome)
837 }
838 })
839 .collect();
840 let mut remaining = ready.clone();
841 while let Some((index, node, outcome)) = batch.next().await {
842 remaining.retain(|&other| other != index);
843 let id = node.id.clone();
844 *state.runs.entry(id.clone()).or_default() += 1;
845 state.order.push(id.clone());
846 match outcome {
847 Some(Ok(output)) => {
848 let NodeOutput {
849 text, usage: spent, ..
850 } = output;
851 usage += spent;
852 *state.finished.entry(id.clone()).or_default() += 1;
853 state.outputs.insert(id, text);
854 finished.push(index);
855 }
856 Some(Err(source)) => {
857 tracing::warn!(graph.node = %id, error = %source, "graph node failed");
858 failures.push(GraphFailure::Node { node: id, source });
859 }
860 None => failures.push(GraphFailure::NodeTimeout { node: id }),
861 }
862 if !remaining.is_empty()
866 && let Some((id, checkpoints)) = checkpoints
867 {
868 let counted = executions - remaining.len();
869 let saved = snapshot(
870 &state, &usage, &last, counted, &remaining, &finished, &failures,
871 );
872 if let Err(error) = checkpoints.save(id, &saved).await {
873 tracing::warn!(%error, "could not save a finished graph node");
874 }
875 }
876 }
877 }
878 if !finished.is_empty() {
879 last = names(&finished);
880 }
881 ready = Vec::new();
882 for edge in &inner.edges {
883 if finished.contains(&edge.from) && !ready.contains(&edge.to) && edge.holds(&state)
884 {
885 ready.push(edge.to);
886 }
887 }
888 }
889 if let Some((id, checkpoints)) = checkpoints
890 && !failures
891 .iter()
892 .any(|failure| matches!(failure, GraphFailure::Checkpoint { .. }))
893 {
894 let saved = snapshot(&state, &usage, &last, executions, &[], &[], &failures);
896 if let Err(error) = checkpoints.save(id, &saved).await {
897 tracing::warn!(%error, "could not save the graph run's end");
898 }
899 }
900 let run = GraphRun {
901 state,
902 last,
903 usage,
904 elapsed: before + started.elapsed(),
905 };
906 if failures.is_empty() {
907 Ok(run)
908 } else {
909 Err(GraphError { failures, run })
910 }
911 }
912
913 fn input(&self, index: usize, state: &GraphState) -> String {
915 let inner = &*self.inner;
916 let mut sources: Vec<(&str, &str)> = Vec::new();
917 for edge in inner.edges.iter().filter(|edge| edge.to == index) {
918 let Some(from) = inner.nodes.get(edge.from) else {
919 continue;
920 };
921 let from = from.id.as_str();
922 if let Some(output) = state.outputs.get(from)
923 && !sources.iter().any(|(seen, _)| *seen == from)
924 && edge.holds(state)
925 {
926 sources.push((from, output));
927 }
928 }
929 if sources.is_empty() {
930 return state.task.clone();
931 }
932 let mut text = format!(
933 "Original task: {}\n\nInputs from previous nodes:\n",
934 state.task
935 );
936 for (from, output) in sources {
937 let _ = write!(text, "\nFrom {from}:\n{output}\n");
938 }
939 text.trim_end().to_owned()
940 }
941}
942
943impl Node for Graph {
944 fn run<'a>(
948 &'a self,
949 input: String,
950 io: &'a NodeIo<'a>,
951 ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
952 Box::pin(async move {
953 let saving = io.saving().map(|saving| {
954 let checkpoints = self.inner.checkpoints.clone();
955 let checkpoints =
956 checkpoints.unwrap_or_else(|| saving.checkpoints.with_kind("graph"));
957 Saving::new(checkpoints, saving.run_id.clone())
958 });
959 let emit = |event| match event {
960 GraphEvent::Text { text, .. } => io.text(&text),
961 GraphEvent::Question(question) => io.forward(question),
962 _ => {}
963 };
964 let emit: Option<Emit<'_, GraphEvent>> = io.is_streaming().then_some(&emit);
965 let run = self.run_task(input, saving, true, emit).await?;
966 Ok(NodeOutput::new(run.answer()).with_usage(run.usage))
967 })
968 }
969}