What Are the Different Reasoning Engines Available in Semantica? (Forward Chaining & Rete Guide)

Semantica provides a Rete-based forward-chaining production-rule engine, a unified Reasoner façade supporting both forward and backward chaining, and a specialized TemporalReasoning extension for time-based constraints.

The semantica-agi/semantica repository implements a flexible reasoning stack designed for efficient pattern matching and logical inference. Understanding the different reasoning engines available in Semantica allows you to select the appropriate strategy for production-rule systems, goal-driven queries, or temporal logic applications.

Overview of Semantica Reasoning Engines

Semantica organizes its inference capabilities into four distinct components that share a common core infrastructure:

  • ReteEngine – A low-level, forward-chaining production-rule engine implementing the classic Rete algorithm for efficient pattern matching
  • Reasoner – A high-level façade that orchestrates both forward-chaining (via Rete) and backward-chaining (Datalog-style) inference
  • TemporalReasoning – An extension of forward chaining that supports temporal operators like before, after, and interval constraints
  • Rule Actions – A side-effect system supporting AssertAction, RetractAction, CallAction, and EmitEventAction for provenance tracking and event emission

All engines operate on Rule dataclasses and store facts as plain strings (e.g., Person(John)) in a working-memory set.

ReteEngine: The Forward-Chaining Production-Rule Engine

Located in semantica/reasoning/rete_engine.py, the ReteEngine class provides the foundational forward-chaining implementation. It constructs a network of AlphaNode, BetaNode, and TerminalNode instances to eliminate redundant condition evaluations during rule matching.

The engine efficiently handles:

  • Pattern matching across large fact bases through the Rete network topology
  • Activation de-duplication to prevent redundant rule firings
  • Rule actions including AssertAction, RetractAction, CallAction, and EmitEventAction

Direct ReteEngine Usage

For applications requiring maximum control or standalone rule processing, instantiate ReteEngine directly:

from semantica.reasoning import ReteEngine, Fact

engine = ReteEngine()

# Add a rule with pattern variables

engine.add_rule(
    """
    IF Person(?x) AND HasAge(?x, ?age) AND ?age >= 18 THEN Adult(?x)
    """
)

# Insert facts into working memory

engine.add_fact("Person(Alice)")
engine.add_fact("HasAge(Alice, 20)")

# Execute forward chaining

new_facts = engine.forward_chain()
print(new_facts)  # → ['Adult(Alice)']

The forward_chain() method returns all conclusions derived during the inference cycle, with automatic handling of variable binding (e.g., ?x → Alice).

The Reasoner Façade: Unified Forward and Backward Chaining

The Reasoner class in semantica/reasoning/reasoner.py serves as the primary API entry point for most applications. It wraps the ReteEngine for forward-chaining operations while adding a recursive backward-chaining implementation for goal-driven queries.

Forward-Chaining Capabilities

When you call forward_chain() on a Reasoner instance, the façade delegates to its internal ReteEngine, managing rule priorities and fact persistence automatically:

from semantica.reasoning import Reasoner, Rule

r = Reasoner()

# Define a rule using the Rule dataclass

r.add_rule(
    Rule(
        rule_id="adult_rule",
        name="Adult detection",
        conditions=["Person(?x)", "HasAge(?x, ?age)", "?age >= 18"],
        conclusion="Adult(?x)",
        priority=10,
    )
)

r.add_fact("Person(Clara)")
r.add_fact("HasAge(Clara, 22)")

results = r.forward_chain()

# Returns [InferenceResult(conclusion='Adult(Clara)', ...)]

Backward-Chaining for Goal-Driven Inference

The backward_chain method enables Datalog-style or Prolog-like goal proving through recursive rule evaluation and variable unification:


# Ask whether a specific goal is provable

result = r.backward_chain("Adult(Clara)")

# Returns InferenceResult with bindings or None if not provable

# Check non-provable goals

print(r.backward_chain("Adult(Bob)"))  # → None (if Bob doesn't meet conditions)

This dual-mode operation allows the same rule base to support both data-driven (forward) and goal-driven (backward) inference strategies.

TemporalReasoning for Time-Based Constraints

Implemented in semantica/reasoning/temporal_reasoning.py, the TemporalReasoning class extends the standard forward-chaining process with temporal operators. This specialized engine handles:

  • Interval logic (e.g., events occurring within time windows)
  • Temporal relations (before, after, during, overlaps)
  • Time-stamped facts for event sequencing

The temporal extensions use the same Rule and fact infrastructure but add temporal pattern matching nodes to the Rete network.

Working with Rule Actions and Side Effects

Both the ReteEngine and Reasoner support action lists that execute when rules fire. These enable side effects beyond simple assertion of conclusions:

from semantica.reasoning import AssertAction, EmitEventAction

r.add_rule(
    Rule(
        rule_id="notify_adult",
        name="Notify adult",
        conditions=["Adult(?x)"],
        conclusion="Adult(?x)",
        actions=[
            EmitEventAction(event="adult_detected:?x"),
            AssertAction(fact="Notified(?x)"),
        ],
    )
)

# Set up event listening

r.on_event(lambda name, payload: print(f"EVENT → {name}", payload))

r.add_fact("Person(Dave)")
r.add_fact("HasAge(Dave, 45)")
r.forward_chain()

# Output:

# EVENT → adult_detected:Dave {'bindings': {'x': 'Dave'}}

# Fact 'Notified(Dave)' is now in working memory

The EmitEventAction triggers callbacks with variable bindings, while AssertAction adds derived facts directly to working memory.

Summary

  • ReteEngine (semantica/reasoning/rete_engine.py) provides the core forward-chaining implementation using the Rete algorithm with AlphaNode, BetaNode, and TerminalNode networks
  • Reasoner (semantica/reasoning/reasoner.py) offers a unified façade supporting both forward_chain() (Rete-based) and backward_chain() (Datalog-style) inference methods
  • TemporalReasoning (semantica/reasoning/temporal_reasoning.py) extends forward chaining with specialized operators for time-based constraints and interval logic
  • All engines share common data structures including the Rule dataclass, string-based facts, and action types (AssertAction, RetractAction, CallAction, EmitEventAction)

Frequently Asked Questions

What is the Rete algorithm and why does Semantica use it?

The Rete algorithm is a pattern-matching algorithm for production-rule systems that maintains a network of nodes to avoid redundant condition evaluations. Semantica implements this in ReteEngine to ensure efficient inference as the fact base grows, minimizing the computational cost of checking rule conditions against working memory.

When should I use the ReteEngine directly versus the Reasoner façade?

Use ReteEngine directly when you need lightweight, standalone forward chaining without backward-chaining support or when integrating the engine into a custom architecture. Use the Reasoner façade when you need both forward and backward chaining, rule priorities, or the higher-level API methods like infer_facts and on_event.

Does Semantica support backward chaining or Prolog-style queries?

Yes. The Reasoner class provides backward_chain(goal), which implements recursive goal-driven inference with variable unification. This enables Prolog-style queries on the same rule base used for forward chaining, returning InferenceResult objects containing variable bindings or None when goals are not provable.

How does TemporalReasoning differ from the standard ReteEngine?

TemporalReasoning extends the standard forward-chaining loop with temporal operators and interval handling while maintaining the same Rete network structure. It processes time-stamped facts and temporal constraints (e.g., before(EventA, EventB)) that the standard ReteEngine does not natively support, making it suitable for event sequencing and time-based logic applications.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →