Chatbot1 / app.py
HaoMingSun's picture
Update app.py
f30f844 verified
raw
history blame
2.16 kB
from openai import OpenAI
import gradio as gr
import os
# Set your OpenAI API key
client = OpenAI(api_key=os.environ["APITOKEN"])
greetings = ["hello", "hi", "hey", "greetings", "good morning", "good afternoon", "good evening"]
def chatbot(input, conversation_history=[]):
if input:
# Check if the input starts with a common greeting, case-insensitive
#if any(input.lower().startswith(greet) for greet in greetings):
conversation_history = [] # Reset the conversation history if a greeting is detected
# Append the user's input to the conversation history
conversation_history.append(f"User: {input}")
# Define the structured interview messages
messages = [
{"role": "system", "content": "Your role is to answer the questions from the users friendly."},
]
# Extend the conversation history with the user's messages
messages.extend([{"role": "user", "content": message} for message in conversation_history])
try:
# Generate a response using OpenAI's GPT model
chat = client.chat.completions.create(model="gpt-3.5-turbo", messages=messages)
reply = chat.choices[0].message.content
except Exception as e:
# Handle errors gracefully
reply = "Sorry, I encountered an error. Please try again."
print(f"Error: {e}") # Logging the error to the console
# Append the chatbot's response to the conversation history
conversation_history.append(f"Chatbot: {reply}")
return reply, conversation_history # Return the updated conversation history to maintain state
return "", conversation_history # If no input, return empty string and current conversation history
# Gradio interface
inputs = [gr.components.Textbox(lines=7, label="Chat with AI"), gr.components.State()]
outputs = [gr.components.Textbox(label="Reply"), gr.components.State()]
gr.Interface(fn=chatbot, inputs=inputs, outputs=outputs, title="AI Chatbot",
description="Ask anything you want",
theme="Default").launch(share=True)