▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Conversation memory
Keep chat history in a list to build a real chatbot.
🎬 Video version coming soon — read it now
Here's a surprise: the API has no memory. Each request is independent. ChatGPT seems to remember because the app sends the whole conversation every time. Your code must do the same.
Proof
Keep the history in a list
Each turn appends the user's message and then the assistant's reply. The list grows: user, assistant, user, assistant...
A chatbot in a loop
That's a working chatbot: a while loop, a list and a function.
Rules for the history list
- The first message must have role
"user". - Roles normally alternate between user and assistant.
- You can edit the list: start fresh with
history.clear(), or remove old turns.
Cost and length grow
Because the whole history is sent each time, turn 20 costs far more than turn 1. Models also have a maximum context window. For long chats:
- Keep only the last N turns:
messages=history[-20:](make sure the slice still starts with a user message) - Or ask the model to summarise the conversation so far, and start a new history with that summary
Save and resume
Load it later with json.load, and the conversation continues where it left off.
len(history) and the last few items. Nine times out of ten, a message never got appended.In one line
The API remembers nothing, so keep the conversation in a list of messages, append every turn, and send it all each time.
Share with a friend