Skip to content
IT Vizag
← Python Meets AI

▶ 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

Lesson 5 of 10 · 2 min read

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

🔒 Code example: sign up free (above) to unlock it.

Keep the history in a list

🔒 Code example: sign up free (above) to unlock it.

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

🔒 Code example: sign up free (above) to unlock it.

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

🔒 Code example: sign up free (above) to unlock it.

Load it later with json.load, and the conversation continues where it left off.

Tip: When a chatbot "forgets" something, print 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.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend