Repository navigation
Counting tokens per customer when your API calls models through LiteLLM #50640
supertj
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
This is about a setup where you sell an API to your own customers, and behind it you call models through the LiteLLM Python SDK. LiteLLM tells you how many tokens each call used. What it can't know is which of your customers the call was for, or what their plan allows. That's the part we handle in our own API layer, and the usage object LiteLLM returns gives us the number to count.
Here's a FastAPI endpoint. The UsageRail middleware checks the caller's API key, rate limit and quota before the endpoint runs. The app is set to count units (Settings > What counts as usage in the console), so
track()records the tokens against that customer; in an app that counts requests,track()does nothing.To try it without a provider key, pass
mock_response="Hello"toacompletion. LiteLLM then returns a canned response with a token count, and the rest of the flow works the same.Notes from wiring this up:
max_tokensplus the largest prompt you accept). If a request uses more than it reserved, the extra still counts, but it can take the customer past their quota.track()keeps the last value. It replaces, it doesn't add. If one request makes several model calls (a tool loop, say), add upusage.total_tokensyourself and calltrack()with the total.acompletionraises and your endpoint returns a 4xx or 5xx, the request is recorded but doesn't count toward the customer's usage or quota, whatever you passed totrack().track()number per request means a token on a large model counts the same as one on a small model. If that's wrong for your pricing, multiply by a per-model factor before you pass the number in. (Route weights don't help here: a request that callstrack()counts the tracked number, not the weight.)Disclosure: I work on UsageRail. FastAPI setup and options: https://usagerail.com/docs/fastapi
All reactions