MediumContext ManagementPython 3
Context Window Packer
Select system and recent conversation messages without exceeding a token budget.
30m1 sample tests1 hidden tests
Choose which chat messages fit into a bounded context window.
Requirements
- Define
pack_messages(messages, max_tokens). - Each message is a dict with
id,role, andtokens. - Return the selected message IDs in original order.
- Keep the first system message if it fits.
- Fill the remaining budget with the newest non-system messages.
- Skip any message that does not fit.
- Never exceed
max_tokens.
Example
python
1messages = [
2 {"id": "sys", "role": "system", "tokens": 2},
3 {"id": "old", "role": "user", "tokens": 3},
4 {"id": "new", "role": "assistant", "tokens": 4},
5]
6assert pack_messages(messages, 6) == ["sys", "new"]Constraints
- Preserve conversation order in the returned IDs.
- Prefer recency for non-system messages.
- Do not mutate the input messages.
Editor
Results
Run sample tests or submit all tests.