# Logic and Rule-Based Reasoning — Artificial Intelligence

Source: https://www.skillbyai.com/en/artificial-intelligence/k-rules

> If these facts hold, conclude that.

## Facts, rules, inference

Logic-based AI represents knowledge as **facts** and **rules** and uses **inference** to derive new facts. **Forward chaining** starts from known facts and applies rules until nothing new follows (good for monitoring and alerts). **Backward chaining** starts from a goal and works back to see whether facts support it (good for diagnosis questions). Expert systems used thousands of such rules. Rule systems are transparent (every conclusion has a trace) and still widely used in business rules engines, compliance checks and configuration.

## Represent facts, derive new ones

Symbolic AI stores knowledge explicitly and reasons over it with rules.

![Three ideas: rules, knowledge graphs, limits.](assets/figures/artificial-intelligence/section-4-map.svg) — Figure 4.1 — Rules, knowledge graphs and limits.

## Forward chaining over three rules, run

I ran this with plain Python 3 (standard library only), with fixed random seeds where randomness is used. From fever, cough and recent travel, the engine derives respiratory_infection and then recommend_test in the first pass. It cannot derive isolate because test_positive is unknown, and it says so rather than guessing.

```python
facts = {"has_fever", "has_cough", "recent_travel"}
rules = [  # (conditions, conclusion)
    ({"has_fever", "has_cough"}, "respiratory_infection"),
    ({"respiratory_infection", "recent_travel"}, "recommend_test"),
    ({"recommend_test", "test_positive"}, "isolate"),
]
changed = True; round_no = 0
while changed:
    changed = False; round_no += 1
    for conds, concl in rules:
        if conds <= facts and concl not in facts:
            facts.add(concl); changed = True
            print(f"round {round_no}: {sorted(conds)} => {concl}")
print("final facts:", sorted(facts))
print("'isolate' derived:", "isolate" in facts, "(needs test_positive, which is unknown)")
```

Output:

```
round 1: ['has_cough', 'has_fever'] => respiratory_infection
round 1: ['recent_travel', 'respiratory_infection'] => recommend_test
final facts: ['has_cough', 'has_fever', 'recent_travel', 'recommend_test', 'respiratory_infection']
'isolate' derived: False (needs test_positive, which is unknown)
```

## Keep rules testable

Write test cases for rule sets just like code; conflicting or unreachable rules are common as rule bases grow.

**Quiz:** What does forward chaining do?

- [ ] Searches a game tree
- [ ] Starts from a goal and works backwards
- [ ] Trains a neural network
- [x] Applies rules to known facts repeatedly to derive new facts

*Answer:* Applies rules to known facts repeatedly to derive new facts. Data-driven inference.
