Worked tutorial · about 30 minutes
Build a token budget with invented rates
Calculate three fictional workloads, add a clearly defined reserve, and test whether longer outputs fit a fixed practice budget.
Original editorial exercise · fictional practice data · checked 25 October 2026
Your deliverable is a small planning sheet: token totals, separate input and output costs, reserve, headroom, and a stress case. Every count and rate below is invented. The unit is fictional practice credits, with no currency value; these are not any provider's prices. No service is called and no token usage is measured.
1. Download the planning assumptions
Use an input rate of 0.20 and output rate of 0.80 practice credits per 1,000 tokens. The budget is 150.00 credits. Reserve an additional 20% of the calculated base cost. For this exercise, input and output counts cover every request once; retries, cached-input rates, taxes and other charges are outside the model.
| Workload | Requests | Input each | Output each |
|---|---|---|---|
| outline | 120 | 750 | 200 |
| revise | 80 | 1500 | 500 |
| review | 40 | 2400 | 300 |
2. Calculate before opening the answer
- For each row, multiply requests by input tokens per request. Repeat for output tokens.
- Divide each token total by 1,000 before multiplying by its matching rate. Add input and output cost to obtain base cost.
- Add all base costs, then calculate reserve = base × 0.20 and all-in cost = base + reserve. Headroom is budget minus all-in cost.
- Stress the plan by increasing output tokens by 50%, keeping request counts and input tokens fixed. Recalculate reserve from the new base cost.
input cost = requests × input tokens each ÷ 1000 × input rate
output cost = requests × output tokens each ÷ 1000 × output rate
all-in cost = (input cost + output cost) × 1.20 The reserve is 20% of base cost. Reserving 20% of the 150-credit budget would answer a different question. Keep intermediate values exact; round displayed costs to two decimal places using half-up rounding.
3. Check the worked calculation
Show row totals, reserve and stress result
| Workload | Total input / output tokens | Input cost | Output cost | Base cost |
|---|---|---|---|---|
| outline | 90,000 / 24,000 | 18.00 | 19.20 | 37.20 |
| revise | 120,000 / 40,000 | 24.00 | 32.00 | 56.00 |
| review | 96,000 / 12,000 | 19.20 | 9.60 | 28.80 |
| Total: 240 requests | 306,000 / 76,000 | 61.20 | 60.80 | 122.00 |
Baseline reserve = 122.00 × 0.20 = 24.40. All-in = 146.40, leaving 3.60 credits. The baseline fits.
In the stress case, output grows to 114,000 tokens, costing 91.20 credits. Input still costs 61.20. Base = 152.40, reserve = 30.48, and all-in = 182.88. Headroom is −32.88: the plan exceeds the budget by 32.88 credits.
4. Reproduce the sheet with decimal arithmetic
Save the downloads together. Python 3.10 or later uses only its standard library:
python calculate_budget.py budget.json
python calculate_budget.py budget.json --check answer_key.json The calculator reads the assumptions and prints results; an exact answer-key match exits with status 0. Rates are strings converted directly to Decimal, and rounding happens at display time. Python's decimal documentation explains exact decimal representation, string construction and rounding control.
Show the complete calculator
"""Calculate an invented practice-credit budget offline; Python 3.10+, stdlib."""
import argparse
import json
from decimal import Decimal, ROUND_FLOOR, ROUND_HALF_UP
from pathlib import Path
D = Decimal
THOUSAND = D(1000)
def money(value):
return str(value.quantize(D("0.01"), rounding=ROUND_HALF_UP))
def calculate(data):
rates = data["rates_per_1000_tokens"]
input_rate, output_rate = D(rates["input"]), D(rates["output"])
budget, reserve = D(data["budget"]), D(data["reserve_fraction_of_base_cost"])
stress = D(data["stress_output_multiplier"])
if (not all(x.is_finite() for x in [input_rate, output_rate, budget, reserve, stress])
or input_rate < 0 or output_rate <= 0 or budget < 0 or reserve < 0 or stress < 0):
raise ValueError("Rates and limits must be finite and nonnegative; output rate must be positive")
rows = []
input_total = output_total = requests = 0
for row in data["workloads"]:
values = [row[key] for key in ("requests", "input_tokens_per_request", "output_tokens_per_request")]
if any(type(value) is not int or value < 0 for value in values):
raise ValueError("Request and token counts must be nonnegative integers")
count, input_each, output_each = values
tokens_in, tokens_out = count * input_each, count * output_each
cost_in, cost_out = D(tokens_in) * input_rate / THOUSAND, D(tokens_out) * output_rate / THOUSAND
rows.append({"name": row["name"], "input_tokens": tokens_in, "output_tokens": tokens_out,
"input_cost": money(cost_in), "output_cost": money(cost_out),
"base_cost": money(cost_in + cost_out)})
input_total += tokens_in
output_total += tokens_out
requests += count
input_cost = D(input_total) * input_rate / THOUSAND
output_cost = D(output_total) * output_rate / THOUSAND
def scenario(multiplier):
base = input_cost + output_cost * multiplier
held = base * reserve
all_in = base + held
return {"base_cost": money(base), "reserve": money(held), "all_in": money(all_in),
"headroom": money(budget - all_in), "within_budget": all_in <= budget}
available_for_output = budget / (1 + reserve) - input_cost
capacity = (available_for_output * THOUSAND / output_rate).to_integral_value(rounding=ROUND_FLOOR)
return {"unit": data["unit"], "requests": requests, "input_tokens": input_total,
"output_tokens": output_total, "rows": rows, "baseline": scenario(D(1)),
"stress": scenario(stress),
"max_total_output_tokens_with_baseline_input": int(capacity) if capacity >= 0 else None,
"extra_output_tokens_above_baseline": int(capacity) - output_total if capacity >= 0 else None}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", type=Path)
parser.add_argument("--check", type=Path)
args = parser.parse_args()
result = calculate(json.loads(args.input.read_text(encoding="utf-8")))
print(json.dumps(result, indent=2))
if args.check and result != json.loads(args.check.read_text(encoding="utf-8")):
parser.exit(1, "Answer mismatch: compare the printed values with your answer.\n")
if __name__ == "__main__":
main()
5. Find the output limit and explain the assumption
With input fixed at its baseline total, what is the largest whole number of total output tokens that fits the budget, including reserve? Solve this yourself before opening the answer.
Show the output-token ceiling
The base-cost ceiling is 150 ÷ 1.20 = 125.00. Fixed input uses 61.20, leaving 63.80 for output. The ceiling is floor(63.80 ÷ 0.80 × 1,000) = 79,750 output tokens, or 3,750 above baseline. At 79,751 output tokens, all-in is 150.00096, which exceeds the budget even though a two-decimal display would show 150.00. Compare exact values before rounding.
This ceiling is an aggregate planning result. It does not promise that any individual request can be capped without changing its result. A real plan needs permitted usage measurements, current applicable rate terms, and the extra charges actually relevant to that service. The exercise itself requires none of those purchases or accounts.
To check the structure of a generated response, use the JSON contract exercise.
Sources and scope
All workloads, rates and budget rules are original fictional practice assumptions. The linked Python source supports the arithmetic behavior only. Source checked 25 October 2026.