Download inference_engine.py from dthart/Build3pt2: direct link, hf CLI and curl.
- Browser
- Download file 6.22 kB
-
https://huggingface.co/spaces/dthart/Build3pt2/resolve/main/inference_engine.py
- Command line
-
hf download hf://spaces/dthart/Build3pt2/inference_engine.py
-
curl -L -o inference_engine.py https://huggingface.co/spaces/dthart/Build3pt2/resolve/main/inference_engine.py
6.22 kB
| """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 | |
| 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) | |