Python · Exercise 1 of 6Next
Intermediate
Trim a chat history to a token budget
Write trim_to_budget(messages, budget). The first message is the system message and is always kept. Then keep the newest messages that fit, so the total token count of the kept messages is at most budget.
Count tokens with the provided count_tokens(text), which counts one token per word. Each message is a dictionary, and its text is under the key "content". Return a new list with the kept messages in their original order. Do not change the list you were given. (Tokens: Topic 16.4.)
What Check tests
- Keeps the system message and the newest messages that fit
- Keeps everything when the budget is large
- Keeps only the system message when nothing else fits
- Stops at the first message that does not fit (never skips a newer one to keep an older one)
- Does not change the input list
Stuck? One hint at a time
The solution unlocks after your first Check. Try first: that is where the learning happens.
main.py
Sign in to run your code.
Output
Press Run to see what your program prints.