Skip to main content
Python · Apache 2.0

Rules for what you know. LLM for what you don't.

A small, typed, declarative rules engine for Python. Replace brittle if/elif chains with typed, composable predicates - and route only genuine edge cases to the model.

pip install ai-rules-engine

ticket_router.py
from airules import Fact, KnowledgeEngine, Rule, Default, StringField
from pydantic_ai import Agent
class Ticket(Fact):
subject: StringField
body: StringField
class TicketRouter(KnowledgeEngine[Ticket, Team]):
@Rule(Ticket.subject.contains("billing", case_insensitive=True)
| Ticket.body.contains("invoice", case_insensitive=True))
def billing(self, ticket: Ticket) -> Team:
return Team.BILLING
@Rule(Ticket.subject.contains("password", case_insensitive=True))
def auth(self, ticket: Ticket) -> Team:
return Team.AUTH
@Default
def llm_fallback(self, ticket: Ticket) -> Team:
# Only reached for inputs no rule could predict
return agent.run_sync(ticket.subject).output

Fully Typed

KnowledgeEngine[FactType, ReturnType] - your editor catches misspelled fields and mismatched return types before you run anything. Pyright strict-friendly throughout.

Zero-Cost Pre-Filter

Deterministic rules evaluate in microseconds at zero API cost. Only inputs that fall outside every rule reach the model - the ones that genuinely need reasoning.

Serializable Rules

Predicates compose with & | ~ and round-trip through to_dict(). Call describe() to dump the entire rule set - diff deployments, build a rules editor, or feed it back into the LLM so it knows exactly what's already covered.

The two-tier pattern

Most decisions in production are already known. A rules engine handles them for free. The LLM handles the rest.

Incoming fact
Typed input - a ticket, event, request, or any structured data
KnowledgeEngine
Evaluates rules top-to-bottom. First match wins. Returns instantly at zero cost.
↓ if no rule matched
@Default → LLM
The model only sees the genuinely unknown inputs - and it sees the full rule set so it won't contradict a rule that already exists.

Ready to cut your LLM spend?

Add a rules layer in front of your model in minutes.