langgraph4rust 0.2.3

A powerful Rust implementation of a stateful workflow engine inspired by Python's LangGraph
Documentation

langgraph4rust ๐Ÿฆ€

CI Crates.io Docs.rs Downloads License: Apache 2.0 Rust

English | ็ฎ€ไฝ“ไธญๆ–‡ | Deutsch | ๆ—ฅๆœฌ่ชž

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:

[dependencies]
langgraph4rust = "0.2.0"

๐Ÿš€ Quick Start

Basic Example

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:

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.

#[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
// 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:

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:

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 Simple linear workflow - perfect starting point
conditional_routing Dynamic path selection based on state
parallel_execution Concurrent node execution
custom_state Implementing custom state backends
data_pipeline Multi-stage data processing pipeline
error_handling Robust error handling strategies

Run any example:

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

Key Methods

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

# 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

# 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 file for details.

๐Ÿ™ Acknowledgments

๐Ÿ“ž Support


Built with โค๏ธ using Rust's type system and async capabilities