Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Context and generation budgets

Calculate the capacity of a complete request and connect input size, output budget, growth in the next turn, and evidence retention.

Learning objectives: Calculate capacity for a request and the next turn of tool results, and distinguish context overflow, output truncation, and network interruption.

Content checked: 2026-10-04 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Debugging · Diagnose failures. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: A long conversation needs to be located or a tool loop fails.

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
  1. Assemble the request

    Count instructions, history, tool definitions, and evidence separately.

  2. Check constraints

    Check both total capacity and the separate output limit.

  3. Call and check status

    Distinguish completion, budget exhaustion, refusal, and transport interruption.

  4. Prepare for the next round

    Recount after adding tool results to check whether necessary evidence is retained.

Debugging · Diagnose failures

Use response states to diagnose overflow, truncation, and lost evidence

Objectives of this level: Failure stages can be located based on request, response and evidence snapshots.

Visual guide · Recount the next request

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.

Preserve facts that distinguish causes

Record input counts by component, generation settings, terminal response status, tool-result size, and evidence IDs. Debug logs must respect the evidence's access rules; troubleshooting does not justify retaining all user text. A single request-failed message cannot distinguish capacity rejection, network failure, and incomplete generation.

Construct three separate failures

Keep the generation budget fixed and enlarge tool results until the input rule fails. Next, keep input within capacity but lower the output allowance and inspect the incomplete artifact. Finally, interrupt transport. The numeric lab covers no transport interruption, so verify that case with a real interface or a reliable test double. Increasing tokens is not a common remedy for all three.

Check what compression removed

A summary can shorten evidence while dropping exception clauses. Label the evidence each fixed task must retain, then compare coverage and answers before and after compression. A request that now fits demonstrates a capacity improvement. If it silently omits necessary conditions, the repair is incomplete.

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

  1. Calculate by hand first, then run the script to verify
  2. Change tool result increment and recalculate
  3. Deliberately exceed the independent output limit, check the wrong branch
Downloadcontext_budget.py ↓
python3 context_budget.py
View 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
View the running environment, output and verification records →

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

Write a checklist to list observation signals and processing methods for capacity rejection, generation truncation, and streaming interruption.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

The same request runs after compression. Can you declare the problem fixed?

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.

All linked explanations and exercises (3 )

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.