Skip to content

Nodes, edges and routing

A node is an async function of the current state and a NodeCtx. It returns a partial state update.

g.add_node_fn("draft", |s: Value, _ctx: NodeCtx| async move {
Ok::<Value, NodeError>(json!({"log": [format!("draft about {}", s["topic"])]}))
})?;

Three ways to add a node:

  • add_node_fn(name, closure) for a closure.
  • add_node(name, node) for anything that implements Node, for example node_fn(..), a compiled subgraph (Pregel) or warpra_prebuilt::ToolNode.
  • add_node_with(name, node, NodeOpts) to set options: retry, cache, defer, metadata, input_keys, timeout, error_handler and destinations.

Nodes in the same superstep run concurrently on tokio. Their writes are applied in a fixed task order.

g.add_edge(START, "draft")?.add_edge("draft", "review")?.add_edge("review", END)?;

add_edge returns the builder, so calls chain. add_sequence adds several nodes and links them in order. add_join_edge([a, b], c) waits for all of a and b before c runs.

A router reads the state and returns the next node. The optional path map lists the possible targets, which also feeds the graph drawing. This is from the chatbot example:

g.add_conditional_edges(
"agent",
|s: &Value| {
let has_calls = s["messages"].as_array().and_then(|m| m.last())
.is_some_and(|m| m["tool_calls"].as_array().is_some_and(|c| !c.is_empty()));
if has_calls { "tools" } else { END }
},
Some(&[("tools", "tools"), (END, END)]),
)?;
g.add_edge("tools", "agent")?;

Cycles are allowed. A recursion limit stops runaway loops with GraphError::Recursion. Set it per run with RunConfig::with_recursion_limit(n).

A router can return a list of SendPackets. Each packet runs the target node once, with the packet’s argument as the node’s whole input. This is map-reduce: results merge through the reducer in Send order.

let mut g = StateGraph::new()
.last_value("subjects")
.reducer_with_initial("results", reducers::append, json!([]))
.last_value("summary");
g.add_node_fn("generate", |_s: Value, _c: NodeCtx| async move {
Ok::<Value, NodeError>(json!({"subjects": ["a", "bb", "ccc"]}))
})?;
g.add_node_fn("worker", |input: Value, _c: NodeCtx| async move {
let s = input["subject"].as_str().unwrap_or("").to_string();
Ok::<Value, NodeError>(json!({"results": [s.len()]}))
})?;
g.add_node_fn("collect", |input: Value, _c: NodeCtx| async move {
let total: u64 = input["results"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).sum();
Ok::<Value, NodeError>(json!({"summary": total}))
})?;
g.add_edge(START, "generate")?;
g.add_conditional_edges(
"generate",
|s: &Value| s["subjects"].as_array().unwrap().iter()
.map(|x| SendPacket::new("worker", json!({"subject": x})))
.collect::<Vec<_>>(),
None,
)?;
g.add_edge("worker", "collect")?.add_edge("collect", END)?;
// results == [1, 2, 3], summary == 6

SendPacket is Warpra’s Send type. It is exported under that name so use warpra::* does not shadow Rust’s Send trait. The canonical path is warpra::types::Send. A packet can carry its own timeout with with_timeout(..).

A node can return a Command instead of a plain update. It writes state and picks the next node in one step. Declare the possible targets with NodeOpts::destinations so the graph drawing knows them. From the human_approval example:

g.add_node_with(
"review",
node_fn(|s: Value, ctx: NodeCtx| async move {
let decision = ctx.interrupt(json!({"question": "Send this email?", "draft": s["draft"]}))?;
let approved = decision == json!("approve");
Ok::<_, NodeError>(Command::new().update(json!({"approved": approved})).goto(if approved { "send" } else { END }))
}),
NodeOpts::new().destinations(["send"]),
)?;

Command supports:

  • update(value): a state update.
  • goto(..): the next node or nodes.
  • resume(value) and resume_map(..): answers to interrupts, passed as invoke input.
  • parent(): send the command to the parent graph.

A compiled graph is a Node, so you can add it to another graph with add_node. Subgraph checkpoints live in their own namespaces (node:task_id|node:task_id). Subgraph interrupts and PARENT commands bubble up. Pregel::get_subgraphs and find_subgraph list and look them up.

app.draw_mermaid() returns a Mermaid diagram. Pregel::get_graph(xray) returns the drawing JSON the server serves from /assistants/{id}/graph.

Warpra is open source under Apache-2.0. Made by Liceron.