Building a Chatbot with OpenAI Codex and Python

OpenAI Codex is a powerful AI system that can generate code and natural language for various tasks, such as creating websites, apps, games, and chatbots. In this tutorial, we will show you how to build a simple chatbot with OpenAI Codex and Python, using the OpenAI API and the Streamlit library.

Prerequisites

To follow this tutorial, you will need:

  • An OpenAI API key. You can request access to the OpenAI API here.
  • A Python 3 environment with the following packages installed: openai, streamlit, requests. You can use pip or conda to install them.
  • A code editor or IDE of your choice.

Step 1: Define the Chatbot Task

The first step is to define the chatbot task that we want OpenAI Codex to perform. This involves writing a prompt that describes the chatbot’s purpose, personality, and behavior. The prompt should also include some examples of how the chatbot should respond to different user inputs.

For this tutorial, we will create a chatbot that acts as a personal assistant for booking appointments. The chatbot should be friendly, helpful, and professional. It should ask the user for their name, phone number, email, and preferred date and time for the appointment. It should also confirm the booking details and thank the user at the end.

Here is an example of a prompt that defines this chatbot task:

You are a personal assistant chatbot that can book appointments for users. You are friendly, helpful, and professional. You ask the user for their name, phone number, email, and preferred date and time for the appointment. You also confirm the booking details and thank the user at the end.

Example:

User: Hi
Bot: Hello, welcome to the appointment booking service. I am your personal assistant chatbot. What is your name?
User: John Smith
Bot: Nice to meet you, John Smith. What is your phone number?
User: 123-456-7890
Bot: Thank you. What is your email address?
User: [email protected]
Bot: Got it. When would you like to book your appointment?
User: Next Monday at 10 am
Bot: Okay, I have booked your appointment for next Monday at 10 am. Please confirm if this is correct.
User: Yes, that's correct
Bot: Great. Your appointment has been confirmed. Thank you for using our service. Have a nice day.

Some additional sentences are:

Source: Conversation with Bing, 6/15/2023
(1) Build your own AI assistant in 10 lines of code – Python. https://community.openai.com/t/build-your-own-ai-assistant-in-10-lines-of-code-python/83210.
(2) Building a Chatbot with OpenAI’s GPT-3 engine, Twilio SMS and Python. https://www.twilio.com/blog/openai-gpt-3-chatbot-python-twilio-sms.
(3) Create Your First Chatbot Using GPT 3.5, OpenAI, Python and Panel.. https://towardsai.net/p/machine-learning/create-your-first-chatbot-using-gpt-3-5-openai-python-and-panel.
(4) Building AI-Powered Chatbots with OpenAI API: A Step-by-Step Guide. https://medium.com/muthoni-wanyoike/building-ai-powered-chatbots-with-openai-api-a-step-by-step-guide-5f4888b1d65e.
(5) Build Your Own Chat Bot in Python with OpenAI’s GPT-3 – Coder’s Den. https://codersden.hashnode.dev/build-your-own-chat-bot-in-python-with-openais-gpt-3.
(6) Anyone Can Create A Chatbot With Codex – Medium. https://cobusgreyling.medium.com/anyone-can-create-a-chatbot-with-codex-5a9e53ffb35e.

Step 2: Generate Code with OpenAI Codex

OpenAI Codex is a system that can generate code and natural language for various tasks, given a natural language prompt. To use OpenAI Codex, we need to access the OpenAI API and use the Completion.create method. This method takes several arguments, such as:

  • The engine argument, which specifies the name of the OpenAI Codex model to use. In this case, we use davinci-codex, which is the most powerful and versatile model available.
  • The prompt argument, which specifies the natural language prompt that defines the task. In this case, we use the prompt that we wrote in the previous step.
  • The max_tokens argument, which specifies how many tokens (words or characters) to generate. In this case, we use 200, which is enough to generate a simple chatbot script.
  • The temperature argument, which specifies how creative or diverse you want the output to be. In this case, we use 0.5, which is a moderate value that balances between randomness and consistency.
  • The stop argument, which specifies when to stop generating text. In this case, we use ###, which is a special token that we add at the end of our prompt to indicate the end of the code.

To generate code with OpenAI Codex, we can use the following Python code:

# Import openai library
import openai

# Set your OpenAI API key
openai.api_key = "<your_api_key>"

# Choose your OpenAI Codex model
engine = "davinci-codex"

# Write your prompt
prompt = """
You are a personal assistant chatbot that can book appointments for users. You are friendly, helpful, and professional. You ask the user for their name, phone number, email, and preferred date and time for the appointment. You also confirm the booking details and thank the user at the end.

Example:

User: Hi
Bot: Hello, welcome to the appointment booking service. I am your personal assistant chatbot. What is your name?
User: John Smith
Bot: Nice to meet you, John Smith. What is your phone number?
User: 123-456-7890
Bot: Thank you. What is your email address?
User: [email protected]
Bot: Got it. When would you like to book your appointment?
User: Next Monday at 10 am
Bot: Okay, I have booked your appointment for next Monday at 10 am. Please confirm if this is correct.
User: Yes, that's correct
Bot: Great. Your appointment has been confirmed. Thank you for using our service. Have a nice day.
# Write your code below

# Import requests library
import requests

# Define a function to send requests to the OpenAI API
def openai_request(prompt):
    # Set the URL and headers for the request
    url = "https://api.openai.com/v1/engines/davinci-codex/completions"
    headers = {
        "Authorization": f"Bearer {openai.api_key}",
        "Content-Type": "application/json"
    }
    # Set the data for the request
    data = {
        "prompt": prompt,
        "max_tokens": 50,
        "temperature": 0.5,
        "stop": "n"
    }
    # Send a POST request and get the response
    response = requests.post(url, headers=headers, json=data)
    # Parse the response and return the generated text
    result = response.json()
    text = result["choices"][0]["text"]
    return text

# Define a function to handle user input and generate bot output
def chatbot():
    # Print a welcome message
    print("Hello, welcome to the appointment booking service. I am your personal assistant chatbot.")
    # Start a loop to get user input and generate bot output
    while True:
        # Get user input
        user_input = input("User: ")
        # Check if user wants to quit
        if user_input.lower() == "quit":
            break
        # Generate bot output using OpenAI Codex
        bot_output = openai_request(user_input)
        # Print bot output
        print(f"Bot: {bot_output}")

This code does the following:

  • Imports the openai and requests libraries and sets your OpenAI API key.
  • Defines a function called openai_request that takes a prompt as an argument and sends a request to the OpenAI API using the Completion.create method. The function returns the generated text from the response.
  • Defines a function called chatbot that handles user input and generates bot output using the openai_request function. The function prints a welcome message and starts a loop to get user input and generate bot output. The loop breaks if the user types “quit”.

Step 3: Create a Web Interface with Streamlit

Streamlit is a library that allows you to create interactive web apps with Python. It is very easy to use and requires minimal code. To use Streamlit, we need to install it using pip or conda and run it using the streamlit run command.

To create a web interface for the chatbot, we can use the following Python code:

# Import streamlit library
import streamlit as st

# Import openai_request function from previous step
from openai_request import openai_request

# Create a title for the web app
st.title("Appointment Booking Chatbot")

# Create a sidebar for user input
user_input = st.sidebar.text_input("Type your message here")

# Create a button to send user input
send_button = st.sidebar.button("Send")

# Create a container for chat history
chat_history = st.empty()

# Initialize an empty list to store chat messages
messages = []

# Define a function to format chat messages
def format_message(role, text):
    # Use different colors for user and bot messages
    if role == "User":
        color = "#008080"
    elif role == "Bot":
        color = "#800080"
    # Return the formatted message as HTML
    return f"<div style='color:{color}; font-size: 18px; padding: 10px; border-radius: 10px;'>{role}: {text}</div>"

# Check if send button is clicked
if send_button:
    # Append user input to messages list
    messages.append(format_message("User", user_input))
    # Generate bot output using openai_request function
    bot_output = openai_request(user_input)
    # Append bot output to messages list
    messages.append(format_message("Bot", bot_output))
    # Update chat history with messages list
    chat_history.markdown("".join(messages), unsafe_allow_html=True)

This code does the following:

  • Imports the streamlit library and the openai_request function from the previous step.
  • Creates a title for the web app using the st.title function.
  • Creates a sidebar for user input using the st.sidebar.text_input function.
  • Creates a button to send user input using the st.sidebar.button function.
  • Creates a container for chat history using the st.empty function.
  • Initializes an empty list to store chat messages.
  • Defines a function called format_message that takes a role and a text as arguments and returns a formatted message as HTML. The function uses different colors for user and bot messages.
  • Checks if the send button is clicked using an if statement.
  • Appends user input to the messages list using the format_message function.
  • Generates bot output using the openai_request function.
  • Appends bot output to the messages list using the format_message function.
  • Updates chat history with the messages list using the chat_history.markdown function. The function takes an argument called unsafe_allow_html to render HTML code.

Step 4: Test and Deploy the Chatbot

To test the chatbot, we can run the code using the streamlit run command in the terminal. This will launch a local web server and open a browser window with the web app. We can then type our messages in the sidebar and click the send button to see the chatbot’s responses.

To deploy the chatbot, we can use Streamlit Cloud, which is a service that allows you to host and share your Streamlit apps online. To use Streamlit Cloud, we need to:

  • Sign up for a Streamlit Cloud account here.
  • Connect our GitHub account and select the repository where we have our code.
  • Choose a deployment option (free, personal, or team) and a visibility option (private or public).
  • Wait for Streamlit Cloud to build and deploy our app.
  • Share the app URL with anyone who wants to use our chatbot.

Alternatively, we can also use other cloud platforms or services to deploy our chatbot, such as Heroku, AWS, or Google Cloud.

Conclusion

In this tutorial, we have shown you how to build a simple chatbot with OpenAI Codex and Python, using the OpenAI API and the Streamlit library. We have used the example of booking appointments, but you can apply the same steps to any other chatbot task.

Building a chatbot with OpenAI Codex can help you create interactive and intelligent conversational agents for various purposes and domains. However, building a chatbot is not a trivial task and requires careful design, testing, and evaluation. You also need to consider ethical and social implications of using AI for communication.

We hope you have enjoyed this tutorial and learned something new. If you have any questions or feedback, please let us know in the comments below. Happy coding!

Related Post