Spaces:
Sleeping
Sleeping
File size: 2,338 Bytes
c380b8d addfeb0 c380b8d f708ede c380b8d f708ede c380b8d f708ede c380b8d f708ede c380b8d addfeb0 c380b8d f708ede c380b8d f708ede c380b8d f708ede c380b8d f708ede c380b8d addfeb0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
from openai import OpenAI
import gradio as gr
import os
# Set your OpenAI API key
client = OpenAI(api_key="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")
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. If they ask weird questions or input things you do not understand, just say: 'Sorry, this question is beyond my understanding. Please try another one!"},
]
# 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) |