Messages and Roles
Part of the Calling Models From Code section of Coddy's AI Engineering journey. Lesson 2 of 22.
messages is a list of turns. Each turn is a dict with a role and a content: "user" for what the person says, "assistant" for what the model said. The list starts with a user turn and ends with the user turn you want answered.
messages = [
{"role": "user", "content": "My city is Lisbon."},
{"role": "assistant", "content": "Lisbon is lovely."},
{"role": "user", "content": "What is my city?"},
]
response = client.messages.create(model="claude-opus-5-5", max_tokens=100, messages=messages)
print(response.content[0].text)This prints Your city is Lisbon.
The API is stateless: it keeps nothing between calls. A chat app remembers a conversation because it sends the whole list every time, adding the model's reply and the next question to it. Send the last question alone and the model has never heard of Lisbon.
Challenge
EasyShow that the model only knows what you send it.
- The starter reads a name and a question.
- Send three messages: the user says
My name is <name>., the assistant repliesNice to meet you, <name>., then the user asks the question. PrintWith history:and the reply. - Send the question as the only message and print
Without history:and the reply.
Use model="claude-opus-5-5" and max_tokens=200 for both calls. For example, for the input Sam and What is my name? the program prints:
With history: Your name is Sam.
Without history: I don't know your name yet.Try it yourself
import coddy_ai as anthropic # in production: import anthropic
client = anthropic.Anthropic()
name = input()
question = input()
# 1. Send a conversation: the user says "My name is <name>.",
# the assistant replies "Nice to meet you, <name>.", then the user asks the question.
# Print "With history: " and the reply.
# 2. Send the question alone and print "Without history: " and the reply.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Calling Models From Code
1First Model Calls
Your First Model CallMessages and RolesSystem PromptsReading the ResponseRecap: Shop Help DeskPractice on your own: Online Python compiler