Lesson 10 of 23 · Part 1: API Basics

Conversation Loop

Build a multi-turn chatbot that remembers context across messages.

Last time: A "system" message placed first tells the AI who to be before it reads the question.
Today: We build a chatbot you can talk to again and again, keeping its memory in a list.
while Trueinput()→quit?→append→create()→append→print↺
messages
no list yet
Chat window
Source Code
1# 3_conversation_loop.py
2from openai import OpenAI
3client = OpenAI()
4
5messages = [{"role": "system", "content": "You are a helpful assistant."}]
6
7print("Chat started! Type 'quit' to exit.\n")
8
9while True:
10    user_input = input("You: ")
11    if user_input.lower() == "quit":
12        break
13
14    messages.append({"role": "user", "content": user_input})
15
16    response = client.chat.completions.create(
17        model="gpt-4o-mini",
18        messages=messages
19    )
20
21    assistant_msg = response.choices[0].message.content
22    messages.append({"role": "assistant", "content": assistant_msg})
23    print(f"AI: {assistant_msg}\n")
24
25print("Goodbye!")

No output yet...

← Prev
1/0
Next: JSON Output →