File size: 3,563 Bytes
c27c51b
 
 
 
 
 
 
 
 
1e5d9f3
 
c27c51b
 
1e5d9f3
c27c51b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e5d9f3
c27c51b
 
 
 
 
 
 
1e5d9f3
c27c51b
 
 
 
 
 
 
 
 
 
1e5d9f3
c27c51b
 
 
 
 
 
1e5d9f3
c27c51b
 
 
 
 
 
 
 
 
 
 
 
 
 
1e5d9f3
 
 
 
 
 
 
 
c27c51b
 
1e5d9f3
 
c27c51b
1e5d9f3
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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)