This project demonstrates how the Agentic Java approach and the Tools4AI framework can be used to build a modern, flexible Business Rules Engine.
Instead of defining rules in a proprietary DSL (like Drools), you define them as natural language, transform them into typed Java POJOs, and evaluate them via deterministic Java logic.
The Agentic Business Rules Engine is a lightweight, LLM-powered framework
for building enterprise business logic systems in Java. Unlike traditional
rule engines like Drools that require learning proprietary DSLs, this
framework lets business users write rules in plain English.
Key Features:
- Natural Language Rule Definition - Write rules as simple text
- Type-Safe Java Execution - All logic runs in standard Java POJOs
- Zero Downtime Updates - Change thresholds and policies instantly
- No DSL Complexity - Skip the learning curve of Drools DRL syntax
- AI-Powered Parsing - OpenAI transforms text into structured rules
- Deterministic Execution - Predictable, debuggable business logic
- Enterprise Ready - Audit trails, validation, and fallback mechanisms
Perfect For:
β E-commerce dynamic pricing and discount engines
β Insurance underwriting and claims processing
β Financial services loan approval workflows
β Healthcare authorization and benefits management
β Supply chain allocation and routing rules
β Content moderation and compliance policies
How It Works:
- Business analysts write rules in plain English (businessrules.txt)
- LLM parser transforms text into typed Java POJOs (PricingRules.java)
- Domain objects (Order, Customer) are evaluated against rules
- Standard Java @Action methods execute deterministic business logic
- Results include decisions, discounts, flags, and audit trails
Unlike Drools, Easy Rules, or other BRE platforms, this approach:
- Eliminates DSL syntax errors and debugging complexity
- Enables business users to own rule changes
- Reduces deployment cycles from weeks to minutes
- Maintains full type safety and IDE support
- Works with existing Java infrastructure
Built on the Tools4AI framework with support for OpenAI, Claude,
and other LLM providers. 100% open source !
code for the article is here https://github.com/vishalmysore/agenticjava
π‘ How This Maps to a Traditional Rules Engine
| Classic Concept | Agentic Equivalence |
|---|---|
| Rule Definition (DSL) | Natural language text (businessrules.txt) |
| Rule Parser | OpenAIPromptTransformer |
| Rule Model | Typed Java POJO (PricingRules) |
| Facts | Domain POJOs (Order, Customer) |
| Rule Evaluation | Plain Java logic |
| Rule Execution |
@Action methods |
| Audit / Explanation | Logs + Audit Trail |
π οΈ The Architecture: Rules as Data, Not Code
This approach allows rules to live outside compiled code while maintaining type-safe execution.
1. Unstructured Rule Definition (businessrules.txt)
Gold customers get 10 percent discount.
Orders above 50000 require approval.
Orders from restricted regions like Shadowreach or Veridiania must be flagged.
2. Typed Rules Model (PricingRules.java)
@Data
public class PricingRules {
private double goldDiscountPercent;
private double approvalThreshold;
@ListType(String.class)
private List<String> restrictedRegions;
public boolean isValid() {
return goldDiscountPercent >= 0 && goldDiscountPercent <= 100
&& approvalThreshold >= 0;
}
}
3. Rule Loader (RuleLoader.java)
The RuleLoader transforms natural language rules into typed POJOs using AI:
public class RuleLoader {
private static PricingRules cachedRules;
public static PricingRules getRules() {
if (cachedRules == null) {
cachedRules = loadRules();
}
return cachedRules;
}
private static PricingRules loadRules() {
System.out.println("Audit: Attempting to load and transform business rules...");
try {
String unstructuredRules = new String(
Files.readAllBytes(Paths.get("src/main/resources/businessrules.txt")));
OpenAIPromptTransformer transformer = new OpenAIPromptTransformer();
PricingRules rules = (PricingRules) transformer.transformIntoPojo(unstructuredRules, PricingRules.class);
if (rules != null && rules.isValid()) {
System.out.println("Audit: Rules successfully transformed and validated.");
return rules;
} else {
System.err.println("Audit Warning: Transformed rules failed validation. Using defaults.");
return createDefaultRules();
}
} catch (IOException | AIProcessingException e) {
System.err.println("Audit Error: Failed to load rules: " + e.getMessage());
return createDefaultRules();
}
}
}
4. Domain Models (Order.java)
@Data
public class Order {
private String orderId;
private double amount;
private String customerId;
private boolean isGoldCustomer;
private String region;
}
5. Deterministic Evaluation (PricingAction.java)
@Agent(groupName = "Business Rules", groupDescription = "Evaluates business rules for orders")
public class PricingAction {
@Action(description = "Evaluate pricing rules for an order")
public PricingDecision evaluatePricing(Order order, PricingRules rules) {
PricingDecision decision = new PricingDecision();
decision.setFinalPrice(order.getAmount());
// Apply gold customer discount
if (order.isGoldCustomer()) {
decision.applyDiscount(rules.getGoldDiscountPercent(), order.getAmount());
}
// Check if approval is required
if (order.getAmount() > rules.getApprovalThreshold()) {
decision.setApprovalRequired(true);
}
// Flag restricted regions
if (rules.getRestrictedRegions() != null &&
rules.getRestrictedRegions().contains(order.getRegion())) {
decision.addFlag("RESTRICTED_REGION");
}
return decision;
}
}
6. Main Application (BusinessRulesExample.java)
public class BusinessRulesExample {
public static void main(String[] args) {
System.setProperty("tools4ai.properties.path", "io/github/vishalmysore/rules/tools4ai.properties");
AIProcessor processor = PredictionLoader.getInstance().createOrGetAIProcessor();
try {
// Load business rules from natural language text
PricingRules rules = RuleLoader.getRules();
System.out.println("\nLoaded Rules:");
System.out.println(" Gold Discount: " + rules.getGoldDiscountPercent() + "%");
System.out.println(" Approval Threshold: $" + rules.getApprovalThreshold());
System.out.println(" Restricted Regions: " + rules.getRestrictedRegions());
// Create an order
Order order = new Order();
order.setOrderId("ORD-999");
order.setAmount(60000.0);
order.setGoldCustomer(true);
order.setRegion("Shadowreach");
// Evaluate using AI processor
PricingDecision decision = (PricingDecision) processor.processSingleAction(
"Evaluate pricing rules for order with orderId " + order.getOrderId()
+ " amount " + order.getAmount()
+ " isGoldCustomer " + order.isGoldCustomer()
+ " region " + order.getRegion()
+ " using rules with goldDiscountPercent " + rules.getGoldDiscountPercent()
+ " approvalThreshold " + rules.getApprovalThreshold()
+ " restrictedRegions " + rules.getRestrictedRegions());
printDecision(decision);
} catch (AIProcessingException e) {
e.printStackTrace();
}
}
}
π Why This Matters
- Zero Deployment Churn: Change business thresholds or discount percentages in the text file; the system reloads logic without a redeploy.
- Language as an Interface: Business analysts can review and update rules in plain English.
- No DSL Complexity: Avoid learning complex proprietary languages. If you know Java, you can evaluate rules.
- Hybrid Safety: LLMs are used for interpreting intent, but the execution of the business rule is standard, debuggable Java.
π₯ Who This Is For
- Java teams looking for a lightweight alternative to Drools or complex BREs.
- Architects who want "Language as Code" patterns without losing control or safety.
- Backend engineers who want to bridge the gap between business intent and type-safe systems.
π Getting Started
mvn clean compile
java -cp "target/classes;..." io.github.vishalmysore.rules.BusinessRulesExample
Expected Output
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Agentic Business Rules Engine - Powered by tools4ai β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Audit: Attempting to load and transform business rules...
Audit: Rules successfully transformed and validated.
Loaded Rules:
Gold Discount: 10.0%
Approval Threshold: $50000.0
Restricted Regions: [Shadowreach, Veridiania]
Evaluating Order: ORD-999
Order Amount: $60000.0
Gold Customer: true
Region: Shadowreach
---------------------------------------------------------------
Scenario 1: Direct Evaluation via RuleLoader
Pricing Decision Result:
Final Price: $54000.0
Discount Applied: $6000.0
Approval Required: true
Flags: [RESTRICTED_REGION]
===============================================================
What Happened:
- β
Natural language rules were transformed into
PricingRulesPOJO - β 10% gold customer discount applied: $60,000 β $54,000
- β Approval required (order > $50,000 threshold)
- β Restricted region flagged (Shadowreach)
πΌ Real-World Use Cases
1. E-Commerce Dynamic Pricing
Rules File:
Premium members get 15 percent off electronics.
Orders over 1000 dollars get free shipping.
Flash sale items have an additional 20 percent discount.
Buy 3 or more items and get 10 percent bulk discount.
Use Case: Update pricing rules daily during sales events without deploying new code. Marketing teams can modify discounts in plain English, and the system automatically applies them across millions of transactions.
2. Insurance Underwriting
Rules File:
Applicants under 25 years old have a 30 percent premium increase.
Non-smokers receive a 15 percent discount.
Applicants from high-risk zip codes require manual review.
Claims history with more than 2 incidents in 5 years requires underwriter approval.
Use Case: Insurance companies can adjust underwriting criteria based on market conditions, regulatory changes, or risk assessment updates without IT intervention.
3. Loan Approval Workflow
Rules File:
Credit scores below 650 require manual review.
Loan amounts above 50000 need two approvals.
Debt-to-income ratio above 43 percent is automatically declined.
First-time borrowers with income verification get expedited processing.
Use Case: Financial institutions can quickly adapt lending criteria based on economic conditions, risk appetite, or regulatory requirements.
4. Healthcare Authorization
Rules File:
Procedures costing more than 5000 dollars require pre-authorization.
Out-of-network providers need additional documentation.
Elective procedures have a 30-day waiting period.
Emergency services are auto-approved regardless of cost.
Use Case: Healthcare systems can update authorization rules based on policy changes, budget constraints, or clinical guidelines without system downtime.
5. Supply Chain Allocation
Rules File:
Priority customers get first allocation during shortages.
Orders from regions with high inventory get same-day processing.
Perishable goods from warehouses older than 5 days ship first.
International orders require customs documentation review.
Use Case: Supply chain managers can dynamically adjust allocation rules based on inventory levels, demand patterns, or business priorities.
6. Content Moderation
Rules File:
Posts with profanity require human review.
Users with reputation below 10 have posts flagged automatically.
Content from restricted countries needs compliance check.
Images with low quality scores are rejected.
Use Case: Social platforms can adjust moderation policies based on community standards, legal requirements, or abuse patterns without redeploying content filtering services.
π― Key Benefits
For Business Users
- No Technical Knowledge Required: Write rules in plain English
- Immediate Updates: Change thresholds and percentages instantly
- Transparency: Rules are readable and auditable by non-technical stakeholders
For Developers
- Type-Safe Execution: All rule evaluations happen in strongly-typed Java
- Debuggable: Step through rule logic with standard debugging tools
- Testable: Write JUnit tests for rule evaluation logic
- Version Controlled: Rules are text files tracked in Git
For Organizations
- Regulatory Compliance: Easy to audit and explain decision-making
- Reduced Time-to-Market: Business rules changes don't require full SDLC
- Lower Costs: No need for specialized rules engine expertise
- Flexibility: Works with existing Java infrastructure
π§ How to Extend
Adding New Rule Types
- Create new domain model:
@Data
public class ShippingRules {
private double freeShippingThreshold;
private List<String> expeditedRegions;
private int standardDeliveryDays;
}
- Create rules text file:
src/main/resources/shippingrules.txt:
Orders over 50 dollars get free shipping.
Expedited regions include California and New York.
Standard delivery takes 5 business days.
- Create action handler:
@Agent(groupName = "Shipping Rules")
public class ShippingAction {
@Action(description = "Calculate shipping cost and delivery time")
public ShippingDecision calculateShipping(Order order, ShippingRules rules) {
// Your logic here
}
}
π Configuration
Edit src/main/resources/io/github/vishalmysore/rules/tools4ai.properties:
# AI Model Configuration
baseurl=http://langchain4j.dev/demo/openai/v1
timeout=PT1M
packages=io.github.vishalmysore.rules
# For production, use real OpenAI:
# baseurl=https://api.openai.com/v1
# apikey=your-api-key-here
β οΈ Important Notes
- The AI is used only for parsing rules into structured data, not for runtime decisions
- All business logic execution is deterministic Java code
- Rules are cached after first load for performance
- Failed rule transformations fall back to safe defaults
[!NOTE]
This model aligns naturally with MCP-style tool invocation, but remains fully usable without centralized orchestration layers.
Built with Tools4AI.
β οΈ Production Readiness Disclaimer
This is an educational proof-of-concept, not a production-ready system.
Before deploying to production, you must:
- β Add comprehensive security validation and authentication
- β Implement extensive testing (unit, integration, regression)
- β Establish monitoring, logging, and audit trails
- β Create rule governance and approval workflows
- β Handle LLM service failures with fallbacks and circuit breakers
- β Comply with industry regulations (SOX, GDPR, HIPAA, etc.)
- β Performance test under production load
- β Implement rule versioning and rollback capabilities
- β Add cost monitoring for LLM API usage
- β Validate all AI-parsed rules before execution
This example demonstrates architectural patternsβproduction deployment
requires enterprise-grade engineering practices tailored to your specific
requirements and risk profile.
Top comments (0)