By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Your support triage service has a golden test. It sends the same ticket twice and asserts that the summary is identical. The test passed for three weeks. On Wednesday it failed, and nobody had touched the prompt.
Two separate causes hide behind that failure. The service estimates token counts with a rough rule, so a long ticket can push the request to the edge of the limit. And the model is a sampler, not a lookup table, so the same input can produce different text. Both belong in your design, not in your incident log.
A token is the unit a model reads and bills. It is a fragment of a word, produced by a tokenizer. English prose averages roughly four characters per token, so 100 words is about 130 tokens. Treat that ratio as an estimate and never as a measurement.
Count three things before you send a request: the system prompt, the tool definitions, and the messages you are about to append. After the call, the usage block in the response is the authority. Before the call, use the provider's token counter.
Every model has a context window: the maximum number of tokens it can read in one request. The prompt and the answer share that window. If you spend the whole window on the prompt, the answer has no room to start.
The model converts the prompt into a probability for every token in its vocabulary. The sampler then picks one token, appends it, and repeats. Sampling settings change how that pick is made.
| Setting | What it does | When it bites you |
|---|---|---|
| temperature | Flattens or sharpens the probability distribution | High values make labels and numbers drift between runs |
| top_p | Keeps only the most likely tokens up to a probability mass | Rarely needed on top of temperature; changing both makes runs hard to compare |
| temperature 0 | Always takes the most likely token | Cuts most variation, but not every last source of it |
Temperature 0 is the closest thing to a deterministic setting, and it is still not a guarantee. Floating-point arithmetic is not exact, and servers batch requests together, so the sums differ from run to run. Expect near-identical output, not byte-identical output.
Think of the window as a budget with three parts. Fixed costs are the system prompt and the tool schemas, which you send on every call. Growth is the conversation history and every tool result. Whatever remains is room for the answer.
Notice that nothing here is free. A client library that appends a greeting, a retry that resends the prompt and a tool that returns raw JSON all spend from the same budget.
# Estimate the prompt size before you send it. No API call, no key needed.
CHARS_PER_TOKEN = 4 # rough English estimate; use the provider counter for real work
def estimate_tokens(text: str) -> int:
return (len(text) + CHARS_PER_TOKEN - 1) // CHARS_PER_TOKEN
system_prompt = "You triage support tickets. Reply with JSON." * 25
tool_schema = '{"name": "lookup_order", "description": "Find an order by id."}' * 10
messages = ["My invoice shows the wrong total.", "Which invoice number?"] * 30
prompt_tokens = (
estimate_tokens(system_prompt)
+ estimate_tokens(tool_schema)
+ sum(estimate_tokens(message) for message in messages)
)
print("prompt tokens ~", prompt_tokens)
# A fixture ceiling for the exercise. It is not a real model limit.
limit = 800
answer_reserve = 200
print("fits:", prompt_tokens + answer_reserve <= limit)Once you accept that output varies, your tests change shape. Stop asserting on exact text. Assert on properties: the label is one of the allowed values, the JSON parses against the schema, the total equals the sum of the line items.
ALLOWED_LABELS = {"billing", "technical", "account"}
def check_label(raw: str) -> str:
label = raw.strip().lower()
if label not in ALLOWED_LABELS:
raise ValueError(f"label outside the contract: {raw!r}")
return label
print(check_label("Billing "))
for candidate in ["Account", "refund request"]:
try:
print(check_label(candidate))
except ValueError as exc:
print(exc)Rewrite one flaky assertion in your own service. This takes about fifteen minutes, and the result is a test you can trust.
usage block from a real response, and note the ratio you get.Key takeaways
A token is a fragment of a word; four characters per token is an estimate, not a measurement.
The prompt and the answer share one context window, so reserve room for the answer.
Sampling settings decide how the next token is chosen; temperature 0 narrows variation but does not remove it.
Test properties and contracts, not exact text.
Log the usage block on every request so cost and context stay observable.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.