pub struct RuleEngine { /* private fields */ }Expand description
Advanced rule engine powered by rust-rule-engine
Implementations§
Source§impl RuleEngine
impl RuleEngine
Sourcepub fn new() -> Self
pub fn new() -> Self
Create a new rule engine with default knowledge base
Examples found in repository?
examples/grl_rules.rs (line 56)
5fn main() -> anyhow::Result<()> {
6 println!("=== Rust Logic Graph - GRL Rules Example ===\n");
7
8 // Example 1: Simple GRL Rule
9 println!("Example 1: Simple Age Verification");
10 println!("-----------------------------------");
11
12 let mut context1 = HashMap::new();
13 context1.insert("age".to_string(), json!(25));
14 context1.insert("verified".to_string(), json!(false));
15
16 let grl1 = r#"
17rule "AgeVerification" {
18 when
19 age >= 18
20 then
21 verified = true;
22}
23"#;
24
25 let rule1 = GrlRule::new("age_verify", grl1);
26 match rule1.evaluate(&context1) {
27 Ok(result) => println!("✓ Rule executed: {:?}", result),
28 Err(e) => println!("✗ Rule failed: {}", e),
29 }
30
31 // Example 2: Complex Business Rules
32 println!("\nExample 2: E-commerce Discount Rules");
33 println!("-------------------------------------");
34
35 let mut context2 = HashMap::new();
36 context2.insert("cart_total".to_string(), json!(150.0));
37 context2.insert("is_member".to_string(), json!(true));
38 context2.insert("discount".to_string(), json!(0.0));
39
40 let grl2 = r#"
41rule "MemberDiscount" salience 10 {
42 when
43 is_member == true && cart_total >= 100.0
44 then
45 discount = 0.15;
46}
47
48rule "RegularDiscount" salience 5 {
49 when
50 cart_total >= 100.0 && discount == 0.0
51 then
52 discount = 0.10;
53}
54"#;
55
56 let mut engine2 = RuleEngine::new();
57 engine2.add_grl_rule(grl2)?;
58
59 match engine2.evaluate(&context2) {
60 Ok(result) => println!("✓ Discount rules executed: {:?}", result),
61 Err(e) => println!("✗ Rules failed: {}", e),
62 }
63
64 // Example 3: Using from_simple helper
65 println!("\nExample 3: Simple Rule Helper");
66 println!("------------------------------");
67
68 let mut context3 = HashMap::new();
69 context3.insert("temperature".to_string(), json!(35.0));
70 context3.insert("alert".to_string(), json!(false));
71
72 let rule3 = GrlRule::from_simple(
73 "temperature_alert",
74 "temperature > 30.0",
75 "alert = true"
76 );
77
78 println!("Generated GRL:");
79 println!("{}", rule3.grl_content);
80
81 match rule3.evaluate(&context3) {
82 Ok(result) => println!("✓ Temperature alert: {:?}", result),
83 Err(e) => println!("✗ Rule failed: {}", e),
84 }
85
86 // Example 4: Multiple Conditions
87 println!("\nExample 4: Loan Approval Rules");
88 println!("-------------------------------");
89
90 let mut context4 = HashMap::new();
91 context4.insert("credit_score".to_string(), json!(720));
92 context4.insert("income".to_string(), json!(75000));
93 context4.insert("debt_ratio".to_string(), json!(0.3));
94 context4.insert("approved".to_string(), json!(false));
95
96 let grl4 = r#"
97rule "LoanApproval" {
98 when
99 credit_score >= 700 &&
100 income >= 50000 &&
101 debt_ratio < 0.4
102 then
103 approved = true;
104}
105"#;
106
107 let mut engine4 = RuleEngine::new();
108 engine4.add_grl_rule(grl4)?;
109
110 match engine4.evaluate(&context4) {
111 Ok(result) => println!("✓ Loan approval processed: {:?}", result),
112 Err(e) => println!("✗ Approval failed: {}", e),
113 }
114
115 println!("\n=== All GRL Rules Executed Successfully! ===");
116 Ok(())
117}More examples
examples/grl_graph_flow.rs (line 104)
6async fn main() -> anyhow::Result<()> {
7 // Initialize tracing
8 tracing_subscriber::fmt()
9 .with_max_level(tracing::Level::INFO)
10 .init();
11
12 println!("=== Rust Logic Graph - GRL Integration Example ===");
13 println!("Scenario: Loan Application with Advanced GRL Rules\n");
14
15 // Load graph definition
16 let def = GraphIO::load_from_file("examples/grl_graph_flow.json")?;
17
18 // Create custom executor with GRL-powered nodes
19 let mut executor = Executor::new();
20
21 // Input validation with GRL
22 executor.register_node(Box::new(RuleNode::new(
23 "input_validation",
24 "loan_amount > 0 && loan_amount <= 1000000"
25 )));
26
27 // Fetch customer data
28 executor.register_node(Box::new(DBNode::new(
29 "fetch_customer",
30 "SELECT * FROM customers WHERE id = ?"
31 )));
32
33 // Risk assessment with complex GRL rules
34 executor.register_node(Box::new(RuleNode::new(
35 "risk_assessment",
36 "credit_score >= 600 && income >= loan_amount * 3"
37 )));
38
39 // Fraud detection AI
40 executor.register_node(Box::new(AINode::new(
41 "fraud_detection",
42 "Analyze transaction patterns for fraud indicators"
43 )));
44
45 // Final approval decision
46 executor.register_node(Box::new(RuleNode::new(
47 "approval_decision",
48 "risk_score < 50 && fraud_score < 30"
49 )));
50
51 // Notification
52 executor.register_node(Box::new(AINode::new(
53 "notification",
54 "Generate approval/rejection notification email"
55 )));
56
57 // Create graph with initial context
58 let mut graph = Graph::new(def);
59
60 // Set application data
61 graph.context.data.insert("loan_amount".to_string(), json!(50000));
62 graph.context.data.insert("credit_score".to_string(), json!(720));
63 graph.context.data.insert("income".to_string(), json!(180000));
64 graph.context.data.insert("customer_id".to_string(), json!(12345));
65
66 println!("Application Data:");
67 println!(" Loan Amount: $50,000");
68 println!(" Credit Score: 720");
69 println!(" Annual Income: $180,000");
70 println!(" Customer ID: 12345\n");
71
72 // Execute the graph
73 println!("Processing loan application through GRL-powered workflow...\n");
74 executor.execute(&mut graph).await?;
75
76 // Display results
77 println!("\n=== Application Results ===\n");
78
79 if let Some(validation) = graph.context.data.get("input_validation_result") {
80 println!("✓ Input Validation: {}", validation);
81 }
82
83 if let Some(customer) = graph.context.data.get("fetch_customer_result") {
84 println!("✓ Customer Data Retrieved");
85 }
86
87 if let Some(risk) = graph.context.data.get("risk_assessment_result") {
88 println!("✓ Risk Assessment: {}", risk);
89 }
90
91 if let Some(fraud) = graph.context.data.get("fraud_detection_result") {
92 println!("✓ Fraud Detection Completed");
93 }
94
95 if let Some(decision) = graph.context.data.get("approval_decision_result") {
96 println!("✓ Approval Decision: {}", decision);
97 }
98
99 println!("\n=== GRL-Powered Workflow Complete ===");
100
101 // Demonstrate standalone GRL engine
102 println!("\n=== Bonus: Advanced GRL Rules ===\n");
103
104 let mut grl_engine = RuleEngine::new();
105
106 let advanced_rules = r#"
107rule "HighValueLoan" salience 100 {
108 when
109 loan_amount > 100000 && credit_score < 750
110 then
111 requires_manual_review = true;
112 approval_tier = "senior";
113}
114
115rule "StandardApproval" salience 50 {
116 when
117 loan_amount <= 100000 && credit_score >= 650
118 then
119 auto_approve = true;
120 approval_tier = "standard";
121}
122
123rule "RiskMitigation" salience 25 {
124 when
125 debt_to_income_ratio > 0.4
126 then
127 requires_collateral = true;
128 interest_rate_adjustment = 1.5;
129}
130"#;
131
132 grl_engine.add_grl_rule(advanced_rules)?;
133
134 println!("Advanced GRL rules loaded:");
135 println!(" - High Value Loan Review");
136 println!(" - Standard Approval Process");
137 println!(" - Risk Mitigation Measures");
138
139 println!("\n✅ All systems operational with rust-rule-engine integration!");
140
141 Ok(())
142}Sourcepub fn add_grl_rule(&mut self, grl_content: &str) -> Result<(), RuleError>
pub fn add_grl_rule(&mut self, grl_content: &str) -> Result<(), RuleError>
Add a rule using GRL (Grule Rule Language) syntax
Examples found in repository?
examples/grl_rules.rs (line 57)
5fn main() -> anyhow::Result<()> {
6 println!("=== Rust Logic Graph - GRL Rules Example ===\n");
7
8 // Example 1: Simple GRL Rule
9 println!("Example 1: Simple Age Verification");
10 println!("-----------------------------------");
11
12 let mut context1 = HashMap::new();
13 context1.insert("age".to_string(), json!(25));
14 context1.insert("verified".to_string(), json!(false));
15
16 let grl1 = r#"
17rule "AgeVerification" {
18 when
19 age >= 18
20 then
21 verified = true;
22}
23"#;
24
25 let rule1 = GrlRule::new("age_verify", grl1);
26 match rule1.evaluate(&context1) {
27 Ok(result) => println!("✓ Rule executed: {:?}", result),
28 Err(e) => println!("✗ Rule failed: {}", e),
29 }
30
31 // Example 2: Complex Business Rules
32 println!("\nExample 2: E-commerce Discount Rules");
33 println!("-------------------------------------");
34
35 let mut context2 = HashMap::new();
36 context2.insert("cart_total".to_string(), json!(150.0));
37 context2.insert("is_member".to_string(), json!(true));
38 context2.insert("discount".to_string(), json!(0.0));
39
40 let grl2 = r#"
41rule "MemberDiscount" salience 10 {
42 when
43 is_member == true && cart_total >= 100.0
44 then
45 discount = 0.15;
46}
47
48rule "RegularDiscount" salience 5 {
49 when
50 cart_total >= 100.0 && discount == 0.0
51 then
52 discount = 0.10;
53}
54"#;
55
56 let mut engine2 = RuleEngine::new();
57 engine2.add_grl_rule(grl2)?;
58
59 match engine2.evaluate(&context2) {
60 Ok(result) => println!("✓ Discount rules executed: {:?}", result),
61 Err(e) => println!("✗ Rules failed: {}", e),
62 }
63
64 // Example 3: Using from_simple helper
65 println!("\nExample 3: Simple Rule Helper");
66 println!("------------------------------");
67
68 let mut context3 = HashMap::new();
69 context3.insert("temperature".to_string(), json!(35.0));
70 context3.insert("alert".to_string(), json!(false));
71
72 let rule3 = GrlRule::from_simple(
73 "temperature_alert",
74 "temperature > 30.0",
75 "alert = true"
76 );
77
78 println!("Generated GRL:");
79 println!("{}", rule3.grl_content);
80
81 match rule3.evaluate(&context3) {
82 Ok(result) => println!("✓ Temperature alert: {:?}", result),
83 Err(e) => println!("✗ Rule failed: {}", e),
84 }
85
86 // Example 4: Multiple Conditions
87 println!("\nExample 4: Loan Approval Rules");
88 println!("-------------------------------");
89
90 let mut context4 = HashMap::new();
91 context4.insert("credit_score".to_string(), json!(720));
92 context4.insert("income".to_string(), json!(75000));
93 context4.insert("debt_ratio".to_string(), json!(0.3));
94 context4.insert("approved".to_string(), json!(false));
95
96 let grl4 = r#"
97rule "LoanApproval" {
98 when
99 credit_score >= 700 &&
100 income >= 50000 &&
101 debt_ratio < 0.4
102 then
103 approved = true;
104}
105"#;
106
107 let mut engine4 = RuleEngine::new();
108 engine4.add_grl_rule(grl4)?;
109
110 match engine4.evaluate(&context4) {
111 Ok(result) => println!("✓ Loan approval processed: {:?}", result),
112 Err(e) => println!("✗ Approval failed: {}", e),
113 }
114
115 println!("\n=== All GRL Rules Executed Successfully! ===");
116 Ok(())
117}More examples
examples/grl_graph_flow.rs (line 132)
6async fn main() -> anyhow::Result<()> {
7 // Initialize tracing
8 tracing_subscriber::fmt()
9 .with_max_level(tracing::Level::INFO)
10 .init();
11
12 println!("=== Rust Logic Graph - GRL Integration Example ===");
13 println!("Scenario: Loan Application with Advanced GRL Rules\n");
14
15 // Load graph definition
16 let def = GraphIO::load_from_file("examples/grl_graph_flow.json")?;
17
18 // Create custom executor with GRL-powered nodes
19 let mut executor = Executor::new();
20
21 // Input validation with GRL
22 executor.register_node(Box::new(RuleNode::new(
23 "input_validation",
24 "loan_amount > 0 && loan_amount <= 1000000"
25 )));
26
27 // Fetch customer data
28 executor.register_node(Box::new(DBNode::new(
29 "fetch_customer",
30 "SELECT * FROM customers WHERE id = ?"
31 )));
32
33 // Risk assessment with complex GRL rules
34 executor.register_node(Box::new(RuleNode::new(
35 "risk_assessment",
36 "credit_score >= 600 && income >= loan_amount * 3"
37 )));
38
39 // Fraud detection AI
40 executor.register_node(Box::new(AINode::new(
41 "fraud_detection",
42 "Analyze transaction patterns for fraud indicators"
43 )));
44
45 // Final approval decision
46 executor.register_node(Box::new(RuleNode::new(
47 "approval_decision",
48 "risk_score < 50 && fraud_score < 30"
49 )));
50
51 // Notification
52 executor.register_node(Box::new(AINode::new(
53 "notification",
54 "Generate approval/rejection notification email"
55 )));
56
57 // Create graph with initial context
58 let mut graph = Graph::new(def);
59
60 // Set application data
61 graph.context.data.insert("loan_amount".to_string(), json!(50000));
62 graph.context.data.insert("credit_score".to_string(), json!(720));
63 graph.context.data.insert("income".to_string(), json!(180000));
64 graph.context.data.insert("customer_id".to_string(), json!(12345));
65
66 println!("Application Data:");
67 println!(" Loan Amount: $50,000");
68 println!(" Credit Score: 720");
69 println!(" Annual Income: $180,000");
70 println!(" Customer ID: 12345\n");
71
72 // Execute the graph
73 println!("Processing loan application through GRL-powered workflow...\n");
74 executor.execute(&mut graph).await?;
75
76 // Display results
77 println!("\n=== Application Results ===\n");
78
79 if let Some(validation) = graph.context.data.get("input_validation_result") {
80 println!("✓ Input Validation: {}", validation);
81 }
82
83 if let Some(customer) = graph.context.data.get("fetch_customer_result") {
84 println!("✓ Customer Data Retrieved");
85 }
86
87 if let Some(risk) = graph.context.data.get("risk_assessment_result") {
88 println!("✓ Risk Assessment: {}", risk);
89 }
90
91 if let Some(fraud) = graph.context.data.get("fraud_detection_result") {
92 println!("✓ Fraud Detection Completed");
93 }
94
95 if let Some(decision) = graph.context.data.get("approval_decision_result") {
96 println!("✓ Approval Decision: {}", decision);
97 }
98
99 println!("\n=== GRL-Powered Workflow Complete ===");
100
101 // Demonstrate standalone GRL engine
102 println!("\n=== Bonus: Advanced GRL Rules ===\n");
103
104 let mut grl_engine = RuleEngine::new();
105
106 let advanced_rules = r#"
107rule "HighValueLoan" salience 100 {
108 when
109 loan_amount > 100000 && credit_score < 750
110 then
111 requires_manual_review = true;
112 approval_tier = "senior";
113}
114
115rule "StandardApproval" salience 50 {
116 when
117 loan_amount <= 100000 && credit_score >= 650
118 then
119 auto_approve = true;
120 approval_tier = "standard";
121}
122
123rule "RiskMitigation" salience 25 {
124 when
125 debt_to_income_ratio > 0.4
126 then
127 requires_collateral = true;
128 interest_rate_adjustment = 1.5;
129}
130"#;
131
132 grl_engine.add_grl_rule(advanced_rules)?;
133
134 println!("Advanced GRL rules loaded:");
135 println!(" - High Value Loan Review");
136 println!(" - Standard Approval Process");
137 println!(" - Risk Mitigation Measures");
138
139 println!("\n✅ All systems operational with rust-rule-engine integration!");
140
141 Ok(())
142}Sourcepub fn evaluate(&mut self, context: &HashMap<String, Value>) -> RuleResult
pub fn evaluate(&mut self, context: &HashMap<String, Value>) -> RuleResult
Evaluate all rules against the given context
Examples found in repository?
examples/grl_rules.rs (line 59)
5fn main() -> anyhow::Result<()> {
6 println!("=== Rust Logic Graph - GRL Rules Example ===\n");
7
8 // Example 1: Simple GRL Rule
9 println!("Example 1: Simple Age Verification");
10 println!("-----------------------------------");
11
12 let mut context1 = HashMap::new();
13 context1.insert("age".to_string(), json!(25));
14 context1.insert("verified".to_string(), json!(false));
15
16 let grl1 = r#"
17rule "AgeVerification" {
18 when
19 age >= 18
20 then
21 verified = true;
22}
23"#;
24
25 let rule1 = GrlRule::new("age_verify", grl1);
26 match rule1.evaluate(&context1) {
27 Ok(result) => println!("✓ Rule executed: {:?}", result),
28 Err(e) => println!("✗ Rule failed: {}", e),
29 }
30
31 // Example 2: Complex Business Rules
32 println!("\nExample 2: E-commerce Discount Rules");
33 println!("-------------------------------------");
34
35 let mut context2 = HashMap::new();
36 context2.insert("cart_total".to_string(), json!(150.0));
37 context2.insert("is_member".to_string(), json!(true));
38 context2.insert("discount".to_string(), json!(0.0));
39
40 let grl2 = r#"
41rule "MemberDiscount" salience 10 {
42 when
43 is_member == true && cart_total >= 100.0
44 then
45 discount = 0.15;
46}
47
48rule "RegularDiscount" salience 5 {
49 when
50 cart_total >= 100.0 && discount == 0.0
51 then
52 discount = 0.10;
53}
54"#;
55
56 let mut engine2 = RuleEngine::new();
57 engine2.add_grl_rule(grl2)?;
58
59 match engine2.evaluate(&context2) {
60 Ok(result) => println!("✓ Discount rules executed: {:?}", result),
61 Err(e) => println!("✗ Rules failed: {}", e),
62 }
63
64 // Example 3: Using from_simple helper
65 println!("\nExample 3: Simple Rule Helper");
66 println!("------------------------------");
67
68 let mut context3 = HashMap::new();
69 context3.insert("temperature".to_string(), json!(35.0));
70 context3.insert("alert".to_string(), json!(false));
71
72 let rule3 = GrlRule::from_simple(
73 "temperature_alert",
74 "temperature > 30.0",
75 "alert = true"
76 );
77
78 println!("Generated GRL:");
79 println!("{}", rule3.grl_content);
80
81 match rule3.evaluate(&context3) {
82 Ok(result) => println!("✓ Temperature alert: {:?}", result),
83 Err(e) => println!("✗ Rule failed: {}", e),
84 }
85
86 // Example 4: Multiple Conditions
87 println!("\nExample 4: Loan Approval Rules");
88 println!("-------------------------------");
89
90 let mut context4 = HashMap::new();
91 context4.insert("credit_score".to_string(), json!(720));
92 context4.insert("income".to_string(), json!(75000));
93 context4.insert("debt_ratio".to_string(), json!(0.3));
94 context4.insert("approved".to_string(), json!(false));
95
96 let grl4 = r#"
97rule "LoanApproval" {
98 when
99 credit_score >= 700 &&
100 income >= 50000 &&
101 debt_ratio < 0.4
102 then
103 approved = true;
104}
105"#;
106
107 let mut engine4 = RuleEngine::new();
108 engine4.add_grl_rule(grl4)?;
109
110 match engine4.evaluate(&context4) {
111 Ok(result) => println!("✓ Loan approval processed: {:?}", result),
112 Err(e) => println!("✗ Approval failed: {}", e),
113 }
114
115 println!("\n=== All GRL Rules Executed Successfully! ===");
116 Ok(())
117}Trait Implementations§
Auto Trait Implementations§
impl Freeze for RuleEngine
impl !RefUnwindSafe for RuleEngine
impl Send for RuleEngine
impl Sync for RuleEngine
impl Unpin for RuleEngine
impl !UnwindSafe for RuleEngine
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more