# Python SDK

> Guard costly work with a with block, and call every API operation from Python, typed from the API itself.

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](/docs/reference/).

## Install

```bash
pip install limitry
```

## 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 the `LIMITRY_API_KEY` environment variable. If that isn’t set, it reads `LIMITRY_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](/docs/test-and-live/) explains the difference.
* With a **personal access token**, pass it as `token` and name the workspace. The token acts in test unless you name live: `Limitry(token=token, workspace="acme", environment="live")`.

## 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:

```python
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:

```python
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

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](/docs/rolling-and-concurrency/#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.

* `guard` and `reserve` take `timeout=`, 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=` and `extra_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 = n` sets what the work used. It takes a whole number from 0 to 1,000,000,000. It raises `ValueError` for 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

Every API operation is a method, named after the operation in the [API reference](/docs/reference/). For example, `limits.create` is `limitry.limits.create()`:

```python
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 `failMode` becomes `fail_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

* [`checks.create()`](/docs/reference/checks/#check-whether-a-subject-may-act)

  Check whether a subject may act

* [`checks.list()`](/docs/reference/checks/#list-checks)

  List checks

### Reservations

* [`reservations.commit()`](/docs/reference/reservations/#commit-a-reservation)

  Commit a reservation

* [`reservations.extend()`](/docs/reference/reservations/#extend-a-reservation)

  Extend a reservation

* [`reservations.get()`](/docs/reference/reservations/#get-a-reservation)

  Get a reservation

* [`reservations.release()`](/docs/reference/reservations/#release-a-reservation)

  Release a reservation

### Limits

* [`limits.archive()`](/docs/reference/limits/#archive-a-limit)

  Archive a limit

* [`limits.create()`](/docs/reference/limits/#create-a-limit)

  Create a limit

* [`limits.credits.create()`](/docs/reference/limits/#add-credits-to-a-balance)

  Add credits to a balance

* [`limits.credits.get()`](/docs/reference/limits/#get-a-credit)

  Get a credit

* [`limits.credits.list()`](/docs/reference/limits/#list-a-balances-credits)

  List a balance's credits

* [`limits.get()`](/docs/reference/limits/#get-a-limit)

  Get a limit

* [`limits.list()`](/docs/reference/limits/#list-limits)

  List limits

* [`limits.restore()`](/docs/reference/limits/#restore-an-archived-limit)

  Restore an archived limit

* [`limits.sync()`](/docs/reference/limits/#sync-limits-from-a-list)

  Sync limits from a list

* [`limits.update()`](/docs/reference/limits/#change-a-limit)

  Change a limit

### Subjects

* [`subjects.get()`](/docs/reference/subjects/#get-a-subject)

  Get a subject

* [`subjects.import_()`](/docs/reference/subjects/#name-many-subjects)

  Name many subjects

* [`subjects.list()`](/docs/reference/subjects/#list-subjects)

  List subjects

* [`subjects.names.delete()`](/docs/reference/subjects/#erase-a-subjects-name-and-labels)

  Erase a subject's name and labels

* [`subjects.reset()`](/docs/reference/subjects/#reset-a-subjects-limits)

  Reset a subject's limits

* [`subjects.standing()`](/docs/reference/subjects/#get-where-a-subject-stands)

  Get where a subject stands

* [`subjects.update()`](/docs/reference/subjects/#update-a-subject)

  Update a subject

### Usage

* [`usage.overview()`](/docs/reference/usage/#get-every-limits-usage-at-once)

  Get every limit's usage at once

* [`usage.query()`](/docs/reference/usage/#get-a-limits-usage-over-time)

  Get a limit's usage over time

* [`usage.subjects()`](/docs/reference/usage/#list-who-is-using-a-limit)

  List who is using a limit

### Workspace

* [`workspace.get()`](/docs/reference/workspace/#get-the-current-workspace)

  Get the current workspace

* [`workspace.invitations.list()`](/docs/reference/workspace/#list-pending-invitations)

  List pending invitations

* [`workspace.members.list()`](/docs/reference/workspace/#list-workspace-members)

  List workspace members

* [`workspace.plan_usage.get()`](/docs/reference/workspace/#get-your-plans-usage-this-period)

  Get your plan's usage this period

* [`workspace.teams.list()`](/docs/reference/workspace/#list-teams)

  List teams

### Webhooks

* [`workspace.event_types.list()`](/docs/reference/webhooks/#list-event-types)

  List event types

* [`workspace.webhook_deliveries.list()`](/docs/reference/webhooks/#list-an-endpoints-deliveries)

  List an endpoint's deliveries

* [`workspace.webhook_deliveries.redeliver()`](/docs/reference/webhooks/#redeliver-an-event)

  Redeliver an event

* [`workspace.webhook_endpoints.create()`](/docs/reference/webhooks/#add-a-webhook-endpoint)

  Add a webhook endpoint

* [`workspace.webhook_endpoints.delete()`](/docs/reference/webhooks/#remove-a-webhook-endpoint)

  Remove a webhook endpoint

* [`workspace.webhook_endpoints.enable()`](/docs/reference/webhooks/#re-enable-a-webhook-endpoint)

  Re-enable a webhook endpoint

* [`workspace.webhook_endpoints.get()`](/docs/reference/webhooks/#get-a-webhook-endpoint)

  Get a webhook endpoint

* [`workspace.webhook_endpoints.list()`](/docs/reference/webhooks/#list-webhook-endpoints)

  List webhook endpoints

* [`workspace.webhook_endpoints.test()`](/docs/reference/webhooks/#send-a-test-event)

  Send a test event

* [`workspace.webhook_endpoints.update()`](/docs/reference/webhooks/#update-a-webhook-endpoint)

  Update a webhook endpoint

### Approvals

* [`workspace.approval_actions.list()`](/docs/reference/approvals/#list-the-actions-you-can-ask-approval-for)

  List the actions you can ask approval for

* [`workspace.approval_requests.create()`](/docs/reference/approvals/#ask-a-person-to-approve-an-action)

  Ask a person to approve an action

* [`workspace.approval_requests.get()`](/docs/reference/approvals/#check-an-approval-request)

  Check an approval request

* [`workspace.approval_requests.redeem()`](/docs/reference/approvals/#redeem-an-approved-request)

  Redeem an approved request

### Audit events

* [`workspace.audit_events.list()`](/docs/reference/audit-events/#list-workspace-audit-events)

  List workspace audit events

### Personal access tokens

* [`user.me()`](/docs/reference/personal-access-tokens/#get-the-current-user)

  Get the current user

* [`user.revoke_token()`](/docs/reference/personal-access-tokens/#revoke-the-token-making-this-request)

  Revoke the token making this request

## 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`.

```python
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 names
print(limit.to_json())
```

* `to_dict()` and `to_json()` return the fields the API sent, with the API’s field names.
* The models are in `limitry.types`, such as `limitry.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 `datetime` objects.

## Lists

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:

```python
for limit in limitry.limits.list():
    print(limit.name)
```

To work one page at a time, use the page itself:

```python
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](/docs/pagination/).

## Errors

Every error the SDK raises is a `LimitryError`, including `LimitReachedError` and `UnavailableError`. When the API returns an [error](/docs/errors/), 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__`.

```python
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

These apply to every method. `guard` and `reserve` keep their own, shorter `timeout=`, as [If your code can’t reach Limitry](#if-your-code-cant-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-After` asks, up to 60 seconds. When the API asks for longer, the SDK raises the error instead.
* Every write sends an [idempotency key](/docs/idempotency/), 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 to `with_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:

```python
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

| 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.

## Async

`AsyncLimitry` has the same methods, and you `await` each call. `guard` and `reserve` become `async with`:

```python
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:

```python
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.
