adk_graph/functional/mod.rs
1//! # Functional API for Graph Workflows
2//!
3//! The Functional API provides a higher-level programming model for `adk-graph`
4//! that allows developers to write agent workflows as normal async Rust functions
5//! with automatic checkpointing, typed state reducers, and interrupt/resume support.
6//!
7//! ## Overview
8//!
9//! Rather than manually constructing nodes, edges, and routers, developers annotate
10//! functions with `#[entrypoint]` and `#[task]` macros and use standard Rust control
11//! flow (`if`, `for`, `match`, `loop`) to express workflow logic.
12//!
13//! This module is gated behind the `functional` feature flag.
14//!
15//! ## Features
16//!
17//! - **[`TaskContext`]**: Runtime context for tasks providing state, checkpointing, and streaming
18//! - **[`ReducedValue<T>`](ReducedValue)**: Append-only state container persisted across checkpoints
19//! - **[`UntrackedValue<T>`](UntrackedValue)**: Transient state container excluded from checkpoints
20//! - **[`MessagesValue`]**: Chat message container with ID-based deduplication
21//! - **[`TypedReducer`]**: Custom merge strategies for typed state values
22//! - **[`ExecutionLog`]**: Task completion tracking for resume-skip behavior
23//! - **[`StateSchemaValidator`]**: Schema validation for initial state and task output
24//!
25//! ## Quick Start
26//!
27//! `#[task]` generates a `__task_<name>` wrapper next to the function. Call the wrapper: it
28//! records the call in the run's execution log and checkpoints its result, so a resumed run
29//! returns the recorded result instead of running the task again. Calling the function
30//! itself runs it with neither. `#[entrypoint]` generates `<Name>Agent`, which runs the
31//! workflow against a checkpointer.
32//!
33//! ```rust
34//! use std::sync::Arc;
35//!
36//! use adk_graph::checkpoint::{Checkpointer, MemoryCheckpointer};
37//! use adk_graph::error::Result;
38//! use adk_graph::functional::TaskContext;
39//! use adk_graph::node::ExecutionConfig;
40//! use adk_graph::state::State;
41//! use adk_rust_macros::{entrypoint, task};
42//! use serde_json::{Value, json};
43//!
44//! #[task]
45//! async fn fetch_data(_ctx: &mut TaskContext) -> Result<Value> {
46//! Ok(json!("data result"))
47//! }
48//!
49//! #[task(retry(max_attempts = 3, backoff = "1s"))]
50//! async fn process(_ctx: &mut TaskContext, data: &str) -> Result<Value> {
51//! Ok(json!(format!("processed: {data}")))
52//! }
53//!
54//! #[entrypoint]
55//! async fn my_workflow(ctx: &mut TaskContext) -> Result<Value> {
56//! let data = __task_fetch_data(ctx).await?;
57//! let result = __task_process(ctx, data.as_str().unwrap_or_default()).await?;
58//! ctx.set("output", result);
59//! Ok(Value::Null)
60//! }
61//!
62//! # #[tokio::main]
63//! # async fn main() -> Result<()> {
64//! let checkpointer = Arc::new(MemoryCheckpointer::new());
65//! let agent = MyWorkflowAgent::new(checkpointer.clone());
66//! let state = agent.invoke(State::new(), ExecutionConfig::new("thread-1")).await?;
67//! assert_eq!(state["output"], json!("processed: data result"));
68//! // The run checkpointed the thread; a resume replays the recorded task results.
69//! assert!(checkpointer.load("thread-1").await?.is_some());
70//! # Ok(())
71//! # }
72//! ```
73//!
74//! ## Typed State Reducers
75//!
76//! ```rust,ignore
77//! use adk_graph::functional::{ReducedValue, UntrackedValue, MessagesValue, ChatMessage, MessageRole};
78//!
79//! // Append-only accumulator — persisted across checkpoints
80//! let mut results: ReducedValue<String> = ReducedValue::default();
81//! results.push("step 1 output".to_string());
82//! results.push("step 2 output".to_string());
83//! assert_eq!(results.len(), 2);
84//!
85//! // Transient value — excluded from checkpoints
86//! let mut temp: UntrackedValue<Vec<u8>> = UntrackedValue::default();
87//! temp.set(vec![1, 2, 3]);
88//!
89//! // Chat messages with deduplication
90//! let mut messages = MessagesValue::default();
91//! messages.push(ChatMessage {
92//! id: "msg-1".to_string(),
93//! role: MessageRole::User,
94//! content: "Hello".to_string(),
95//! metadata: Default::default(),
96//! });
97//! ```
98
99mod context;
100mod error;
101pub mod execution_log;
102pub mod messages;
103pub mod reducers;
104mod resume;
105pub mod schema;
106mod task_id;
107pub mod typed_reducer;
108
109pub use context::TaskContext;
110pub use error::FunctionalError;
111pub use execution_log::{ExecutionLog, TaskRecord, TaskStatus};
112pub use messages::{ChatMessage, MessageRole, MessagesValue};
113pub use reducers::{ReducedValue, UntrackedValue};
114pub use schema::{ExpectedType, StateSchemaValidator};
115/// Items the `#[entrypoint]` and `#[task]` expansions call; not public API.
116#[doc(hidden)]
117pub mod __private {
118 pub use super::resume::load_resume_point;
119 pub use super::task_id::__private::*;
120
121 /// Runs `workflow` until it finishes or `token` is cancelled.
122 ///
123 /// Called by the `#[entrypoint]` expansion, so the generated code needs no
124 /// `tokio` macros of its own.
125 pub async fn until_cancelled<T>(
126 token: &tokio_util::sync::CancellationToken,
127 workflow: impl std::future::Future<Output = crate::error::Result<T>>,
128 ) -> crate::error::Result<T> {
129 tokio::select! {
130 biased;
131 () = token.cancelled() => Err(crate::error::GraphError::Cancelled),
132 result = workflow => result,
133 }
134 }
135}
136pub use task_id::task_call_id;
137pub use typed_reducer::{AppendReducer, MergeReducer, ReplaceReducer, TypedReducer};