Skip to main content

Python SDK

pip install limitr

limitr runs the Limitr engine in-process, on Stof's native runtime, in Python 3.9 and later. It depends on stof (0.11.5 or later) and nothing else. It's the same engine as the TypeScript SDK, with the same policies, events, and Cloud connection.

from limitr import Limitr

limitr = Limitr(policy_text) # or Limitr.cloud(token)

The package is typed (py.typed): Decision, Customer, Cap, Estimate, and EntitlementSource are TypedDicts you can import from limitr.

Coming from TypeScript​

Every TypeScript method has a Python one, with these differences:

  • snake_case names: ensureCustomer is ensure_customer, addAltID is add_alt_id, docCall is doc_call.
  • No await. Methods are plain calls and return plain values.
  • Keyword arguments in place of option objects and long positional lists: reserve(customer, ent, context=...), add_customer_cap(id, 20, cap_id='budget', resets=True), allow(customer, ent, 1, detail=True).
  • None where TypeScript has null or undefined, and dicts and lists for records.
  • Events arrive as dicts, not JSON strings.
  • Times are ms since the epoch or a datetime (Ex. expires_on=datetime.now() + timedelta(days=14)).
  • Amounts are floats (3.0), since a meter can count fractions.
  • Errors raise: an invalid policy raises ValueError from Limitr(...). Calls themselves don't raise for unknown customers or entitlements; they're denied.

Creating the engine​

CallNotes
Limitr(policy='Limitr policy: {}', format='stof', validate=True)Loads the engine and the policy and validates it (raises ValueError with the message when invalid). policy is text (Stof, JSON, YAML, TOML), a dict with 'json', or bytes with 'bstf'. Limitr.new(...) is the same.
Limitr.cloud(token, ...)Connects to Limitr Cloud. The policy and customers come from Cloud. None when Cloud refuses the token.

Create one engine per process (or per policy) and keep it. It holds every customer's state in memory.

MethodReturns
valid()(ok, message)
version()The engine version.
set_max_execution_time(ms)Time limit for each policy call (default 5,000 ms; None for none).
difference(other, symmetric=False)A diff of two policies.
doc_call(path, *args)Calls any engine function, Ex. doc_call('policy.set_customer_refs', id, refs).
docThe underlying Stof document (a pystof.Doc). See Runtime.
module(name, data, setup=None)Load a Stof module (bytes) into the policy document. setup(doc) runs again after each Cloud policy update.
close()Send batched usage to Cloud and close the connection (nothing to do for a local engine).

Metering​

MethodReturnsNotes
allow(customer, entitlement, value=0, event=True, overhead=None, force=False, detail=False)bool, or a Decision with detailDecide and meter. event: True, False, or event data (a dict or text). overhead: the actual cost in runes. force: record usage that already happened. detail: return the decision and its reason (see Why a call was refused).
check(customer, entitlement, value=0, context=None, overhead=None, detail=False)bool, or a Decision with detailThe same decision, no changes.
increment(customer, entitlement, event=True) / decrement(...)boolBy the limit's increment.
check_increment(customer, entitlement) / check_decrement(...)bool
set(customer, entitlement, value, event=True)boolMoves the meter to value (allows the difference).
features(customer, context=None)list of names, or NoneEntitlements the customer can use now.

value can carry units in text ('250MB').

Reservations and estimates​

MethodReturns
reserve(customer, entitlement, value=None, context=None, basis=None, segment=None, ttl=None, quantile=0.9, overhead=None)Hold ID, or None when not allowed now.
settle(customer, entitlement, hold, value, event=True, overhead=None, basis=None, segment=None)bool
release(customer, entitlement, hold)bool
held(customer, entitlement)Room held now.
estimate(customer, entitlement, context=None, quantile=0.9, basis=None, segment=None){'value', 'overhead', 'samples', 'source', 'scope'} or None.
observe(customer, entitlement, value, context=None, overhead=None, basis=None, segment=None)bool

See Reservations and estimates.

Reads​

MethodReturns
value(customer, entitlement, percent=False, grants=True)Usage this period.
remaining(customer, entitlement, percent=False, grants=True)Room left (None for observe limits).
limit(id, entitlement, grants=True)The limit (id can be a plan).
allowance(customer, entitlement, grants=True)What can run now, counting the governor.
cost(id, entitlement)The standard increment.
resets(id, entitlement)When the meter resets next (ms).
rate(customer, entitlement) / acceleration(...)Usage per ms, and its change.
projected_exhaustion(customer, entitlement, smoothed=False, grants=True)When the limit runs out at this rate (ms).
entitlement(id, entitlement)The entitlement as the customer (or plan) has it.
meter_object(id, entitlement) / limit_object(id, entitlement)The meter and limit records.
remaining_credit(customer, credit)Grant balance in a credit.

Customers​

MethodReturnsNotes
ensure_customer(id, plan='', type='user', label='User', refs=None, alts=None, metadata=None)boolCreates it if missing. True if it was created. IDs can't contain a period (IDs).
create_customer(...) (same arguments)recordCreates or updates. None if it couldn't be created.
customer(id)Customer or None
customers()records by ID
customer_metadata(id) / customer_refs(id)
set_customer(record, event=True)Replace from a saved record.
ensure_set_customer(record, event=True)boolSet only if not loaded.
load_customers(records)A list, or a dict keyed by ID.
remove_customer(id)bool
set_customer_plan(id, plan, overwrite_meters=True)boolPass False to keep usage (the engine's own default). Included packs move by plan_change (Plan changes).
set_customer_period(id, start, end=None, event=True) / set_customer_expires(id, expires, event=True)bool
add_alt_id(existing, alt, event=True) / remove_alt_id(alt, event=True)boolFalse for an alt ID with a period.
create_customer_override(id, entitlement, value=None, expires_on=None, credit=None, mode=None, increment=None, resets=None, reset_inc=None, reset_sch=None)Per-customer limit.
remove_customer_override(id, entitlement)bool
give_entitlement(customer, entitlement, plan=None, expires_on=None)bool
take_entitlement(customer, entitlement, expires_on=None)bool
restore_entitlement(customer, entitlement)bool
set_customer_rules(customer, rules, event=True)boolThe customer's rules by name, replacing the ones it had.
entitlement_source(customer, entitlement)EntitlementSource or NoneWhere access and the limit come from.
apply_customer_topup(id, topup)bool
ensure_customer_included_topups(id, event=True)Grants included topups the customer is missing. Creating a customer and changing its plan already do this.
ensure_customer_plan_quantity(id)boolCharge the plan's subscription once (after its trial).

See Customers.

Spend caps and margin​

MethodReturns
add_customer_cap(id, value, cap_id='', credit='rune', exchangeable=None, ignore_grants=False, overage_only=False, observe_only=False, overhead_cost=False, follow_decrements=False, scope=None, resets=False, reset_inc=None, reset_sch=None, expires_on=None, send_events=True, hard_trailing=False, shared=False, shared_with=None)Cap or None.
customer_cap(id, cap_id)Cap or None.
reset_customer_cap(id, cap_id, event=True) / remove_customer_cap(...)bool
customer_margin_snapshot(customer)Revenue, cost, and margin this period (a dict).
margin_snapshot(plan, usage)Margin for hypothetical usage (usage is a dict of entitlement to amount).
start_margin_measurement(customer, cap_id, overage_only=True, ignore_grants=True, credit='rune', exchangeable=True)Starts measuring a session.
capture_margin_measurement(customer, cap_id, stop=True){'charged', 'costs', 'margin', 'raw_margin', 'charged_cap', 'costs_cap'} (margin in percent).

See Spend caps and Cost and margin.

Plans and credits​

MethodReturns
plan(id, default=True) / default_plan()A plan record.
set_plan(id, plan_stof) / delete_plan(id)Add, replace, or remove a plan.
plan_period(id) / plan_trial_period(id) / plan_sub_entitlement_name(id)
credit(id) / credit_for(id, entitlement)A credit record.
credit_exchange(in_credit, out_credit='rune', value=1)A conversion.
set_exchange_pair(name, value, currency='rune', event=True)Add or replace an exchange pair. False, with nothing changed, if it can't reach runes.
exchange_pair(name) / remove_exchange_pair(name, event=True)Read a pair ({'value', 'currency'}), or remove one.

Events​

MethodNotes
add_handler(name, handler)handler(key, value) gets every event. Objects arrive as dicts.
remove_handler(name) / clear_handlers()
set_notifications(contents, format='stof')Add notifications.

Handlers run during the call that sent the event. A handler that raises is logged (to the limitr logger) and never fails the call. An async def handler is scheduled on the running event loop, not awaited. A handler can't call back into the same engine while it runs (that call raises): record what you need from the event, and act on it after the call or on another thread. See Events.

Capabilities​

MethodReturns
set_capabilities(contents, format='stof')Adds capabilities.
capability(name)The capability.
run_capability(name, args=None, customer=None)Its result.
claude_tools(customer=None)Tool definitions for the Claude API.
claude_tool_use(tool_use, customer=None)Runs a tool_use block (a dict or JSON text); returns the tool_result.

See AI tools, Claude Agent SDK, and Claude Messages API.

Limitr Cloud​

Limitr.cloud(token, ...):

ArgumentDefaultNotes
token(required)Your Cloud API token.
policy'active'A policy ID, or the active policy.
connect_timeout5,000 msHow long to wait for the first connection. Raises CloudError when the policy doesn't arrive in time.
deny_unconnectedTrueDeny allow while disconnected, so servers can't drift apart.
validateTrueValidate the policy Cloud sends.
http_hostsTrueHosts the policy may call: True for any public host, a list for only those, False for none.
max_execution_time5,000 msTime limit for each policy call.
batch_ms250 msHow long to collect usage before sending it to Cloud together (0 sends each call right away).
MethodNotes
connectedWhether the Cloud connection is open (a property).
add_cloud_customer(id, timeout=3000)Fetch a customer from Cloud. Done for you on first use.
flush_cloud_batch()Send batched usage now.
close()Send batched usage and close. Call it on shutdown (Ex. atexit.register(limitr.close)).

The connection runs on a background thread, so your code never waits on it except to load a customer Cloud hasn't sent yet. See Connect your app.

Limitr Network​

MethodNotes
network(secret_key=None, key_store=None, name=None, channels=None, cloud=True)This policy's LimitrNetwork: serve its routes as a provider, or connect(url, plan, spend, expires) to a provider as a consumer.
allow_network_host(url)Let the policy reach a provider at a private address (Ex. http://localhost:8787 while testing).

LimitrNetwork.serve(handler, port) runs a provider on a small threaded HTTP server, and wsgi(handler) mounts it in any WSGI app. LimitrNetwork, NetworkCall, Request, and Response are exported from limitr. The Network tutorial walks through a provider and a consumer.

Threads and asyncio​

Each method call runs on its own, one at a time, so a single allow is safe under load. One engine is safe to share across threads (Ex. a WSGI server's workers): calls take turns behind a lock, and the GIL is released while the engine runs, so other Python threads keep going. With asyncio, call it directly: a local engine never touches the network.

Two calls in a row aren't one unit: another request can run between a check and the allow after it. Use reserve when concurrent calls mustn't overspend.

Skills for coding agents​

The limitr-py skill covers this SDK, next to limitr (policies, engine functions, events) and stof (the language). They're in the Claude Code plugin (/plugin marketplace add dev-formata-io/limitr) and packaged as zips in the repo's content/ folder. See the introduction.