Token and Cost Control
🎯 Introduction
AI models typically charge for input and output tokens. Long contexts and frequent model calls can exceed a budget. This article uses the OpenAI SDK and a tokenizer to limit tokens per call, read actual usage, estimate costs, and reject subsequent calls when cumulative quotas are exhausted.
🧱 Understand AI call costs
| Control | Unit | Purpose |
|---|---|---|
| Per-call input and output limits | Tokens | Limit consumption for each call |
| Cumulative token quota | Tokens | Reject subsequent calls once cumulative usage reaches the quota |
| Cumulative cost limit | US dollars | Reject subsequent calls once estimated cumulative costs reach the limit |
Input, output, and cached input tokens may have different prices, so a token quota is not equivalent to a monetary budget.
🛠 Limit input tokens
Use Node.js 22, OpenAI SDK 5.12.2, and js-tiktoken 1.0.21:
npm install openai@5.12.2 js-tiktoken@1.0.21
Set your API key and a model ID available to your account. This example uses a text model supporting Chat Completions, max_completion_tokens, and the o200k_base encoding. See the model list.
export OPENAI_API_KEY='your API key'
export OPENAI_MODEL='your model ID'
Create input.mjs:
import { getEncoding } from 'js-tiktoken';
const encoding = getEncoding('o200k_base');
export function validateInput(question) {
if (typeof question !== 'string' || !question.trim()) {
throw new Error('INVALID_INPUT');
}
// Reject oversized text before tokenization
if (Buffer.byteLength(question, 'utf8') > 8000) {
throw new Error('INPUT_TOO_LARGE');
}
const tokens = encoding.encode(question, [], []).length;
if (tokens > 500) {
throw new Error('INPUT_TOKEN_LIMIT');
}
return tokens;
}
Create test-input.mjs:
import { validateInput } from './input.mjs';
const inputs = ['Hello', ' ', 'hello '.repeat(600), 'a'.repeat(8001)];
for (const input of inputs) {
try {
console.log('PASS', validateInput(input));
} catch (error) {
console.log(error.message);
}
}
Run node test-input.mjs. Expected output:
PASS 1
INVALID_INPUT
INPUT_TOKEN_LIMIT
INPUT_TOO_LARGE
This counts only user text and is not an upper bound for the full request. Real applications must also limit system instructions, message history, retrieved material, tool definitions, and message framing overhead.
🛠 Limit output tokens
Create model.mjs:
import OpenAI from 'openai';
const openai = new OpenAI({
timeout: 10000,
maxRetries: 0
});
const model = process.env.OPENAI_MODEL;
export async function callModel(question) {
return await openai.chat.completions.create({
model,
messages: [{ role: 'user', content: question }],
max_completion_tokens: 200
});
}
max_completion_tokens limits total generated tokens, including reasoning tokens the model may use. Answers may be truncated when the limit is reached.
Create test-model.mjs:
import { callModel } from './model.mjs';
const response = await callModel('Introduce Vue in one sentence.');
console.log(response.choices[0].message.content);
console.log(response.usage);
Run node test-model.mjs. Expected output excerpt (answers and usage vary by model):
Vue is a JavaScript framework for building user interfaces.
{ prompt_tokens: 20, completion_tokens: 15, total_tokens: 35, ... }
... indicates omitted fields.
🛠 Track usage and calculate costs
The response's usage field records actual token usage for the call:
| Field | Meaning |
|---|---|
prompt_tokens | Input tokens, including cached input |
completion_tokens | Generated tokens |
total_tokens | Total input and generated tokens |
prompt_tokens_details.cached_tokens | Cached input tokens |
Subtract cached tokens from input tokens before calculating the uncached input cost to avoid double counting.
Create cost.mjs:
// Hypothetical prices in US dollars per million tokens, for teaching only
const prices = { input: 0.4, cachedInput: 0.1, output: 1.6 };
export function estimateCost(usage) {
const cached = usage.prompt_tokens_details?.cached_tokens ?? 0;
const input = usage.prompt_tokens - cached;
return (
input * prices.input +
cached * prices.cachedInput +
usage.completion_tokens * prices.output
) / 1000000;
}
In production, configure official prices for the actual response model and billing mode. This estimate excludes tool calls, other modalities, and special billing items.
🛠 Enforce cumulative quotas
Append the following to cost.mjs. Reject a user's next call once they accumulate 10,000 tokens or $0.01 in estimated costs during this process's lifetime.
const totals = new Map();
export function getUsage(userId) {
return totals.get(userId) ?? { tokens: 0, cost: 0 };
}
export function checkQuota(userId) {
const usage = getUsage(userId);
if (usage.tokens >= 10000) {
throw new Error('TOKEN_QUOTA_EXCEEDED');
}
if (usage.cost >= 0.01) {
throw new Error('COST_LIMIT');
}
}
export function recordUsage(userId, usage) {
const previous = getUsage(userId);
const next = {
tokens: previous.tokens + usage.total_tokens,
cost: previous.cost + estimateCost(usage)
};
totals.set(userId, next);
return next;
}
Create test-cost.mjs to verify cost calculations and both quota limits:
import { checkQuota, recordUsage } from './cost.mjs';
const usage = {
prompt_tokens: 2000,
completion_tokens: 500,
total_tokens: 2500,
prompt_tokens_details: { cached_tokens: 1000 }
};
const total = recordUsage('user-1', usage);
console.log(total.cost.toFixed(6));
recordUsage('cost-user', {
prompt_tokens: 0,
completion_tokens: 7000,
total_tokens: 7000
});
recordUsage('token-user', {
prompt_tokens: 10000,
completion_tokens: 0,
total_tokens: 10000
});
for (const userId of ['cost-user', 'token-user']) {
try {
checkQuota(userId);
} catch (error) {
console.log(error.message);
}
}
Run node test-cost.mjs:
0.001300
COST_LIMIT
TOKEN_QUOTA_EXCEEDED
With $0.001 remaining, the next call could still cost $0.002. A cumulative quota check is therefore not a strict budget cap.
Replace test-model.mjs with the following to verify cumulative usage from real calls. Both calls run in the same process.
import { validateInput } from './input.mjs';
import { callModel } from './model.mjs';
import { checkQuota, recordUsage } from './cost.mjs';
async function request(userId, question) {
validateInput(question);
checkQuota(userId);
const response = await callModel(question);
if (!response.usage) {
throw new Error('USAGE_UNKNOWN');
}
const total = recordUsage(userId, response.usage);
console.log('Cumulative tokens:', total.tokens);
console.log('Cumulative estimated cost:', total.cost.toFixed(6));
}
try {
await request('user-1', 'Introduce Vue in one sentence.');
await request('user-1', 'Introduce Node.js in one sentence.');
} catch (error) {
console.log(error.message);
}
Running node test-model.mjs may incur API charges. The following assumes each call uses 20 uncached input tokens and 15 output tokens:
Cumulative tokens: 35
Cumulative estimated cost: 0.000032
Cumulative tokens: 70
Cumulative estimated cost: 0.000064
usage must not be treated as free. Record requests pending reconciliation and reconcile them later. Persist records in production and maintain consistent billing periods and quotas for users and the application.❓ Questions and answers
Q1: Why can two calls with the same input text cost different amounts?
Message history, generation length, and cache hits may differ, changing billable usage. Settle costs using provider-reported usage and applicable prices.
🧪 Exercise
In test-cost.mjs, record a call for a new user with an estimated cost below $0.01 and run checkQuota. Add another call that takes the cumulative cost above $0.01 while keeping tokens below 10,000.
Acceptance criteria: The first check passes and the second returns COST_LIMIT. Explain why the last call can exceed the monetary quota.
🎉 You have learned model token limits, usage tracking, and cumulative cost control.
