checks.create() Python SDK
The Python SDK is a small typed client for Python 3.10 and later.
guard and reserve put a limit around your code in a with block.
Every API operation is also a typed method, and its shape comes from the
same definitions the API uses to validate requests. The SDK always
matches the API reference.
Install
Section titled “Install”pip install limitryYour key
Section titled “Your key”Create an API key in the app under Settings → Developers. Give the key your app runs with Check limits. Give a script that also creates limits, subjects or credits Manage limits.
Limitry()reads your key from theLIMITRY_API_KEYenvironment variable. If that isn’t set, it readsLIMITRY_TOKEN, the variable the CLI uses. If you set neither, it raises an error naming the variable.- To pass the key yourself, use
Limitry(api_key=key). - A test key (
lim_test_…) acts in test, and a live key (lim_live_…) acts in live. Test and live explains the difference. - With a personal access token, pass it as
tokenand name the workspace. The token acts in test unless you name live:Limitry(token=token, workspace="acme", environment="live").
Guard costly work
Section titled “Guard costly work”Say each of your users has a $2 AI budget a month, counted in cents. You
only know what a reply cost once it’s done. reserve holds what the
reply will probably cost (5 cents here), runs the block, then charges
what it actually cost. If the block raises, reserve releases the hold:
from limitry import LimitReachedError, Limitry, UnavailableError
limitry = Limitry() # uses the LIMITRY_API_KEY environment variable
try: with limitry.reserve( subject={"kind": "user", "id": "user_123"}, action="ai-call", cost=5 ) as reservation: response = call_model(prompt) reservation.cost = price_cents(response.usage) # your prices, in cents print(response.text)except LimitReachedError as error: print(f"Try again in {error.retry_after_seconds} seconds")except UnavailableError as error: print(f"No decision ({error.reason}), and this limit fails closed")A refusal raises LimitReachedError. Its reason is limit_reached
or too_many_reservations. It also carries limit_id, limit_name,
retry_after_seconds and the whole decision.
Both errors share the base class LimitryError, as every error the SDK
raises does. A mistake in your request, such as an action name that
isn’t valid, raises the API’s error instead, such as
BadRequestError.
When every request costs the same, guard is simpler. It checks the limit,
then runs the block only if Limitry allows it. Here it counts one
request to your API against a limit of 60 a minute for each key:
from limitry import Limitry
limitry = Limitry() # uses the LIMITRY_API_KEY environment variable
with limitry.guard(subject={"kind": "apikey", "id": "key_42"}, action="api-request"): response = handle_request(request) print(response)If your code can’t reach Limitry
Section titled “If your code can’t reach Limitry”If guard or reserve gets no decision, each limit’s fail mode decides.
With open, the work runs. With closed, they raise
UnavailableError, and never LimitReachedError. Its reason says
what happened: timeout, unreachable, plan_limit_reached or
rate_limited. Its __cause__ holds the failure itself.
“No decision” means one of these, within timeout (1.5 seconds by
default) and counting every retry:
| What happened | What the SDK does |
|---|---|
A network error, or a 408, 429, 500, 502, 503 or 504 |
Retries at most twice with the same key, then the fail mode decides. |
A 402, because the workspace is past its plan |
The fail mode decides. |
A 503 with the code moving or busy |
Retries with the same key while the wait still fits, then the fail mode decides. |
A 503 with moving means a busy workspace’s counts are moving between
Limitry’s servers, which takes a few seconds. One with busy means
there were too many checks at once, and Limitry charged nothing. Each retry waits for the response’s Retry-After, or a second if that’s shorter.
It then adds a random backoff that grows each time, so clients don’t all
retry together.
A concurrent limit that fails open still runs no more than its
amount at once in your process. Past that, reserve raises
UnavailableError. Concurrency
explains why.
The commit or release after the block gets the same time as the check. If a commit doesn’t get through in that time, the SDK lets it go. The block’s work stands. The reservation expires with no charge. Limitry never counts that work. This happens only while Limitry is moving counts or has too much to do.
guardandreservetaketimeout=, the most a check adds to your request, its tries included. It’s in seconds.- They also take
fail_mode=to fix the fail mode for every limit,idempotency_key=andextra_headers=. - When a guard’s check times out and its limits fail open, the block
runs. The guard then finishes the check after the block, within
timeout, so it counts once. reservation.cost = nsets what the work used. It takes a whole number from 0 to 1,000,000,000. It raisesValueErrorfor anything else, before the work’s usage could be lost.reservation.extend()raises the API’s error, for example when the reservation has already expired.
Methods
Section titled “Methods”Every API operation is a method, named after the operation in the
API reference. For example, limits.create is
limitry.limits.create():
from limitry import Limitry
limitry = Limitry() # uses the LIMITRY_API_KEY environment variable
limit = limitry.limits.create( name="AI budget", subject={"kind": "user"}, action="ai-call", amount=200, unit="cents", window="month",)limits = limitry.limits.list()print(limit.id, len(limits.items))- Ids in the path are arguments, and everything else is a keyword
argument in Python’s style, so
failModebecomesfail_mode=. - Because the types come from the API itself, your editor completes every method, keyword argument and response field.
Here is every method. Each one links to its fields and a full example under Endpoints:
Checks
- Check whether a subject may act
checks.list() - List checks
Reservations
reservations.commit() - Commit a reservation
reservations.extend() - Extend a reservation
reservations.get() - Get a reservation
reservations.release() - Release a reservation
Limits
limits.archive() - Archive a limit
limits.create() - Create a limit
limits.credits. create() - Add credits to a balance
limits.credits. get() - Get a credit
limits.credits. list() - List a balance's credits
limits.get() - Get a limit
limits.list() - List limits
limits.restore() - Restore an archived limit
limits.sync() - Sync limits from a list
limits.update() - Change a limit
Subjects
subjects.get() - Get a subject
subjects.import_() - Name many subjects
subjects.list() - List subjects
subjects.names. delete() - Erase a subject's name and labels
subjects.reset() - Reset a subject's limits
subjects.standing() - Get where a subject stands
subjects.update() - Update a subject
Usage
usage.overview() - Get every limit's usage at once
usage.query() - Get a limit's usage over time
usage.subjects() - List who is using a limit
Workspace
workspace.get() - Get the current workspace
workspace.invitations. list() - List pending invitations
workspace.members. list() - List workspace members
workspace.plan_usage. get() - Get your plan's usage this period
workspace.teams. list() - List teams
Webhooks
workspace.event_types. list() - List event types
workspace.webhook_deliveries. list() - List an endpoint's deliveries
workspace.webhook_deliveries. redeliver() - Redeliver an event
workspace.webhook_endpoints. create() - Add a webhook endpoint
workspace.webhook_endpoints. delete() - Remove a webhook endpoint
workspace.webhook_endpoints. enable() - Re-enable a webhook endpoint
workspace.webhook_endpoints. get() - Get a webhook endpoint
workspace.webhook_endpoints. list() - List webhook endpoints
workspace.webhook_endpoints. test() - Send a test event
workspace.webhook_endpoints. update() - Update a webhook endpoint
Approvals
workspace.approval_actions. list() - List the actions you can ask approval for
workspace.approval_requests. create() - Ask a person to approve an action
workspace.approval_requests. get() - Check an approval request
workspace.approval_requests. redeem() - Redeem an approved request
Audit events
workspace.audit_events. list() - List workspace audit events
Personal access tokens
user.me() - Get the current user
user.revoke_token() - Revoke the token making this request
Responses
Section titled “Responses”A method returns a model of the response. Its fields are attributes in
Python’s style, so the API’s failMode is limit.fail_mode.
from limitry import Limitry
limitry = Limitry() # uses the LIMITRY_API_KEY environment variable
limit = limitry.limits.get("lmt_123")print(limit.name, limit.fail_mode)
print(limit.to_dict()) # the API's own field namesprint(limit.to_json())to_dict()andto_json()return the fields the API sent, with the API’s field names.- The models are in
limitry.types, such aslimitry.types.Limit. Each one is a pydantic model. - The SDK keeps a field the API adds later. You can read it by its API name until you update the SDK.
- The SDK also keeps a value it doesn’t know yet, such as a new status, as it came. It never raises an error.
- Timestamps are
datetimeobjects.
A list method returns its first page. When you iterate over the page, the SDK fetches the next pages as it goes, so the loop sees every item:
for limit in limitry.limits.list(): print(limit.name)To work one page at a time, use the page itself:
page = limitry.limits.list(limit=10)print(page.items, page.next_cursor)if page.has_next_page(): page = page.get_next_page()Read more about pagination.
Errors
Section titled “Errors”Every error the SDK raises is a LimitryError, including
LimitReachedError and UnavailableError. When the API returns an
error, the SDK raises an APIError of the class for its
HTTP status:
| Status | Error |
|---|---|
| 400 | BadRequestError |
| 401 | AuthenticationError |
| 402 | PlanLimitError |
| 403 | PermissionDeniedError |
| 404 | NotFoundError |
| 409 | ConflictError |
| 422 | UnprocessableEntityError |
| 429 | RateLimitError |
| 500 or above | InternalServerError |
| Any other | APIError |
An APIError carries these attributes:
| Attribute | What it holds |
|---|---|
status_code |
The HTTP status. |
code |
The error’s code, such as not_found. |
message |
What went wrong. |
request_id |
The request’s id. Quote it when you contact us. |
details |
What was wrong with each field, as {"path", "message"} entries. |
docs |
A link to the code’s entry on the Errors page. |
headers |
The response’s headers, such as Retry-After. |
When the SDK can’t reach the API, it raises an APIConnectionError. An
attempt that runs out of time raises an APITimeoutError, a kind of
APIConnectionError. Either one keeps the network error as its
__cause__.
from limitry import APIConnectionError, Limitry, NotFoundError
limitry = Limitry() # uses the LIMITRY_API_KEY environment variable
try: limit = limitry.limits.get("lmt_123") print(limit.name)except NotFoundError: print("No such limit")except APIConnectionError: print("The API couldn't be reached. Try again later.")Retries and timeouts
Section titled “Retries and timeouts”These apply to every method. guard and reserve keep their own,
shorter timeout=, as
If your code can’t reach Limitry
shows.
The SDK retries a failed attempt twice: after a network error, a
timeout, or a 408, 429, 500, 502, 503 or 504. It doesn’t
retry a 501.
- It waits as long as
Retry-Afterasks, up to 60 seconds. When the API asks for longer, the SDK raises the error instead. - Every write sends an idempotency key, the same on each retry, so the write happens only once.
- To make your own retries safe too, pass your key:
idempotency_key=key. - To change how often it retries, pass
max_retries=to the client or towith_options().
Each attempt waits up to 60 seconds for a response. The SDK retries a
timed-out attempt with the same key. To change the limit, pass
timeout= in seconds to the client, to one call, or to
with_options() for the calls made through it:
limitry.limits.list(timeout=5)limitry.with_options(timeout=5, max_retries=0).limits.list()To limit a whole AsyncLimitry call, retries included, wrap it in
asyncio.timeout(). Past it, the call stops at once, even while it
waits to retry, and raises a TimeoutError.
Client options
Section titled “Client options”| Option | What it does |
|---|---|
api_key |
Your API key. Without it, LIMITRY_API_KEY. |
token |
A personal access token, used with workspace. Without it, LIMITRY_TOKEN. |
workspace |
The workspace a personal access token acts in. |
environment |
test or live, for a personal access token. Without it, test. |
base_url |
The API’s address, without /v1. Without it, LIMITRY_BASE_URL, then the live API. |
timeout |
The seconds each attempt may take. 60 by default. |
max_retries |
How many times to retry a failed attempt. 2 by default. |
default_headers |
Headers to send with every call. |
http_client |
Your own httpx.Client, or httpx.AsyncClient for AsyncLimitry. |
Every method also takes these keyword arguments:
| Argument | What it does |
|---|---|
idempotency_key |
Your key for this write. Writes only. |
extra_headers |
Headers to send with this call only. |
timeout |
The seconds each attempt of this call may take. |
with_options() takes timeout, max_retries and default_headers. It
returns the same client with those defaults. Its default_headers go
with the client’s own, not in place of them.
AsyncLimitry has the same methods, and you await each call. guard
and reserve become async with:
import asyncio
from limitry import AsyncLimitry
async def main() -> None: async with AsyncLimitry() as limitry: async with limitry.reserve( subject={"kind": "user", "id": "user_123"}, action="ai-call", cost=5 ) as reservation: response = await call_model(prompt) reservation.cost = price_cents(response.usage) print(response.text)
asyncio.run(main())Cancelling the task stops the check at once, for example with
asyncio.timeout() around the async with. The block never runs, and
no fail mode applies.
A list is the exception to await. You await it for its first page,
or use async for to go through every item:
from limitry import AsyncLimitry
async def print_limits(limitry: AsyncLimitry) -> None: async for limit in limitry.limits.list(): print(limit.name)async with closes the client when the block ends. Without it, call
await limitry.close() when you’re done.