Menu
CoddyTech

Chat With Memory

Part of the Calling Models From Code section of Coddy's AI Engineering journey. Lesson 20 of 22.

challenge icon

Challenge

Medium

Build a chat loop that remembers the conversation. Each input line is one thing the user says, until the line quit.

  1. Keep a messages list. For each line, append it as a user turn and send the whole list with system=SYSTEM, model="claude-opus-5-5" and max_tokens=200.
  2. Print Echo: and the reply text (find the text block by its type), then append the reply to messages as an assistant turn, so the next call carries it.
  3. When the line is quit, stop without calling the model and print Turns: <number of replies>, then Input tokens: <total>: the sum of usage.input_tokens over 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?
quit

the program prints:

Echo: I'm not sure about that.
Echo: Your city is Oslo.
Turns: 2
Input tokens: 77

Try 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