chat-bot-test / chatbot.py
alliwene's picture
Upload folder using huggingface_hub
2d11cde
Raw
History Blame Contribute Delete
3.05 kB
import os
import re
from dotenv import load_dotenv
import openai
import gradio as gr
load_dotenv()
openai.api_key = os.getenv("API_KEY")
def chat(
user_input: str,
message_history=[],
role="user",
model="gpt-3.5-turbo",
):
message_history.append(
{"role": "system", "content": "You are a helpful assistant."}
)
message_history.append({"role": role, "content": f"{user_input}"})
completion = openai.ChatCompletion.create(
model=model,
messages=message_history,
)
reply_content = completion.choices[0].message.content
message_history.append({"role": "assistant", "content": f"{reply_content}"})
# conversation_display = "\n\n".join(
# [
# f"{message['role']}: {message['content']}"
# for message in message_history
# if message["role"] != "system"
# ]
# )
# return reply_content, conversation_display
response = [
(message_history[i]["content"], message_history[i + 1]["content"])
for i in range(2, len(message_history) - 1, 2)
] # convert to tuples of list
return response
# Create the Gradio interface
# iface = gr.Interface(
# fn=chat,
# inputs=gr.Textbox(placeholder="Enter your message..."),
# outputs=[
# gr.Textbox(label="Assistant Reply"),
# gr.Textbox(label="Conversation History"),
# ],
# )
# creates a new Blocks app and assigns it to the variable demo.
with gr.Blocks() as demo:
# creates a new Chatbot instance and assigns it to the variable chatbot.
chatbot = gr.Chatbot()
# creates a new Row component, which is a container for other components.
with gr.Row():
"""creates a new Textbox component, which is used to collect user input.
The show_label parameter is set to False to hide the label,
and the placeholder parameter is set"""
txt = gr.Textbox(
show_label=False, placeholder="Enter text and press enter"
).style(container=False)
"""
sets the submit action of the Textbox to the predict function,
which takes the input from the Textbox, the chatbot instance,
and the state instance as arguments.
This function processes the input and generates a response from the chatbot,
which is displayed in the output area."""
txt.submit(chat, txt, chatbot) # submit(function, input, output)
# txt.submit(lambda :"", None, txt) #Sets submit action to lambda function that returns empty string
"""
sets the submit action of the Textbox to a JavaScript function that returns an empty string.
This line is equivalent to the commented out line above, but uses a different implementation.
The _js parameter is used to pass a JavaScript function to the submit method."""
txt.submit(
None, None, txt, _js="() => {''}"
) # No function, no input to that function, submit action to textbox is a js function that returns empty string, so it clears immediately.
if __name__ == "__main__":
demo.launch()