Skip to main content

A Python module for rule-based content validation, correction, and enforcement in LLM applications.

Project description

fabricatio-rule

MIT Python Versions PyPI Version PyPI Downloads PyPI Downloads Build Tool: uv

LLM-backed rule drafting, content validation, and correction enforcement for Fabricatio agents.

Installation

pip install fabricatio[rule]
# or
uv pip install fabricatio[rule]

Overview

fabricatio-rule provides capability mixins and actions that let Fabricatio agents validate and correct content against structured, machine-readable rulesets. Rulesets are drafted from natural language requirements using the agent's configured LLM, then applied to strings or structured objects (implementing Display/WithBriefing). Violations produce typed Improvement objects — making downstream correction workflows fully automated.

Key Types

Class Role
Rule A single rule: name, description, plus lists of violation_examples and compliance_examples. Extends WithBriefing, Language, SketchedAble, PersistentAble.
RuleSet A named collection of Rule instances. Has a gather(*rulesets) classmethod to merge multiple rulesets into one. Extends the same base classes as Rule.
RuleSetMetadata A Patch[RuleSet] for updating a ruleset's name and description fields, used internally during drafting.
CheckKwargs Typed kwargs for check operations; extends ReferencedKwargs[Improvement] with a ruleset: RuleSet field.

Capabilities

Check — rule-based validation

from fabricatio_rule.capabilities.check import Check

An ABC mixin (extends EvidentlyJudge, Propose) that adds rule-aware validation to any agent:

class Check(EvidentlyJudge, Propose, ABC):
    async def draft_ruleset(
        self, ruleset_requirement: str, rule_count: int = 0, **kwargs
    ) -> Optional[RuleSet]: ...

    async def check_string_against_rule(
        self, input_text: str, rule: Rule, reference: str = "", **kwargs
    ) -> Optional[Improvement]: ...

    async def check_obj_against_rule(
        self, obj: M, rule: Rule, reference: str = "", **kwargs
    ) -> Optional[Improvement]: ...

    async def check_string(
        self, input_text: str, ruleset: RuleSet, reference: str = "", **kwargs
    ) -> Optional[List[Improvement]]: ...

    async def check_obj(
        self, obj: M, ruleset: RuleSet, reference: str = "", **kwargs
    ) -> Optional[List[Improvement]]: ...
  • draft_ruleset breaks a natural language requirement into individual rule requirements, proposes Rule instances and a RuleSetMetadata patch, then assembles the final RuleSet.
  • check_string / check_obj validate content against every rule in a ruleset concurrently, returning a list of Improvement objects (one per violation).
  • check_string_against_rule / check_obj_against_rule validate against a single rule. They use evidently_judge to confirm a violation, then propose an Improvement if one is found.

Censor — check-then-correct workflows

from fabricatio_rule.capabilities.censor import Censor

An ABC mixin (extends Correct, Check) that combines validation and correction:

class Censor(Correct, Check, ABC):
    async def censor_string(
        self, input_text: str, ruleset: RuleSet, **kwargs
    ) -> Optional[str]: ...

    async def censor_obj(
        self, obj: M, ruleset: RuleSet, **kwargs
    ) -> Optional[M]: ...

    async def censor_obj_inplace(
        self, obj: M, ruleset: RuleSet, **kwargs
    ) -> Optional[M]: ...

Each method checks the input against the ruleset, gathers any Improvement results, then applies corrections via fabricatio-improve's Correct capability. Returns the corrected value, or the original if no violations are found.

Actions

DraftRuleSet

from fabricatio_rule.actions.rules import DraftRuleSet

An Action (mixing in Check and FromMapping) that drafts a RuleSet from a natural language requirement and stores it in the agent's context under output_key (default "drafted_ruleset"). Supports batch creation via from_mapping.

GatherRuleset

from fabricatio_rule.actions.rules import GatherRuleset

An Action (mixing in FromMapping) that gathers multiple RuleSet instances from the agent's context into a single merged ruleset via RuleSet.gather(). Validates that all named keys exist and reference RuleSet instances.

Configuration

from fabricatio_rule.config import rule_config

@dataclass
class RuleConfig:
    ruleset_requirement_breakdown_template: str  # template for breaking down requirements
    rule_requirement_template: str               # template for proposing individual rules
    check_string_template: str                   # template for check strings

Loaded via fabricatio-core's CONFIG.load("rule", RuleConfig). Customize template names at runtime to swap prompt strategies.

Usage

from fabricatio_rule.actions.rules import DraftRuleSet, GatherRuleset
from fabricatio_rule.capabilities.censor import Censor
from fabricatio_rule.models.rule import RuleSet


class MyCensor(Censor):
    """Agent that validates and corrects content against rules."""
    pass


async def example():
    # Generate a ruleset from a natural language requirement
    draft = DraftRuleSet(
        ruleset_requirement="Professional tone: no slang, no contractions, formal grammar",
        output_key="style_rules",
    )
    style_rules: RuleSet = await draft._execute()

    # Check and correct content
    censor = MyCensor()
    result = await censor.censor_string(
        "this aint right lol",
        style_rules,
    )
    print(f"Corrected: {result}")

Merging multiple rulesets:

async def merge_example(cxt):
    gather = GatherRuleset(
        to_gather=["style_rules", "grammar_rules"],
        output_key="all_rules",
    )
    combined = await gather._execute(**cxt)
    # combined is RuleSet.gather(style_rules, grammar_rules)

Package Structure

fabricatio-rule/
├── python/fabricatio_rule/
│   ├── actions/
│   │   └── rules.py           # DraftRuleSet, GatherRuleset
│   ├── capabilities/
│   │   ├── check.py           # Check mixin
│   │   └── censor.py          # Censor mixin
│   ├── models/
│   │   ├── rule.py            # Rule, RuleSet
│   │   ├── patch.py           # RuleSetMetadata
│   │   └── kwargs_types.py    # CheckKwargs
│   └── config.py              # RuleConfig, rule_config
└── python/tests/
    ├── test_check.py
    └── test_ruleset.py

Dependencies

  • fabricatio-core — base interfaces, templates, action infrastructure
  • fabricatio-improveImprovement model and Correct capability
  • fabricatio-judgeEvidentlyJudge for violation detection
  • fabricatio-capabilities — base capability patterns (Patch, ProposedUpdateAble)

License

MIT — see LICENSE

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fabricatio_rule-0.1.15-py3-none-any.whl (21.0 kB view details)

Uploaded Python 3

File details

Details for the file fabricatio_rule-0.1.15-py3-none-any.whl.

File metadata

  • Download URL: fabricatio_rule-0.1.15-py3-none-any.whl
  • Upload date:
  • Size: 21.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for fabricatio_rule-0.1.15-py3-none-any.whl
Algorithm Hash digest
SHA256 0be92e31da29c03ec133e696363337659f05d16243b752ba75fad067391edbea
MD5 76e4b86f1241baa7fbf6059dd4aada32
BLAKE2b-256 59f3ab4daca087a38f5b3f7a2c1b8b36c89cc63b1cc7590ef6434b52d3d9050d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page