Review the prerequisites
Suitable for: We have understood the premise that input and generation jointly occupy capacity.
- Token
- A unit used by the model to encode and measure content; it does not correspond to a fixed number of Chinese characters or words. The lab supplies token counts directly and does not implement tokenization.
- Context
- The information available to the model in this request, including instructions, history, tool definitions, and source material.
- Generation budget
- The limit on generated content. Some APIs also count reasoning usage toward this budget; check the target API's rules.
- Safety margin
- Headroom reserved by the application for counting errors or expected growth. It does not replace actual token counts.
How does the mechanism work?
Step-by-step explanation
- Assemble the request
Count instructions, history, tool definitions, and evidence separately.
- Check constraints
Check both total capacity and the separate output limit.
- Call and check status
Distinguish completion, budget exhaustion, refusal, and transport interruption.
- Prepare for the next round
Recount after adding tool results to check whether necessary evidence is retained.
Implementation · Build it
Turn capacity rules into a testable function
Objectives of this level: Ability to run budget experiments and include the next round of increments in the review.
Visual guide · Recount the next request
These counts assume the lab’s shared 32,000-unit capacity. An independent output limit still applies; character counts and provider tokens are different units. Select the figure to open it at full size.
Count components before summing them
The offline lab's components count instructions, history, tool definitions, and evidence separately. remaining validates count types and the independent output limit before calculating capacity. It rejects booleans because Python bool values can behave as integers, while the contract requires explicit counts.
Check again on every round
A request that fits on round one may overflow on round two. Tool results, model responses, and new questions all add input, and real interfaces can charge for message structure too. This lab accepts given numbers. A production adapter needs the target model's counting method and actual usage records to calibrate estimates.
Passing the budget check is only one condition
The budget function establishes that local capacity rules permit the request. It checks no relevance, citation completeness, or tool authorization. A partial JSON object left after generation reaches its limit cannot be executed because an earlier capacity check passed. Complete-response status, parsing, and business checks remain necessary.
Run experiments and observe counterexamples
Offline arithmetic experiment for a given number of tokens; no model calls, no verification of tokenizers, streaming, or actual vendor limitations.
Python 3.10+ · Runs by default using only the standard library · Runs on your computer
- Calculate by hand first, then run the script to verify
- Change tool result increment and recalculate
- Deliberately exceed the independent output limit, check the wrong branch
python3 context_budget.pyView the entry-point script
"""Given token counts: no tokenizer, model request or provider-specific limit."""
import json
def remaining(context, output_limit, output, reserve, components):
values = [context, output_limit, output, reserve, *components.values()]
if any(type(v) is not int or v < 0 for v in values):
raise ValueError("counts must be non-negative integers")
if output > output_limit:
raise ValueError("output limit exceeded")
return context - sum(components.values()) - output - reserve
def demo():
components = dict(instructions=2000, history=10000, tools=3000, evidence=8000)
output = 6000
result = 4000
before = remaining(32000, 8000, output, 1000, components)
after = remaining(32000, 8000, output, 1000, {**components, "result": result})
return dict(input_tokens=sum(components.values()), current_room=before,
next_turn_room=after, next_turn_fits=after >= 0)
if __name__ == "__main__":
print(json.dumps(demo(), sort_keys=True))
Expected output when running locally
{"current_room": 2000, "input_tokens": 23000, "next_turn_fits": false, "next_turn_room": -2000}- Complete input items are consistent
- Next round of capacity recalculation
- Passing the experiment does not mean passing the answer quality
code example
Full contract terms determine exceptions
Ordinary summarization tasks become dependent on precise explanations of definitions, negatives, and exceptions.
When the budget is insufficient, can you summarize all the terms and explain them?
The abstract can locate relevant sections, but read the full definitions, terms, and exceptions of the applicable version before key conclusions, and retain the citation. If the combination still exceeds the window, split it into acceptable sub-tasks according to the problem, save the intermediate claims and basis and then synthesize them; if the necessary context cannot be retained, narrow the scope of the conclusion. Changing tokens cannot offset errors caused by missing conditions.
Capacity adjustments must retain evidence that determines the conclusion, and independent acceptance of semantic adequacy is required.
Acceptance task for this level
Download context_budget.py, and after running it, change result to 1000, and then change output to 9000.
Reading this browser’s record…
Hide the answer and check your understanding
If the function returns a positive number, does that prove the answer is correct?
Expand reference derivation
It only shows that the supplied counts satisfy the capacity rules. Evidence quality, generation status, factual support, and business results still require separate verification.
Further explanations and practice
When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.
Sources and verification scope
The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.