gale.ai.rules module

This file contains a small forward-chaining, production-rule system: Rule pairs a condition with an action and a priority, and RuleEngine repeatedly fires the highest-priority applicable rule against a shared working memory until none applies (or a maximum number of iterations is reached), the same “IF condition THEN action” style used in classic expert systems and rule-based game AI.

Author: Alejandro Mujica (aledrums@gmail.com)

class gale.ai.rules.Rule(name, condition, action, priority=0.0)[source]

Bases: object

A single production rule: condition is checked against the RuleEngine’s working memory, and action is called when it’s the highest-priority rule whose condition currently holds.

Usage example:

Rule(

name=”flee_when_low_health”, condition=lambda memory: memory.get(“health”, 100) < 20, action=lambda memory: memory.__setitem__(“goal”, “flee”), priority=10,

)

Parameters:
  • name (str)

  • condition (Callable[[Dict[str, Any]], bool])

  • action (Callable[[Dict[str, Any]], None])

  • priority (float)

class gale.ai.rules.RuleEngine(rules, working_memory=None)[source]

Bases: object

Forward-chains a set of rules against a shared working memory: each call to run() re-evaluates every rule’s condition, fires the single highest-priority rule that currently applies, and repeats (since firing a rule may make others applicable, or the same one inapplicable) until no rule applies or max_iterations is reached.

Usage example:

engine = RuleEngine([

Rule(“flee”, lambda m: m[“health”] < 20, lambda m: m.update(goal=”flee”), priority=10), Rule(“attack”, lambda m: m[“enemy_visible”], lambda m: m.update(goal=”attack”), priority=5), Rule(“patrol”, lambda m: True, lambda m: m.update(goal=”patrol”), priority=0),

]) engine.working_memory.update(health=100, enemy_visible=True) fired = engine.run() # [“attack”] – only “attack” applies and firing it doesn’t unlock another

Parameters:
  • rules (Sequence[Rule])

  • working_memory (Dict[str, Any] | None)

run(max_iterations=100)[source]
Parameters:

max_iterations (int) – Maximum number of rules to fire in this call, as a safeguard against rules that keep re-triggering each other forever.

Returns:

The name of each rule fired, in the order they fired. Stops early, before max_iterations, as soon as the same rule would fire again against an unchanged working_memory (a steady state reached), without firing it that extra time.

Return type:

Sequence[str]