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

License

MIT — see LICENSE

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.16-py3-none-any.whl (21.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: fabricatio_rule-0.1.16-py3-none-any.whl
  • Upload date:
  • Size: 21.3 kB
  • Tags: Python 3
  • Uploaded using 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}

File hashes

Hashes for fabricatio_rule-0.1.16-py3-none-any.whl
Algorithm Hash digest
SHA256 cd46f2c8b422ed381dd7735602c07529b2afed5d735e7f1d04f93857feee6d5f
MD5 f7bd49bbd1083492a96760345b207414
BLAKE2b-256 888d5e531f421d3fa725f4d4ba01cd07f38b4e661727f7e66ff60794fa274a57

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.1.16 This release

1 file

0.1.15

1 file

0.1.13

1 file

0.1.12

1 file

0.1.11

1 file

0.1.10

1 file

0.1.9

1 file

0.1.8

1 file

0.1.7

1 file

0.1.6

1 file

0.1.5

1 file

0.1.4

1 file

0.1.3

1 file

0.1.1

1 file

0.1.0

2 files

Supported by

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