USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
Br
Ethiopian Birr
¥
China Yuan Renminbi
Pakistan Rupee
£
Egypt Pound
د.إ
United Arab Emirates dirham
R
South Africa Rand
ر.س
Saudi Arabia Riyal

Building Chatbots using OpenAI GPT- 4 Preview and Python

Created by Vishal Verma in Articles 6 Feb 2024
Share

Chatbots have revolutionized user interactions, providing intelligent and responsive interfaces in applications. In this comprehensive tutorial, we will guide you through creating a chatbot using the Tkinter library for the graphical user interface and OpenAI's GPT-4 Preview model for natural language processing.


Prerequisites


Before diving into the tutorial, ensure you have the following prerequisites:

1. Python: Make sure you have Python installed on your machine. You can download the latest version from the official Python website.

2. Tkinter Library: Tkinter is the standard GUI toolkit for Python and comes bundled with most Python installations. No separate installation is needed.

3. OpenAI GPT-4 Preview API Key: Sign up for access to the OpenAI GPT-4 Preview and obtain your API key. Use H2OGPTE to get the API Key.

4. H2OGPTE Library: Install the H2OGPTE library, which facilitates communication with the GPT-4 model.


Step 1: Set up Python Environment


Ensure Python is correctly installed on your machine.


Step 2: Acquire OpenAI GPT-4 Preview API Key


Sign up for access to the OpenAI GPT-4 Preview and obtain your API key.


Step 3: Install H2OGPTE Library


Install the H2OGPTE library to facilitate communication with the GPT-4 model.


pip install h2ogpte

Step 4: Write the Python Code


Create a Python script using the provided code below. Save it as a .py file.


import tkinter as tk
from tkinter import ttk
from h2ogpte import H2OGPTE

class ChatGPTApp:
def __init__(self, master):
self.master = master
self.master.title("Building ChatGPT Like AI-Assistant")

# Set up the H2OGPTE client
self.API_KEY = "Your_API_Key"
self.REMOTE_ADDRESS = "https://h2ogpte.genai.h2o.ai"
self.client = H2OGPTE(address=self.REMOTE_ADDRESS, api_key=self.API_KEY)
self.llm = "gpt-4-1106-preview"

# Font style
font_style = ('Arial', 12)

# Chat history displayed in the app
self.chat_history = []

# Create a themed frame for the chat history
self.chat_frame = ttk.Frame(master)
self.chat_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)

# Display chat history with a gap between window and responses
self.chat_history_text = tk.Text(
self.chat_frame, height=15, width=50, state=tk.DISABLED, wrap=tk.WORD,
font=font_style, background="#e0f7fa", foreground="#000000")
self.chat_history_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, pady=(0, 10))

# Scrollbar for the chat history
scrollbar = ttk.Scrollbar(self.chat_frame, command=self.chat_history_text.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.chat_history_text.config(yscrollcommand=scrollbar.set)

# Text input for user prompts
self.user_input = ttk.Entry(master, width=50, font=font_style, foreground="#000000")
self.user_input.pack(pady=10, padx=10, fill=tk.X)

# Send button to send user prompts
self.send_button = ttk.Button(master, text="Send", command=self.send_message, style="Send.TButton")
self.send_button.pack(pady=10)

# Bind Enter key to send_message function
self.user_input.bind("", lambda event: self.send_message())

# Configure font for the button
self.master.option_add('*TButton*Font', font_style)

def send_message(self):
user_prompt = self.user_input.get().strip()
if user_prompt:
bot_response = self.get_bot_response(user_prompt)
self.chat_history.append(("user", user_prompt))
self.chat_history.append(("bot", bot_response))
self.display_chat_history()

def get_bot_response(self, prompt):
return self.client.answer_question(question=prompt, llm=self.llm).content

def display_chat_history(self):
self.chat_history_text.config(state=tk.NORMAL)
new_messages = self.chat_history[-2:]
for msg_type, message in new_messages:
if msg_type == "user":
self.chat_history_text.insert(tk.END, f"You: {message}\n", "user")
else:
self.chat_history_text.insert(tk.END, f"Bot: {message}\n\n", "bot")
self.chat_history_text.config(state=tk.DISABLED)
self.user_input.delete(0, tk.END)

if __name__ == "__main__":
root = tk.Tk()
app = ChatGPTApp(root)

# Configure text widget tags for user and bot messages
app.chat_history_text.tag_configure("user", foreground="#000000", justify="right")
app.chat_history_text.tag_configure("bot", foreground="#0000FF", justify="left")

root.mainloop()

Step 5: Detailed Explanation


Now, let's break down the key components of the code:


Line 1-2: Import Libraries


import tkinter as tk
from tkinter import ttk
from h2ogpte import H2OGPTE


  • Imports the necessary libraries, including Tkinter for GUI components and H2OGPTE for communication with the GPT-4 model.



Line 4-14: ChatGPTApp Class Initialization


class ChatGPTApp:
def __init__(self, master):
self.master = master
self.master.title("Building ChatGPT Like AI-Assistant")


  • Initializes the ChatGPTApp class with the Tkinter master window and sets the window title.



Line 16-22: Set up H2OGPTE Client


        # Set up the H2OGPTE client
self.API_KEY = "Your_API_Key"
self.REMOTE_ADDRESS = "https://h2ogpte.genai.h2o.ai"
self.client = H2OGPTE(address=self.REMOTE_ADDRESS, api_key=self.API_KEY)
self.llm = "gpt-4-1106-preview"


  • Configures the H2OGPTE client with the API key, remote address, and specifies the GPT-4 language model.



Line 24-25: Font Style Definition


        # Font style
font_style = ('Arial', 12)


  • Sets up a font style for the GUI components.



Line 27-34:


Chat History Initialization


        # Chat history displayed in the app
self.chat_history = [] # Use a list to store messages in order


  • Initializes an empty list to store chat history messages.



Line 36-61: GUI Components Setup


        # Create a themed frame for the chat history
self.chat_frame = ttk.Frame(master)
self.chat_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)

# Display chat history with a gap between window and responses
self.chat_history_text = tk.Text(
self.chat_frame, height=15, width=50, state=tk.DISABLED, wrap=tk.WORD,
font=font_style, background="#e0f7fa", foreground="#000000")
self.chat_history_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, pady=(0, 10))

# Scrollbar for the chat history
scrollbar = ttk.Scrollbar(self.chat_frame, command=self.chat_history_text.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.chat_history_text.config(yscrollcommand=scrollbar.set)


  • Sets up the Tkinter GUI components, including the chat history display, input field, and buttons.



Line 63-79: send_message Method


    def send_message(self):
user_prompt = self.user_input.get().strip()
if user_prompt:
bot_response = self.get_bot_response(user_prompt)
self.chat_history.append(("user", user_prompt))
self.chat_history.append(("bot", bot_response))
self.display_chat_history()


  • Defines a method to handle sending user messages, getting bot responses, and updating the chat history display.



Line 81-85: get_bot_response Method


    def get_bot_response(self, prompt):
return self.client.answer_question(question=prompt, llm=self.llm).content


  • Defines a method to interact with the GPT-4 model and obtain a response to the user's input.



Line 87-103: display_chat_history Method


    def display_chat_history(self):
self.chat_history_text.config(state=tk.NORMAL)
new_messages = self.chat_history[-2:]
for msg_type, message in new_messages:
if msg_type == "user":
self.chat_history_text.insert(tk.END, f"You: {message}\n", "user")
else:
self.chat_history_text.insert(tk.END, f"Bot: {message}\n\n", "bot")
self.chat_history_text.config(state=tk.DISABLED)
self.user_input.delete(0, tk.END)


  • Defines a method to update the chat history display with user and bot messages.



Line 105-110: Main Application Execution


if __name__ == "__main__":
root = tk.Tk()
app = ChatGPTApp(root)

# Configure text widget tags for user and bot messages
app.chat_history_text.tag_configure("user", foreground="#000000", justify="right")
app.chat_history_text.tag_configure("bot", foreground="#0000FF", justify="left")

root.mainloop()


  • Creates an instance of the ChatGPTApp class, configures tags for user and bot messages, and starts the Tkinter main loop.

Main Application Execution Snapshots





This is how you can create a ChatGPT-Like bot using OpenAI API.

GitHub Repository Link: Click Here


Conclusion


This tutorial has guided you through the process of building a chatbot using Tkinter and the OpenAI GPT-4 Preview model. By understanding each line of code, you've gained valuable insights into creating a responsive and interactive chatbot interface.


Feel free to experiment further by customizing the GUI, exploring advanced features of the GPT-4 model, or integrating additional functionalities. This tutorial serves as a foundation for creating powerful and intelligent chatbot applications in Python. Happy coding!

Comments (3)

Melkam Student
7 Feb 2024 | 09:28 pm
Beautifull. I love to learn about Gen AI and this is the right place I want to start. Thank you for your series articles and i am very eager to see what you will give us in the next edition
Team Zokas Staff
7 Feb 2024 | 09:30 pm
wonderful article. I really like this article and I also enjoyed your previous article too. I would love to see more from you. Thank you for sharing
Ermias Haile Gebregiorgis Student
31 Aug 2024 | 07:08 pm
Thank for sharing very important information.

Share

Share this post with others

GDPR

When you visit any of our websites, it may store or retrieve information on your browser, mostly in the form of cookies. This information might be about you, your preferences or your device and is mostly used to make the site work as you expect it to. The information does not usually directly identify you, but it can give you a more personalized web experience. Because we respect your right to privacy, you can choose not to allow some types of cookies. Click on the different category headings to find out more and manage your preferences. Please note, that blocking some types of cookies may impact your experience of the site and the services we are able to offer.