A chatbot GUI#
This is a graphical user interface around a basic chatbot. Feel free to modify this text.
# This Jupyter notebook can be used to build a graphical user interface for a chatbot.
# Just run this from the terminal:
#
# voila gui.ipynb
import os
os.environ['OPENAI_API_KEY'] = 'sk-...'
import openai
def prompt_chatGPT(message:str, model="gpt-3.5-turbo"):
"""A prompt helper function that sends a message to openAI
and returns only the text response.
"""
import os
# convert message in the right format if necessary
if isinstance(message, str):
message = [{"role": "user", "content": message}]
# setup connection to the LLM
client = openai.OpenAI()
# submit prompt
response = client.chat.completions.create(
model=model,
messages=message
)
# extract answer
return response.choices[0].message.content
prompt = prompt_chatGPT
chat_history = []
def prompt_with_memory(message:str):
# convert message in the right format and store it in memory
question = {"role": "user", "content": message}
chat_history.append(question)
# receive answer
response = prompt(chat_history)
# convert answer in the right format and store it in memory
answer = {"role": "assistant", "content": message}
chat_history.append(answer)
return response
# Here we can inject knowledge into the chatbot, by telling things the user of our chatbot won't see.
_ = prompt_with_memory("""
You are an extremely talented Python programmer, but you are rude and pedantic.
You tend to tell everyone that you know things better than everybody else.
Keep your answers 2-3 sentences short.
""")
import ipywidgets as widgets
from IPython.display import display
# Create widgets
output_label = widgets.HTML(value="")
text_input = widgets.Text(placeholder="Type something here...")
submit_button = widgets.Button(description="Submit")
def on_submit(e):
question = text_input.value
if len(question) == 0:
return
text_input.value = ""
# submit prompt to LLM
answer = prompt_with_memory(question)
# Append question and answer to the existing HTML content
output_label.value += f"""
<div style='text-align:right; color: blue; font-size: 20px'>{question}</div>
<div style='text-align:left; color: darkgreen; font-size: 20px'>{answer}</div>
"""
# Attach the event handler to the text field and the button
text_input.continuous_update = False
text_input.observe(on_submit)
submit_button.on_click(on_submit)
# Arrange the widgets for display
display(output_label, widgets.HBox([text_input, submit_button]))