# How to Implement Expert Systems Using Knowledge Representation in AI for Beginners

> Learn to implement expert systems using knowledge representation in AI. Understand rule-based AI programs, knowledge bases, and inference engines for beginner AI enthusiasts.

- Repository: [Microsoft/AI-For-Beginners](https://github.com/microsoft/AI-For-Beginners)
- Tags: how-to-guide
- Published: 2026-08-29

---

**Expert systems are rule-based AI programs that encode domain knowledge in a knowledge base and use an inference engine to draw conclusions through forward or backward chaining.**

To implement expert systems using knowledge representation in AI for Beginners, you will work with the **microsoft/AI-For-Beginners** curriculum, specifically the Symbolic AI lesson series that demonstrates how to build production rule systems using Python.

## Understanding Expert System Architecture

According to the curriculum in [`lessons/2-Symbolic/README.md`](https://github.com/microsoft/AI-For-Beginners/blob/main/lessons/2-Symbolic/README.md), a production rule expert system consists of three distinct layers that separate data from logic.

### Knowledge Base

The **knowledge base** stores the domain model as a collection of **facts** and **production rules**. Facts represent specific data points (e.g., "the animal has fur"), while rules define conditional logic in the form "IF condition THEN action." In the `Animals.ipynb` notebook, this layer is implemented by subclassing `experta.Fact` to declare typed fields that rules will match against.

### Inference Engine

The **inference engine** executes the reasoning process. It matches facts against rule antecedents (left-hand side) and triggers consequent actions (right-hand side). The curriculum demonstrates **forward chaining** (data-driven reasoning) using the `KnowledgeEngine.run()` method, which iteratively fires rules until no new facts are derived. The engine automatically handles **conflict resolution**, selecting which rule to fire when multiple patterns match.

### User Interface

A thin **user interface** layer allows non-programmers to add facts, query conclusions, or view explanations. The lesson suggests building a reusable *expert-systems shell* that loads domain-specific rules from external files (JSON or a simple DSL) at runtime.

## Building an Expert System with Experta

The curriculum utilizes **Experta**, a modern Python wrapper around the classic CLIPS rule engine, to demonstrate symbolic AI without low-level rule syntax.

### Define the Knowledge Base with Fact Classes

First, declare the data schema by subclassing `Fact`. In `lessons/2-Symbolic/Animals.ipynb`, the example defines an `Animal` fact class with attributes like `has_fur` and `lays_eggs`:

```python
from experta import Fact, KnowledgeEngine, Rule, MATCH

class Animal(Fact):
    """An animal with properties needed for classification."""
    pass

```

### Create the Inference Engine

Next, subclass `KnowledgeEngine` and decorate methods with `@Rule` to define production rules. Each rule uses pattern matching on the left-hand side and inference logic on the right-hand side:

```python
class AnimalClassifier(KnowledgeEngine):
    @Rule(Animal(has_fur=True, lays_eggs=False))
    def mammal(self):
        print("This is a mammal.")
        
    @Rule(Animal(has_fur=MATCH.fur, lays_eggs=True))
    def bird_with_fur(self, fur):
        # Demonstrates pattern variable binding with MATCH

        pass

```

### Execute Forward Chaining

Load initial facts using `engine.reset()` and `engine.declare()`, then trigger inference with `engine.run()`:

```python
engine = AnimalClassifier()
engine.reset()
engine.declare(Animal(name="Kangaroo", has_fur=True, lays_eggs=False))
engine.run()

```

The `run()` method activates forward chaining, evaluating rules in order of specificity (salience) until the knowledge base reaches a stable state.

## Complete Implementation Example

The following runnable example distills the pattern demonstrated in `lessons/2-Symbolic/Animals.ipynb` into a standalone Python script. Save this as [`expert_system.py`](https://github.com/microsoft/AI-For-Beginners/blob/main/expert_system.py) and ensure you have installed Experta via the [`environment.yml`](https://github.com/microsoft/AI-For-Beginners/blob/main/environment.yml) specifications in the repository:

```python

# expert_system.py

# Requires: pip install experta (as specified in environment.yml)

from experta import Fact, KnowledgeEngine, Rule, MATCH

# 1️⃣ Knowledge Base – define the data shape

class Animal(Fact):
    """An animal with properties needed for classification."""
    pass

# 2️⃣ Inference Engine – encode the rules

class AnimalClassifier(KnowledgeEngine):
    @Rule(Animal(has_fur=MATCH.fur, lays_eggs=True))
    def bird_with_fur(self, fur):
        print(f"A bird with {'furry' if fur else 'no'} feathers detected.")
        
    @Rule(Animal(has_fur=True, lays_eggs=False))
    def mammal(self):
        print("This is a mammal.")
        
    @Rule(Animal(has_fur=False, lays_eggs=True))
    def bird(self):
        print("This is a bird.")

# 3️⃣ Load facts and run

if __name__ == "__main__":
    engine = AnimalClassifier()
    engine.reset()
    engine.declare(Animal(name="Penguin", has_fur=False, lays_eggs=True))
    engine.declare(Animal(name="Kangaroo", has_fur=True, lays_eggs=False))
    engine.run()

```

Executing the script produces:

```

This is a bird.
This is a mammal.

```

## Extending Your Expert System

Once the basic architecture is functional, you can adapt the pattern for any domain (medical diagnosis, troubleshooting, configuration).

- **Adding new fact types** – Create additional `Fact` subclasses (e.g., `Symptom`, `Diagnosis`) to represent different entities in your domain model.
- **Backward chaining** – Implement goal-driven reasoning using `@DefFacts` generators and `salience` parameters in `@Rule` decorators to prioritize hypothesis testing over data saturation.
- **Persistence layer** – Export the declared facts to JSON and reload them at runtime, transforming the engine into a reusable expert-systems shell as described in [`lessons/2-Symbolic/README.md`](https://github.com/microsoft/AI-For-Beginners/blob/main/lessons/2-Symbolic/README.md).

## Summary

- **Expert systems** separate domain knowledge (facts and rules) from the inference process (engine).
- The **microsoft/AI-For-Beginners** curriculum implements this using the **Experta** library in `lessons/2-Symbolic/Animals.ipynb`.
- **KnowledgeEngine** subclasses define rules using the `@Rule` decorator, while **Fact** subclasses declare the data schema.
- **Forward chaining** starts with known facts and applies rules via `engine.run()` until no new conclusions are derived.
- The architecture supports **backward chaining** and external rule loading for building reusable shells.

## Frequently Asked Questions

### How do I install the Experta library used in the AI for Beginners curriculum?

Install Experta using pip as specified in the repository's [`environment.yml`](https://github.com/microsoft/AI-For-Beginners/blob/main/environment.yml) file. Run `pip install experta` in your Python environment, or create a Conda environment using the [`environment.yml`](https://github.com/microsoft/AI-For-Beginners/blob/main/environment.yml) located at the repository root to install all lesson dependencies at once.

### What is the difference between forward chaining and backward chaining in expert systems?

**Forward chaining** is data-driven: the engine starts with known facts in the knowledge base and applies rules to derive new facts until reaching a conclusion. **Backward chaining** is goal-driven: the engine starts with a hypothesis and works backwards to find facts that support or refute it. The Experta library supports both through salience settings and goal-based rule structures.

### Can non-programmers create rules for this expert system?

Yes. By building an **expert-systems shell** that loads rules from external files (JSON, YAML, or a domain-specific language), you can allow domain experts to author rules without modifying Python code. The [`lessons/2-Symbolic/README.md`](https://github.com/microsoft/AI-For-Beginners/blob/main/lessons/2-Symbolic/README.md) file discusses this architecture for creating reusable knowledge bases.

### How does the inference engine handle conflicting rules?

Experta's inference engine includes a **conflict resolution** strategy that selects which rule to fire when multiple rules match the current facts. By default, it considers rule specificity and declaration order. You can control priority explicitly using the `salience` parameter in the `@Rule` decorator, where higher salience values indicate higher priority.