Module 7, Lecture 7.1 | Implementing Context Management
Module 7 is the implementation module: each lecture takes a context-management strategy introduced conceptually in Module 4 and writes the real code, running against the agent and instrumentation built in Module 6. This lecture starts with the simplest strategy — the sliding window — which keeps the most recent messages and drops the rest once token usage crosses a threshold. The strategy is easy to describe but easy to get subtly wrong: a naive messages[-n:] slice silently breaks the agent because the messages array has structure a blind cut ignores. The lecture establishes the single safe hook point (the top of the inner loop, before each API call, when the array is in a complete state) and the two Messages API constraints every strategy must respect — pair integrity (a tool_use must keep its tool_result) and alternating roles. It then builds a pair-aware window that walks forward to a safe cut, prepends the first user message as a task anchor so the goal survives, and inserts a synthetic acknowledgment to keep roles alternating. Sliding window is effective at shrinking context but lossy: everything between the anchor and the recent tail is discarded — which sets up selective preservation in the next lecture.
Read the full lecture narrative
tool_use and tool_result content blocks and the agentic loop. This is the source of the pair-integrity constraint the sliding window has to respect — cutting between a tool_use and its matching tool_result produces a 400 error.