← Building with AI

Limits: context window and max_tokens

Stay inside the limits and notice when you hit them.

Start this lesson

Two limits matter. The context window is the most tokens the model can read in one request (your whole history plus prompt). max_tokens is the most it may write back. If the history grows too big, drop the oldest messages until it fits. If a reply stops with 'max_tokens', tell the user it was cut off instead of pretending it is complete.

def fit(history, limit):
    history = list(history)            # copy, so we don't change the original
    while len(history) > 1 and messages_tokens(history) > limit:
        history.pop(0)                 # drop the oldest message
    return history

pop(0) removes the first (oldest) item. The loop stops when the history fits or only the newest message is left.

Context windows are large today (often hundreds of thousands of tokens), but cost grows with every token you send, so trimming still saves money.

If dropping one message leaves an assistant message first, drop that too, as you did in the trimming lesson.