Prak2005's picture
Update app.py
1e5d9f3 verified
import gradio as gr
import os
import logging
from crewai import Agent, Task, Crew
from langchain_openai import ChatOpenAI
# Setup logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
# Load API Key from Hugging Face Secrets
api_key = os.environ.get("OPENAI_API_KEY") # Hugging Face does not support .env files
if not api_key:
logging.error("❌ ERROR: OpenAI API Key is missing! Add it in Hugging Face Secrets.")
exit(1)
logging.info("βœ… OpenAI API Key loaded successfully.")
# Initialize AI Model
try:
llm = ChatOpenAI(model_name="gpt-4o-mini", temperature=0.7, openai_api_key=api_key)
logging.info("βœ… ChatOpenAI initialized successfully.")
except Exception as e:
logging.error(f"❌ ERROR: Failed to initialize ChatOpenAI: {e}")
exit(1)
# Define AI Agent
try:
chatbot_agent = Agent(
role="AI Support Assistant",
goal="Provide accurate, helpful, and friendly answers to customer FAQs.",
backstory="You are a highly trained AI customer support assistant with deep knowledge of FAQs.",
llm=llm
)
logging.info("βœ… AI Agent initialized successfully.")
except Exception as e:
logging.error(f"❌ ERROR: Failed to initialize AI agent: {e}")
exit(1)
# Predefined FAQs
faq_list = {
"business hours": "πŸ“… We are open from 9 AM to 6 PM, Monday to Friday.",
"track order": "πŸ“¦ You can track your order using the tracking link sent to your email.",
"refund policy": "πŸ’° We offer a 30-day money-back guarantee. Contact support for details.",
"support contact": "πŸ“ž You can contact our support team at support@example.com or call +1 234 567 890."
}
# Define CrewAI System
try:
crew = Crew(agents=[chatbot_agent], tasks=[]) # Initialized with no tasks yet
logging.info("βœ… CrewAI initialized successfully.")
except Exception as e:
logging.error(f"❌ ERROR: Failed to initialize CrewAI: {e}")
exit(1)
# Define Chatbot Response Function
def chatbot_response(question):
try:
logging.info(f"πŸ” Received question: {question}")
# Check predefined FAQs
for key in faq_list:
if key in question.lower():
logging.info("βœ… Matched FAQ response.")
return faq_list[key]
# Ensure CrewAI has the correct task
task = Task(
description=f"Answer this customer query in a detailed, professional, and helpful manner: '{question}'",
agent=chatbot_agent,
expected_output="A well-structured and relevant response."
)
# Add the task to Crew
crew.tasks = [task]
response = crew.kickoff()
if not response:
raise ValueError("❌ ERROR: CrewAI did not return a response.")
logging.info(f"βœ… AI Crew Response: {response}")
return response
except Exception as e:
logging.error(f"❌ ERROR in chatbot response: {e}")
return "⚠️ Sorry, something went wrong. Please try again."
# Deploy with Gradio UI
interface = gr.Interface(
fn=chatbot_response,
inputs=gr.Textbox(label="Ask me anything:", placeholder="Type your question here..."),
outputs=gr.Textbox(label="AI Response"),
title="πŸ€– AI Customer Support Chatbot",
description="Ask me anything, and I'll provide a useful response!",
theme="default"
)
if __name__ == "__main__":
logging.info("πŸš€ Launching Gradio on Hugging Face Spaces...")
interface.launch(server_name="0.0.0.0", server_port=7860, share=True)