graph_flow/lib.rs
1//! # graph-flow
2//!
3//! A high-performance, type-safe framework for building multi-agent workflow systems in Rust.
4//!
5//! ## Features
6//!
7//! - **Type-Safe Workflows**: Compile-time guarantees for workflow correctness
8//! - **Flexible Execution**: Step-by-step, batch, or mixed execution modes
9//! - **Built-in Persistence**: PostgreSQL and in-memory storage backends with
10//! optimistic locking
11//! - **LLM Integration**: Optional integration with Rig for AI agent capabilities
12//! - **Human-in-the-Loop**: Natural workflow interruption and resumption
13//! - **Async/Await Native**: Built from the ground up for async Rust
14//!
15//! ## Quick Start
16//!
17//! ```rust
18//! use graph_flow::{Context, Task, TaskResult, NextAction, GraphBuilder, FlowRunner, InMemorySessionStorage, Session, SessionStorage};
19//! use async_trait::async_trait;
20//! use std::sync::Arc;
21//!
22//! // Define a task
23//! struct HelloTask;
24//!
25//! #[async_trait]
26//! impl Task for HelloTask {
27//! fn id(&self) -> &str {
28//! "hello_task"
29//! }
30//!
31//! async fn run(&self, context: Context) -> graph_flow::Result<TaskResult> {
32//! let name: String = context.get("name").unwrap_or("World".to_string());
33//! let greeting = format!("Hello, {}!", name);
34//!
35//! context.set("greeting", greeting.clone())?;
36//! Ok(TaskResult::new(Some(greeting), NextAction::Continue))
37//! }
38//! }
39//!
40//! # #[tokio::main]
41//! # async fn main() -> graph_flow::Result<()> {
42//! // Build the workflow
43//! let hello_task = Arc::new(HelloTask);
44//! let graph = Arc::new(
45//! GraphBuilder::new("greeting_workflow")
46//! .add_task(hello_task.clone())
47//! .build()?
48//! );
49//!
50//! // Set up session storage and runner
51//! let session_storage = Arc::new(InMemorySessionStorage::new());
52//! let flow_runner = FlowRunner::new(graph.clone(), session_storage.clone());
53//!
54//! // Create and execute session
55//! let session = Session::new_from_task("user_123".to_string(), hello_task.id());
56//! session.context.set("name", "Alice".to_string())?;
57//! session_storage.save(session).await?;
58//!
59//! let result = flow_runner.run("user_123").await?;
60//! println!("Response: {:?}", result.response);
61//! # Ok(())
62//! # }
63//! ```
64//!
65//! ## Core Concepts
66//!
67//! ### Tasks
68//!
69//! Tasks are the building blocks of your workflow. They implement the [`Task`] trait:
70//!
71//! ```rust
72//! use graph_flow::{Task, TaskResult, NextAction, Context};
73//! use async_trait::async_trait;
74//!
75//! struct MyTask;
76//!
77//! #[async_trait]
78//! impl Task for MyTask {
79//! fn id(&self) -> &str {
80//! "my_task"
81//! }
82//!
83//! async fn run(&self, context: Context) -> graph_flow::Result<TaskResult> {
84//! // Your task logic here
85//! Ok(TaskResult::new(Some("Done!".to_string()), NextAction::End))
86//! }
87//! }
88//! ```
89//!
90//! ### Context
91//!
92//! The [`Context`] provides thread-safe state management across your workflow.
93//! Its methods are synchronous, so they work both in async tasks and in
94//! edge-condition closures:
95//!
96//! ```rust
97//! # use graph_flow::Context;
98//! # fn main() -> graph_flow::Result<()> {
99//! let context = Context::new();
100//!
101//! // Store and retrieve data
102//! context.set("key", "value")?;
103//! let value: Option<String> = context.get("key");
104//!
105//! // Chat history management
106//! context.add_user_message("Hello!".to_string());
107//! context.add_assistant_message("Hi there!".to_string());
108//! # Ok(())
109//! # }
110//! ```
111//!
112//! ### Graph Building
113//!
114//! Use [`GraphBuilder`] to create workflows. [`GraphBuilder::build`] validates
115//! the graph (edge endpoints and the start task must exist) and returns an
116//! immutable [`Graph`]:
117//!
118//! ```rust
119//! # use graph_flow::{GraphBuilder, Task, TaskResult, NextAction, Context};
120//! # use async_trait::async_trait;
121//! # use std::sync::Arc;
122//! # struct Task1; struct Task2; struct Task3;
123//! # #[async_trait] impl Task for Task1 { fn id(&self) -> &str { "task1" } async fn run(&self, _: Context) -> graph_flow::Result<TaskResult> { Ok(TaskResult::new(None, NextAction::End)) } }
124//! # #[async_trait] impl Task for Task2 { fn id(&self) -> &str { "task2" } async fn run(&self, _: Context) -> graph_flow::Result<TaskResult> { Ok(TaskResult::new(None, NextAction::End)) } }
125//! # #[async_trait] impl Task for Task3 { fn id(&self) -> &str { "task3" } async fn run(&self, _: Context) -> graph_flow::Result<TaskResult> { Ok(TaskResult::new(None, NextAction::End)) } }
126//! # fn main() -> graph_flow::Result<()> {
127//! # let task1 = Arc::new(Task1); let task2 = Arc::new(Task2); let task3 = Arc::new(Task3);
128//! let graph = GraphBuilder::new("my_workflow")
129//! .add_task(task1.clone())
130//! .add_task(task2.clone())
131//! .add_task(task3.clone())
132//! .add_edge(task1.id(), task2.id())
133//! .add_conditional_edge(
134//! task2.id(),
135//! |ctx| ctx.get::<bool>("condition").unwrap_or(false),
136//! task3.id(), // if true
137//! task1.id(), // if false
138//! )
139//! .build()?;
140//! # Ok(())
141//! # }
142//! ```
143//!
144//! ### Execution
145//!
146//! Use [`FlowRunner`] for convenient session-based execution:
147//!
148//! ```rust,no_run
149//! # use graph_flow::{FlowRunner, InMemorySessionStorage, Session, Graph, SessionStorage};
150//! # use std::sync::Arc;
151//! # #[tokio::main]
152//! # async fn main() -> graph_flow::Result<()> {
153//! # let graph = Arc::new(Graph::new("test"));
154//! let storage = Arc::new(InMemorySessionStorage::new());
155//! let runner = FlowRunner::new(graph, storage.clone());
156//!
157//! // Create session
158//! let session = Session::new_from_task("session_id".to_string(), "start_task");
159//! storage.save(session).await?;
160//!
161//! // Execute workflow
162//! let result = runner.run("session_id").await?;
163//! # Ok(())
164//! # }
165//! ```
166//!
167//! ## Features
168//!
169//! - **Default**: Core workflow functionality
170//! - **`rig`**: Enables LLM integration via the Rig crate
171//!
172//! ## Storage Backends
173//!
174//! - [`InMemorySessionStorage`]: For development and testing
175//! - `PostgresSessionStorage`: PostgreSQL storage, available with the `postgres` feature
176
177pub mod context;
178pub mod error;
179pub mod graph;
180pub mod runner;
181pub mod storage;
182#[cfg(feature = "postgres")]
183pub mod storage_postgres;
184pub mod task;
185pub mod fanout;
186
187// Re-export commonly used types
188pub use context::{ChatHistory, Context, MessageRole, SerializableMessage};
189pub use error::{GraphError, Result};
190pub use graph::{ExecutionResult, ExecutionStatus, Graph, GraphBuilder};
191pub use runner::FlowRunner;
192pub use storage::{
193 GraphStorage, InMemoryGraphStorage, InMemorySessionStorage, Session, SessionStorage,
194};
195#[cfg(feature = "postgres")]
196pub use storage_postgres::PostgresSessionStorage;
197pub use task::{NextAction, Task, TaskResult};
198pub use fanout::FanOutTask;
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203 use async_trait::async_trait;
204 use std::sync::Arc;
205
206 struct TestTask {
207 id: String,
208 }
209
210 #[async_trait]
211 impl Task for TestTask {
212 fn id(&self) -> &str {
213 &self.id
214 }
215
216 async fn run(&self, context: Context) -> Result<TaskResult> {
217 let input: String = context.get("input").unwrap_or_default();
218 context.set("output", format!("Processed: {}", input))?;
219
220 Ok(TaskResult::new(
221 Some("Task completed".to_string()),
222 NextAction::End,
223 ))
224 }
225 }
226
227 #[tokio::test]
228 async fn test_simple_graph_execution() {
229 let task = Arc::new(TestTask {
230 id: "test_task".to_string(),
231 });
232
233 let graph = GraphBuilder::new("test_graph")
234 .add_task(task)
235 .build()
236 .unwrap();
237
238 let mut session = Session::new_from_task("s1".to_string(), "test_task");
239 session.context.set("input", "Hello, World!").unwrap();
240
241 let result = graph.execute_session(&mut session).await.unwrap();
242
243 assert!(result.response.is_some());
244 assert!(matches!(result.status, ExecutionStatus::Completed));
245
246 let output: String = session.context.get("output").unwrap();
247 assert_eq!(output, "Processed: Hello, World!");
248 }
249
250 #[tokio::test]
251 async fn test_build_rejects_dangling_edge() {
252 let task = Arc::new(TestTask {
253 id: "only_task".to_string(),
254 });
255
256 let result = GraphBuilder::new("bad_graph")
257 .add_task(task)
258 .add_edge("only_task", "missing_task")
259 .build();
260
261 assert!(matches!(result, Err(GraphError::InvalidEdge(_))));
262 }
263
264 #[tokio::test]
265 async fn test_build_rejects_unknown_start_task() {
266 let task = Arc::new(TestTask {
267 id: "only_task".to_string(),
268 });
269
270 let result = GraphBuilder::new("bad_graph")
271 .add_task(task)
272 .set_start_task("missing_task")
273 .build();
274
275 assert!(matches!(result, Err(GraphError::TaskNotFound(_))));
276 }
277
278 #[tokio::test]
279 async fn test_storage() {
280 let graph_storage = InMemoryGraphStorage::new();
281 let session_storage = InMemorySessionStorage::new();
282
283 let graph = Arc::new(Graph::new("test"));
284 graph_storage
285 .save("test".to_string(), graph.clone())
286 .await
287 .unwrap();
288
289 let retrieved = graph_storage.get("test").await.unwrap();
290 assert!(retrieved.is_some());
291
292 let session =
293 Session::new_from_task("session1".to_string(), "task1").with_graph_id("test");
294
295 session_storage.save(session).await.unwrap();
296 let retrieved_session = session_storage.get("session1").await.unwrap();
297 assert!(retrieved_session.is_some());
298 assert_eq!(retrieved_session.unwrap().graph_id, "test");
299 }
300}