adk-graph
Graph-based workflow orchestration for Rust Agent Development Kit (ADK-Rust) agents, inspired by LangGraph.
Stability: Stable — follows semantic versioning, so breaking changes wait for the next major release. See STABILITY.md.
Overview
adk-graph builds stateful agent workflows as graphs of nodes and edges. It brings LangGraph-style capabilities to ADK-Rust: a GraphAgent implements the ADK Agent trait, so a graph runs under a Runner, streams through it, and sits beside LlmAgent and the workflow agents.
Features
- Graph-Based Workflows: Define agent workflows as directed graphs with nodes and edges
- AgentNode: Wrap LLM agents as graph nodes with custom input/output mappers. Under a
Runnerthe agent sees the caller's session — its id, and its state with the graph's state on top, so instruction templates resolve — andGraphAgentstreams the agent's events to the caller as they are produced, so the session records them. An agent's failure isGraphError::AgentFailed, which keeps the agent'sAdkErrorcategory and code - Cyclic Support: Native support for loops and iterative reasoning (ReAct pattern)
- Conditional Routing: Dynamic edge routing based on state
- Decision nodes:
DecisionNoderoutes by a model's typed decision, made with structured output, and writes the route, rationale and confidence to state; its call counts against the run budget - Fan-out / fan-in: parallel branches run concurrently in a super-step. A node with more than one incoming direct edge is deferred automatically, so it runs once after the branches that can still reach it arrive — branches of unequal length, a merge after a conditional branch, a node re-entered by a loop, and an entry node that is also a join run correctly with no configuration.
mark_deferredsets afan_in_timeoutor an n-of-mmin_predecessorsquorum - State Management: Typed state with reducers (overwrite, append, sum, custom)
- Checkpointing: Persistent state after each step — memory, SQLite, PostgreSQL, Redis, MongoDB, Neo4j, Firestore — every backend proven by one conformance suite; per-thread versions refuse a second writer with
GraphError::CheckpointConflictinstead of interleaving - Durability modes:
Sync(default),Async, orExitper run; a step with a declaredNonIdempotentnode writes earlier checkpoints first - Pending writes: when one node of a parallel step fails, the finished nodes are not run again on resume
- Durable Resume: Automatically resume from the last checkpoint after a crash — skips nodes of every checkpointed step. Execution is at-least-once: a crash mid-step re-runs that step's nodes; see Execution Guarantees
- Human-in-the-Loop: Interrupt before/after nodes, dynamic interrupts. A pause is resumable, including one raised inside a subgraph. Every pause of a step reaches the caller, and
NodeContext::resume_valuehands a paused node the answer to that pause alone. Each dynamic pause has a stable id (Interrupt::id), may declare a JSON Schema for its answer (NodeOutput::with_response_schema, checked on resume), andExecutionConfig::strict_resumeaccepts answers only under the ids of pending pauses, refusing stale ones withGraphError::ResumeRejected - Subgraphs: run a compiled graph as a node with mapped channels (
SubgraphNode). A pause inside pauses the parent, and a channel mapping that names a channel neither side declares fails when the parent compiles - Routing from inside a node:
NodeOutput::with_gotonames successors and replaces the node's declared edges;AgentNode::with_goto_mapperroutes on what the agent answered;with_goto_parenthands control to a node of the parent graph - Reliability: per-node retry with backoff and jitter that never exceeds
max_delay, a concurrency bound, per-node timeouts, graph-wideNodeDefaults, andwith_node_error_handlerto recover once a retry budget is spent. A failure no handler recovers stops the step: queued nodes do not start and sibling retries stop waiting - Invoking a node directly:
ctx.run_node_withruns a node the graph has no edge to, sized from state, and records it so a resume does not pay for it twice; concurrent calls under one run id run the child once - As a tool:
NodeToolexposes a graph or a single node through theTooltrait, so anLlmAgentcan call a whole graph - Bounded growth:
RetentionPolicylimits how many checkpoints a thread keeps, by count or age, after every save or on demand withCheckpointer::prune. It never removes what a resume still needs — the newest checkpoint, each pause no run has resumed, each effect-log entry — or a checkpoint it pins;Checkpointer::deleteremoves a whole thread. Every backend runs the same conformance case - Run records: every checkpoint carries its run, the steps finished since the previous one (each node's start, duration, status, written keys and attempt) and a fork's lineage, so an observer reads a run's history from checkpoints alone;
CompiledGraph::shapereports the graph's nodes, edges and entry nodes - Fork with edits (feature:
time-travel):TimeTravelHandle::forkbranches a new thread from a checkpoint with channels overwritten, keeps waiting joins, and records the fork's lineage; the source thread is never written - Governed nodes:
with_governed_nodeputs a node's call on the governed path — approval, edits, the kill switch and the action ledger — so it runs at most once per call in its lineage, forks included; a run without an action ledger, or a graph without a checkpointer, does not run it - Strictness, opt-in:
with_strict_channelsfails the run when a node writes a channel the schema does not declare - Streaming: Five stream modes (values, updates, messages, custom, debug)
- ADK Integration:
before_agent_callbackandafter_agent_callbackonGraphAgentBuilder; aGraphAgentruns under anyRunner - YAML and JSON workflows (feature:
yaml):WorkflowDefinitionreads a workflow file — agent and LLM nodes,set, function, action and interrupt nodes, conditional routes over a safe condition language, interrupts and checkpointing — validates it with each issue's path, line and column, and builds it against aWorkflowRegistry;schemas/workflow.schema.jsongives editors completion, andadk-rust graph runruns a file. See YAML Workflows - Functional API (feature:
functional): Write workflows as async functions with automatic checkpointing - Typed State Reducers: ReducedValue, UntrackedValue, MessagesValue containers
- State Schema Validation: Type-level validation at workflow boundaries
- Proc Macros:
#[entrypoint]and#[task](fromadk-rust-macros) generate the workflow agent and the recorded task wrappers
Architecture
┌─────────────────────────────────────────┐
│ Agent Trait │
│ (name, description, run, sub_agents) │
└────────────────┬────────────────────────┘
│
┌───────────────────────┼───────────────────────┐
│ │ │
┌──────▼──────┐ ┌─────────▼─────────┐ ┌─────────▼─────────┐
│ LlmAgent │ │ GraphAgent │ │ RealtimeAgent │
│ (text-based)│ │ (graph workflow) │ │ (voice-based) │
└─────────────┘ └───────────────────┘ └───────────────────┘
Quick Start
Add to your Cargo.toml:
[]
= "3.0.0"
= "3.0.0"
= "3.0.0"
= "3.0.0"
= "1"
= "1"
= { = "1", = ["macros", "rt-multi-thread"] }
Basic Graph with AgentNode
The program needs a GOOGLE_API_KEY.
use LlmAgentBuilder;
use ;
use ;
use GeminiModel;
use ;
use HashMap;
use Arc;
/// Writes the text of the agent's final response to one state channel.
+ Send + Sync
async
Conditional Routing with LLM Classification
use ;
use ;
use ;
use HashMap;
use Arc;
/// `classifier` is an `LlmAgent` instructed to reply with one word:
/// positive, negative, or neutral.
Human-in-the-Loop with Risk Assessment
use Agent;
use ;
use ;
use HashMap;
use Arc;
async
GraphError::Interrupted carries an InterruptedExecution: its interrupt is the first pause
and interrupts holds every pause of the step, in node-name order. A dynamic pause carries its
id (Interrupt::id), which answers it as a resume key too; see
Interrupt Ids, Typed Answers and Strict Resume.
ReAct Agent with Tools
use ;
use ;
use ;
use HashMap;
use Arc;
/// `reasoner` is an `LlmAgent` (named "reasoner") with tools.
An LlmAgent already runs its own tool loop inside one node; a graph cycle like this one fits
when each reasoning step must be checkpointed or routed.
Node Types
AgentNode
Wraps any ADK Agent (typically LlmAgent) as a graph node named after the agent:
use ;
use AgentNode;
use ;
use HashMap;
use Arc;
Without mappers, the input is the last messages entry or the input channel, and the output is
one messages entry per response the agent completes, with its whole text whether the model
streamed it or not. A custom output mapper receives every event the agent yielded, streamed
partial chunks included; the non-partial events carry each response's complete content.
FunctionNode
Simple async functions for data processing:
use ;
use ;
SubgraphNode
Run a compiled graph as a node. The inner graph keeps its own channels, edges and interrupt gates, and exchanges named channels with its parent.
use ;
use Arc;
/// `inner` reads `text` and writes `length`.
Channels both schemas declare under one name pass through; isolated() requires
every exchange to be named. Each activation runs on its own thread,
<parent thread>/<node name>@<parent step>, so a later pass of a loop or a later turn
runs the subgraph again. A pause inside pauses the parent and resumes without
re-running finished work. A mapping naming a channel neither side declares fails at
compile(), as does a subgraph with an interrupt gate but no checkpointer — that
one would re-enter at its first node and pay for its work twice. A failure of an agent
inside names its path, such as drafting.writer.
A node inside can hand control to its parent:
use NodeOutput;
use json;
Routing From Inside a Node
A conditional edge fixes its targets when the graph is built. A goto does not, and may name any node in the graph:
use Agent;
use ;
use ;
use HashMap;
use Arc;
// A plain node.
// An LLM-backed node, routing on what it answered.
A goto replaces that node's declared edges. Naming END stops the branch, and
an unknown name fails the run with GraphError::UnknownRouteTarget.
Reliability and Limits
Each of these is off by default.
use ToolEffect;
use ;
use json;
| Default | Value |
|---|---|
| Super-steps per run | 100 (CompiledGraph::with_recursion_limit or GraphAgentBuilder::recursion_limit; ExecutionConfig::with_recursion_limit overrides it for one run) |
| Retry when no policy is attached | one attempt |
RetryPolicy::default() |
ten attempts; 1s initial delay doubling to a 60s cap, with full jitter — the nine sleeps average about 151s in total |
| Concurrency | the whole frontier |
| Checkpoints kept | every one, until a retention policy is set; a policy keeps the newest, open pauses and effect-log entries |
| Durability | Durability::Sync: each super-step's checkpoint is written before the next starts |
An interrupt is never retried and never reaches an error handler: a pause is not a failure.
Invoking a Node Directly
When the number of sub-tasks comes from state rather than the graph's shape:
use ;
use ;
async
The target needs no edge. Each completed child is recorded under
<parent>@<step>/<child>@<run_id> while the parent's step runs, so a parent that is
retried or resumed is served the recorded answer instead of executing the child again —
which matters when the child costs a model call or charges a card. The record is
dropped once the step completes, so a parent re-entered by a loop runs its children
again. A child with a policy set by with_node_retry is retried under it.
A Graph as a Tool
use ;
use Llm;
use ;
use Arc;
The parameter schema is derived from the graph's channels, so the tool description
and the graph cannot drift apart. It reports itself long-running, so a graph that
pauses travels the existing tool-confirmation path. Each call runs on its own
checkpoint thread, tool_call_thread_id(app, user, session, function_call_id), so a
second call runs the graph again. A graph failure reaches the agent as the graph's
AdkError.
State Management
Channels and Reducers
use ;
Checkpointing
The SQLite checkpointer needs the sqlite feature.
use ;
async
The shared-database checkpointers are PostgresCheckpointer, RedisCheckpointer,
MongoCheckpointer, Neo4jCheckpointer, and FirestoreCheckpointer, each behind the feature of
the same name. Every checkpoint carries a per-thread version: save refuses a version that is
not greater than every stored version of the thread with GraphError::CheckpointConflict
(graph.checkpoint.conflict), and load and list order by version.
Durable Resume
When a checkpointer is configured, the executor automatically checks for existing checkpoints before starting. If a checkpoint exists for the thread ID, execution resumes from where it left off — skipping already-completed nodes:
use *;
use Arc;
async
When streaming, a StreamEvent::Resumed event is emitted to indicate execution was restored from a checkpoint.
A checkpoint records the frontier still to run and the arrivals a fan-in node is waiting on. A dynamic or tool-confirmation pause saves the successors of every node that completed in the step plus the paused node, so a sibling's downstream work still runs after the resume.
Execution Guarantees
Node execution is at-least-once. A super-step runs its nodes and applies their updates before it saves its checkpoint:
| Event | Effect on resume |
|---|---|
| Crash while a super-step is running | Every node of that step runs again, including nodes that had finished |
| A node of a super-step fails | No queued node of the step starts; finished nodes are kept as pending writes; a resume runs only the nodes that did not finish |
| Pause or completed step | No node of a checkpointed step runs again |
Make a node with external side effects idempotent, for example with an idempotency key derived from the thread id and step.
GraphAgent Turns
GraphAgent::run keys its thread by session_thread_id(app_name, user_id, session_id) — the three parts joined with :, with % and : percent-encoded inside each —
so two users who choose the same session id never share checkpoints, and
each call is a turn. A
paused thread resumes; a finished thread runs again from its entry nodes, starting
from the previous turn's final state with the new input merged on top. The recursion
limit applies per turn. invoke keeps the direct-graph behaviour, where a finished
thread returns its final state. A turn that resumes a paused node answers it: the node
reads the turn's text with ctx.resume_value(), or what
GraphAgentBuilder::resume_mapper returns.
A turn yields the agent nodes' events before the output mapper's, and every event it builds
carries the turn's invocation id. A step with several pauses yields one event per pause; read
each with GraphInterruptPayload::from_event.
Run Records, Forks and Governed Nodes
| Capability | API | Where it lives |
|---|---|---|
| Graph shape | CompiledGraph::shape() → GraphShape { nodes, edges, entry } |
Computed from the compiled graph |
| Run and step records | Checkpoint::run_record(), step_records(), lineage() |
Checkpoint metadata adk.graph.run, adk.graph.steps, adk.graph.lineage |
| Fork with edits | TimeTravelHandle::fork(ForkSpec), time_travel::fork_thread |
A new thread whose lineage names its root, parent and parent checkpoint |
| Governed nodes | CompiledGraph::with_governed_node, GraphAgentBuilder::governed_node, Node::call_args, Node::run_call, Node::will_act, CompiledGraph::governed_shapes, HttpActionPolicy::credential_key |
The approval store, the action ledger and the effect log {root}:effects |
A pause checkpoint has the same step number as the completed checkpoint before it, so
checkpoints are addressed by id. A governed node's failures are NodeExecutionFailed
messages that start with a stable code (graph.not_run, graph.refused, …), read back
with GovernedError::code_of. See
Graph Checkpointing
and Graph Agents.
Examples
Standalone examples, in this repository unless the row names adk-playground:
| Example | Shows |
|---|---|
graph_runtime |
Dispatch, streaming, retries, pauses, and cancellation under a Runner, over memory, SQLite, and Redis checkpointers |
graph_correctness |
Joins after conditional branches and loops, agent errors, subgraphs, run_node children, and graph tools |
coding_graph in adk-playground |
Implement, parallel reviewers, synthesize, and a revise loop |
graph_goto_routing in adk-playground |
An LlmAgent classifier that names the next node |
graph_subgraph_claims in adk-playground |
A claim pipeline built from nested graphs |
graph_resilient_research in adk-playground |
A graph exposed to an LlmAgent as a tool |
competitive_graph_resume |
Resume from a checkpoint |
functional_workflow in adk-playground |
The Functional API, with no API key |
Comparison with LangGraph
| Feature | LangGraph | adk-graph |
|---|---|---|
| State Management | TypedDict + Reducers | StateSchema + Reducers |
| Execution Model | Pregel super-steps | Pregel super-steps |
| Checkpointing | Memory, SQLite, Postgres, Redis, MongoDB | Memory, SQLite, PostgreSQL, Redis, MongoDB, Neo4j, Firestore |
| Human-in-Loop | interrupt_before/after | interrupt_before/after + dynamic |
| Streaming | 5 modes | 5 modes |
| Cycles | Native support | Native support |
| Type Safety | Python typing | Rust type system |
| LLM Integration | LangChain | AgentNode + ADK agents |
Feature Flags
No feature is enabled by default.
| Flag | Description |
|---|---|
sqlite |
Enable SQLite checkpointer |
postgres, redis, mongodb, neo4j, firestore |
Checkpointers for shared databases |
conformance |
CheckpointerHarness and checkpointer_conformance_tests! for testing a backend |
functional |
Functional API: TaskContext, typed reducers, schema validation, cancellation |
node-cache |
Per-node result caching; redis-cache adds a Redis store |
delta-checkpoint |
Store the difference between super-steps instead of full state |
time-travel |
Step, fork, and state history |
action |
ActionNodeExecutor for adk-action node configurations |
action-http, action-rss, action-trigger |
HTTP and notification nodes, RSS feeds, cron/webhook trigger runtime |
action-db, action-email |
Placeholders only — see Action Nodes |
action-full |
action, action-trigger, action-http, action-db, action-email, action-rss |
yaml |
definition: workflows from YAML or JSON files, their validation and JSON Schema (implies action) |
full |
sqlite, action-full and yaml |
Through the adk-rust umbrella, its action feature enables this crate's action, action-db,
and action-email, and its action-http feature enables action-http and action-rss.
adk-rust has no action-db, action-email, action-rss, or action-code feature.
Action Nodes
ActionNodeExecutor runs an adk-action configuration as a graph node.
| Node type | Status |
|---|---|
| Trigger, Set, Transform, Switch, Loop, Merge, Wait, File | Implemented |
Code with language: rust |
Implemented (evaluates JSON or interpolates text) |
HTTP, Notification (action-http), RSS (action-rss) |
Implemented |
| Database, Email | Not implemented in any feature configuration; rejected when the graph compiles |
Code with language: javascript or typescript |
Not implemented; rejected when the graph compiles |
Paths and URLs come from workflow state, so both are confined:
- File nodes stay inside the allowed roots — the working directory unless
with_file_rootsnames others. A..component, or a path that resolves outside every root through a symbolic link, fails the node. - HTTP, notification, and RSS nodes accept only the schemes, hosts, and
redirect count an
HttpActionPolicypermits (with_http_policy). The default allowshttpsandhttpto any public host and up to 5 redirects, each re-checked; a host that is, or resolves to, a loopback, private, link-local or metadata address is refused unlessallow_private_networksis set. Logs omit the query string, and the notification webhook URL is logged by host only.
SQLx compatibility
ADK-Rust 3.0 SQL backends use SQLx 0.9. SQLx types appear in this crate's public
API — SqliteCheckpointer::from_pool and PostgresCheckpointer::from_pool — so an application that passes in its own pool must depend on
SQLx 0.9 too. Applications that let ADK open its own connections need no SQLx
dependency. The SQLx 0.9 migration guide
lists who is affected and what changed, and its
TLS behaviour section
covers PostgreSQL certificate verification.
Functional API
The Functional API (feature: functional) provides a higher-level programming model that lets you write agent workflows as normal async Rust functions with automatic checkpointing, typed state reducers, and interrupt/resume support.
Quick Start
[]
= { = "3.0.0", = ["functional"] }
= "3.0.0"
= "1"
= { = "1", = ["macros", "rt-multi-thread"] }
#[task] generates a __task_<name> wrapper that records the call in the run's
ExecutionLog; call the wrapper so a resumed run replays the recorded result.
#[entrypoint] generates <Name>Agent with new(checkpointer) and invoke(state, config).
use ;
use ;
use ;
use Arc;
async
async
async
async
The typed containers work on their own:
use ;
Features
| Type | Purpose |
|---|---|
TaskContext |
Runtime context for tasks (state, checkpointing, streaming, interrupts) |
ReducedValue<T> |
Append-only accumulator persisted across checkpoints |
UntrackedValue<T> |
Transient data excluded from checkpoints |
MessagesValue |
Chat messages with ID-based deduplication |
StateSchemaValidator |
Type validation for state and task output |
ExecutionLog |
Task completion tracking for resume-skip, and recorded interrupt answers |
TypedReducer |
Custom merge strategies (ReplaceReducer, AppendReducer, MergeReducer) |
Resume, Interrupts, and Cancellation
- Resume from a checkpoint — the generated
invokeloads the checkpoint thatExecutionConfig::with_resume_from(checkpoint_id)names, and returnsGraphError::CheckpointErrorwithout running a task when the thread has no checkpoint with that id. To continue where a thread left off, pass the idCheckpointer::load(thread_id)returns. - Interrupts —
TaskContext::interruptsuspends the run withGraphError::Suspended, which names the interrupt'scontinuation_key. Supply the answer withExecutionConfig::with_resume_value(continuation_key, value)and invoke again. The first answer is recorded in the execution log and checkpointed, so a run resumed from any later checkpoint replays it. - Cancellation —
ExecutionConfig::with_cancellation_token(token); cancelling the token stops the run, which returnsGraphError::Cancelledand starts no further task.
A #[task] retry policy never retries a suspension or a cancellation.
Task Identity
#[task] records each call of a task under its own key,
{task}#{ordinal}:{arg_hash} (task_call_id): the ordinal counts the task's calls
within the run, and the hash covers the arguments that implement Serialize. A
task called in a loop records one result per call, and a resumed run replays each
call's own result. A call whose arguments differ from the recorded call at the same
position runs again.
Tasks are at-least-once: a crash after a task's body finishes but before its completion is checkpointed runs it again on resume.
License
Apache-2.0
Part of ADK-Rust
This crate is part of the ADK-Rust framework for building AI agents in Rust.