Chat With Memory
Part of the Calling Models From Code section of Coddy's AI Engineering journey. Lesson 20 of 22.
Challenge
MediumBuild a chat loop that remembers the conversation. Each input line is one thing the user says, until the line quit.
- Keep a
messageslist. For each line, append it as a user turn and send the whole list withsystem=SYSTEM,model="claude-opus-5-5"andmax_tokens=200. - Print
Echo:and the reply text (find the text block by its type), then append the reply tomessagesas an assistant turn, so the next call carries it. - When the line is
quit, stop without calling the model and printTurns: <number of replies>, thenInput tokens: <total>: the sum ofusage.input_tokensover every call.
The input tokens grow each turn, because each call sends the whole history again: that is what a long chat costs. The stand-in has nothing to say to a plain statement, so it answers I'm not sure about that.; a real model would reply politely. For example, for this input:
My city is Oslo.
What is my city?
quitthe program prints:
Echo: I'm not sure about that.
Echo: Your city is Oslo.
Turns: 2
Input tokens: 77Try it yourself
import coddy_ai as anthropic # in production: import anthropic
client = anthropic.Anthropic()
SYSTEM = "You are Echo, a friendly assistant. Answer in one sentence."
# Write your code below
All lessons in Calling Models From Code
Practice on your own: Online Python compiler