Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Workflows and graphs

A single agent decides its own steps. A workflow is for when you want to decide them: clean the input, then ask an agent, then wait for a person to approve, then act. Troupekit gives you two ways to write one. The Graph builder chains agents and tool fns in a line, in Rust. A workflow TOML file adds routers, human pauses, fan-out and joins. Both run as a graph run that is checkpointed after each step and can resume after a crash.

The Graph builder

In a chain, each node reads the output of the node before it. The first node reads the run's input, and the last node's output is the answer. We start with two tool fns:

#![allow(unused)]
fn main() {
/// Trims the input.
#[tool]
fn clean_text(input: String) -> String {
    input.trim().to_string()
}

/// Counts characters of the cleaned text.
#[tool]
fn count_chars(clean: String) -> usize {
    clean.chars().count()
}
}

Then we chain them and run the graph once:

#![allow(unused)]
fn main() {
let report = Graph::new("lab3")
    .step("clean", clean_text)
    .step("count", count_chars)
    .run_with("  abc ")
    .await
    .unwrap();
assert_eq!(report.output(), &json!("3"));
assert_eq!(report.state()["clean"], json!("abc"));
assert_eq!(report.state()["input"], json!("  abc "));
}

Notice how the data moves. count_chars takes an argument named clean, and that name is what wires it to the clean node: a fn node's argument names must equal the ids of the nodes that feed it, and the first node's argument is input. Every node's output also stays in the run state, which is why the test can read clean and input back.

You add an agent the same way, with .agent(id, agent). The agent keeps its own model. Its tools and evals join the graph, and the graph takes over its storage, retries and events. An agent that brings its own limits, laws or ledger makes build fail, because the graph would otherwise drop that spend cap without telling you.

.edge(from, to) sets the order explicitly. The edges must form one chain; with no edges, the nodes run in the order you added them. .checkpoints(..), .limits(..), .ledger(..), .max_steps(..) and .retries(..) work as they do on an agent.

run returns the output value. run_with returns a GraphReport, which also gives you state(), usage(), steps(), run_id() and trace_path(). To continue a run after a crash, give the graph .checkpoints(Storage::sqlite(path)) and keep its run id before the run can crash. run_with returns the id only once the run ends, so start the run with BuiltGraph::start(input): it saves the first checkpoint and returns the run id before any node runs. Store that id, then drive the run with BuiltGraph::resume(run_id), or with resume_for(run_id, budget) for a time-boxed window. After a crash, call resume(run_id) with the same id. The default in-memory store is lost when the process exits.

Workflow TOML

When the flow needs branches or a person in the loop, write it as TOML instead. A workflow file has a name, a start node, typed shared state, nodes and edges:

name = "plan-week"
start = "plan"
max_steps = 50
max_retries = 3

[state]
goal = "string"
plan = "{steps: list}"
approved = "bool"
note = "string"

[[nodes]]
id = "plan"
kind = "agent"
persona = "planner"
prompt = "Plan the week."
reads = ["goal"]
writes = "plan"

[[nodes]]
id = "approve"
kind = "human"
ask = "approval"
prompt = "Approve this plan?"
reads = ["plan"]
writes = "approved"

[[nodes]]
id = "route"
kind = "router"
condition = "flag(approved)"

[[nodes]]
id = "save"
kind = "tool"
tool = "save_plan"
reads = ["plan"]
writes = "note"

[[nodes]]
id = "done"
kind = "end"

[[edges]]
from = "plan"
to = "approve"

[[edges]]
from = "approve"
to = "route"

[[edges]]
from = "route"
to = "save"
when = "true"

[[edges]]
from = "route"
to = "plan"
when = "false"

[[edges]]
from = "save"
to = "done"

Node kinds

KindKeysDoes
agentpersona, prompt, reads, writesruns a persona on the state keys it reads
tooltool, reads, writescalls one tool
humanask, prompt, reads, writespauses the run until someone answers; ask is approval or question
routerconditionpicks one out-edge by the label its condition returns
joinnonewaits for every branch of a fan-out
endnonefinishes the run

Approval and routing work together. A human node with ask = "approval" must write a bool key, and a router can then branch on it with the built-in condition flag(key), which returns "true" or "false". You can register your own conditions with Conditions::register. A condition must be deterministic: when a step is replayed after a crash, it has to route the same way it did the first time.

State keys are typed with the same syntax as persona output, for example list<T> or enum(x, y), with a trailing ? for nullable. Agents and personas lists every type.

Workflow::parse checks the whole file before anything runs: fields, node kinds, state keys, edges, reachability, cycles that have no router, and joins after a fan-out. It returns the first problem it finds.

KeyRuleDefault
name1 to 64 of [a-z0-9-], not starting with -required
starta node idrequired
max_steps1 to 10 000200
max_retries0 to 505
trace, trace_content, trace_filesee Tracing and budgetsoff

Hosting runs

In a long-lived service you usually do not call a workflow directly. troupekit-host runs workflows from a leased job queue: a Runner claims a job, steps the run on from its latest checkpoint and saves it again. It has two modes. Worker mode, runner.work(opts, shutdown), ticks in a loop, for a process that stays up. Step mode, runner.tick(opts), processes the due jobs once, which fits one serverless request.

A paused run waits in the store until you act on it. runner.resume(run_id, node, answer) answers a human node, and runner.raise_budget(run_id, limits) raises the limits of a run paused on its budget.

This is how the kill and resume example starts a run. We parse the workflow, create the run with its input, and put it on the queue:

#![allow(unused)]
fn main() {
async fn start(troupe: &Troupe) -> RunId {
    let wf = Workflow::parse("three.toml", WORKFLOW).expect("valid workflow");
    let input: Map<String, Value> = [("goal".to_string(), json!("survive"))]
        .into_iter()
        .collect();
    let io = io(troupe, false);
    let run = GraphRun::new(wf, input, Limits::default(), io.as_ref())
        .await
        .expect("run");
    troupe.runner(io).enqueue(&run).await.expect("enqueue");
    run.run_id()
}
}

See Kill and resume a workflow for the whole program.

Note

Version 0.5 adds team, crew and handoff patterns in TOML, parallel branches with declared reducers, fan-out over lists, and forking a run from any checkpoint.