# Use Limitry with LiteLLM

> Give each of your users an AI budget on the LiteLLM proxy or in the LiteLLM SDK, charged at the cost LiteLLM works out for each call.

LiteLLM gives your product one API for every model, and works out what each call cost. Limitry charges that cost to each of your users’ budgets. LiteLLM’s own budgets for keys and teams keep working beside it, and your users each get an allowance of their own.

## 1. Create the budget

Create the 200-cent monthly budget from [Limit AI spend per user](/docs/guides/limit-ai-spend/#1-create-the-budget). It counts in cents, with the action `ai-call`.

## 2a. On the LiteLLM proxy

One hook file gives every request through the proxy a budget check. Before the call, it reserves a few cents for the user the request names. After the call, it commits the cost LiteLLM reports. Save it next to your `config.yaml` as `limitry_budget.py`:

```python
import math

import litellm
from fastapi import HTTPException
from limitry import AsyncLimitry
from litellm.integrations.custom_logger import CustomLogger

# Uses the LIMITRY_API_KEY environment variable.
limitry = AsyncLimitry()

def cents(dollars: float | None) -> int:
    return math.ceil((dollars or 0) * 100)

class LimitryBudget(CustomLogger):
    async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):
        if not data.get("user"):
            raise HTTPException(status_code=400, detail="Name the user in `user`.")
        decision = await limitry.checks.create(
            subject={"kind": "user", "id": data["user"]},
            action="ai-call",
            cost=5,
            mode="reserve",
        )
        if not decision.allowed or decision.reservation is None:
            raise HTTPException(status_code=429, detail="This user's AI budget has run out.")
        data.setdefault("metadata", {})["limitry_reservation"] = decision.reservation.id
        return data

    async def async_post_call_success_hook(self, data, user_api_key_dict, response):
        reservation_id = data["metadata"]["limitry_reservation"]
        cost = cents(response._hidden_params.get("response_cost"))
        await limitry.reservations.commit(reservation_id, cost=cost)
        return response

    async def async_post_call_streaming_iterator_hook(
        self, user_api_key_dict, response, request_data
    ):
        chunks = []
        async for chunk in response:
            chunks.append(chunk)
            yield chunk
        reply = litellm.stream_chunk_builder(chunks, messages=request_data["messages"])
        reservation_id = request_data["metadata"]["limitry_reservation"]
        cost = cents(litellm.completion_cost(reply))
        await limitry.reservations.commit(reservation_id, cost=cost)

proxy_handler_instance = LimitryBudget()
```

Then point the proxy at it in `config.yaml`:

```yaml
litellm_settings:
  callbacks: limitry_budget.proxy_handler_instance
```

Your app names the user in the `user` field of each request, as the OpenAI API does. Every language and SDK that talks to the proxy works unchanged.

## 2b. In the LiteLLM SDK

Calling LiteLLM from your own Python code? Reserve around the call, and commit LiteLLM’s price for it:

```python
import math

import litellm
from limitry import Limitry

# Uses the LIMITRY_API_KEY environment variable.
limitry = Limitry()

def answer(user_id: str, prompt: str) -> str:
    with limitry.reserve(
        subject={"kind": "user", "id": user_id}, action="ai-call", cost=5
    ) as reservation:
        response = litellm.completion(
            model="openai/gpt-6.2-sol",
            messages=[{"role": "user", "content": prompt}],
        )
        # LiteLLM prices each call, in US dollars.
        reservation.cost = math.ceil(litellm.completion_cost(response) * 100)
        return response.choices[0].message.content or ""
```

When the user is over budget, `reserve` raises `LimitReachedError` before the call, so you can show your own message.

## What you see

* Each request commits the cents LiteLLM charged for it, streamed or not.
* On the [Usage](/docs/usage/) page, each user’s AI spend this month, across every model behind LiteLLM.
* A user over budget gets a `429` from the proxy, with “This user’s AI budget has run out.” The model call never starts, so it costs you nothing.

Related: [Reservations](/docs/reservations/), [Budgets at several levels](/docs/guides/several-levels/).
