← Building with AI

Trimming long conversations

Keep the newest messages so the request stays small.

Start this lesson

Every model has a context window: the most text it can read in one request. Long chats also cost more, because the whole history is sent each time. A simple fix is to keep only the newest messages. One rule to remember: the list must still start with a user message, so if trimming leaves an assistant message first, drop it too.

history = [
    {"role": "user", "content": "Hi"},
    {"role": "assistant", "content": "Hello!"},
    {"role": "user", "content": "Tell me a joke"},
    {"role": "assistant", "content": "Why did the cat sit on the computer? To keep an eye on the mouse."},
    {"role": "user", "content": "Another one!"},
]
recent = history[-3:]            # the newest 3 messages
print([m["role"] for m in recent])  # ['user', 'assistant', 'user']

A negative slice like history[-3:] takes items from the end. It makes a new list and leaves history as it was.

Trimming has a cost: the model forgets what you dropped. Bigger apps keep important facts (like the user's name) somewhere else, or ask the model to write a short summary of old messages and keep that instead.