Command Palette

Search for a command to run...

Hectal
Phase 12: Building a Production LLM Service
LLM Engineering · Exercise 2 of 6 PreviousNext
Intermediate

Trim a conversation to a budget

messages is a list of (role, text) pairs, oldest first. Write trim(messages, budget) that returns the newest messages whose words add up to at most budget, in the original order.

Count words with len(text.split()). Always keep the last message, even when it alone is over the budget. Stop at the first older message that does not fit (do not skip it to include an even older one).

What Check tests

  1. Keeps the newest messages that fit, in order
  2. Everything is kept when it fits
  3. The last message is always kept
  4. It stops at the first message that does not fit
  5. An empty list gives an empty 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.