# langgraph4rust ๐ฆ
[](https://github.com/langGraph4rust/langgraph4rust/actions/workflows/ci.yml)
[](https://crates.io/crates/langgraph4rust)
[](https://docs.rs/langgraph4rust)
[](https://crates.io/crates/langgraph4rust)
[](LICENSE)
[](https://www.rust-lang.org/)
**A powerful Rust implementation of a stateful workflow engine inspired by Python's LangGraph library.**
`langgraph4rust` provides a flexible, type-safe, and async-first framework for building, executing, and managing complex workflow graphs with support for parallel execution and conditional routing.
## โจ Features
- **๐๏ธ Declarative Graph Building**: Define workflows using an intuitive builder pattern
- **โก Parallel Execution**: Multiple nodes can execute simultaneously when dependencies allow
- **๐ Conditional Routing**: Dynamic path selection based on runtime state conditions
- **๐ก Streaming Execution**: Real-time, push-based `StreamEvent` stream for observing workflow progress
- **๐พ State Management**: Built-in JSON-based state persistence with full type safety
- **๐ Extensible Architecture**: Custom node implementations via traits
- **โ
Comprehensive Validation**: Graph structure validation before execution prevents runtime errors
- **๐ฏ Async-First Design**: Built on Tokio for efficient asynchronous operations
## ๐ฆ Installation
Add this to your `Cargo.toml`:
```toml
[dependencies]
langgraph4rust = "0.2.0"
```
## ๐ Quick Start
### Basic Example
```rust
use langgraph4rust::*;
use std::collections::HashSet;
use std::sync::Arc;
use async_trait::async_trait;
// Define a custom node
#[derive(Clone)]
struct GreetingNode;
#[async_trait]
impl AgentNode<DefaultMemoryState> for GreetingNode {
async fn apply(&self, state: Arc<DefaultMemoryState>) -> Result<(), LangGraphError> {
let message = "Hello from langgraph4rust! ๐";
println!("{}", message);
state.set("greeting", message).await?;
Ok(())
}
}
#[tokio::main]
async fn main() -> Result<(), LangGraphError> {
// Create graph builder
let mut builder = StateGraphBuilder::new();
// Add nodes to the graph
builder.add_node("greet", Box::new(GreetingNode));
// Define edges (workflow connections)
builder.add_edge(START_NODE, HashSet::from(["greet".to_string()]));
builder.add_edge("greet", HashSet::from([END_NODE.to_string()]));
// Compile and execute
let graph = builder.compile()?;
let state = Arc::new(DefaultMemoryState::new());
graph.invoke(state).await?;
Ok(())
}
```
Run this example:
```bash
cargo run --example hello_world
```
## ๐ฏ Core Concepts
### Nodes ๐ท
Nodes are the fundamental building blocks of your workflow. Each node implements the [`AgentNode`] trait and contains logic to process and modify the shared state.
```rust
#[derive(Clone)]
struct MyNode;
#[async_trait]
impl AgentNode<DefaultMemoryState> for MyNode {
async fn apply(&self, state: Arc<DefaultMemoryState>) -> Result<(), LangGraphError> {
// Your node logic here
state.set("result", "processed").await?;
Ok(())
}
}
```
### Edges โก๏ธ
Edges define the control flow between nodes:
- **Static edges**: Always connect to fixed target nodes
- **Conditional edges**: Dynamically choose targets based on current state
```rust
// Static edge
builder.add_edge("node_a", HashSet::from(["node_b".to_string()]));
// Conditional edge: routers are *synchronous* closures that inspect the state
// and return the name of the next node. Multiple routers may be supplied;
// their returned targets are unioned into the next step.
builder.add_conditional_edge(
"decision_node",
vec![Box::new(|_state: &DefaultMemoryState| {
// Return the chosen target node name based on the state.
"node_x".to_string()
})],
);
```
### State ๐พ
The state is shared across all nodes and persists throughout execution:
```rust
let state = Arc::new(DefaultMemoryState::new());
// Set values
state.set("key", "value").await?;
// Get typed values
let value: String = state.get("key").await?.unwrap();
```
### Streaming Execution ๐ก
In addition to `invoke()`, a compiled graph can be executed as a **push-based
event stream**. This is ideal for progress reporting, logging, and live UIs:
```rust
use langgraph4rust::*;
use std::collections::HashSet;
use std::sync::Arc;
use async_trait::async_trait;
#[derive(Clone)]
struct WorkNode;
#[async_trait]
impl AgentNode<DefaultMemoryState> for WorkNode {
async fn apply(&self, state: Arc<DefaultMemoryState>) -> Result<(), LangGraphError> {
state.set("done", true).await?;
Ok(())
}
}
#[tokio::main]
async fn main() -> Result<(), LangGraphError> {
let mut builder = StateGraphBuilder::new();
builder.add_node("work", Box::new(WorkNode));
builder.add_edge(START_NODE, HashSet::from(["work".to_string()]));
builder.add_edge("work", HashSet::from([END_NODE.to_string()]));
let graph = Arc::new(builder.compile()?);
let state = Arc::new(DefaultMemoryState::new());
// `stream` consumes the Arc<StateGraph> and yields `StreamEvent`s.
let mut events = graph.stream(state);
while let Some(event) = events.next().await {
match event {
StreamEvent::WorkflowStarted => println!("โถ workflow started"),
StreamEvent::NodeFinished { name, elapsed, .. } => {
println!("โ node '{name}' finished in {elapsed:?}")
}
StreamEvent::WorkflowFinished { total_steps, elapsed, .. } => {
println!("โ done: {total_steps} steps in {elapsed:?}")
}
StreamEvent::WorkflowError { error, .. } => eprintln!("โ failed: {error}"),
_ => {}
}
}
Ok(())
}
```
The stream always terminates with either `WorkflowFinished` (success) or
`WorkflowError` (failure) as its final event โ errors are delivered *as events*
rather than via the return value.
## ๐ Examples
Explore the `examples/` directory for complete working examples:
| [hello_world](examples/hello_world.rs) | Simple linear workflow - perfect starting point |
| [conditional_routing](examples/conditional_routing.rs) | Dynamic path selection based on state |
| [parallel_execution](examples/parallel_execution.rs) | Concurrent node execution |
| [custom_state](examples/custom_state.rs) | Implementing custom state backends |
| [data_pipeline](examples/data_pipeline.rs) | Multi-stage data processing pipeline |
| [error_handling](examples/error_handling.rs) | Robust error handling strategies |
Run any example:
```bash
cargo run --example <example_name>
```
## ๐๏ธ Architecture
```
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ StateGraphBuilder โ
โ (Declarative graph construction API) โ
โโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ compile()
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ StateGraph โ
โ (Validated, executable workflow) โ
โ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โ
โ โ Node A โโโโถโ Node B โโโโถโ Node C โ โ
โ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โ
โ โฒ โ โ
โ โโโโโโโโโโโ(state)โโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ invoke() / stream()
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ DefaultMemoryState โ
โ (JSON-based persistent state storage) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
```
## ๐ง API Reference
### Core Types
- **[`StateGraphBuilder`](src/core/state_graph_builder.rs)**: Builder for constructing workflow graphs
- **[`StateGraph`](src/core/state_graph.rs)**: Compiled, executable graph instance
- **[`AgentNode`](src/core/agent_node.rs)**: Trait for implementing custom nodes
- **[`AgentState`](src/core/agent_state.rs)**: Trait for state management backends
- **[`DefaultMemoryState`](src/core/agent_state.rs)**: Built-in JSON-based state implementation
- **[`LangGraphError`](src/core/error.rs)**: Error type for the library
- **[`StreamEvent`](src/core/state_graph_stream.rs)**: Events emitted by the streaming API
### Key Methods
```rust
// Building graphs
StateGraphBuilder::new() // Create new builder
builder.add_node(name, node) // Add a node
builder.add_edge(from, to) // Add static edge
builder.add_conditional_edge(from, routers) // Add conditional edge (routers: Vec<Box<dyn Fn(&S) -> String>>)
builder.compile() // Validate & build graph
// Executing workflows
graph.invoke(initial_state) // Run the workflow to completion
graph.stream(initial_state) // Run with a push-based StreamEvent stream
// Managing state
state.set(key, value).await // Store value
state.get::<T>(key).await? // Retrieve typed value
```
## ๐งช Testing
Run the test suite:
```bash
# Unit tests
cargo test
# Run specific example tests
cargo test --example hello_world
# Integration tests (if available)
cargo test --test integration_test
```
## ๐ค Contributing
Contributions are welcome! Please feel free to submit Pull Requests.
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
### Development Setup
```bash
# Clone the repository
git clone https://github.com/langGraph4rust/langgraph4rust.git
cd langgraph4rust
# Build the project
cargo build
# Run examples
cargo run --example hello_world
# Run tests
cargo test
```
## ๐ Requirements
- **Rust**: 2024 edition or later
- **Tokio**: Async runtime (included as dependency)
- **Platform**: macOS, Linux, Windows (tested)
## ๐ License
This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.
## ๐ Acknowledgments
- Inspired by [LangChain/LangGraph](https://github.com/langchain-ai/langgraph) Python library
- Built with [Rust](https://www.rust-lang.org/) ecosystem tools
- Async runtime powered by [Tokio](https://tokio.rs/)
## ๐ Support
- ๐ Check the [examples](examples/) for usage patterns
- ๐ Report issues via [GitHub Issues](https://github.com/langGraph4rust/langgraph4rust/issues)
- ๐ฌ Discussions welcome in [GitHub Discussions](https://github.com/langGraph4rust/langgraph4rust/discussions)
---
**Built with โค๏ธ using Rust's type system and async capabilities**