File size: 6,217 Bytes
6d598a9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | """Small, domain-independent forward-chaining inference engine."""
from dataclasses import dataclass, field
from typing import Any
from knowledge_base import INPUT_FACTS, RECOMMENDATIONS, RULES, UNKNOWN, Rule
@dataclass
class InferenceResult:
input_facts: dict[str, Any]
derived_facts: dict[str, Any]
diagnoses: list[str]
recommendations: list[str]
trace: list[str]
unknown_inputs: list[str]
conflicts: list[str] = field(default_factory=list)
def normalize_status_code(raw_value: Any) -> int | str:
"""Return an integer status code or UNKNOWN for blank/invalid input."""
if raw_value in (None, "", UNKNOWN):
return UNKNOWN
try:
code = int(str(raw_value).strip())
except (TypeError, ValueError):
return UNKNOWN
return code if 100 <= code <= 599 else UNKNOWN
def status_class(code: int | str) -> str:
if not isinstance(code, int):
return UNKNOWN
return f"{code // 100}xx"
def _condition_matches(facts: dict[str, Any], name: str, expected: Any) -> bool:
"""UNKNOWN never satisfies a condition unless a rule explicitly expects it."""
actual = facts.get(name, UNKNOWN)
return actual == expected
def _rule_matches(rule: Rule, facts: dict[str, Any]) -> bool:
return all(
_condition_matches(facts, name, expected)
for name, expected in rule.conditions.items()
)
def infer(input_facts: dict[str, Any]) -> InferenceResult:
"""Apply rules repeatedly until no new fact or diagnosis can be produced."""
cleaned = dict(input_facts)
cleaned["status_code"] = normalize_status_code(cleaned.get("status_code"))
cleaned["status_class"] = status_class(cleaned["status_code"])
working_memory = dict(cleaned)
derived_facts: dict[str, Any] = {}
diagnoses: list[str] = []
trace: list[str] = []
conflicts: list[str] = []
fired_rules: set[str] = set()
ordered_rules = sorted(RULES, key=lambda rule: rule.priority, reverse=True)
changed = True
while changed:
changed = False
for rule in ordered_rules:
if rule.rule_id in fired_rules or not _rule_matches(rule, working_memory):
continue
fired_rules.add(rule.rule_id)
conditions = ", ".join(
f"{name}={expected}" for name, expected in rule.conditions.items()
)
trace.append(
f"{rule.rule_id} fired ({conditions}) -> "
f"{rule.conclusion_name}={rule.conclusion_value}. {rule.explanation}"
)
if rule.category == "diagnosis":
if rule.conclusion_value not in diagnoses:
diagnoses.append(str(rule.conclusion_value))
changed = True
elif rule.category == "conflict":
if rule.explanation not in conflicts:
conflicts.append(rule.explanation)
changed = True
else:
current = working_memory.get(rule.conclusion_name, UNKNOWN)
if current not in (UNKNOWN, rule.conclusion_value):
message = (
f"Conflicting values for {rule.conclusion_name}: "
f"{current!r} and {rule.conclusion_value!r}."
)
if message not in conflicts:
conflicts.append(message)
elif current != rule.conclusion_value:
working_memory[rule.conclusion_name] = rule.conclusion_value
derived_facts[rule.conclusion_name] = rule.conclusion_value
changed = True
recommendations: list[str] = []
for diagnosis in diagnoses:
for recommendation in RECOMMENDATIONS.get(diagnosis, []):
if recommendation not in recommendations:
recommendations.append(recommendation)
unknown_inputs = [
description
for name, description in INPUT_FACTS.items()
if cleaned.get(name, UNKNOWN) == UNKNOWN
]
return InferenceResult(
input_facts=cleaned,
derived_facts=derived_facts,
diagnoses=diagnoses,
recommendations=recommendations,
trace=trace,
unknown_inputs=unknown_inputs,
conflicts=conflicts,
)
def render_report(result: InferenceResult) -> str:
"""Render a human-readable, evidence-backed report for the interface."""
sections: list[str] = []
if result.conflicts:
lines = "\n".join(f"- {item}" for item in result.conflicts)
sections.append(
"## Conflicting information\n"
f"{lines}\n\nCorrect these inputs before accepting a recommendation."
)
if result.diagnoses:
lines = "\n".join(f"{index}. **{item}**" for index, item in enumerate(result.diagnoses, 1))
sections.append(f"## Supported conclusion(s)\n{lines}")
else:
sections.append(
"## No supported conclusion\n"
"The supplied facts did not activate a diagnostic rule. "
"Provide additional evidence or revise the knowledge base; do not guess."
)
if result.recommendations:
lines = "\n".join(f"- {item}" for item in result.recommendations)
sections.append(f"## Recommended checks\n{lines}")
if result.derived_facts:
lines = "\n".join(
f"- `{name}` = `{value}`" for name, value in result.derived_facts.items()
)
sections.append(f"## Derived facts\n{lines}")
if result.trace:
lines = "\n".join(f"- {item}" for item in result.trace)
sections.append(f"## Inference trace\n{lines}")
if result.unknown_inputs:
lines = "\n".join(f"- {item}" for item in result.unknown_inputs)
sections.append(
"## Information still unknown\n"
f"{lines}\n\nUnknown information was not treated as false."
)
sections.append(
"## Human review\n"
"Review the reported facts and inference trace before acting. "
"This starter demonstrates bounded reasoning and does not replace documentation, logs, or expert judgment."
)
return "\n\n".join(sections)
|