Skip to main content

regula_core/
lib.rs

1//! REGULA Core - Core abstractions for the REGULA agentic orchestration framework.
2//!
3//! This crate provides the fundamental building blocks for constructing
4//! LangGraph-style agent graphs in Rust:
5//!
6//! - **State**: The `GraphState` trait and channel system for managing graph state.
7//! - **Nodes**: The `Node` trait for defining graph nodes (agents, tools, etc.).
8//! - **Edges**: Normal and conditional edges for graph control flow.
9//! - **Graph**: The `StateGraph` builder and `CompiledStateGraph` for execution.
10//!
11//! # Example
12//!
13//! ```ignore
14//! use regula_core::prelude::*;
15//!
16//! #[derive(Clone, Serialize, Deserialize)]
17//! struct MyState {
18//!     messages: Vec<String>,
19//!     done: bool,
20//! }
21//!
22//! impl GraphState for MyState {
23//!     fn channels() -> HashMap<String, ChannelSpec> {
24//!         let mut channels = HashMap::new();
25//!         channels.insert("messages".to_string(), ChannelSpec::LastValue);
26//!         channels.insert("done".to_string(), ChannelSpec::LastValue);
27//!         channels
28//!     }
29//! }
30//!
31//! let graph = StateGraph::<MyState>::new()
32//!     .add_node("agent", node_fn(|state, config| async {
33//!         Ok(NodeOutput::update(json!({"messages": ["Hello!"]})))
34//!     }))
35//!     .add_edge(start(), "agent")
36//!     .add_edge("agent", end())
37//!     .compile(Default::default())?;
38//! ```
39
40// Re-export commonly used external crates
41pub use async_trait::async_trait;
42pub use serde;
43pub use serde_json;
44
45// Module declarations
46pub mod channel;
47pub mod config;
48pub mod constants;
49pub mod edge;
50pub mod error;
51pub mod graph;
52pub mod node;
53pub mod state;
54
55// Re-exports for convenience
56pub use channel::{Channel, ChannelSpec};
57pub use config::{ConfigSnapshot, RunnableConfig};
58pub use constants::{end, start, NodeId, END_NODE, START_NODE};
59pub use edge::{async_router_fn, router_fn, Edge, EdgeRouter, RouteOutput};
60pub use error::{RegulaError, Result};
61pub use graph::{CompileConfig, CompiledStateGraph, StateGraph};
62pub use node::{node_fn, node_fn_named, BoxedNode, Command, CommandGoto, Node, NodeOutput, RetryPolicy};
63pub use state::{DynState, GraphState};
64
65/// Prelude module for convenient imports.
66///
67/// Import with `use regula_core::prelude::*;` to get all commonly used types.
68pub mod prelude {
69    pub use crate::channel::{Channel, ChannelSpec};
70    pub use crate::config::RunnableConfig;
71    pub use crate::constants::{end, start, NodeId};
72    pub use crate::edge::{async_router_fn, router_fn, Edge, EdgeRouter, RouteOutput};
73    pub use crate::error::{RegulaError, Result};
74    pub use crate::graph::{CompileConfig, CompiledStateGraph, StateGraph};
75    pub use crate::node::{node_fn, Command, CommandGoto, Node, NodeOutput};
76    pub use crate::state::GraphState;
77    pub use crate::partial_state;
78
79    // Re-export useful external types
80    pub use async_trait::async_trait;
81    pub use serde::{Deserialize, Serialize};
82    pub use serde_json::json;
83}
84
85#[cfg(test)]
86mod tests {
87    use super::prelude::*;
88    use std::collections::HashMap;
89
90    #[derive(Clone, Debug, Serialize, Deserialize)]
91    struct TestState {
92        messages: Vec<String>,
93        counter: i32,
94    }
95
96    impl GraphState for TestState {
97        fn channels() -> HashMap<String, ChannelSpec> {
98            let mut channels = HashMap::new();
99            channels.insert("messages".to_string(), ChannelSpec::LastValue);
100            channels.insert("counter".to_string(), ChannelSpec::LastValue);
101            channels
102        }
103    }
104
105    #[test]
106    fn test_integration_build_graph() {
107        let agent_node = node_fn(|state: &TestState, _config: &RunnableConfig| {
108            let counter = state.counter;
109            async move {
110                Ok(NodeOutput::update(serde_json::json!({
111                    "counter": counter + 1
112                })))
113            }
114        });
115
116        let result = StateGraph::<TestState>::new()
117            .add_node("agent", agent_node)
118            .add_edge(start(), "agent")
119            .add_edge("agent", end())
120            .compile(Default::default());
121
122        assert!(result.is_ok());
123        let graph = result.unwrap();
124        assert_eq!(graph.node_names().count(), 1);
125    }
126
127    #[test]
128    fn test_integration_conditional_graph() {
129        let agent_node = node_fn(|_state: &TestState, _config: &RunnableConfig| {
130            async move {
131                Ok(NodeOutput::update(serde_json::json!({
132                    "counter": 1
133                })))
134            }
135        });
136
137        let tools_node = node_fn(|_state: &TestState, _config: &RunnableConfig| {
138            async move {
139                Ok(NodeOutput::update(serde_json::json!({
140                    "counter": 2
141                })))
142            }
143        });
144
145        let router = router_fn(|state: &TestState| {
146            if state.counter >= 5 {
147                RouteOutput::end()
148            } else {
149                RouteOutput::one("tools")
150            }
151        });
152
153        let result = StateGraph::<TestState>::new()
154            .add_node("agent", agent_node)
155            .add_node("tools", tools_node)
156            .add_edge(start(), "agent")
157            .add_conditional_edges("agent", router)
158            .add_edge("tools", "agent")
159            .compile(Default::default());
160
161        assert!(result.is_ok());
162    }
163
164    #[test]
165    fn test_partial_state_macro() {
166        let update = partial_state! {
167            messages: vec!["hello"],
168            counter: 42,
169        };
170
171        assert_eq!(update["messages"][0], "hello");
172        assert_eq!(update["counter"], 42);
173    }
174}