Skip to content

PyRulesEngine Guide & Tutorial

Welcome to the ultimate guide to PyRulesEngine! This tutorial provides an extensive deep-dive into creating complex evaluation mechanisms using JSON/YAML configurations.

Overview

PyRulesEngine relies on two components during runtime: 1. The Decision Model (JDM): The YAML or JSON file dictating your workflows, parameters, operator logics, and actions. 2. The Execution Engine: The Python-based RulesEngine instance that consumes a runtime inputs dictionary and executes it against the JDM schemas using Google Common Expression Language (CEL).


1. Workflows & Basic Rules

A Workflow encapsulates a list of individually named Rules. A Rule represents a single point of validation against specific input parameters using CEL.

Configuration (BasicWorkflow.yaml)

We use a LambdaExpression to map a logical assertion.

- WorkflowName: BasicWorkflow
  Version: "1.0.0"
  Rules:
    - RuleName: AgeCheck
      RuleExpressionType: LambdaExpression
      Expression: "user.age >= 18"
      SuccessEvent: AdultConfirmed
      ErrorMessage: "User is a minor."

Execution Example

The Input:

# The input dictionary passed to the engine
inputs = {
    "user": {"name": "Alice", "age": 20}
}

Executing & Output:

results = await engine.execute_all_rules_async("BasicWorkflow", inputs)
print(results[0].is_success)     # Output: True
print(results[0].success_event)  # Output: AdultConfirmed

[!IMPORTANT] CEL booleans are lowercase: true and false. Using True or False in an Expression string will result in a syntax error.


2. Parameter Aliasing (LocalParams)

Sometimes input objects are extremely nested (e.g., invoice.data.client.billing.status). Instead of typing that long path repeatedly in the Expression, you can map it to an alias.

Configuration (LocalParamCheck.yaml)

- WorkflowName: BillingCheck
  Version: "1.0.0"
  Rules:
    - RuleName: VerifyBilling
      RuleExpressionType: LambdaExpression
      LocalParams:
        - Name: status
          Expression: invoice.data.client.billing.status
      Expression: status == "PAID"
      SuccessEvent: InvoiceCleared

3. Evaluator Operations (And, Or, AndAlso, OrElse)

You can build heavily nested logical structures using the Operator and Rules fields.

  • And / Or: Evaluates all child rules before aggregating results.
  • AndAlso: Short-circuiting AND. If the first rule is false, it skips the rest.
  • OrElse: Short-circuiting OR. If the first rule is true, it skips the rest.

Configuration (AggregatorFlow.yaml)

- WorkflowName: CartAggregator
  Version: "1.0.0"
  Rules:
    - RuleName: ApplyDiscountTree
      Operator: AndAlso
      Rules:
        - RuleName: IsVip
          Expression: "customer.is_vip == true"
        - RuleName: HighValueTransaction
          Expression: "cart.total > 500.00"

4. Collection Macros (CEL Native)

CEL provides powerful macros for processing collections. These replace the legacy Linq syntax.

  • collection.exists(var, condition): Returns true if any element matches.
  • collection.all(var, condition): Returns true if all elements match.
  • collection.filter(var, condition): Returns a filtered collection.

Configuration (MacroWorkflow.yaml)

- WorkflowName: SecurityWorkflow
  Version: "1.0.0"
  Rules:
    - RuleName: HasAdminRights
      Expression: "user.roles.exists(role, role.name == 'Administrator')"

5. Math Extensions

PyRulesEngine extends CEL with built-in math functions for production business logic:

  • abs(x): Absolute value.
  • min(a, b, ...): Minimum value.
  • max(a, b, ...): Maximum value.
  • round(x): Rounds to nearest integer.

Configuration (MathWorkflow.yaml)

- WorkflowName: PricingLogic
  Rules:
    - RuleName: ApplySurcharge
      Expression: "max(cart.items.map(i, i.price)) > 100.0"
      SuccessEvent: HIGH_VALUE_SURCHARGE

6. Workflows Call Workflows (Actions)

Use OnSuccess or OnFailure actions to chain workflows.

File A (Pipeline.yaml):

- WorkflowName: PaymentPipeline
  Rules:
    - RuleName: HighRiskTransfer
      Expression: "transaction.amount > 1000"
      Actions:
        OnSuccess:
          Name: ExecuteWorkflow
          Context:
            WorkflowName: RiskCheckingWorkflow

[!TIP] Use the MCP Generate Tool to describe these complex flows in natural language; it will automatically generate the corresponding JDM YAML and validate the CEL syntax for you!