← All Exercises
Fit a Conversation Into a Token Budget
intermediatejavascript
Background
Context overflow errors come from adding a message without accounting for the reserved output budget. Dropping oldest-first is the standard mitigation.
Problem
Reserve output tokens, then keep the newest conversation messages that fit the remaining context window, reporting which were dropped and what remains.
Input
JSON object: { contextWindow, systemTokens, messages: [{ role, tokens }], reserveForOutput }Output
JSON object: { kept: string[], dropped: string[], usedTokens, remainingTokens }Sample tests
Sample 1
Input: {"contextWindow":8000,"systemTokens":1000,"messages":[{"role":"user","tokens":500},{"role":"assistant","tokens":3000},{"role":"user","tokens":3000}],"reserveForOutput":1000}Expected: {"kept":["assistant","user"],"dropped":["user"],"usedTokens":7000,"remainingTokens":0}Sample 2
Input: {"contextWindow":4096,"systemTokens":500,"messages":[{"role":"user","tokens":200}],"reserveForOutput":1000}Expected: {"kept":["user"],"dropped":[],"usedTokens":700,"remainingTokens":2396}Your solution
Learning objective
Manage LLM context explicitly instead of retrying after overflow errors.