← Building with AI

Keeping conversation history

The model has no memory. Your list is its memory.

Start this lesson

An AI API does not remember you between requests. Each call starts fresh. A chatbot seems to remember because the program keeps a history list and sends the WHOLE list every time: add the user's message, call the model, then add the model's answer as an assistant message. Forget that last step and the bot forgets what it said.

# To run on your own computer with an API key (it cannot run in this browser).
# First: pip install anthropic, and set the ANTHROPIC_API_KEY environment variable.
import anthropic
client = anthropic.Anthropic()
history = []

def chat(text):
    history.append({"role": "user", "content": text})
    reply = client.messages.create(model="claude-sonnet-5-5", max_tokens=300, messages=history)
    answer = reply.content[0].text
    history.append({"role": "assistant", "content": answer})
    return answer

print(chat("My favourite fruit is mango."))
print(chat("Suggest a smoothie with my favourite fruit."))

The second question works only because the first exchange is still in history.

Since you send the whole history every time, long chats cost more tokens per message. Later you will learn to trim old messages.