use std::collections::HashMap;
use std::fmt::Write as _;
use std::sync::Arc;
use std::time::{Duration, Instant};
use futures::StreamExt;
use futures::stream::FuturesUnordered;
use rig_core::completion::Usage;
use rig_core::wasm_compat::{WasmBoxedFuture, WasmBoxedStream, WasmCompatSend, WasmCompatSync};
use serde::{Deserialize, Serialize};
use tracing::Instrument;
use crate::BuildError;
use crate::checkpoint::{CheckpointError, Checkpoints, Saving};
use crate::events::{Emit, events};
use crate::human::{Clock, Question};
use crate::node::{Node, NodeError, NodeIo, NodeOutput};
#[cfg(not(target_family = "wasm"))]
type Condition = Arc<dyn Fn(&GraphState) -> bool + Send + Sync>;
#[cfg(target_family = "wasm")]
type Condition = Arc<dyn Fn(&GraphState) -> bool>;
#[derive(Clone)]
pub struct Graph {
inner: Arc<Inner>,
}
struct Inner {
nodes: Vec<GraphNode>,
edges: Vec<Edge>,
entries: Vec<usize>,
max_node_executions: Option<usize>,
execution_timeout: Duration,
node_timeout: Duration,
checkpoints: Option<Checkpoints>,
}
struct GraphNode {
id: String,
node: Box<dyn Node>,
}
struct Edge {
from: usize,
to: usize,
condition: Option<Condition>,
}
impl Edge {
fn holds(&self, state: &GraphState) -> bool {
self.condition
.as_ref()
.is_none_or(|condition| condition(state))
}
}
#[must_use]
pub struct GraphBuilder {
nodes: Vec<(String, Box<dyn Node>)>,
edges: Vec<(String, String, Option<Condition>)>,
entries: Vec<String>,
max_node_executions: Option<usize>,
execution_timeout: Duration,
node_timeout: Duration,
checkpoints: Option<Checkpoints>,
}
impl Graph {
pub fn builder() -> GraphBuilder {
GraphBuilder {
nodes: Vec::new(),
edges: Vec::new(),
entries: Vec::new(),
max_node_executions: None,
execution_timeout: Duration::from_secs(15 * 60),
node_timeout: Duration::from_secs(5 * 60),
checkpoints: None,
}
}
}
impl GraphBuilder {
pub fn node(mut self, id: impl Into<String>, node: impl Node + 'static) -> Self {
self.nodes.push((id.into(), Box::new(node)));
self
}
pub fn edge(mut self, from: impl Into<String>, to: impl Into<String>) -> Self {
self.edges.push((from.into(), to.into(), None));
self
}
pub fn edge_if(
mut self,
from: impl Into<String>,
to: impl Into<String>,
condition: impl Fn(&GraphState) -> bool + WasmCompatSend + WasmCompatSync + 'static,
) -> Self {
self.edges
.push((from.into(), to.into(), Some(Arc::new(condition))));
self
}
pub fn entry(mut self, id: impl Into<String>) -> Self {
self.entries.push(id.into());
self
}
pub fn max_node_executions(mut self, max: usize) -> Self {
self.max_node_executions = Some(max);
self
}
pub fn execution_timeout(mut self, timeout: Duration) -> Self {
self.execution_timeout = timeout;
self
}
pub fn node_timeout(mut self, timeout: Duration) -> Self {
self.node_timeout = timeout;
self
}
pub fn checkpoints(
mut self,
store: impl rig_memory::AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
) -> Self {
self.checkpoints = Some(Checkpoints::new(store, "graph"));
self
}
pub fn build(self) -> Result<Graph, BuildError> {
if self.nodes.is_empty() {
return Err(BuildError::Empty);
}
let mut nodes: Vec<GraphNode> = Vec::with_capacity(self.nodes.len());
for (id, node) in self.nodes {
if nodes.iter().any(|other| other.id == id) {
return Err(BuildError::DuplicateName(id));
}
nodes.push(GraphNode { id, node });
}
let index = |id: &str| {
nodes
.iter()
.position(|node| node.id == id)
.ok_or_else(|| BuildError::UnknownName(id.to_owned()))
};
let mut edges = Vec::with_capacity(self.edges.len());
for (from, to, condition) in self.edges {
edges.push(Edge {
from: index(&from)?,
to: index(&to)?,
condition,
});
}
let entries = if self.entries.is_empty() {
let starts: Vec<usize> = (0..nodes.len())
.filter(|&node| !edges.iter().any(|edge| edge.to == node))
.collect();
if starts.is_empty() {
return Err(BuildError::NoEntry);
}
starts
} else {
let mut entries = Vec::new();
for id in &self.entries {
let entry = index(id)?;
if !entries.contains(&entry) {
entries.push(entry);
}
}
entries
};
if self.max_node_executions.is_none() && has_cycle(nodes.len(), &edges) {
return Err(BuildError::UnboundedCycle);
}
Ok(Graph {
inner: Arc::new(Inner {
nodes,
edges,
entries,
max_node_executions: self.max_node_executions,
execution_timeout: self.execution_timeout,
node_timeout: self.node_timeout,
checkpoints: self.checkpoints,
}),
})
}
}
fn has_cycle(nodes: usize, edges: &[Edge]) -> bool {
let mut incoming = vec![0usize; nodes];
for edge in edges {
if let Some(count) = incoming.get_mut(edge.to) {
*count += 1;
}
}
let mut free: Vec<usize> = incoming
.iter()
.enumerate()
.filter(|(_, count)| **count == 0)
.map(|(node, _)| node)
.collect();
let mut peeled = 0;
while let Some(node) = free.pop() {
peeled += 1;
for edge in edges.iter().filter(|edge| edge.from == node) {
if let Some(count) = incoming.get_mut(edge.to) {
*count -= 1;
if *count == 0 {
free.push(edge.to);
}
}
}
}
peeled < nodes
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GraphState {
task: String,
outputs: HashMap<String, String>,
runs: HashMap<String, usize>,
#[serde(default)]
finished: HashMap<String, usize>,
order: Vec<String>,
}
impl GraphState {
pub fn task(&self) -> &str {
&self.task
}
pub fn output(&self, id: &str) -> Option<&str> {
self.outputs.get(id).map(String::as_str)
}
pub fn runs(&self, id: &str) -> usize {
self.runs.get(id).copied().unwrap_or(0)
}
pub fn order(&self) -> &[String] {
&self.order
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct GraphRun {
pub state: GraphState,
pub last: Vec<String>,
pub usage: Usage,
pub elapsed: Duration,
}
impl GraphRun {
pub fn output(&self, id: &str) -> Option<&str> {
self.state.output(id)
}
pub fn answer(&self) -> String {
match self.last.as_slice() {
[only] => self.output(only).unwrap_or_default().to_owned(),
last => {
let mut text = String::new();
for id in last {
let _ = write!(
text,
"From {id}:\n{}\n\n",
self.output(id).unwrap_or_default()
);
}
text.trim_end().to_owned()
}
}
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub struct GraphError {
pub failures: Vec<GraphFailure>,
pub run: GraphRun,
}
impl std::fmt::Display for GraphError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.failures.as_slice() {
[] => f.write_str("the graph run failed"),
[only] => only.fmt(f),
[first, rest @ ..] => write!(f, "{first} (and {} more failures)", rest.len()),
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum GraphEvent {
Resumed {
done: Vec<String>,
},
NodeStarted {
node: String,
},
Text {
node: String,
text: String,
},
NodeFinished {
node: String,
output: String,
},
NodeFailed {
node: String,
error: String,
},
Question(Question),
Finished(Box<Result<GraphRun, GraphError>>),
}
#[derive(Serialize, Deserialize)]
struct Saved {
finished: bool,
state: GraphState,
usage: Usage,
last: Vec<String>,
executions: usize,
ready: Vec<String>,
#[serde(default)]
batch_done: Vec<String>,
failed: Vec<String>,
active_ms: u64,
elapsed_ms: u64,
}
fn millis(duration: Duration) -> u64 {
u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum GraphFailure {
#[error("node {node:?} failed: {source}")]
Node {
node: String,
#[source]
source: NodeError,
},
#[error("node {node:?} did not finish in time")]
NodeTimeout {
node: String,
},
#[error("checkpoint: {error}")]
Checkpoint {
#[source]
error: CheckpointError,
},
#[error("the graph ran out of time")]
Timeout,
#[error("the graph reached its limit of {limit} node runs")]
MaxNodeExecutions {
limit: usize,
},
}
fn run_span(run_id: Option<&str>) -> tracing::Span {
tracing::info_span!(
"graph.run",
graph.run_id = run_id,
graph.node_runs = tracing::field::Empty,
graph.usage.input_tokens = tracing::field::Empty,
graph.usage.output_tokens = tracing::field::Empty,
otel.status_code = tracing::field::Empty,
error.type = tracing::field::Empty,
)
}
fn record_outcome(span: &tracing::Span, outcome: &Result<GraphRun, GraphError>) {
let run = match outcome {
Ok(run) => run,
Err(error) => {
span.record("otel.status_code", "ERROR");
if let Some(failure) = error.failures.first() {
span.record("error.type", failure.kind());
}
&error.run
}
};
span.record("graph.node_runs", run.state.order().len());
if let Some(tokens) = run.usage.input_tokens {
span.record("graph.usage.input_tokens", tokens);
}
if let Some(tokens) = run.usage.output_tokens {
span.record("graph.usage.output_tokens", tokens);
}
}
fn record_node<T>(span: &tracing::Span, outcome: &Option<Result<T, NodeError>>) {
let kind = match outcome {
Some(Ok(_)) => return,
Some(Err(_)) => "node_failed",
None => "timeout",
};
span.record("otel.status_code", "ERROR");
span.record("error.type", kind);
}
impl GraphFailure {
fn kind(&self) -> &'static str {
match self {
Self::Node { .. } => "node_failed",
Self::NodeTimeout { .. } => "node_timeout",
Self::Timeout => "timeout",
Self::MaxNodeExecutions { .. } => "max_node_executions",
Self::Checkpoint { .. } => "checkpoint",
}
}
}
impl Graph {
pub async fn run(&self, task: impl Into<String>) -> Result<GraphRun, GraphError> {
let span = run_span(None);
let outcome = self
.run_task(task.into(), None, false, None)
.instrument(span.clone())
.await;
record_outcome(&span, &outcome);
outcome
}
pub async fn run_as(
&self,
run_id: &str,
task: impl Into<String>,
) -> Result<GraphRun, GraphError> {
let span = run_span(Some(run_id));
let outcome = self
.run_task(task.into(), self.saving(Some(run_id)), false, None)
.instrument(span.clone())
.await;
record_outcome(&span, &outcome);
outcome
}
pub fn stream_as<'a>(
&'a self,
run_id: &'a str,
task: impl Into<String>,
) -> WasmBoxedStream<'a, GraphEvent> {
self.stream_events(task.into(), Some(run_id))
}
pub fn stream(&self, task: impl Into<String>) -> WasmBoxedStream<'_, GraphEvent> {
self.stream_events(task.into(), None)
}
fn stream_events<'a>(
&'a self,
task: String,
run_id: Option<&'a str>,
) -> WasmBoxedStream<'a, GraphEvent> {
let span = run_span(run_id);
events(
move |sender| async move {
let emit = move |event| {
let _ = sender.send(event);
};
let outcome = self
.run_task(task, self.saving(run_id), false, Some(&emit))
.instrument(span.clone())
.await;
record_outcome(&span, &outcome);
outcome
},
|outcome| GraphEvent::Finished(Box::new(outcome)),
)
}
fn saving(&self, run_id: Option<&str>) -> Option<Saving> {
run_id
.zip(self.inner.checkpoints.clone())
.map(|(id, checkpoints)| Saving::new(checkpoints, id))
}
async fn run_task(
&self,
task: String,
saving: Option<Saving>,
nested: bool,
emit: Option<Emit<'_, GraphEvent>>,
) -> Result<GraphRun, GraphError> {
let inner = &*self.inner;
let started = Instant::now();
let checkpoints = saving
.as_ref()
.map(|saving| (saving.run_id.as_str(), &saving.checkpoints));
let fail = |error: CheckpointError, state: GraphState, before: Duration| GraphError {
failures: vec![GraphFailure::Checkpoint { error }],
run: GraphRun {
state,
last: Vec::new(),
usage: Usage::default(),
elapsed: before + started.elapsed(),
},
};
let index_of = |id: &str| inner.nodes.iter().position(|node| node.id == id);
let saved = match checkpoints {
Some((id, checkpoints)) => match checkpoints.load::<Saved>(id).await {
Ok(Some(saved)) if saved.finished && nested => {
return Ok(GraphRun {
state: saved.state,
last: saved.last,
usage: saved.usage,
elapsed: Duration::from_millis(saved.elapsed_ms),
});
}
Ok(saved) => saved.filter(|saved| !saved.finished),
Err(error) => return Err(fail(error, GraphState::default(), Duration::ZERO)),
},
None => None,
};
let mut state;
let mut usage;
let mut last;
let mut executions;
let mut ready = Vec::new();
let mut carried = Vec::new();
let clock;
let before;
match saved {
None => {
state = GraphState {
task,
..GraphState::default()
};
usage = Usage::default();
last = Vec::new();
executions = 0;
ready = inner.entries.clone();
clock = Clock::resumed(Duration::ZERO);
before = Duration::ZERO;
}
Some(saved) => {
before = Duration::from_millis(saved.elapsed_ms);
for (ids, into) in [
(
saved.ready.iter().chain(&saved.failed).collect::<Vec<_>>(),
&mut ready,
),
(saved.batch_done.iter().collect(), &mut carried),
] {
for id in ids {
let Some(index) = index_of(id) else {
let error = CheckpointError::UnknownNode(id.clone());
return Err(fail(error, saved.state, before));
};
if !into.contains(&index) {
into.push(index);
}
}
}
tracing::info!(done = saved.state.order.len(), "graph run resumed");
if let Some(emit) = emit {
emit(GraphEvent::Resumed {
done: saved.state.order.clone(),
});
}
clock = Clock::resumed(Duration::from_millis(saved.active_ms));
state = saved.state;
usage = saved.usage;
last = saved.last;
executions = saved.executions;
}
}
let clock = &clock;
let mut failures = Vec::new();
let names = |indices: &[usize]| -> Vec<String> {
indices
.iter()
.filter_map(|&index| inner.nodes.get(index))
.map(|node| node.id.clone())
.collect()
};
let snapshot = |state: &GraphState,
usage: &Usage,
last: &[String],
executions: usize,
ready: &[usize],
batch_done: &[usize],
failures: &[GraphFailure]| Saved {
finished: ready.is_empty() && batch_done.is_empty() && failures.is_empty(),
state: state.clone(),
usage: *usage,
last: last.to_vec(),
executions,
ready: names(ready),
batch_done: names(batch_done),
failed: failures
.iter()
.filter_map(|failure| match failure {
GraphFailure::Node { node, .. } | GraphFailure::NodeTimeout { node } => {
Some(node.clone())
}
_ => None,
})
.collect(),
active_ms: millis(clock.active()),
elapsed_ms: millis(before + started.elapsed()),
};
'run: while !ready.is_empty() || !carried.is_empty() {
let mut finished = std::mem::take(&mut carried);
if !ready.is_empty() {
if let Some((id, checkpoints)) = checkpoints {
let saved = snapshot(
&state, &usage, &last, executions, &ready, &finished, &failures,
);
if let Err(error) = checkpoints.save(id, &saved).await {
failures.push(GraphFailure::Checkpoint { error });
break 'run;
}
}
if let Some(limit) = inner.max_node_executions
&& executions + ready.len() > limit
{
failures.push(GraphFailure::MaxNodeExecutions { limit });
break 'run;
}
let remaining = inner.execution_timeout.saturating_sub(clock.active());
if remaining.is_zero() {
failures.push(GraphFailure::Timeout);
break 'run;
}
let budget = inner.node_timeout.min(remaining);
executions += ready.len();
let mut batch: FuturesUnordered<_> = ready
.iter()
.filter_map(|&index| Some((index, inner.nodes.get(index)?)))
.map(|(index, node)| {
let input = self.input(index, &state);
let part = state.finished.get(&node.id).copied().unwrap_or(0) + 1;
let saving = saving
.as_ref()
.map(|saving| saving.part("node", &node.id, part));
let span = tracing::info_span!(
"graph.node",
graph.node = %node.id,
otel.status_code = tracing::field::Empty,
error.type = tracing::field::Empty,
);
async move {
let Some(emit) = emit else {
let io = NodeIo::quiet(&node.id).saving_to(saving);
let run = node.node.run(input, &io).instrument(span.clone());
let outcome = clock.within(budget, run).await;
record_node(&span, &outcome);
return (index, node, outcome);
};
emit(GraphEvent::NodeStarted {
node: node.id.clone(),
});
let on_text = |text: &str| {
emit(GraphEvent::Text {
node: node.id.clone(),
text: text.to_owned(),
})
};
let on_question = |question: Question| {
tracing::info!(graph.node = %node.id, "human.question");
emit(GraphEvent::Question(question.pausing(clock)))
};
let io = NodeIo::streaming(&node.id, &on_text, &on_question)
.saving_to(saving);
let run = node.node.run(input, &io).instrument(span.clone());
let outcome = clock.within(budget, run).await;
record_node(&span, &outcome);
let id = node.id.clone();
emit(match &outcome {
Some(Ok(output)) => GraphEvent::NodeFinished {
node: id,
output: output.text.clone(),
},
Some(Err(error)) => GraphEvent::NodeFailed {
node: id,
error: error.to_string(),
},
None => GraphEvent::NodeFailed {
node: id,
error: "did not finish in time".to_owned(),
},
});
(index, node, outcome)
}
})
.collect();
let mut remaining = ready.clone();
while let Some((index, node, outcome)) = batch.next().await {
remaining.retain(|&other| other != index);
let id = node.id.clone();
*state.runs.entry(id.clone()).or_default() += 1;
state.order.push(id.clone());
match outcome {
Some(Ok(output)) => {
let NodeOutput {
text, usage: spent, ..
} = output;
usage += spent;
*state.finished.entry(id.clone()).or_default() += 1;
state.outputs.insert(id, text);
finished.push(index);
}
Some(Err(source)) => {
tracing::warn!(graph.node = %id, error = %source, "graph node failed");
failures.push(GraphFailure::Node { node: id, source });
}
None => failures.push(GraphFailure::NodeTimeout { node: id }),
}
if !remaining.is_empty()
&& let Some((id, checkpoints)) = checkpoints
{
let counted = executions - remaining.len();
let saved = snapshot(
&state, &usage, &last, counted, &remaining, &finished, &failures,
);
if let Err(error) = checkpoints.save(id, &saved).await {
tracing::warn!(%error, "could not save a finished graph node");
}
}
}
}
if !finished.is_empty() {
last = names(&finished);
}
ready = Vec::new();
for edge in &inner.edges {
if finished.contains(&edge.from) && !ready.contains(&edge.to) && edge.holds(&state)
{
ready.push(edge.to);
}
}
}
if let Some((id, checkpoints)) = checkpoints
&& !failures
.iter()
.any(|failure| matches!(failure, GraphFailure::Checkpoint { .. }))
{
let saved = snapshot(&state, &usage, &last, executions, &[], &[], &failures);
if let Err(error) = checkpoints.save(id, &saved).await {
tracing::warn!(%error, "could not save the graph run's end");
}
}
let run = GraphRun {
state,
last,
usage,
elapsed: before + started.elapsed(),
};
if failures.is_empty() {
Ok(run)
} else {
Err(GraphError { failures, run })
}
}
fn input(&self, index: usize, state: &GraphState) -> String {
let inner = &*self.inner;
let mut sources: Vec<(&str, &str)> = Vec::new();
for edge in inner.edges.iter().filter(|edge| edge.to == index) {
let Some(from) = inner.nodes.get(edge.from) else {
continue;
};
let from = from.id.as_str();
if let Some(output) = state.outputs.get(from)
&& !sources.iter().any(|(seen, _)| *seen == from)
&& edge.holds(state)
{
sources.push((from, output));
}
}
if sources.is_empty() {
return state.task.clone();
}
let mut text = format!(
"Original task: {}\n\nInputs from previous nodes:\n",
state.task
);
for (from, output) in sources {
let _ = write!(text, "\nFrom {from}:\n{output}\n");
}
text.trim_end().to_owned()
}
}
impl Node for Graph {
fn run<'a>(
&'a self,
input: String,
io: &'a NodeIo<'a>,
) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
Box::pin(async move {
let saving = io.saving().map(|saving| {
let checkpoints = self.inner.checkpoints.clone();
let checkpoints =
checkpoints.unwrap_or_else(|| saving.checkpoints.with_kind("graph"));
Saving::new(checkpoints, saving.run_id.clone())
});
let emit = |event| match event {
GraphEvent::Text { text, .. } => io.text(&text),
GraphEvent::Question(question) => io.forward(question),
_ => {}
};
let emit: Option<Emit<'_, GraphEvent>> = io.is_streaming().then_some(&emit);
let run = self.run_task(input, saving, true, emit).await?;
Ok(NodeOutput::new(run.answer()).with_usage(run.usage))
})
}
}