Start learning free

LESSON 3 OF 129 · AI ENGINEERING: CALLING A MODEL

A Conversation in Python

Practice

A model remembers nothing between calls. Each request starts from zero: the model sees only what this request holds. So a follow-up like "And how much is it?", sent alone, makes no sense to it.

The conversation: since the model keeps no memory, your program keeps it. The messages list is the conversation, and every call sends all of it. After each answer you append it as a message with the role "assistant", then you append the next user message. A list ready to send looks like this one, written by hand:

messages = [
    {"role": "user", "content": "Do you sell candles?"},
    {"role": "assistant", "content": "Yes, vanilla and pine."},
    {"role": "user", "content": "Which one is cheaper?"},
]

The roles take turns, and the last message is the one the model must answer.

This lesson's program must print the first three lines below. The check then adds the fourth: the roles your last call sent.

Shop: For tea lovers we have the Teapot.
Alone: How much is what? Tell me which product you mean.
With the conversation: The Teapot costs $22.
Roles sent in the last call: user, assistant, user

Your task: the first question is already asked: its answer is in answer, and the customer's next message is in follow_up. First send follow_up alone and print what comes back. Then append the model's answer and follow_up to messages, send the whole list and print the new answer.


Assignment
Follow the Coding Tutorial to send a follow-up question alone, then with the whole conversation, and print both answers.


Hint
The order matters: append the assistant's answer first, then follow_up, so the roles read user, assistant, user. The system prompt goes with every call.


STEP 1 OF 6
    Ctrl + Enter to check

    Ai Conversation in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free