Build ChatGPT Based ChatBot For Yourself!

We all know that ChatGPT has come with a shbang, and now has become an integral part of our routine. It’s like the next Google, but on drugs! It’s about time we start layering it up and start using it in our own environment. One way we can do it, is, by using ChatGPT’s API and use it to build a chatbot.

 

 

Here is the code that you can use to build the desktop application.

 

Dependencies – All of these can be installed using PIP Command

 

  1. Get your API fromt ChatGPT using this link. You can also download it from Profile –> API.
  2. Pip install these libraries.
    1. tkinter
    2. Customtkinter
    3. OpenAI
    4. Pickle
  3. And, you will need an IDE. I’ve used the code on atom and visual code, and it works. Happy to hear from you guys if it doesnt.

Hi, Its me!

I would love to connect with like minded people and listen to your story. If you enjoy my blog, please follow me on any of the social media platforms. Thanks. 


The Code

Once you have all the above, viola! Paste the following code in your IDE and you have a working app backed by ChatGPT.

from tkinter import *
import customtkinter
import openai
import os
import pickle

#submit to ChatGPT
def speak():
    if chat_entry.get():
        # define file name
        filename = "api_key"

        try:
            if os.path.isfile(filename):
                # Open the file
                input_file = open(filename, 'rb')

                # Load the data from the file into the variable
                stuff = pickle.load(input_file)

                # Query Chat GPT
                openai.api_key = stuff

                # Create an instance
                openai.Model.list()

                # Define our query
                response = openai.Completion.create(
                    model = "text-davinci-003",
                    prompt = chat_entry.get(),
                    temperature = 0, # you raise the data if you want to get the specific data about something.
                    max_tokens = 60,
                    top_p = 1.0,
                    frequency_penalty = 0.0,
                    presence_penalty = 0.0
                )
                my_text.insert(END, (response['choices'][0]["text"]).strip())
                my_text.insert(END, "\n\n")



            else:
                # if the file doesnt exist, create it.
                input_file = open(filename, 'wb')
                input_file.close()
                # Error message sending to the  API
                my_text.insert(END, "\n\nYou need an ChatGPT API key to talk to the bot. \n Please get your API key from the following link: \n https://platform.openai.com/account/api-keys ")

        except Exception as e:
            my_text.insert(END, f"/n/n there was an error /n/n {e}")

    else:
        my_text.insert(END, f"\n\nHey! Ask me something!!!")

#clear the screen
def clear():
    # clear the main text box
    my_text.delete(1.0, END)

    # Delete everything in the box
    chat_entry.delete(0,END)

# For API
def key():

    # define file name
    filename = "api_key"

    try:
        if os.path.isfile(filename):
            # Open the file
            input_file = open(filename, 'rb')

            # Load the data from the file into the variable
            stuff = pickle.load(input_file)

            # send the output to our entry box
            api_entry.insert(END, stuff)
        else:
            # if the file doesnt exist, create it.
            input_file = open(filename, 'wb')
            input_file.close()

    except Exception as e:
        my_text.insert(END, f"/n/n there was an error /n/n {e}")


    # resize the app
    root.geometry("600x650")
    # reshow the API frame
    api_frame.pack(pady=30)


#def save the API key
def save_key():
    #define file name
    filename = "api_key"

    try:

        #open file
        output_file = open(filename, 'wb')

        #add data to the file
        pickle.dump(api_entry.get(), output_file)

        # Delete the entry box
        api_entry.delete(0,END)

        # Hide API frame
        api_frame.pack_forget()
        # resize the app
        root.geometry("600x500")

    except Exception as e:
        my_text.insert(END, f"/n/n there was an error /n/n {e}")

#Initiate the App
root = customtkinter.CTk()
root.title("Luqman's Bot!")
root.geometry('600x500')
root.iconbitmap('ai_lt.ico') #Custom Logo

#Set Color Scheme
customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("dark-blue")

#Create a text frame
text_frame = customtkinter.CTkFrame(root)
text_frame.pack(pady=20)

# Add text widget to get the chatgpt responses
my_text = Text(text_frame, bg="#343638", width=75, bd=2, fg="#d6d6d6", relief="flat", wrap=WORD, selectbackground="#1f538d")
my_text.grid(row=0, column=0)

# Create Scrollbar for text widget
text_scroll = customtkinter.CTkScrollbar(text_frame,command = my_text.yview)
text_scroll.grid(row=0, column=1, sticky="ns")

# add scrollbar to the textbox
my_text.configure(yscrollcommand=text_scroll.set)

# Entry widget to type stuff to ChatGPT
chat_entry = customtkinter.CTkEntry(root,
            placeholder_text= "Type Something...",
            width=535,
            height=50,
            border_width=2)
chat_entry.pack(pady=10)

# Create buttons frame
button_frame = customtkinter.CTkFrame(root, fg_color="#242424")
button_frame.pack(pady=10)

# Create submit button
submit_button = customtkinter.CTkButton(button_frame,text="Send to Bot!", command=speak)
submit_button.grid(row=0, column=0,padx=25)

# Create clear button
clear_button = customtkinter.CTkButton(button_frame,text="Clear Everything", command=clear)
clear_button.grid(row=0, column=1,padx=35)

# Create api button
api_button = customtkinter.CTkButton(button_frame,text="Update API Key", command=key)
api_button.grid(row=0, column=2,padx=30)

#Api key frame
api_frame = customtkinter.CTkFrame(root, border_width=1)
api_frame.pack(pady=10)

#add API Entry key widget
api_entry = customtkinter.CTkEntry(api_frame, placeholder_text="Enter your API key", width=350, height=50, border_width=1)
api_entry.grid(row=0, column=0, padx=20, pady=20)

# add API button
api_save_button = customtkinter.CTkButton(api_frame, text="Save Key", command=save_key)
api_save_button.grid(row=0, column=1, padx=10)

root.mainloop()

    

By now, you have a working app where you can put the API link and use it for your own. Hope you like this project! Enjoy!

————————–

THIS POST IS WRITTEN BY SYED LUQMAN, A DATA SCIENTIST FROM SHEFFIELDSOUTH YORKSHIRE, AND DERBYSHIREUNITED KINGDOMSYED LUQMAN IS OXFORD UNIVERSITY ALUMNI AND WORKS AS A DATA SCIENTIST FOR A LOCAL COMPANY. SYED LUQMAN HAS FOUNDED INNOVATIVE COMPANY IN THE SPACE OF HEALTH SCIENCES TO SOLVE THE EVER RISING PROBLEMS OF STAFF MANAGEMENT IN NATIONAL HEALTH SERVICES (NHS). YOU CAN CONTACT SYED LUQMAN ON HIS TWITTER, AND LINKEDIN. PLEASE ALSO LIKE AND SUBSCRIBE MY YOUTUBE CHANNEL.

Leave a Comment

Your email address will not be published. Required fields are marked *

×

Hey!

Please click below to start the chat!

× Let's chat?