How to Create Interactive Conversations with a ChatBot in Python

You can access the full course here: WEB-BASED CHATBOT WITH PYTHON AND CHATGPT

Introduction

Welcome to this tutorial on creating a chatbot using GPT-3! In this tutorial, we will explore how to create a simple chatbot that can have a real conversation using GPT-3 and the OpenAI API. We will be using Python to manage these interactions, and by the end of the tutorial, you should be able to have an engaging conversation with your chatbot. To follow this tutorial, you are expected to be familiar with Python programming and have a basic understanding of GPT-3.

Project Files

You will need to set up your own Python environment and the OpenAI library installed. We have included a full copy of the code files used in this tutorial for your reference.

In this lesson, we will learn how to modify our code so that we can have a real conversation with our chatbot. For that, we’ll be using a loop to capture the user input and add it to the conversation.

Download Project Files Here

Creating an Infinite Loop

The first thing we need to do is create an infinite loop. This loop will run until the user presses ‘q‘ to quit the loop:

import openai

openai.api_key = 'YOUR_KEY_HERE'

messages = []

while True:
    # capture user input
    user_input = input('Enter your prompt: ')

    # quit loop if user presses "q"

    # prompt preparation
    messages.append({'role': 'user', 'content': user_input})

    # send the api call
    response = openai.ChatCompletion.create(model='gpt-3.5-turbo', messages=messages)

    # display response in console
    print(response.choices[0].message.content)

In each iteration of the loop, we will capture the user input and add it to the conversation, as follows:

while True:
    # capture user input
    user_input = input('Enter your prompt: ')

    # quit loop if user presses "q"

    # prompt preparation
    messages.append({'role': 'user', 'content': user_input})

    # send the api call
    response = openai.ChatCompletion.create(model='gpt-3.5-turbo', messages=messages)

    # display response in console
    print(response.choices[0].message.content)

    # expanding the conversation
    messages.append(response.choices[0])

    print(messages)

We do that because ChatGPT needs the full conversation (from start to finish) for each interaction to be able to supply us with the next response.

Running our code, we see that we get both our prompt and the bot response printed to the console:

console bot response

Lastly, let’s handle the user input to quit the while loop by calling exit():

while True:
    # capture user input
    user_input = input('Enter your prompt: ')

    # quit loop if user presses "q"
    if user_input == 'q':
        exit()

    # prompt preparation
    messages.append({'role': 'user', 'content': user_input})

    # send the api call
    response = openai.ChatCompletion.create(model='gpt-3.5-turbo', messages=messages)

    # display response in console
    print(response.choices[0].message.content)

    # expanding the conversation
    messages.append(response.choices[0])

Conclusion

And that’s it! You have successfully created a chatbot using GPT-3 and Python! You now have a functional chatbot that can handle real-life conversations by continually updating the conversation and processing user inputs. This project may serve as a great starting point for developing more advanced chatbots or integrating chatbot functionality into your applications.

Now that you have mastered the basics of GPT-3 chatbots, you can continue learning about language models, machine learning, and AI by exploring related courses and tutorials. Dive deeper into the world of chatbots, discover new features, and enhance your skills as a developer. As always, we wish you the best of luck in your future projects!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.

Transcript

Hello and welcome. Currently, our chatbot is not really interactive. We’re able to ask one single question, get a response, and that’s the end of the conversation. What we are gonna be doing in this lesson is modify our code so that we can have a real conversation, meaning we can ask new things after the first prompt and we can dive deeper into the responses that the bot provides to us, which is the way that you use, uh, chat GPT on the web, uh, version.

So essentially, we need to be running all of this code for as long as the conversation is taking place. In order for us to do that, we’re gonna put everything inside of a loop, and it’s gonna be an infinite loop. We’re gonna let the user press, uh, a certain character for the conversation to finish. And what we are gonna be doing in each iteration of the loop is capture the user input, and then we are going to add something here. We’re going to quit the loop. If the user presses, let’s say Q or types exit, sorry, Q, um, then we’re gonna prepare the prompt, send the API call, share the response in the console or display.

But then what we need to do is we actually need to take that response and add it to the full conversation because the way chat GPT works is that each API call needs to have the full conversation for you to get the next response. That is, if you ask chat GPT, for example, what’s the weather like in Arizona? It tells you it’s sunny. If you then want to ask, should I wear sunscreen? You’re gonna have to send the whole conversation to chat GPT. You’re gonna have to send it the first prompt, “How’s the weather in Arizona?” You’re gonna have to send it the initial response you received, and then your new question. So essentially, we need to be expanding the conversation after each interaction.

To do that, we’re gonna type messages.append, and we are gonna pass the last message that we received. We’re gonna add that to our conversation. So in this manner, we are expanding our conversation as it progresses. To give you an idea of what this looks like, I’m going to be printing these messages on the screen.

And also, I want to show you the API reference, which might provide further clarification. So this is the chat API reference. And you can see here that a response has this message object, which is essentially a dictionary that has the role assistant because that’s the response we got and the content. So what we are doing here is just adding that into our conversation.

Let’s try it out and see if it works. So I’m gonna ask, “How is the weather in Arizona?” It’s telling us that it doesn’t have that information, and it’s gonna ask us about which city in Arizona. And then we get this message response. You can see that there is the user content, and then we get this one from OpenAI, which has the response as well as the role assistant. So now I can just type, for example, “Phoenix,” and it should know that I had firstly asked about Arizona and that now we are kind of drilling down about things.

So it’s telling me now that it cannot provide real-time updates, but it’s known to be in a hot desert climate. You can see that this messages list is growing, and now it’s including all of the previous conversations. So it starts with the initial one, and then it’s adding all the responses. You can see that this is working as expected.

What I’m gonna do is remove that print out as well as incorporate this user input so that we can terminate the loop. So if user input equals Q, we are going to exit this program. Let’s try it out to see if it works. I’m gonna type Q, and that should be it. So it exits.

That’s all for this lesson. We’ve recreated chat GPT in the terminal. We can have any kind of interactive conversations here and get any responses and have conversations that are as long as the model’s own capabilities will allow. So that’s all for this lesson. Thank you for watching. I will see you in the next lesson.

Interested in continuing?  Check out our all-access plan which includes 250+ courses, guided curriculums, new courses monthly, access to expert course mentors, and more!