Reject an over-budget prompt before generation starts
Measure how many tokens a character cap really admits, then apply a prompt-plus-output budget at the API boundary.
An API that checks a prompt’s character length is not checking its token cost. The same 1,000 characters can be 221 GPT-2 tokens of English prose, 336 tokens of Python source, or 1,000 tokens of spaces. If the context window is 1,024 and the request also reserves 256 output tokens, a 4,000-character cap can admit a prompt that cannot fit.
This example measures those token classes and computes a character cap that is safe for the worst class. It then shows the budget function that rejects a request before tokenisation or model work. The check is a pure function, so it can run in the HTTP layer and in a unit test without loading a model. The page does not start a server or call a hosted provider.
Run it
From the canonical repository at commit
f958967d70992d7b09d9c75000bd8c543f1644d4:
python examples/ch25/service_lab.py budgetPython 3.11 or later with the GPT-2 tokeniser cached (the command uses it, but no model forward pass). No network, GPU or credentials are required once the tokeniser is present. It finishes in a few seconds.
Implementation
check_budget returns the first violated limit and a message containing the
numbers. The total is prompt tokens plus requested new tokens; the prompt limit
is checked separately. A character cap alone cannot enforce either limit.
@dataclass(frozen=True)
class Limits:
context_window: int = 1024
max_prompt_tokens: int = 1000
max_body_bytes: int = 64 * 1024
def check_budget(prompt_tokens: int, max_new_tokens: int, limits: Limits) -> Optional[Tuple[str, str]]:
"""Return ``(param, message)`` for the first budget violated, or None. The messages carry the numbers."""
if prompt_tokens > limits.max_prompt_tokens:
return "prompt", f"the prompt is {prompt_tokens} tokens; the limit is {limits.max_prompt_tokens}"
total = prompt_tokens + max_new_tokens
if total > limits.context_window:
return "max_new_tokens", f"{prompt_tokens} prompt tokens plus {max_new_tokens} new tokens is {total}; the context window is {limits.context_window}"
return NoneExpected outcome
Observed with the command above (exit 0). Selected stable fields:
"tokeniser": "gpt2 (byte-level BPE, 50,257)",
"chars_per_sample": 1000,
"classes": {
"English prose (this book)": {
"samples": 2,
"chars": 1000,
"tokens_median": 221.0,
"tokens_min": 197,
"tokens_max": 245
},
"schema_char_cap": 4000,
"context_window": 1024,
"reserved_new_tokens": 256,
"char_cap_that_is_safe_for_the_worst_class": 256,The same character count varied by more than four times across classes. Spaces were the worst: 1,000 characters became 1,000 tokens, so a 4,000-character prompt of spaces would be about 4,000 tokens, far beyond the 1,024-token window. The safe cap of 256 characters is a conservative consequence of the worst class and the reserved output, not a universal constant.
Mechanism and limitations
Documented: check_budget checks the prompt limit first, then the sum of
prompt and new tokens against the context window, returning the parameter name
and a message with the actual numbers. Limits defaults to a 1,024-token
window, a 1,000-token prompt limit and a 64 KiB body limit. The test file for the
service exercises the budget, schema compatibility, error envelopes and the
HTTP routes; this page runs only the budget command.
Observed: the command exited 0 with the token classes and safe cap above.
The targeted tests.test_ch25_service_lab is part of the canonical suite; no
independent test count is claimed here.
Not shown: the HTTP server, request validation, streaming, cancellation, a real model, or a hosted API’s tokeniser. The measurement is GPT-2’s tokeniser on samples from this repository, not the tokeniser of every model. A 256-character cap is safe for this worst class but may be unnecessarily strict for English.
Challenge this result
Construct a 1,000-character prompt of spaces and compute its GPT-2 token count
with the tokeniser. Then run it through check_budget with 256 new tokens and
confirm the rejection message. Change the context window to 2,048 and recompute
the safe character cap. Explain why a service should reject on tokens, not
characters, and why it should still impose a byte limit on the request body.
Source and verification
Canonical source:
examples/ch25/service_lab.py
at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests:
tests/test_ch25_service_lab.py
and
tests/test_ch25_api.py
.
Chapter: From Inference Loop to API
.
The run above is a fresh local execution on Windows 11 with Python 3.13.15; it
uses the cached GPT-2 tokeniser and no model forward pass.
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.