Chapter 4 · Quest 4 of 5 · 10 XP
Too Much to Remember
🧠 Models can only read so much at once: that limit is the context window. When a chat gets long, agents keep the system prompt and only the newest messages. Slicing a list makes that easy:
nums = [1, 2, 3, 4, 5] print(nums[-2:]) print(nums[1:]) print(nums[:1])
[4, 5] [2, 3, 4, 5] [1]
[-2:] means "the last 2", [1:] "everything after the first" and [:1] "just the first". + joins two lists into one.
Instructions
- Make
trim(messages, n). - It returns the first message (the system prompt) plus the last
nother messages. - If there are
nmessages or fewer after the system prompt, it returns them all. - Print how many messages
trim(history, 4)keeps.
💡 Hint
messages[:1] is the system prompt in a list. messages[1:] is everything else, and [-n:] on that keeps its last n. Join them with +.
bot.py
Terminal