BUILD A LOCAL CHATBOT · MODULE 2 — GIVING IT A MEMORY · bc-05 Real Python, every page

Module 2.5 · Deepens page 4

The chat loop

The fix for bc-04's amnesia is almost embarrassingly simple: keep a list, append every turn to it, and re-send the whole thing every time. Step through the same two turns — this time watch the actual assembled prompt string grow.

The script

One list, appended to every turn

bc-05-chat-loop.py
history = []  # every turn, user and assistant, accumulates here

def chat(user_message):
    history.append({"role": "user", "content": user_message})
    prompt = tokenizer.apply_chat_template(history, tokenize=False, add_generation_prompt=True)
    inputs = tokenizer(prompt, return_tensors="pt", add_special_tokens=False)
    outputs = model.generate(**inputs, max_new_tokens=30)
    reply = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
    history.append({"role": "assistant", "content": reply})  # the reply joins history too
    return reply

Same apply_chat_template call as bc-04 — the only change is that history now survives between calls instead of being rebuilt from nothing each time. Download bc-05-chat-loop.py ⬇

Try this

Add a Turn 3 to bc-05-chat-loop.py ⬇ — chat("What did I say my name was, again?") — and run it. Predict first: does it still get it right, and does the assembled prompt keep growing the same way?

So what

There's no "conversation" object anywhere in the library — you are the memory, one Python list.