Skip to main content

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

All options below are read through the fabricatio configuration chain (see the Configuration Guide). Set them under the [ext.rule] table in fabricatio.toml, equivalently under [tool.fabricatio.ext.rule] in pyproject.toml, or via FABRICATIO_EXT__RULE__<FIELD_UPPER> environment variables.

[ext.rule]
ruleset_requirement_breakdown_template = "built-in/ruleset_requirement_breakdown"
rule_requirement_template = "built-in/rule_requirement"
check_string_template = "built-in/check_string"
Option Type Default Description
ruleset_requirement_breakdown_template str "built-in/ruleset_requirement_breakdown" The name of the ruleset requirement breakdown template which will be used to breakdown a ruleset requirement.
rule_requirement_template str "built-in/rule_requirement" The name of the rule requirement template which will be used to generate a rule requirement.
check_string_template str "built-in/check_string" The name of the check string template which will be used to check a string.

Access at runtime: from fabricatio_rule.config import rule_config.

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-improve — Improvement model and Correct capability
  • fabricatio-judge — EvidentlyJudge for violation detection
  • fabricatio-capabilities — base capability patterns (Patch, ProposedUpdateAble)

License

MIT — see LICENSE

Metadata

Release files for fabricatio-rule 0.1.16

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distribution (wheel)

Table of built distributions (wheels) for fabricatio-rule 0.1.16
File Interpreter ABI Platform
fabricatio_rule-0.1.16-py3-none-any.whl Python 3 none any Details

Release files / fabricatio_rule-0.1.16-py3-none-any.whl

Download URL fabricatio_rule-0.1.16-py3-none-any.whl
Size 21.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cd46f2c8b422ed381dd7735602c07529b2afed5d735e7f1d04f93857feee6d5f
BLAKE2b-256 checksum
How to use checksums
888d5e531f421d3fa725f4d4ba01cd07f38b4e661727f7e66ff60794fa274a57
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","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}
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page