Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 6: Context Engineering

Week 06 / Lesson 1

Budgeting a model request

Allocate a context window while preserving instructions, evidence, and output space.

Section 1.1 1 of 7

Overview

Focus

Allocate a context window while preserving instructions, evidence, and output space.

Your route through the lesson

  • 1.2 What occupies a context window
  • 1.3 Measuring tokens and reserving output
  • 1.4 Persistent instructions and conversation state
  • 1.5 Put it into practice
  • 1.6 Guided comparison
  • 1.7 A conversation with a new output limit

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 1.2 2 of 7

What occupies a context window

Focus

Count the complete request contents and distinguish available context from durable memory.

A context window is the sequence capacity available to a model request under its runtime configuration. It can contain trusted instructions, conversation messages, retrieved evidence, tool descriptions and results, formatting tokens, and generated output. A long conversation stored on disk is not automatically all present in the current request. The application chooses what to send.

Persistent instructions are rules the application deliberately reinserts when constructing a request. Conversation state is the working record of facts, decisions, unresolved questions, and relevant history. Neither should be confused with model training: adding a message to context does not update model weights. If an instruction is absent from the next request, the model cannot be assumed to remember it from another session.

For a local-only summarizer, preserve the current local-output constraint even if it was stated many turns ago. Old unrelated discussion can be dropped first. The useful ordering is based on task relevance and authority, not simply message age. An older active constraint can matter more than a recent casual remark. Budgeting begins by identifying what must survive before deciding how much remaining history or evidence to include.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A conversation is stored on disk but not sent in the current request. Can the model be assumed to see it?
2. An older local-output constraint remains active; a recent unrelated joke consumes space. What should be retained first?
3. Adding a user message to context performs weight training. Correct?

Section 1.3 3 of 7

Measuring tokens and reserving output

Focus

Measure actual tokenizer output including chat formatting and reserve generation space.

A token is a unit produced by a model's tokenizer, not a character or word. Different tokenizers split the same text differently. Chat templates also insert role markers and separators. To make a real token-budget claim, count the complete serialized request with the intended tokenizer and template, then add the reserved output allowance.

If a declared window is 512 tokens, input measures 390, and output reserve is 64, total use is 454 with 58 spare. Counting only message content can omit formatting overhead. Character counts are acceptable for an explicitly labeled toy ledger, but a character-to-token guess is not an exact model measurement.

The optional real-tokenizer path uses the Transformers library, a package providing model and tokenizer interfaces, without loading model weights. In your exercise environment install it with python -m pip install transformers. Download a small tokenizer artifact with this code:

from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(
    'HuggingFaceTB/SmolLM2-135M-Instruct', trust_remote_code=False)
tokenizer.save_pretrained('tokenizer')

This needs internet and disk space for tokenizer files, normally no account. The lab then uses that local directory. Chat-template documentation explains serialization. Its count is exact for that saved template, not automatically for a different server template.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Input measures 390 tokens, reserve is 64, window is 512. Remaining capacity?
2. Why count through the chat template instead of summing only content tokens?
3. A saved tokenizer counts one template exactly. Does that prove an unrelated server uses the same count?

Section 1.4 4 of 7

Persistent instructions and conversation state

Focus

Build request state that preserves current constraints and explicitly removes revoked ones.

Conversation state should distinguish active instructions from historical statements. A user may first request email delivery and later revoke it in favor of local output. Keeping every old message without a current-state interpretation risks presenting contradictory instructions; dropping all old messages risks losing the revocation's meaning.

Maintain a structured record of active constraints, decisions, tentative options, revoked preferences, and source references. When constructing the next request, include the current constraint and enough evidence to understand its scope. Historical revoked instructions can be represented as revoked rather than repeated as if still active. This is application state management, not a special memory property of the model.

For the local-output example, the request builder retains the system privacy rule, the user's current local-only requirement, and the current question. It omits old unrelated assistant discussion. If space remains, useful evidence can be added under the same budget. Check required constraints directly in the assembled state before sending. A valid token count establishes capacity, while those semantic checks establish preservation; neither substitutes for the other. The model's resulting compliance still requires observed output and effect checks.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Email delivery was revoked in favor of local output. How should current state represent email?
2. A request fits its token budget but omits the active privacy rule. Is budgeting complete?
3. Which should be checked before sending a compacted request?

Section 1.5 5 of 7

Put it into practice

Focus

Run the labeled character fixture and optionally the actual-tokenizer ledger.

Download week06.py, save it in an exercise folder, and run python week06.py --lesson 1. This single practice first runs a standard-library character ledger. It is deliberately labeled characters, NOT model tokens. It completes within seconds on a small processor, preserving the privacy instruction and local-output constraint while dropping old unrelated text.

After the tokenizer setup above, run python week06.py --lesson 1 --tokenizer-dir tokenizer. The optional path loads only local tokenizer files with trust_remote_code=False. apply_chat_template receives the kept messages, tokenize=True, and add_generation_prompt=True. It returns token identifiers including the selected template's generation prefix. len counts those identifiers; the script asserts input tokens plus a 32-token output reserve fit a declared 512-token window.

Expected output clearly separates fixture characters from actual serialized_input_tokens and remaining_tokens. No model inference happens in this script. If the tokenizer package or files are unavailable, record actual token budgeting uncompleted rather than treating the character ledger as a substitute. The measured count applies to the saved tokenizer and template; compare runtime prompt counts if later claiming exact equivalence with a serving endpoint.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. The first report says fixture_unit=characters. What can it establish?
2. Which option invokes actual saved tokenizer accounting?
3. What does len(token_ids) measure after tokenize=True?

Section 1.6 6 of 7

Guided comparison

Focus

Explain the preserved request and its two distinctly labeled measurement paths.

The worked request keeps three messages: a system privacy rule, the user's local-output constraint, and the current question. It removes one long unrelated assistant message. In the default fixture, roles and contents contribute 135 characters, and the reserve adds 64, totaling 199 within a 300-character toy window. That arithmetic is exact in its declared units.

The optional tokenizer path serializes the same kept messages using the downloaded template. Its actual count may differ from 135 because token boundaries and chat markers differ from characters. The script reports the observed count rather than hard-coding a token total in the lesson. It then reserves 32 tokens and checks against 512.

The successful constraint assertion establishes that local output only survives the selection. It does not establish a live model followed that instruction, since no inference occurs. The token assertion establishes local serialization capacity, not that a different server adds no hidden instructions. A complete application evaluation can later compare the prepared request, server-reported prompt usage, output completeness, and authorized effects. The worked result is valuable precisely because each claim names its actual observation and preserves the remaining integration limits.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A character fixture uses input 135 and reserve 64 within window 300. Spare fixture capacity?
2. The actual tokenizer count differs from character count. Is that necessarily a bug?
3. The state retains local output only but no model is called. What remains unproved?

Section 1.7 7 of 7

A conversation with a new output limit

Focus

Recompute the complete budget when a new output limit changes available input space.

A request previously used 700 input tokens and reserved 100 output tokens in a 1000-token configured window. A new task requires a 350-token answer. The old input no longer fits because 700+350=1050. Increasing only the output cap can cause truncation or rejection even though the source text did not change.

The worked builder preserves current instructions and essential evidence, removes 80 tokens of unrelated history using the actual tokenizer, and obtains a measured input of 620. Combined with 350 reserved output tokens, total is 970 and spare capacity is 30. It rechecks that the current local-only constraint and required evidence survived. If they cannot fit, the application should narrow the task or choose another supported configuration rather than silently dropping the rule.

This example treats the stated numbers as measured token counts under one template. It does not assume that deleting eighty characters removes eighty tokens. Whenever content or formatting changes, reserialize and recount. Output reservations are engineering limits rather than guarantees of answer quality: an answer can fit and still be wrong, incomplete in meaning, or unauthorized in effect.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Input 700 plus new output reserve 350 in a 1000-token window fits?
2. After measured input falls to 620 with reserve 350 and window 1000, spare capacity?
3. May a builder assume deleting eighty characters removes eighty model tokens?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Selecting useful evidence for context →