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

09. Tidy Reply

Bots often need answers they can read, not just chat. So we ask the model for JSON: text written like a Python dictionary. json.loads() turns it into a real dict.

import json
text = '{"hp": 10, "class": "mage"}'
hero = json.loads(text)
print(hero["class"])
mage

Ask Pip for JSON and it answers with its mood and battery.

Instructions

  1. Add import json (next to import pip).
  2. Store pip.ask("Give me your mood as JSON") in reply.
  3. Turn it into a dict with json.loads(reply) and store it in data.
  4. Print data["mood"].
Hint

data = json.loads(reply) makes a dict. Then data["mood"] reads one value out of it.

Solution
import pip
import json
reply = pip.ask("Give me your mood as JSON")
data = json.loads(reply)
print(data["mood"])
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 4 / 510 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.