langgraph4rust 0.2.3

A powerful Rust implementation of a stateful workflow engine inspired by Python's LangGraph
Documentation
# langgraph4rust ๐Ÿฆ€

[![CI](https://github.com/langGraph4rust/langgraph4rust/actions/workflows/ci.yml/badge.svg)](https://github.com/langGraph4rust/langgraph4rust/actions/workflows/ci.yml)
[![Crates.io](https://img.shields.io/crates/v/langgraph4rust.svg)](https://crates.io/crates/langgraph4rust)
[![Docs.rs](https://docs.rs/langgraph4rust/badge.svg)](https://docs.rs/langgraph4rust)
[![Downloads](https://img.shields.io/crates/d/langgraph4rust.svg)](https://crates.io/crates/langgraph4rust)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
[![Rust](https://img.shields.io/badge/Rust-1.85%2B-orange.svg)](https://www.rust-lang.org/)

**English** | [็ฎ€ไฝ“ไธญๆ–‡]README.zh-CN.md | [Deutsch]README.de.md | [ๆ—ฅๆœฌ่ชž]README.ja.md

**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:

| Example | Description |
|---------|-------------|
| [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**