Building a Multi-Turn Chatbot
In this lesson, you’ll learn how to build a conversational chatbot using the OpenAI Chat Completions API. This chatbot will retain context across turns, making interactions more natural and coherent.
Prerequisites
Make sure you have:
- Python 3.8 or later
- Installed the OpenAI Python SDK:
pip install openai
The Code
from openai import OpenAI
client = OpenAI()
# Initialize message history with a system prompt
messages = [
{"role": "system", "content": "You are a helpful assistant that answers concisely."}
]
# Run conversation loop
while True:
user_input = input("You: ")
if user_input.lower() in ["bye", "exit", "goodbye", "quit"]:
print("Assistant: Goodbye!")
break
messages.append({"role": "user", "content": user_input})
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
assistant_reply = response.choices[0].message.content
print("Assistant:", assistant_reply)
# Append assistant reply to message history for context
messages.append({"role": "assistant", "content": assistant_reply})
Explanation
- Maintains a conversation loop using a
while Trueblock. - Tracks the conversation using a
messageslist. - Exits cleanly if user types
bye,exit, or similar. - Appends each user and assistant message to the history to retain context.
- Uses
chat.completions.createfor each new turn.
Use Case
This is perfect for creating persistent, intelligent agents like:
- Customer support bots
- Personal assistants
- Educational tutors