Chapter 3 · Part 2
Hold a conversation
Here's the thing that surprises everyone: the API has no memory. Each call to
messages.create() is completely independent — Claude doesn't remember your last question. Ask
"What's the capital of France?" then "What's its population?" as two separate calls, and the
second one has no idea what "its" refers to.
The fix is simple and it's the heart of every chatbot: you keep the history, and resend the whole conversation every time.
Start your chatbot.py
From here we build one program — chatbot.py — that grows over the next three chapters. Start
with a running list of messages and append each turn to it:
from anthropic import Anthropic
client = Anthropic()
messages = [] # the whole conversation lives here
def chat(user_text):
messages.append({"role": "user", "content": user_text}) # add the human turn
reply = client.messages.create(
model="claude-opus-4-8",
max_tokens=1024,
messages=messages, # send ALL of it
)
answer = reply.content[0].text
messages.append({"role": "assistant", "content": answer}) # remember Claude's turn
return answerThe two append lines are the whole trick. Before each call the list holds every turn so far;
after it, we add Claude's reply so the next call includes it. The conversation accumulates.
Prove it remembers
print(chat("My name is Sam and I love astronomy."))
print(chat("What's my name, and suggest a hobby for me?"))Nice to meet you, Sam! Astronomy is a wonderful field to be passionate about.
Your name is Sam! Given your love of astronomy, you might enjoy
astrophotography — capturing the night sky with a camera and telescope.The second answer knows your name and your interest — because the first exchange was still in
messages when we made the second call. That's memory, and you're the one holding it.
Make it interactive
Wrap it in a loop and you have a real chatbot. Add this to the bottom of chatbot.py:
if __name__ == "__main__":
print("Chat with Claude (type 'quit' to exit).")
while True:
user_text = input("\nYou: ")
if user_text.lower() in {"quit", "exit"}:
break
print(f"\nClaude: {chat(user_text)}")python chatbot.pyYou can now have a back-and-forth conversation that remembers everything. There's one rough edge: after you hit enter, the whole reply appears at once after a pause. Real chatbots type it out live — that's the next chapter.