ChatGPT – Build a Chatbot



Chatbots are found in almost every application nowadays. This is because they allow users to have interactive and dynamic conversations. With the help of OpenAI’s powerful language models, such as GPT-3.5, developers can create sophisticated chatbots that can understand and generate human-like text.

In this chapter, we will explore how to create a chatbot using the OpenAI API with Python programming language. So, let’s get started with the step by step implementation of the chatbot.

Step 1: Set Up Your OpenAI Account

First of all, you need to set up an account on the OpenAI platform and obtain your API credentials. Visit the OpenAI website, sign up, and follow the instructions to generate an API key.

It is always recommended to keep your API key secure, as it will be used to authenticate requests to the OpenAI API.

Step 2: Install the OpenAI Python Library

Now, to interact with the OpenAI API, you need to install the OpenAI Python library. Run the following command on your terminal or command prompt −

pip install openai

This command will install OpenAI library to your Python environment.

Step 3: Import Required Libraries

Now, in your Python script, you need to import the OpenAI library and any other libraries you might need for your implementation. For this implementation we only need the OpenAI library.

The following command imports the OpenAI library −

import openai

Step 4: Configure OpenAI API Key

Next, it is required to set up the OpenAI key in Python script to authenticate your requests. In the command below, replace 'your-api-key-goes-here' with the actual API key you obtained from OpenAI.

# Set your OpenAI API key
openai.api_key = 'your-api-key-goes-here'

Step 5: Define the Initial Prompt

After configuring OpenAI API, we need to define the initial prompt variable that will be used to initiate the conversation with the chatbot. For example, we define the following prompt for our implementation purpose −

# Define the initial prompt
prompt = "You: "

You can experiment with different prompts such as your name or your nickname.

Step 6: Implement the Chat Loop

Next, we need to create a loop to simulate a conversation with the chatbot. It will allow the user to input messages and append them to the prompt. And if you want to exit the loop, you can use a predefined command, such as "exit". Check out the code below −

while True:
   user_input = input("You: ")

   # Check for exit command
   if user_input.lower() == 'exit':
      print("Chatbot: Goodbye!")
      break

   # Update the prompt with user input
   prompt += user_input + "\n"

Step 7: Generate Responses

Now, use the OpenAI API to generate responses based on the user's input. For this we need to make a request to the API within the loop as follows −

# Generate responses using the OpenAI API
response = openai.Completion.create(
   engine="gpt-3.5-turbo-instruct",
   prompt=prompt,
   max_tokens=150
)

Step 8: Display and Update the Prompt

At last, we need to display the generated response and update the prompt for the next iteration as well −

# Get and display the chatbot response
chatbot_response = get_chatbot_response(prompt)
print(f"Chatbot: {chatbot_response}")

# Update the prompt with chatbot's response
prompt += f"Chatbot: {chatbot_response}\n"

Run the Chatbot

Now let’s put it all together in a script and run the chatbot −

# Import the OpenAI library
import openai

# Set up your OpenAI API key for authentication
openai.api_key = 'your-api-key-goes-here'

# Define the initial prompt
prompt = "You: "

# Function to get chatbot response using OpenAI API
def get_chatbot_response(prompt):

   # Generate responses using the OpenAI API
   response = openai.Completion.create(
      engine="gpt-3.5-turbo-instruct",
      prompt=prompt,
      max_tokens=150
   )
   return response.choices[0].text.strip()

# Main execution loop
if __name__ == "__main__":

   # Continuous loop for user interaction
   while True:
   
      # Get user input
      user_input = input("You: ")

      # Check for exit command
      if user_input.lower() == 'exit':
         print("Chatbot: Goodbye!")
         break

      # Update the prompt with user input
      prompt += user_input + "\n"

      # Get and display the chatbot response
      chatbot_response = get_chatbot_response(prompt)
      print(f"Chatbot: {chatbot_response}")

      # Update the prompt with chatbot's response
      prompt += f"Chatbot: {chatbot_response}\n"

Note − Replace 'your-api-key-goes-here' with your actual OpenAI API key. This script allows the user to interact with the chatbot in a continuous loop, with the ability to exit by typing "exit."

Let’s see the conversation we have done with our chatbot −

You: Hi
Chatbot: > <@User> Hi there! Is there something I can help you with?

You: I want to know about Artificial Intelligence.
Chatbot: Chatbot: Sure! Artificial Intelligence, or AI, refers to the 
simulation of human intelligence processes by machines. This could include 
things like learning, problem solving, and decision making. 
AI has become increasingly important in various industries and has the 
potential to greatly impact our daily lives in the future. Is there something
specific you would like to know?

You: Suggest me some courses to learn AI using Python.
Chatbot: Chatbot: There are many great online courses available for learning 
AI with Python. Here are a few popular options: "Python for Data Science and 
AI" on Coursera, "Artificial Intelligence with Python" on Udemy, and 
"AI Programming with Python" on edX. 
Each course has its own focus and structure, so be sure to research and choose
the one that best fits your learning goals.

You: Is there any course related to learn AI using Python on tutorialspoint.com?
Chatbot: Chatbot: Yes, there are several courses related to 
AI on tutorialspoint.com. Some popular ones include "Python 
AI Tutorial," "Machine Learning with Python," and 
"Deep Learning with TensorFlow." You can explore these courses and their 
contents to see which one best fits your needs.

You: Can you tell me more about tutorialspoint.com?
Chatbot: Tutorialspoint.com is an online platform that offers a variety of 
tutorials and study materials on various subjects such as programming 
languages, database technologies, web development, and more. 
It was founded in 2006 and has become one of the leading online learning 
platforms for technical subjects. The website provides step-by-step tutorials, 
articles, and videos to help users learn and understand complex concepts
in an easy and interactive way. 
The tutorials are prepared and updated by a team of experts in the field and 
cover a wide range of topics from beginner level to advanced level. 
It also offers certifications and online courses for users to 
enhance their skills and knowledge. 
Overall, tutorialspoint.com is a valuable resource for students, professionals, 
and anyone interested in learning about technical courses.

You: exit
Chatbot: Goodbye!

Conclusion

In this chapter we explained how you can create a chatbot using the OpenAI API with Python. This is a starting point, and you can further enhance your chatbot by handling user input validation, refining prompts, and exploring advanced API features offered by OpenAI.

To learn more, experiment with different prompts, engage in diverse conversations, and tailor the chatbot to meet your specific requirements.

Advertisements