Custom limits
The limits in Settings → LLM cover how much the app, each user and each guest may spend per day or month. Anything that depends on your app, such as a user's plan, credits they bought, or the team they belong to, goes in your own code, in two hooks every model call passes through:
$llm.onCallruns before every call that reaches a provider, of every kind. It can change the call (its model, its input, whom it counts for) or refuse it.$llm.onCallDoneruns after a call that reached a provider, with what it used and cost. It can't refuse; the call has happened.
The limits in Settings → LLM are themselves an onCall handler, built in. Yours run before it, so the built-in limits
count the model and the user your code settled on.
Bind them once, when the app starts: in a hook file in TypeScript, or in your build's Go code. The Go hooks are
llm.OnCall(app) and llm.OnCallDone(app) in the shared contract package (llmc below is
pocketone.dev/ext/contracts/llm), so another extension, a billing one say, can bind them too.
// pb_hooks/limits.pb.ts
$llm.onCall((e: LlmCallEvent) => {
// e.kind ("text", "image", ...), e.op, e.model, e.input, e.subject, e.user ({ collection, id } or null), e.guest
if (String(e.input.prompt ?? "").length > 20000) throw e.refuse("That question is too long.")
e.next()
})
llmc.OnCall(app).BindFunc(func(e *llmc.CallEvent) error {
// e.Kind, e.Op, e.Model, e.Input (a pointer to the operation's input), e.Subject
if in, ok := e.Input.(*textv1.CompleteInput); ok && len(in.Prompt) > 20000 {
return e.Refuse("That question is too long.")
}
return e.Next()
})
onCall
A handler gets one call on its way to a provider:
| TypeScript | Go | |
|---|---|---|
e.kind |
e.Kind |
text, image, speech, transcribe, align, music, video or embed. |
e.op |
e.Op |
The operation: complete, stream, generate, edit, speak, transcribe, align, create (music and video) or embed. |
e.model |
e.Model |
The model, as provider/model. Set it to send the call to another model. |
e.input |
e.Input |
The call's input: prompt, messages, maxTokens, size... as the page passed it. Change any of it. In Go it's a pointer to the operation's input (*textv1.CompleteInput for text, *imagev1.GenerateInput for pictures, ...). |
e.subject |
e.Subject |
Whom the call is for (see Users and guests). Set it to count the call for someone else, or for a name of your own (team:acme). |
e.user |
llmc.ParseSubject(e.Subject) |
The signed-in user the call is for, as { collection, id }, or null. |
e.guest |
llmc.IsGuest(e.Subject) |
true when the call is for a guest. |
e.guestsCapped |
e.GuestsCapped |
Set it to true when your handler takes care of what guests spend (see below). |
Then it does one of two things:
e.next()(Go:return e.Next()) lets the call go on, with whatever the handler changed.throw e.refuse("message")(Go:return e.Refuse("message")) refuses it. The page's$llmcall throws witherr.codelimit(HTTP 429) and your message, the same as a built-in limit's refusal, so onecatchhandles both, and the ledger records it as refused, with your message.
A handler that does neither refuses the call too, with a message saying a handler didn't call e.next(): forgetting
next() never lets a call through unchecked.
Handlers run in the order they're bound, all before the built-in limits. A TypeScript handler runs on the app's JS VM,
but the model call itself doesn't: the handler runs, then the model works off the VM, and the app keeps serving other
requests. A handler may be async, but every call waits for it, so keep it to quick reads.
onCallDone
A handler gets a call that reached a provider, with what it used:
| TypeScript | Go | |
|---|---|---|
e.kind, e.op, e.model, e.subject, e.user, e.guest |
e.Kind, e.Op, e.Model, e.Subject |
As in onCall, with the values the call was made with. |
e.usage |
e.Usage |
What it used: input, output and cached tokens, seconds, and the cost in millionths of a dollar (costMicroUSD, Go CostMicroUSD). |
e.job |
e.Job |
A music or video job's id. A job's onCallDone comes once it's done and its cost is known (when createAsync with wait, or a later getAsync, sees it finish). |
A refused call has no onCallDone. An error a handler throws is logged and doesn't affect the call. The ledger row is
already written when onCallDone runs.
Plan tiers
Free users get 10 questions a day and the small model; paid users get the big one. The plan lives on the user's record; the count comes from the ledger:
// pb_hooks/plans.pb.ts: users have a "plan" select field, "free" or "pro"
$llm.onCall((e: LlmCallEvent) => {
if (!e.user) return e.next() // guests and background work: the built-in limits handle them
const user = $app.findRecordById(e.user.collection, e.user.id)
if (user.get("plan") !== "pro") {
e.model = "vultr/glm-5.3-mini"
e.input.maxTokens = Math.min(e.input.maxTokens || 800, 800)
if ($llm.ledger.spent({ subject: e.subject, window: "day" }).calls >= 10) {
throw e.refuse("Free accounts get 10 questions a day. Upgrade for more, or come back tomorrow.")
}
}
e.next()
})
llmc.OnCall(app).BindFunc(func(e *llmc.CallEvent) error {
p := llmc.ParseSubject(e.Subject)
if p.Kind != "user" {
return e.Next() // guests and background work: the built-in limits handle them
}
user, err := e.App.FindRecordById(p.Collection, p.ID)
if err != nil {
return err
}
if user.GetString("plan") != "pro" {
e.Model = "vultr/glm-5.3-mini"
if in, ok := e.Input.(*textv1.CompleteInput); ok && (in.MaxTokens == 0 || in.MaxTokens > 800) {
in.MaxTokens = 800
}
spent, err := ledgerv1.Contract.Must(e.App).Spent(e.Context, extkit.Internal,
ledgerv1.SpentInput{Subject: e.Subject, Window: "day"})
if err != nil {
return err
}
if spent.Calls >= 10 {
return e.Refuse("Free accounts get 10 questions a day. Upgrade for more, or come back tomorrow.")
}
}
return e.Next()
})
Credits
Users buy credits; every call spends them. Refuse before a call when the balance is empty, and take the cost off after:
// pb_hooks/credits.pb.ts: users have a "credits" number field, in millionths of a dollar
$llm.onCall((e: LlmCallEvent) => {
if (e.user && $app.findRecordById(e.user.collection, e.user.id).getInt("credits") <= 0) {
throw e.refuse("You're out of credits.")
}
e.next()
})
$llm.onCallDone((e: LlmCallDoneEvent) => {
if (e.user && e.usage.costMicroUSD > 0) {
$app.db()
.newQuery("UPDATE " + e.user.collection + " SET credits = credits - {:cost} WHERE id = {:id}")
.bind({ cost: e.usage.costMicroUSD, id: e.user.id })
.execute()
}
e.next()
})
llmc.OnCall(app).BindFunc(func(e *llmc.CallEvent) error {
if p := llmc.ParseSubject(e.Subject); p.Kind == "user" {
user, err := e.App.FindRecordById(p.Collection, p.ID)
if err != nil {
return err
}
if user.GetInt("credits") <= 0 {
return e.Refuse("You're out of credits.")
}
}
return e.Next()
})
llmc.OnCallDone(app).BindFunc(func(e *llmc.CallDoneEvent) error {
if p := llmc.ParseSubject(e.Subject); p.Kind == "user" && e.Usage.CostMicroUSD > 0 {
_, err := e.App.DB().NewQuery("UPDATE {{" + p.Collection + "}} SET [[credits]] = [[credits]] - {:cost} WHERE [[id]] = {:id}").
Bind(dbx.Params{"cost": e.Usage.CostMicroUSD, "id": p.ID}).Execute()
if err != nil {
return err
}
}
return e.Next()
})
The check comes before the call and the cost after it, so a user's last call can take their balance a little below zero.
Team buckets
Count every member's calls toward their team, so a team shares one allowance:
// pb_hooks/teams.pb.ts: users have a "team" relation
$llm.onCall((e: LlmCallEvent) => {
if (e.user) {
const team = $app.findRecordById(e.user.collection, e.user.id).get("team")
if (team) e.subject = "team:" + team
}
e.next()
})
llmc.OnCall(app).BindFunc(func(e *llmc.CallEvent) error {
if p := llmc.ParseSubject(e.Subject); p.Kind == "user" {
if user, err := e.App.FindRecordById(p.Collection, p.ID); err == nil && user.GetString("team") != "" {
e.Subject = "team:" + user.GetString("team")
}
}
return e.Next()
})
The ledger then records the team as the subject, and $llm.ledger.spent({ subject: "team:" + teamId, window: "month" })
is what the team has used. The built-in limits on each signed-in user and each guest count users and guests,
not teams: a team's own allowance is a check in your handler, like the plan tier's above.
Guests in your own code
Guest calls are refused until there's a limit on all guests together, because a guest can clear their cookies and come
back with a fresh allowance (Limits). If your handler takes care of guests itself,
say so with e.guestsCapped = true, and the built-in limits let guest calls through without that limit:
// pb_hooks/guests.pb.ts: guests get the small model, short answers, and 200 calls a day between them
$llm.onCall((e: LlmCallEvent) => {
if (e.guest) {
e.model = "vultr/glm-5.3-mini"
e.input.maxTokens = 300
if ($llm.ledger.spent({ subject: "guests", window: "day" }).calls >= 200) {
throw e.refuse("We've answered all the questions we can today. Come back tomorrow.")
}
e.subject = "guests" // count every guest in one bucket of our own
e.guestsCapped = true
}
e.next()
})
llmc.OnCall(app).BindFunc(func(e *llmc.CallEvent) error {
if llmc.IsGuest(e.Subject) {
e.Model = "vultr/glm-5.3-mini"
if in, ok := e.Input.(*textv1.CompleteInput); ok {
in.MaxTokens = 300
}
spent, err := ledgerv1.Contract.Must(e.App).Spent(e.Context, extkit.Internal,
ledgerv1.SpentInput{Subject: "guests", Window: "day"})
if err != nil {
return err
}
if spent.Calls >= 200 {
return e.Refuse("We've answered all the questions we can today. Come back tomorrow.")
}
e.Subject = "guests" // count every guest in one bucket of our own
e.GuestsCapped = true
}
return e.Next()
})
Counting every guest under one subject of your own makes their shared total one spent call. The ledger then shows
guests instead of each guest's id; keep the subject as it is if you'd rather see each one. Only set guestsCapped
when your code really does cap what guests spend. Otherwise add the limit in Settings → LLM.
Order and the built-in limits
Handlers run by priority, then in the order they're bound. Bound the usual way they have priority 0, and the built-in
limits are bound with the id llmc.LimitsHandlerID and priority llmc.LimitsPriority (1000), so yours run first. In
Go, bind with a higher priority to run after the built-in limits, or unbind them to replace them entirely:
llmc.OnCall(app).Bind(&hook.Handler[*llmc.CallEvent]{
Priority: llmc.LimitsPriority + 1, // after the built-in limits: only calls they let through reach it
Func: func(e *llmc.CallEvent) error {
e.App.Logger().Info("llm call allowed", "model", e.Model, "subject", e.Subject)
return e.Next()
},
})
llmc.OnCall(app).Unbind(llmc.LimitsHandlerID) // no built-in limits: your handlers decide everything
Questions and comments
Comments are a GitHub Discussions thread; sign in with GitHub to post.