Build Your First AI Agent / Chapter 2: Talk to the Model
Feedback
Quest

10. Chat Loop

Models don't remember anything on their own. To hold a conversation, your bot keeps a message history: a list of every message so far, sent in full each time.

messages = []
messages.append({"role": "user", "content": "Hi!"})
reply = pip.chat(messages)
messages.append({"role": "assistant", "content": reply})

Each message is a dict with a role (who said it) and content (what they said). pip.chat() reads the whole list and answers the last user message. That's memory, the simple way. Finish this one for your second badge.

Instructions

  1. Make an empty list: messages = []
  2. Loop over talk. Each time, add {"role": "user", "content": text} to messages.
  3. In the loop, store pip.chat(messages) in reply, print it, and add it as {"role": "assistant", "content": reply}.
  4. At the end, messages holds 6 messages and Pip says Your name is Sam.
Hint

for text in talk: append the user message, then reply = pip.chat(messages), print(reply), then append the assistant message. All 4 lines indented inside the loop.

Solution
import pip
talk = ["Hi!", "My name is Sam.", "What is my name?"]
messages = []
for text in talk:
    messages.append({"role": "user", "content": text})
    reply = pip.chat(messages)
    print(reply)
    messages.append({"role": "assistant", "content": reply})
Still stuck?

Press "Talk it out" at the top. Our Discord opens soon; until then email us and paste your code.

Chapter quests
  1. Chapter 1: Hello, Bot
  2. Chapter 2: Talk to the Model
    1. First Words 10 XP
    2. Who Are You? 10 XP
    3. Fortune Teller 10 XP
    4. Tidy Reply 10 XP
    5. Chat Loop 15 XP
  3. Chapter 3: Tools CLUB
  4. Chapter 4: Memory CLUB
  5. Chapter 5: Loops and Plans CLUB
  6. Chapter 6: Party of Agents CLUB
bot.py
Terminal
Chapter 2: Talk to the ModelQuest 5 / 515 XPBackNext

Talk it out

  1. What did you expect your bot to do?
  2. What did it actually print? Read the terminal, line by line.
  3. What's different? Spelling, capitals, spaces and full stops all count.
  4. Is there an error? It tells you the line number. Look there first.
  5. Read the instructions again, one at a time. Each one is checked on its own.

Badge unlocked:

Your bot got a new part. Chapter complete!

Make your bot

Pick a name and a colour. You can change them later.