Trim Chat History to Fit a Model Context Budget
Last updated: November 29, 2026
Quick Overview
Given a list of chat messages (system, user, assistant) and a token budget, return the subset to send to the model: always keep system messages, then keep the most recent turns that fit, preserving order.
Mistral AI
November 29, 20260
0
0 solved
Given a list of chat messages (system, user, assistant) and a token budget, return the subset to send to the model: always keep system messages, then keep the most recent turns that fit, preserving order.
A warm-up in the style of a Mistral AI backend or Le Chat engineering screen, where long conversations must be cut down before hitting a model's context window. The interviewer checks clean greedy logic, that order is preserved, and that you think about what truncation does to conversation coherence.
What the Interviewer Expects
- Always keep system messages and fail loudly if they alone exceed the budget
- Walk from newest to oldest and stop at the first message that does not fit
- Return messages in original order
- Treat the tokenizer as an injected function rather than hard-coding word counts
- Discuss coherence issues such as starting on an orphaned assistant turn
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you keep tool-call and tool-result messages together as one unit?
- How would you reserve room for the model's reply (max_tokens)?
- When would you summarize dropped turns instead of discarding them?
- How do you avoid re-tokenizing the whole history on every request?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: messages (dicts with role, content), an integer budget, and count_tokens(text). Output: a list in original order where system messages are always present and the remaining slots go to...
High-Level Design
- Sum the cost of all system messages; error if over budget.
- Iterate from the last message backwards, adding each non-system message while it fits.
- Stop at the first one that does not fit, so t...