rohitg00/ai-engineering-from-scratch · error · ValueError

rule missing required field

Error message

rule {r.get('name')} missing required field

What it means

Engine.__init__ checks every rule for its required fields (name, predicate, action, severity); the guard fires when at least one rule dict omits one of them, meaning that rule could never be evaluated or reported correctly.

Solutions

  1. Add the missing required field to the offending rule
  2. Validate rule dicts against a required-keys schema at load time
  3. Reject partially authored rules in CI before they reach the Engine
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at phases/19-capstone-projects/86-constitutional-rules-engine/code/main.py:139 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of rohitg00/ai-engineering-from-scratch@39ea8a1c6d (2026-08-26). Data as JSON: /api/errors/841453035c047a66. Report an issue: GitHub.

Appendix: source

Thrown at phases/19-capstone-projects/86-constitutional-rules-engine/code/main.py:139

        return (wc >= int(node["min_words"])), (f"word count {wc}" if wc < int(node["min_words"]) else None)
    raise ValueError(f"unknown predicate: {list(node.keys())}")


class Engine:
    def __init__(self, rules: list[dict[str, Any]] | None = None, path: Path | None = None) -> None:
        if rules is not None:
            self._rules = rules
        else:
            target = path or DEFAULT_RULES_PATH
            data = load_yaml(target.read_text())
            if not isinstance(data, dict) or "rules" not in data:
                raise ValueError("constitution must be a mapping with a 'rules' key")
            self._rules = data["rules"]
        for r in self._rules:
            if r.get("severity") not in SEVERITY_ORDER:
                raise ValueError(f"rule {r.get('name')} has bad severity {r.get('severity')}")
            if "name" not in r or "explanation" not in r or "must" not in r:
                raise ValueError(f"rule {r.get('name')} missing required field")

    def rules(self) -> list[dict[str, Any]]:
        return list(self._rules)

    def evaluate(self, text: str) -> EngineReport:
        report = EngineReport(text=text)
        for rule in self._rules:
            name = str(rule["name"])
            sev = str(rule["severity"])
            expl = str(rule["explanation"])
            applies, _ = _eval_predicate(rule.get("applies_when"), text)
            if not applies:
                report.results.append(
                    RuleResult(rule_name=name, severity=sev, status="not_applicable", explanation=expl)
                )
                continue
            satisfied, span = _eval_predicate(rule["must"], text)
            if satisfied:

View on GitHub (pinned to 39ea8a1c6d)