How I budget AI tokens in a Laravel SaaS
The last part of the series: real Laravel code from this site for per-feature AI budgets, usage logging, a monthly token cap and plain error messages.
Six parts of theory are only useful if they change how you build. In this last part I'll show how the AI writing helper on this site handles tokens, cost and limits, with real code from its Laravel backend. If you missed the start, begin with part 1: what is a token in AI?
What the helper does
When I write a post, the editor has AI buttons: plan an outline, draft the next section, review the text, suggest internal links, write image alt text. Every answer is a suggestion. Nothing changes until I accept it, and nothing here publishes a post.
All of it goes through one class, AiWriter, so there's exactly one place where tokens are spent and counted.
1. Give every feature its own output budget
From part 2: output costs five times more than input. So each feature gets its own max_tokens and effort level, set in code, not left to chance:
- Outline: medium effort, up to 8,000 output tokens.
- Review: medium effort, up to 10,000.
- Internal links: low effort, up to 4,000.
- Alt text: low effort, up to 2,000.
Low effort means less thinking, and thinking is billed as output. A one-line alt text doesn't need a long think.
2. Cap the input too
From part 3: everything you send fills the context window and the bill. Three habits keep the input small:
- Plain text, not HTML. The helper strips the tags before sending. For my part 1 article that's the difference between 2,693 tokens of HTML and 1,737 tokens of text (counted with tiktoken).
- A hard limit. Text over 80,000 characters is refused with a message asking for a smaller selection.
- Summaries, not full posts. The links feature sends the slug, title and excerpt of up to 60 other posts, not their full text.
private const MAX_INPUT_CHARS = 80_000;
3. Log every call, even failures
Every request writes one row: who asked, for which feature, which model, and the real input and output tokens from the API's usage field. Failed calls are logged too, marked as not OK, so I can see errors as well as spending.
AiUsage::create([
...$usage,
'ok' => true,
'model' => $message->model,
'input_tokens' => $message->usage->inputTokens,
'output_tokens' => $message->usage->outputTokens,
]);I trust these numbers over any estimate. As part 1 showed, a tokenizer count before the call is only close; the usage field after the call is what you pay for.
4. A monthly token cap
Before any call, the helper adds up this month's input and output tokens. If they've reached the cap, it stops with a clear message instead of a surprise bill. The cap comes from configuration, with a default of 2,000,000 tokens a month.
$cap = (int) config('jwhero.ai.monthly_token_cap');
if ($cap > 0 && AiUsage::monthTokens() >= $cap) {
throw new RuntimeException(
'This month’s AI allowance is used up. It resets on the 1st, or raise AI_MONTHLY_TOKEN_CAP.'
);
}The sum itself is one query:
public static function monthTokens(): int
{
return (int) static::query()
->where('created_at', '>=', now()->startOfMonth())
->sum(DB::raw('input_tokens + output_tokens'));
}5. Turn API errors into plain messages
From part 4: a 429 means "not now". The SDK retries twice on its own. If it's still busy, the editor sees a sentence a person understands, not a stack trace:
- Rate limited or overloaded: "The AI service is busy right now. Try again in a minute."
- Bad key: "The AI key was refused. Check AI_API_KEY in .env."
- Timeout or no connection: "Could not reach the AI service. Check AI_BASE_URL and that it is online."
6. Handle the stop reason
An answer can stop early. The helper checks why:
max_tokens: the answer was cut off at the output budget, so the editor says "The answer was too long and got cut off. Try a shorter selection."refusal: the model declined, and the editor suggests rewording.
Without this check, a cut-off answer can look like a finished one. With structured JSON output, a cut-off answer is often invalid JSON too, so catching it early saves a confusing error later.
7. Ask for structure, not prose
Each feature asks for JSON that matches a schema: the review returns a list of issues with a kind, a quote and a suggestion. Structured output keeps answers short and predictable, so there are fewer wasted tokens and no fragile text parsing.
What I'd add for a bigger SaaS
- Per-customer caps, not only one global cap, so one heavy tenant can't use everyone's allowance.
- A cost column, calculated from the model's price at the time of the call, because prices change.
- Prompt caching for the shared house-voice instructions and long documents (part 2).
- Queued jobs with backoff for anything that doesn't need an instant answer (part 4).
- Streaming for long free-text answers (part 6).
The series in one list
- What is a token in AI?
- How AI pricing works
- Context window explained
- AI rate limits and 429 errors
- Claude's 5-hour and weekly limits
- Why AI answers take time
- How I budget AI tokens in a Laravel SaaS (this post)
Quick summary
- Put every AI call through one class, so spending is counted in one place.
- Give each feature its own output budget and effort level.
- Log the real usage from every response, including failures.
- Stop at a monthly cap with a clear message.
- Turn errors and stop reasons into plain sentences.
References
- Pricing, Claude Platform Docs, Anthropic, accessed 24 November 2026.
- Rate limits, Claude Platform Docs, Anthropic, accessed 24 November 2026.
- Context windows, Claude Platform Docs, Anthropic, accessed 24 November 2026.
- Database: Query Builder, Laravel Documentation.
Questions people ask
How do I track AI token usage in Laravel?
Save the input and output tokens from every API response in a table, with the user, feature and model, including failed calls.
How do I cap AI costs in a Laravel app?
Sum this month's tokens before each call and stop with a clear message once a configured cap is reached.
Should I send HTML to an AI model?
Usually not. Stripping tags first cut a 1,308-word article from 2,693 to 1,737 tokens in my test.
How do I handle AI rate limit errors in Laravel?
Let the SDK retry a few times, run heavy work in queued jobs with backoff, and show the user a plain message if the service is still busy.