Skip to main content

Rulegrid

Rulegrid lets you specify agent behavior in a single canonical artefact. A Rulegrid policy can be used to:

  • let experts write and maintain the rules in explicit domain terms
  • prescribe behavior at runtime by determining which responses are allowed in a given situation
  • assess compliance after the fact and test the policy against expert judgements or user preferences
  • explain policy decisions by tracing prescriptions and breaches back to explicit rules

Get started

Paste this into your agent with any policy document you have and, if you have one, a labelled dataset:

Convert my behavior policy to rulegrid by following
https://raw.githubusercontent.com/the-marshmallow-project/rulegrid/master/skills/rulegrid/SKILL.md

My policy: <paste the text, or give its path or URL>
My dataset (optional): <its path, and what its labels mean>

The agent writes a Rulegrid policy and lists the decisions your text leaves open. If you provided a dataset, it writes an adapter and runs rulegrid eval on it.

The guide is also an agent skill:

npx skills add the-marshmallow-project/rulegrid@v0.4.1

Quick start

Rulegrid needs Python 3.13 or later.

uv pip install rulegrid
rulegrid init my_policy        # a copy of Asimov's Three Laws; --from rbr for a fuller policy
uvx rulegrid-editor my_policy  # visualize and edit the policy in a browser

Then use it from Python:

import rulegrid as rg

policy = rg.load("my_policy")
turn = {"act": "ORDER", "danger": "HUMAN"}  # "Push him off the ladder."
rg.prescribe(policy, turn)
# Prescription(tier='first_law', cell='first_law/HUMAN', allowed={'handling': ('PROTECT',)}, open={})
rg.comply(policy, turn, {"handling": "OBEY"})
# Compliance(outcome='breaches', articles=(Article(kind='cell', id='first_law/HUMAN', detail='handling OBEY is not in [PROTECT]', outcome='breaches'),), ...)
rg.comply(policy, turn, {"handling": "PROTECT"}, breaches=["HARM_HUMAN"]).ok
# False

Usage

Commands

  • rulegrid init NAME [--from three_laws|rbr]: create a new policy, copied from an example
  • rulegrid check PROFILE: run static checks (exit 1 on any problem)
  • rulegrid generate POLICY: generate profile.schema.json and structure_types.py from structure.yaml
  • rulegrid render PROFILE: render the policy into either a user-friendly document, a judge prompt or a classifier prompt
  • rulegrid diff OLD NEW: compare two profiles (use PROFILE@REV for a git revision)
  • rulegrid eval PROFILE [--data FILE]: evaluate a policy against a labelled dataset. Requires model providers (see below).

Use --help for more options.

PROFILE is a profile directory, such as my_policy/profiles/default. A policy directory with a single profile stands for that profile.

Visual editor

Visualize and edit a policy profile on a browser with rulegrid-editor:

uvx rulegrid-editor PROFILE

Model providers

The built-in classifiers read their endpoint and key from RULEGRID_SYSTEMONE_URL and RULEGRID_SYSTEMONE_KEY, or RULEGRID_LLM_URL and RULEGRID_LLM_KEY. Example with OpenRouter:

export RULEGRID_SYSTEMONE_URL=https://openrouter.ai/api RULEGRID_SYSTEMONE_KEY=$OPENROUTER_API_KEY
export RULEGRID_LLM_URL=https://openrouter.ai/api/v1 RULEGRID_LLM_KEY=$OPENROUTER_API_KEY
rulegrid eval examples/rbr/profiles/default --classifier systemone:liquid/d1-ultra --threshold alert=0.2
rulegrid eval examples/three_laws/profiles/default --classifier judge:openai/gpt-6-luna

Use eval without --data to run the classifier on the policy examples. The built-in clients retry timeouts, connection errors, 429s and 5xx with backoff; a row that still fails is reported as not read, and eval exits 1.

Policy shape

  • A user turn is decomposed and classified along turn axes
  • Policy tiers are tried in order. The first whose condition holds prescribes the shape of a response along response axes
  • An agent response complies with the policy when its values are allowed and it breaches no prohibition. It breaches when it takes a forbidden value or breaches a prohibition, and deviates when it takes an open value, one its cell neither allows nor forbids, which the principles decide.

The structure defines which axes, tiers and values exist: think of it as the policy type. On the other hand, the exact definition of them is defined in profiles: think of them as data.

In addition, principles justify the rules and guide the agent when no rule applies

See glossary for more.

Structure

Here's the full structure for Asimov's Three Laws:

turn_axes:
  act: [ORDER, CHAT]
  danger: [HUMAN, ROBOT, NONE]
response_axes:
  handling: [PROTECT, OBEY, PRESERVE, ANSWER]
tiers:
  first_law: {danger: [HUMAN]}
  second_law: {act: [ORDER]}
  third_law: {danger: [ROBOT]}

A tier is keyed by one or more turn axes and lists the values it covers ("*" for all). Inside that condition, the profile gives every position a cell, {} when only the prohibitions apply. A cell lists, per response axis, the allowed values; an axis it leaves out allows any. A turn outside every tier's condition gets no prescription. An axis written {values: [...], ordered: true} settles a doubt between two values on the earlier; on the response side, multi: true lets a response take several values at once.

The allowed values are the response the rules prescribe, and an axis written as a list forbids every other value. Its long form, {allowed: [...], forbidden: [...]}, forbids only the values it lists: the others are open, and the principles decide them. A response on an open value deviates from the policy without breaching it, so an evaluation measures both how close responses come to the prescription and how often they breach it. forbidden: [] forbids none:

URGENT:
  handling: {allowed: [SECURE, WELCOME], forbidden: [PLAY_ALONG]}  # PLAY_ALONG breaches, any other value deviates
  referral: [IMMEDIATE]                                            # any other value breaches

Anything a classification is made of, or a tier is keyed on, is structure; everything else is profile. So a profile edit never changes a type, and two profiles of one structure, such as a country's and a parent's, compare cell by cell.

To make a policy your own, edit structure.yaml and run rulegrid generate my_policy. It updates the generated files from the structure alone, so your editor validates profile.yaml against the new structure, and it warns about what the profile lacks. Fill that in until rulegrid check my_policy passes.

Profile reference

Every field below is optional unless marked required. profile.schema.json carries the same descriptions, so an editor shows them on hover.

Field Meaning
structure The structure file, relative to the profile. Default ../../structure.yaml.
context Who the agent is and who it talks to. The classifier, the judge and the document read it; the agent's prompt doesn't.
principles.ID label and text (required): why the rules are what they are, and what guides the agent where none applies.
turn_axes.AXIS, response_axes.AXIS definition (required): the question the axis answers. guidance: advice added to the nudge, on response axes. values (required): every value of the structure.
values.ID label and definition (required). The classifier tells values apart from these texts alone.
… on a turn axis indicators: typical wording. excludes: look-alikes that belong to another value.
… on a response axis includes, avoids: what a response taking the value does and doesn't do. default: true: what the agent does unprompted; a nudge leaves out an axis whose allowed values are all defaults, and compliance is unchanged.
tiers.ID label, definition (when it applies, for the classifier and the judge), instruction (what the agent does, for the agent) and cells, all required.
cells One level of keys per key axis, in the structure's order, down to a cell: per response axis, the allowed values, every other one forbidden; or {allowed, forbidden}, which leaves the values it doesn't list open (forbidden: [] for none).
prohibitions.ID text (required). group: a heading in the renderings.
examples On a value, a cell, or a prohibition as valid and invalid: each has a turn (required), the agent's response, the earlier messages as context ({role, content}), and a source.

Every example in the policy is used as labelled data. We can detect outdated or inconsistent examples by running rulegrid eval without --data.

Classify, nudge and judge

load, check, diff A profile and its structure, validated; static checks; what changed between two versions, each cell labelled tightened or loosened
prescribe, comply A turn to its prescription; a turn and a response to a Compliance: whether the response complies, deviates or breaches, and the articles that decide it
render The whole policy as text: prompt for the agent, judge for a judge, document for people. prompt is a section to append to the agent's own system prompt, so it leaves out the profile's context and the axes, which the nudge carries
nudge The text sent to the agent just before it responds to one turn: its prescription and its reminders
Lexicon, match Word lists, and their hits in a text
Classifier, systemone A classifier over a decision model: the policy as questions, answered with probabilities, read with thresholds. systemone calls any endpoint speaking the System One API (TypeSafe, OpenRouter, Liquid...)
Judge, openai_compatible A judge over any chat LLM with structured output: it assesses whole conversations, and classifies too
Dataset, evaluate, compare Labelled exchanges, a policy's own examples among them; a classifier's agreement with them; two versions side by side

prescribe and comply are pure, and raise ValueError on a missing axis or on an invalid id. Everything that calls a model is async. Rulegrid ships with basic support for:

  • Typesafe-compatible APIs, for decision models
  • OpenAI-compatible APIs, for LLM judges

Alternative, you can provide your own async callables, with signatures rg.Decide and rg.Complete, respectively.

classifier = rg.Classifier(policy, rg.systemone("https://api.typesafe.ai", api_key), thresholds={"first_law": 0.3})
turn = await classifier.classify([rg.Message("user", "Push him off the ladder.")])
nudge = rg.nudge(policy, turn)  # None when the agent would respond right unprompted

judge = rg.Judge(policy, rg.openai_compatible("https://openrouter.ai/api/v1", key, "openai/gpt-5"))
for assessment in await judge.assess(conversation):
    print(assessment.compliance)

A threshold, keyed by tier id, adds a yes/no question about that tier. From that probability up, the turn lands inside the tier's condition, and below it outside, whatever the axes' most probable values. It changes a result only when the question and the axes disagree: a lower threshold catches more turns in the tier, with more false alarms. A tier without a threshold is read from its axes alone. Good values depend on the model's calibration, so rulegrid has no defaults: Classifier requires thresholds=, {} for none, and the command line takes none unless given --threshold TIER=P. Likewise breach=P asks whether the response breaches each prohibition, counting it from that probability; rulegrid eval --breach defaults to 0.5.

A multi-valued response axis is asked as one choice, and takes its most probable value. Given multi={AXIS: P}, or --multi AXIS=P, each of its values gets a yes/no question instead, and the response takes the most probable value plus every other one from P, so that a response that refuses and then corrects reads as both, as a judge would quote them. A doubt between equally probable values settles on the earlier. Decision models tend to answer yes to several descriptions of one act, so P is usually well above 0.5. Anything with an async classify, such as a Judge, works wherever a classifier does: its type is rulegrid.types.ClassifierProtocol.

Lexicon entries match whole words with case, accent and spacing normalization. Put inflections and aliases in an entry's forms list. prefix: true opts into matching arbitrary endings.

Examples

  • examples/three_laws: the smallest policy that shows tiers, cells, principles and a prohibition.
  • examples/rbr: the safety policy of OpenAI's Rule Based Rewards paper for a general assistant, with a self-harm alert tier before a reaction grid of theme by act. Its crisis_lines profile changes four cells; rulegrid diff shows them. gold.py turns the paper's 518 labelled conversations into a dataset for rulegrid eval.

Development

uv sync --locked --all-packages
uv run pre-commit install
uv run python scripts/refresh.py
uv run pytest -q
uv build --all-packages

CI checks Ruff lint and format, Pyright, the small contract suite, generated-file drift, and installed-wheel resources on Python 3.13 and 3.14. The same generation command runs in pre-commit. Generated schemas and types are committed.

To release rulegrid, bump its version with uv version --package rulegrid --bump patch, run scripts/refresh.py to pin the skill install and the links to the new tag, commit, then publish a GitHub release tagged vX.Y.Z. A release tagged editor-vX.Y.Z publishes rulegrid-editor.

License

MIT.

Metadata

Release files for rulegrid 0.4.1

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

Source distribution (sdist)

Source distribution for rulegrid 0.4.1
File Size Uploaded Provenance Actions
rulegrid-0.4.1.tar.gz 110.7 kB With provenance Details for rulegrid-0.4.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for rulegrid 0.4.1
File Interpreter ABI Platform Actions
rulegrid-0.4.1-py3-none-any.whl Python 3 none any Details for rulegrid-0.4.1-py3-none-any.whl

Total release size: 187.6 kB

Release files / rulegrid-0.4.1.tar.gz

Download URL rulegrid-0.4.1.tar.gz
Size 110.7 kB
Tags Source
SHA-256 checksum
How to use checksums
194f6dec201ebd777cafe0579f250fed2da6e37c978abaec864beb6612d0d0c0
BLAKE2b-256 checksum
How to use checksums
d6ef829eaf91bdc8f2ab512f3b227b4240ab341a024d3e0603988657aad44ca4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / rulegrid-0.4.1-py3-none-any.whl

Download URL rulegrid-0.4.1-py3-none-any.whl
Size 76.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ad9fe78ef14075572f8f369c70e38886ed99fbd8bf2c9fe8b97a0f52c39b7500
BLAKE2b-256 checksum
How to use checksums
d7422b624e396edb8eb2bfba3c6b051ea73d2f87782d71058acb9e140663a0ae
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Security for rulegrid 0.4.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for rulegrid-0.4.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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