In this post we will discuss how to create a Gui that answers your Questions just like a personal assistant , we will create this by using openai api
Installing Required Packages
pip install openai
Code Explanation
lets import the required packages
from tkinter import *
import openai
Lets initialize our tkinter GUI with fixed size and background color
root =Tk()
root.geometry("300x500")
root.config(bg="white")
Lets create variable for our api key and model that we will use for answering our questions (text-davinci-003)
openai.api_key = ""
model_engine ="text-davinci-003"
after that we will create a chat application like GUI for visual show us our answers , it will have 1 listbox show the conversation , input widget for user to type the question and a button to trigger the answering function
message=StringVar()
messagebox=Entry(root,textvariable=message,font=('calibre',10,'normal'),border=2,width=32)
messagebox.place(x=10,y=444)
sendmessageimg=PhotoImage(file='send.png')
sendmessagebutton=Button(root,image=sendmessageimg,command=response,borderwidth=0)
sendmessagebutton.place(x=260,y=440)
lstbx=Listbox(root,height=20,width=43)
lstbx.place(x=15,y=80)
finally we we will create the function that will be triggered when the above mentioned button is pressed it will call complete class from open ai to answer the question and then we will insert the answer in listbox to look like a conversation is happening with a chatbot
def response():
msg = messagebox.get()
lstbx.insert(0,"You : "+msg)
answer = openai.Completion.create(
engine = model_engine,
prompt = msg,
)
message =answer.choices[0].text
print(message)
lstbx.insert(0,"chatbot : "+message)
msg=""
for better explanation watch this video
Complete Code
from tkinter import *
import openai
root =Tk()
root.geometry("300x500")
root.config(bg="white")
openai.api_key = ""
model_engine ="text-davinci-003"
def response():
msg = messagebox.get()
lstbx.insert(0,"You : "+msg)
answer = openai.Completion.create(
engine = model_engine,
prompt = msg,
)
message =answer.choices[0].text
print(message)
lstbx.insert(0,"chatbot : "+message)
msg=""
message=StringVar()
messagebox=Entry(root,textvariable=message,font=('calibre',10,'normal'),border=2,width=32)
messagebox.place(x=10,y=444)
sendmessageimg=PhotoImage(file='send.png')
sendmessagebutton=Button(root,image=sendmessageimg,command=response,borderwidth=0)
sendmessagebutton.place(x=260,y=440)
lstbx=Listbox(root,height=20,width=43)
lstbx.place(x=15,y=80)
root.mainloop()