Trim a chat history to fit the context window
Every model has a context window: a maximum number of tokens it can read at once. Chat apps keep the system prompt, then fit in as many of the most recent messages as they can.
Write fit_history(messages, budget, count_tokens) where messages is a list of dicts like {"role": "user", "content": "..."}, messages[0] is always the system prompt, and count_tokens(text) returns the token count of a string.
Always keep the system prompt. Then walk backwards from the newest message, keeping each message while the running total stays within budget. Stop at the first message that does not fit (do not skip over it to grab older ones). Return the kept messages in their original order.
If the system prompt alone is over budget, return just the system prompt.
def fit_history(messages, budget, count_tokens)Understand the idea
A model can only read a fixed number of tokens, so a chat app must decide which messages to keep. The system prompt always stays. Then you add messages starting from the newest, because recent turns matter most, and stop as soon as one does not fit. You do not skip over a large message to grab older small ones, because that would leave a gap in the conversation. Worked example: budget 10. System prompt is 3 tokens. Other messages, oldest to newest, are m1 = 4, m2 = 5, m3 = 2 tokens. Start at 3. Add m3: total 5. Add m2: total 10, still within budget. Try m1: total 14, too big, so stop. Return [system, m2, m3] in original order. If the system prompt alone is over budget, return only it. Rule: keep system, walk backwards adding while running total <= budget, stop at the first failure, then restore order. Every chat product built on an LLM API needs this trimming.