toolquota
toolquota

how toolquota fits in

Install

consolepip install toolquota

Use

pythonfrom toolquota import Quota, QuotaExceeded, ToolQuota

quota = ToolQuota(
    default=Quota(rate=1, burst=3),                       # any tool: 1/s, 3 at once
    quotas={
        "search": Quota(rate=10 / 60, burst=2, max_calls=40),
        "browser": Quota(rate=1 / 5, burst=1, max_calls=12),
    },
)

def call_tool(name, arguments, tool):
    if not quota.try_acquire(name):
        wait = quota.wait_time(name)
        if wait == float("inf"):
            return {"error": f"{name} has used its whole quota for this run"}
        return {
            "error": f"{name} is rate limited; wait {wait:.1f}s, or tell the user",
            "retry_after": wait,
        }
    return tool(**arguments)

Or let it raise:

pythontry:
    quota.acquire("search")
except QuotaExceeded as error:
    error.wait_time       # seconds, or inf when max_calls is spent
    error.permanent       # True when no amount of waiting helps
    str(error)            # "'search' is rate limited; retry in 0.40s"

Reading it back:

pythonquota.remaining("search")   # calls available now
quota.calls("search")       # calls taken since reset
quota.report()              # {"search": {"calls": 7, "available": 1.4}}
quota.reset()               # new run

How the bucket works

and for tools that must not be hammered at all

pythonnow = 0.0
quota = ToolQuota(clock=lambda: now)

Rules

for an agent and wrong for a shared API key — share a bucket through your own store if that is the case.

is why wait_time is returned rather than used.

really per process.

Limits

arithmetic, so call it from either kind of code.

needs a server is a limiter that breaks the run when the server is down.

Development

consolepython -m venv .venv
.venv/bin/pip install -e ".[test]"
.venv/bin/pytest

The suite covers every line of the package (pytest --cov --cov-branch), and the examples in the docstrings run as tests through --doctest-modules.

License

MIT.

Other libraries here

One problem each, standard library only, no runtime dependencies.