Skip to main content

adk_graph/
lib.rs

1//! # adk-graph
2//!
3//! Graph-based workflow orchestration for ADK-Rust agents, inspired by LangGraph.
4//!
5//! ## Overview
6//!
7//! `adk-graph` builds stateful agent workflows as graphs of nodes and edges. A
8//! [`GraphAgent`] implements the ADK `Agent` trait, so a graph runs under a `Runner`
9//! and streams through it like any other agent.
10//!
11//! ## Features
12//!
13//! - **Graph-Based Workflows**: Define agent workflows as directed graphs
14//! - **Cyclic Support**: Native support for loops and iterative reasoning
15//! - **Conditional Routing**: Dynamic edge routing based on state, or a goto from inside a node
16//! - **Fan-out / fan-in**: Parallel branches in one super-step; a node with several
17//!   incoming edges waits for the predecessors that can still reach it
18//! - **State Management**: Typed state with reducers (overwrite, append, sum, custom)
19//! - **Checkpointing**: Persistent, versioned state after each step, with memory, SQLite,
20//!   PostgreSQL, Redis, MongoDB, Neo4j, and Firestore backends
21//! - **Human-in-the-Loop**: Interrupt before/after nodes, dynamic interrupts, and
22//!   [`NodeContext::resume_value`] for the answer to a pause
23//! - **Streaming**: Multiple stream modes (values, updates, messages, custom, debug)
24//! - **ADK Integration**: [`AgentNode`] runs any ADK agent as a node, and an agent's failure is
25//!   [`GraphError::AgentFailed`] with the agent's own `AdkError`
26//! - **YAML and JSON workflows** (`yaml` feature): the `definition` module reads a workflow
27//!   file, validates it with each issue's line and column, and builds it into a graph
28//! - **Functional API** (`functional` feature): Write workflows as async functions
29//!   with `#[entrypoint]`/`#[task]` macros, automatic checkpointing, typed state
30//!   reducers (ReducedValue, UntrackedValue, MessagesValue), state schema
31//!   validation, interrupt/resume, and loop iteration checkpoint keying
32//!
33//! ## Feature flags
34//!
35//! No feature is on by default; the in-memory checkpointer needs none.
36//!
37//! | Feature | Enables |
38//! |---------|---------|
39//! | `sqlite` | The SQLite checkpointer |
40//! | `postgres`, `redis`, `mongodb`, `neo4j`, `firestore` | Checkpointers for shared databases |
41//! | `conformance` | `CheckpointerHarness` and `checkpointer_conformance_tests!` for testing a backend |
42//! | `functional` | The functional API: `TaskContext`, typed reducers, schema validation, cancellation |
43//! | `node-cache` | Per-node result caching; `redis-cache` adds a Redis store |
44//! | `delta-checkpoint` | The difference between super-steps stored instead of the full state |
45//! | `time-travel` | Step, fork and state history |
46//! | `action` | `ActionNodeExecutor` for `adk-action` node configurations |
47//! | `action-http`, `action-rss`, `action-trigger` | HTTP and notification nodes, RSS feeds, the cron and webhook trigger runtime |
48//! | `action-db`, `action-email` | Placeholders: database and email nodes are rejected when the graph compiles |
49//! | `action-full` | `action`, `action-trigger`, `action-http`, `action-db`, `action-email` and `action-rss` |
50//! | `yaml` | The `definition` module: workflows from YAML or JSON files, their validation and JSON Schema; implies `action` |
51//! | `full` | `sqlite`, `action-full` and `yaml` |
52//!
53//! ## Quick Start
54//!
55//! ```rust
56//! use adk_graph::prelude::*;
57//!
58//! # #[tokio::main(flavor = "current_thread")]
59//! # async fn main() -> adk_graph::Result<()> {
60//! let agent = GraphAgent::builder("processor")
61//!     .description("Process data through multiple steps")
62//!     .channels(&["data", "result"])
63//!     .node_fn("fetch", |_ctx| async move {
64//!         Ok(NodeOutput::new().with_update("data", json!({"items": [1, 2, 3]})))
65//!     })
66//!     .node_fn("transform", |ctx| async move {
67//!         let data = ctx.get("data").cloned().unwrap_or_default();
68//!         Ok(NodeOutput::new().with_update("result", data))
69//!     })
70//!     .edge(START, "fetch")
71//!     .edge("fetch", "transform")
72//!     .edge("transform", END)
73//!     .build()?;
74//!
75//! // Execute
76//! let result = agent.invoke(State::new(), ExecutionConfig::new("thread_1")).await?;
77//! assert_eq!(result["result"], json!({"items": [1, 2, 3]}));
78//! # Ok(())
79//! # }
80//! ```
81//!
82//! ## Loops and Conditional Edges
83//!
84//! ```rust
85//! use adk_graph::prelude::*;
86//!
87//! # #[tokio::main(flavor = "current_thread")]
88//! # async fn main() -> adk_graph::Result<()> {
89//! let agent = GraphAgent::builder("counter")
90//!     .channels(&["count"])
91//!     .node_fn("step", |ctx| async move {
92//!         let count = ctx.get("count").and_then(Value::as_i64).unwrap_or(0);
93//!         Ok(NodeOutput::new().with_update("count", json!(count + 1)))
94//!     })
95//!     .edge(START, "step")
96//!     .conditional_edge(
97//!         "step",
98//!         |state: &State| {
99//!             let count = state.get("count").and_then(Value::as_i64).unwrap_or(0);
100//!             if count < 3 { "step".to_string() } else { END.to_string() }
101//!         },
102//!         [("step", "step"), (END, END)], // Cycle back until the count reaches 3
103//!     )
104//!     .build()?;
105//!
106//! let result = agent.invoke(State::new(), ExecutionConfig::new("thread_2")).await?;
107//! assert_eq!(result["count"], json!(3));
108//! # Ok(())
109//! # }
110//! ```
111
112#![allow(clippy::result_large_err)]
113
114pub mod agent;
115pub mod checkpoint;
116pub mod checkpointers;
117pub mod child;
118#[cfg(feature = "conformance")]
119pub mod conformance;
120pub mod decision;
121pub mod deferred;
122pub mod edge;
123pub mod error;
124pub mod executor;
125pub mod governed;
126pub mod graph;
127pub mod interrupt;
128pub mod node;
129pub mod record;
130pub mod retry;
131pub mod shape;
132pub mod state;
133pub mod stream;
134pub mod subgraph;
135pub mod timeout;
136pub mod tool;
137
138#[cfg(feature = "node-cache")]
139pub mod cache;
140
141#[cfg(feature = "delta-checkpoint")]
142pub mod delta;
143
144#[cfg(feature = "time-travel")]
145pub mod time_travel;
146
147#[cfg(feature = "action")]
148pub mod action;
149#[cfg(feature = "action")]
150pub mod workflow;
151
152#[cfg(feature = "yaml")]
153pub mod definition;
154
155#[cfg(feature = "functional")]
156pub mod functional;
157
158// Functional API re-exports for convenient access
159#[cfg(feature = "functional")]
160pub use functional::schema::{ExpectedType, StateSchemaValidator};
161#[cfg(feature = "functional")]
162pub use functional::{
163    AppendReducer, ExecutionLog, FunctionalError, MergeReducer, MessagesValue, ReducedValue,
164    ReplaceReducer, TaskContext, TypedReducer, UntrackedValue,
165};
166
167// Re-exports
168pub use agent::{GraphAgent, GraphAgentBuilder};
169pub use checkpoint::{Checkpointer, Durability, MemoryCheckpointer, RetentionPolicy};
170pub use decision::DecisionNode;
171pub use deferred::{DeferredNodeConfig, FanInTracker, MergeStrategy};
172pub use edge::{END, Edge, EdgeTarget, Router, START};
173pub use error::{GraphError, InterruptedExecution, Result};
174pub use executor::PregelExecutor;
175pub use governed::{EffectRecord, GovernedError, GovernedNode};
176pub use graph::{CompiledGraph, StateGraph};
177pub use interrupt::{GraphToolConfirmationPause, Interrupt, interrupt, interrupt_with_data};
178pub use node::{AgentNode, ExecutionConfig, FunctionNode, Node, NodeContext, NodeOutput};
179pub use record::{Lineage, NodeRecord, NodeStatus, RunRecord, StepKind, StepRecord};
180pub use shape::{EdgeShape, GovernedShape, GraphShape, NodeKind, NodeShape};
181pub use state::{
182    Channel, Checkpoint, PendingWrite, Reducer, State, StateSchema, StateSchemaBuilder,
183};
184pub use stream::{StreamEvent, StreamMode};
185pub use timeout::{OnTimeout, ProgressHandle, TimeoutPolicy, execute_with_timeout};
186
187#[cfg(feature = "sqlite")]
188pub use checkpoint::SqliteCheckpointer;
189#[cfg(feature = "firestore")]
190pub use checkpointers::firestore::FirestoreCheckpointer;
191#[cfg(feature = "mongodb")]
192pub use checkpointers::mongodb::MongoCheckpointer;
193#[cfg(feature = "neo4j")]
194pub use checkpointers::neo4j::Neo4jCheckpointer;
195#[cfg(feature = "postgres")]
196pub use checkpointers::postgres::PostgresCheckpointer;
197#[cfg(feature = "redis")]
198pub use checkpointers::redis::RedisCheckpointer;
199
200#[cfg(feature = "node-cache")]
201pub use cache::{CacheBackend, NodeCache, NodeCachePolicy, compute_cache_key};
202
203#[cfg(feature = "delta-checkpoint")]
204pub use delta::{
205    CheckpointType, DeltaCheckpointer, DeltaConfig, Diff, MapDelta, StringDelta, StringOp, VecDelta,
206};
207
208#[cfg(feature = "time-travel")]
209pub use time_travel::{ForkError, ForkSpec, StepInfo, TimeTravelHandle, fork_thread};
210
211/// Prelude module for convenient imports
212pub mod prelude {
213    pub use crate::agent::{GraphAgent, GraphAgentBuilder};
214    pub use crate::checkpoint::{Checkpointer, Durability, MemoryCheckpointer};
215    pub use crate::deferred::{DeferredNodeConfig, FanInTracker, MergeStrategy};
216    pub use crate::edge::{END, Edge, EdgeTarget, Router, START};
217    pub use crate::error::{GraphError, InterruptedExecution, Result};
218    pub use crate::graph::{CompiledGraph, StateGraph};
219    pub use crate::interrupt::{
220        GraphToolConfirmationPause, Interrupt, interrupt, interrupt_with_data,
221    };
222    pub use crate::node::{
223        AgentNode, ExecutionConfig, FunctionNode, Node, NodeContext, NodeOutput,
224    };
225    pub use crate::state::{Channel, Checkpoint, Reducer, State, StateSchema, StateSchemaBuilder};
226    pub use crate::stream::{StreamEvent, StreamMode};
227
228    #[cfg(feature = "sqlite")]
229    pub use crate::checkpoint::SqliteCheckpointer;
230
231    #[cfg(feature = "action")]
232    pub use crate::action::ActionNodeExecutor;
233
234    // Re-export commonly used serde_json
235    pub use serde_json::{Value, json};
236}