Key points
- You pay for tokens sent and received: conversation history and a repeated system prompt often outweigh the actual question.
- Log the usage of every call, per feature and per customer, before you try to optimise anything.
- Caching, output limits, the right model for each task and per-customer caps protect your margin without hurting the experience.
Adding an AI feature to a website or SaaS product has become easy: a few lines to call an API, and your app can summarise a case file, draft a reply or triage requests. The next question, usually after the provider’s first invoice, is cost. Unlike flat-rate hosting, every call is billed, and the bill follows your customers’ usage rather than your budget. On the projects where we’ve built these features, cost blowouts rarely came from heavy use. They came from invisible technical choices: a full conversation history resent with every message, an oversized prompt, no limit per customer. Here’s how to understand the bill, measure it and keep it in check.
Where the bill comes from: input and output tokens
Model providers bill per token, a unit that roughly corresponds to a piece of a word. Two meters add up: input tokens (everything you send) and output tokens (what the model generates), with output usually costing more per token. Exact prices change often and differ widely between models, so check your provider’s pricing page rather than a number you read in an article.
What you send as input is often much bigger than you’d think:
- the system prompt, resent with every call: instructions, examples, tone;
- the conversation history for an assistant: each new message resends all previous ones, so a conversation’s cost grows much faster than its message count;
- attached documents: a fifty-page PDF sent to ask about one paragraph;
- automatically added context: product records, knowledge-base excerpts, customer data.
On the output side, an unbounded answer can be very long even though the interface only shows the first part. That’s why you can’t estimate cost just by looking at the user’s question.
Measure before you optimise
The first thing we put in place isn’t an optimisation but a log. Every API response reports the number of tokens it used: just store it, along with the feature and the customer account.
<?php
// After every model call, record what the response itself reports
$response = json_decode($body, true, flags: JSON_THROW_ON_ERROR);
$usage = $response['usage'] ?? [];
// Field names vary by provider (input_tokens / prompt_tokens, etc.)
$input = $usage['input_tokens'] ?? $usage['prompt_tokens'] ?? 0;
$output = $usage['output_tokens'] ?? $usage['completion_tokens'] ?? 0;
$db->prepare(
'INSERT INTO ai_usage (account_id, feature, model, input_tokens, output_tokens, created_at)
VALUES (?, ?, ?, ?, ?, UTC_TIMESTAMP())'
)->execute([$accountId, 'case_summary', $model, $input, $output]);
A single query then tells you what actually costs money:
-- Which features use the most this month?
SELECT feature, model,
COUNT(*) AS calls,
SUM(input_tokens) AS input,
SUM(output_tokens) AS output,
ROUND(AVG(input_tokens)) AS avg_input
FROM ai_usage
WHERE created_at >= DATE_FORMAT(UTC_TIMESTAMP(), '%Y-%m-01')
GROUP BY feature, model
ORDER BY SUM(input_tokens) + SUM(output_tokens) DESC;
The avg_input column is often the most revealing. On a support application we took over, it showed the assistant was sending far more text than needed: the entire help-centre content was being injected into the prompt, whatever the question. Sending only the relevant articles cut the bill without any change in perceived answer quality.
The log also feeds into pricing: multiply tokens by your provider’s prices and you know what each customer really costs you, so you can check your subscription covers it.
Reducing the bill without hurting answers
Once you know where the cost is, there are several levers. We apply them in this order, from simplest to most delicate:
- Cap the output. The
max_tokensparameter (or equivalent) limits answer length. Also ask for a short answer in the prompt: the limit alone cuts the answer off mid-sentence. - Trim the history. For an assistant, keep the latest exchanges and replace older ones with a short summary, generated once.
- Send the right context. Select the useful excerpts (with keyword or semantic search) instead of sending the whole document.
- Match the model to the task. Sorting a request into five categories or extracting a date doesn’t need the most powerful model. Try the task on a smaller model against a set of real examples before deciding.
- Use your provider’s features. Several providers offer prompt caching (a long system prompt that stays identical between calls is billed at a lower rate) and cheaper batch processing for work that can wait. Terms vary, so read your provider’s documentation.
The last lever is often the most effective: don’t call the model again for something you’ve already processed. Summaries of the same document, descriptions of the same product, translations of the same text can all be cached on your side:
<?php
function summarise(string $text, CacheInterface $cache): string
{
$text = trim(preg_replace('/s+/u', ' ', $text)); // same content = same key
$key = 'ai_summary_' . hash('sha256', MODEL . '|' . PROMPT_VERSION . '|' . $text);
$cached = $cache->get($key);
if ($cached !== null) {
return $cached; // no call, no cost
}
$summary = callModel(SYSTEM_PROMPT, $text, maxTokens: 400);
$cache->set($key, $summary, 30 * 86400); // 30 days
return $summary;
}
The PROMPT_VERSION constant matters: when you change the prompt, bump the version and old results stop being served. This kind of cache obviously doesn’t suit answers that depend on changing context, such as a conversation.
Setting caps per customer and per plan
Even optimised, an AI feature is exposed to one very active customer, or a script calling it in a loop. A monthly cap per account, set by plan, protects your margin. The tricky part is stopping two simultaneous requests from both going over it, so we reserve an estimate before the call in a single atomic SQL statement, then correct it with actual usage.
<?php
// Reserve before the call, adjust after: two concurrent requests can't overshoot the cap
function reserveQuota(PDO $db, int $accountId, int $estimation, int $cap): bool
{
$period = gmdate('Y-m');
$db->prepare('INSERT IGNORE INTO ai_quota (account_id, period, used, quota) VALUES (?, ?, 0, ?)')
->execute([$accountId, $period, $cap]);
$stmt = $db->prepare(
'UPDATE ai_quota SET used = used + ?
WHERE account_id = ? AND period = ? AND used + ? <= quota'
);
$stmt->execute([$estimation, $accountId, $period, $estimation]);
return $stmt->rowCount() === 1; // 0 rows updated = cap reached
}
// After the response: replace the estimate with actual usage
$db->prepare('UPDATE ai_quota SET used = used - ? + ? WHERE account_id = ? AND period = ?')
->execute([$estimation, $input + $output, $accountId, gmdate('Y-m')]);
Make the estimate deliberately generous (the output limit plus a cautious guess at input), since the correction gives the difference back afterwards. When the cap is reached, show a clear message explaining the situation and offering the next plan up, rather than a generic error. And warn people beforehand: an alert as they approach the cap avoids discovering the block at the worst possible moment.
Finally, add the standard safeguards of any API: mandatory authentication (never call the model from an unprotected public page), a per-minute rate limit and a maximum accepted text length. Those are what stop a form from becoming an open door to your provider account.
FAQ
Can we predict the cost of an AI feature before launch?
Roughly. Run a sample of real cases through the feature on staging, log the tokens used and multiply by the expected volume. That’s more reliable than any theoretical estimate, and it exposes oversized prompts before go-live.
Should we charge customers separately for AI?
It depends on how much it weighs in your costs. If usage is moderate and predictable, including it in the subscription with a cap is enough. If some customers use it heavily, an included allowance plus usage-based overage is fairer.
Want to add an AI feature to your site or SaaS product without nasty surprises on the bill? We build these integrations with measurement, caching and caps in place from day one.



