From ae312c1298089a1cd421e4b4516a4e7cb62fa29f Mon Sep 17 00:00:00 2001 From: Ayush Kumar Dubey Date: Thu, 24 Oct 2024 00:25:06 +0530 Subject: [PATCH] integrate chatbot using openai api and enhanced user experience --- chatbot.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 chatbot.py diff --git a/chatbot.py b/chatbot.py new file mode 100644 index 0000000..237527b --- /dev/null +++ b/chatbot.py @@ -0,0 +1,43 @@ +import os +import openai +import taipy + +# Initialize OpenAI client with API key from environment variable +openai.api_key = os.environ.get("OPENAI_API_KEY") + +# Create a Taipy GUI +gui = taipy.get_gui() + +# Define the chatbot interface +page = """ +<|{conversation}|table|show_all|width=100%|> +<|{current_user_message}|input|label=Write your message here...|on_action=send_message|class_name=fullwidth|> +""" + +# Function to send messages and handle responses +def send_message(state: taipy.State) -> None: + # Prepare the conversation context + user_message = state.current_user_message.strip() + if user_message: + # Append user message to the context + state.context += f"Human: {user_message}\nAI:" + + # Get response from OpenAI + response = openai.ChatCompletion.create( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": state.context}] + ) + + # Extract the AI's response + ai_message = response['choices'][0]['message']['content'].strip() + + # Update the conversation state + state.context += f"{ai_message}\n" + state.conversation.append({"Human": user_message, "AI": ai_message}) + + # Clear the input field for the next message + state.current_user_message = "" + +# Run the Taipy application +if __name__ == "__main__": + gui.run(dark_mode=True, title="Fest Registration Chatbot", page=page) \ No newline at end of file