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.3.0
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',)})
rg.comply(policy, turn, {"handling": "OBEY"})
# Compliance(ok=False, articles=(Article(kind='cell', id='first_law/HUMAN', detail='handling OBEY is not in [PROTECT]'),), ...)
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 examplerulegrid check PROFILE: run static checks (exit 1 on any problem)rulegrid generate POLICY: generate profile.schema.json and structure_types.py from structure.yamlrulegrid render PROFILE: render the policy into either a user-friendly document, a judge prompt or a classifier promptrulegrid diff OLD NEW: compare two profiles (usePROFILE@REVfor 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.
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.
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. |
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 that cites its articles |
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. 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. Itscrisis_linesprofile changes four cells;rulegrid diffshows them.gold.pyturns the paper's 518 labelled conversations into a dataset forrulegrid 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.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| rulegrid-0.3.0.tar.gz | 104.2 kB | With provenance | Details for rulegrid-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| rulegrid-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for rulegrid-0.3.0-py3-none-any.whl |
Total release size: 177.0 kB
Release files / rulegrid-0.3.0.tar.gz
| Download URL | rulegrid-0.3.0.tar.gz |
|---|---|
| Size | 104.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
7f6a41fb6f5b52b8ad00dc476ccabd5ce4aa204fc2c76634f851abbaffca83ec
|
|
BLAKE2b-256 checksum How to use checksums |
51265aeb5599363fd9865d3e35d58d976937d15af376cbdb1cf3cfb7fc2e17e3
|
| 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 15, 2026.
Transparency logRelease files / rulegrid-0.3.0-py3-none-any.whl
| Download URL | rulegrid-0.3.0-py3-none-any.whl |
|---|---|
| Size | 72.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4f53112c89a8f55f51c359616f73cd0e4be063f7820e088742131579aab58312
|
|
BLAKE2b-256 checksum How to use checksums |
4a3498bb852255b3f261070c3273b15c6349c1262b5e3fa29c7eb8a3185b532a
|
| 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 15, 2026.
Transparency logSecurity for rulegrid 0.3.0
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.
Attestation for rulegrid-0.3.0.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 15, 2026.
Transparency logA 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.