Count tokens before you send
Most token problems start with a request nobody measured. A user pastes a long log. A retrieval step returns twenty chunks. The call goes out, and you find out later from an error, a cut-off reply or the bill. A count before the call turns that into a clear, early failure you control.
Why count yourself
The API will tell you the token count after the call. By then you have paid, and the model may already have dropped or ignored part of the prompt. Counting first lets you trim, summarize or refuse with a useful message.
Pick your own budget for each call path. It should be well under the model's context window, and it must leave room for the reply. Input and output share the same window on most models.
Python, with a real tokenizer
Each vendor has its own tokenizer, so counts differ between models. If you use OpenAI models, tiktoken gives exact counts for their encodings. For other vendors, use their counting tool or endpoint if they have one, and treat any other count as an estimate.
# pip install tiktoken (OpenAI's tokenizer; other vendors count differently)
import tiktoken
LIMIT = 8000 # your own budget for this call, not the model's max
RESERVE_OUTPUT = 1000 # leave room for the reply
def count(messages, encoding="o200k_base"):
enc = tiktoken.get_encoding(encoding)
return sum(len(enc.encode(m["content"])) for m in messages)
def check(messages):
n = count(messages)
if n + RESERVE_OUTPUT > LIMIT:
raise ValueError(f"prompt is {n} tokens, budget is {LIMIT - RESERVE_OUTPUT}")
return n
if __name__ == "__main__":
msgs = [{"role": "system", "content": "Answer in plain English."},
{"role": "user", "content": "Why did my bill go up? " * 50}]
print("tokens:", check(msgs))
try:
check(msgs + [{"role": "user", "content": "x " * 9000}])
except ValueError as e:
print("blocked:", e)
This counts message text only. Chat formats add a few tokens per message for roles and separators, so keep some headroom.
JavaScript, rough estimate
When you have no tokenizer handy, a character-based estimate is better than nothing. Around four characters per token is a common rule of thumb for English text. Code, numbers and other languages can be far off, so use this only as a guard, not for billing.
// Rough guard when you have no tokenizer handy. ~4 characters per token is a
// common rule of thumb for English; code and other languages differ. Estimate only.
function roughTokens(text) { return Math.ceil(text.length / 4); }
const prompt = "Summarize this ticket. ".repeat(400);
const est = roughTokens(prompt);
console.log("estimated tokens:", est);
if (est > 1500) console.log("too long: trim before sending");
What to do when the check fails
- Trim history first: drop old turns, keep the system prompt. See Trim history without losing the goal.
- Cut retrieved text to the top few chunks.
- Shrink tool output to the fields you need.
- Tell the user if their input is simply too big, instead of failing silently.
Checklist
- Set a token budget per call path, with room for output.
- Count before every call, and log the number.
- Fail loudly when over budget.
- Use the vendor's tokenizer when you need exact numbers.