Joey / app.py
LucidMinds3ye's picture
Update app.py
9598d17 verified
import gradio as gr
import time
from business_ai import BusinessAIAssistant
from business_config import BUSINESS_CONFIG, PRODUCTS, SERVICES
# Initialize the AI assistant
ai_assistant = BusinessAIAssistant(BUSINESS_CONFIG, PRODUCTS, SERVICES)
# Predefined responses for common queries
def get_business_response(intent):
responses = {
"hours": f"Our store hours are {BUSINESS_CONFIG['hours']}.",
"location": f"We're located at {BUSINESS_CONFIG['address']}. Come visit us!",
"contact": f"You can reach us at {BUSINESS_CONFIG['phone']} or email {BUSINESS_CONFIG['email']}.",
"products": f"We offer a wide range of {BUSINESS_CONFIG['products']}. What specifically are you interested in?",
"services": f"We provide these services: {BUSINESS_CONFIG['services']}.",
"returns": f"Our return policy: {BUSINESS_CONFIG['return_policy']}.",
"shipping": f"Yes! We offer {BUSINESS_CONFIG['shipping'].lower()}",
"greeting": f"Hello! Welcome to {BUSINESS_CONFIG['name']}. How can I help you today?",
"thanks": "You're welcome! Is there anything else I can help you with?",
"goodbye": f"Thank you for contacting {BUSINESS_CONFIG['name']}. Have a great day!",
"help": "I can help you with: \n• Store hours and location \n• Product information and pricing \n• Return and shipping policies \n• Technical comparisons between products \n• And much more! What do you need help with today?",
"capabilities": f"I'm your virtual assistant for {BUSINESS_CONFIG['name']}! I can answer questions about our products, services, policies, and more. What would you like to know?",
"values": f"Our company values: {BUSINESS_CONFIG['values']}",
"people": f"Key people at our company: {BUSINESS_CONFIG['key_people']}",
"payment": f"We accept these payment methods: {BUSINESS_CONFIG['payment_methods']}."
}
return responses.get(intent, "")
# Function to handle product inquiries
def handle_product_inquiry(product_type, model=None):
if product_type not in PRODUCTS:
available_products = ", ".join(PRODUCTS.keys())
return f"We don't carry that product. We mainly offer {available_products}."
if model:
if model in PRODUCTS[product_type]:
product = PRODUCTS[product_type][model]
return f"Our {model} {product_type} is the {product['name']}, priced at {product['price']}. Features: {product['features']}"
else:
available_models = ", ".join(PRODUCTS[product_type].keys())
return f"We don't have a {model} model for {product_type}. We have {available_models}."
else:
models = PRODUCTS[product_type]
response = f"For {product_type}, we have these models:"
for model_name, details in models.items():
response += f"\n- {model_name}: {details['name']} ({details['price']})"
return response
# Main chat function
def chat_with_bot(message, chat_history):
user_message = message.lower()
bot_response = ""
# Format conversation history for context
conversation_history = ""
for entry in chat_history:
if entry['role'] == 'user':
conversation_history += f"Customer: {entry['content']}\n"
else:
conversation_history += f"Assistant: {entry['content']}\n"
# Check for shipping first (before greetings to avoid "hi" in "shipping" triggering greeting)
if any(word in user_message for word in ["ship", "delivery", "deliver", "shipping", "free shipping"]):
bot_response = get_business_response("shipping")
# Check for returns
elif any(word in user_message for word in ["return", "exchange", "refund"]):
bot_response = get_business_response("returns")
# Check for products
elif any(word in user_message for word in ["product", "sell", "offer", "item", "inventory", "have", "stock"]):
bot_response = get_business_response("products")
# Check for services
elif any(word in user_message for word in ["service", "support", "repair", "maintenance", "warranty"]):
bot_response = get_business_response("services")
# Check for contact info
elif any(word in user_message for word in ["contact", "phone", "call", "email", "reach"]):
bot_response = get_business_response("contact")
# Check for location
elif any(word in user_message for word in ["where", "location", "address", "find", "directions"]):
bot_response = get_business_response("location")
# Check for business hours
elif any(word in user_message for word in ["hour", "time", "open", "close", "when"]):
bot_response = get_business_response("hours")
# Check for company values
elif any(word in user_message for word in ["value", "mission", "believe", "principle"]):
bot_response = get_business_response("values")
# Check for people
elif any(word in user_message for word in ["who", "people", "team", "owner", "ceo", "manager"]):
bot_response = get_business_response("people")
# Check for payment methods
elif any(word in user_message for word in ["pay", "payment", "credit", "debit", "cash", "finance"]):
bot_response = get_business_response("payment")
# Check for help or capabilities
elif any(word in user_message for word in ["help", "what can you do", "how can you help", "capabilities", "what do you know"]):
bot_response = get_business_response("capabilities")
# Check for thanks
elif any(word in user_message for word in ["thank", "appreciate", "thanks"]):
bot_response = get_business_response("thanks")
# Check for goodbye
elif any(word in user_message for word in ["bye", "goodbye", "see you", "farewell"]):
bot_response = get_business_response("goodbye")
# Check for greetings (moved to end to avoid conflicts)
elif any(word in user_message for word in ["hi", "hello", "hey", "greetings", "howdy"]):
bot_response = get_business_response("greeting")
# Handle product inquiries
elif any(word in user_message for word in ["smartphone", "phone", "iphone", "android"]):
if "pro" in user_message or "premium" in user_message or "high-end" in user_message:
bot_response = handle_product_inquiry("smartphone", "pro")
elif "basic" in user_message or "cheap" in user_message or "budget" in user_message:
bot_response = handle_product_inquiry("smartphone", "basic")
else:
bot_response = handle_product_inquiry("smartphone")
elif any(word in user_message for word in ["laptop", "computer", "notebook", "macbook", "pc"]):
if "pro" in user_message or "premium" in user_message or "high-end" in user_message:
bot_response = handle_product_inquiry("laptop", "premium")
elif "standard" in user_message or "basic" in user_message or "budget" in user_message:
bot_response = handle_product_inquiry("laptop", "standard")
else:
bot_response = handle_product_inquiry("laptop")
elif any(word in user_message for word in ["tablet", "ipad", "android tablet"]):
bot_response = "We offer a variety of tablets from leading brands. Would you like information about Apple iPads or Android tablets?"
elif any(word in user_message for word in ["accessory", "accessories", "case", "charger", "headphone"]):
bot_response = "We carry a wide range of accessories including cases, chargers, headphones, and more. Is there a specific accessory you're interested in?"
# For all other questions, use the AI module
else:
bot_response = ai_assistant.generate_response(user_message, conversation_history)
# If the AI module returns a generic response, try to provide something more specific
if "thank you for your question" in bot_response.lower():
if "?" in user_message or "what" in user_message or "how" in user_message:
bot_response = f"I'd be happy to help! At {BUSINESS_CONFIG['name']}, we offer {BUSINESS_CONFIG['products']}. Is there a specific product or service you're interested in?"
else:
bot_response = "How can I assist you today? I can help with product information, store details, or technical support."
# Add a small delay to make it feel more natural
time.sleep(0.3)
# Append to chat history using the new Messages format
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": bot_response})
return "", chat_history
# Simple CSS for basic styling
custom_css = """
#chatbot {
height: 400px;
overflow-y: auto;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 15px;
}
.gr-button {
background-color: #4CAF50 !important;
color: white !important;
}
.send-button {
background-color: #2196F3 !important;
}
.clear-button {
background-color: #f44336 !important;
}
"""
with gr.Blocks(css=custom_css, title=f"{BUSINESS_CONFIG['name']} Support") as demo:
with gr.Column():
gr.Markdown(f"# 🤖 {BUSINESS_CONFIG['name']} Support Chat")
# Plain text instructions - no boxes
gr.Markdown("### 💡 How to Use This Chatbot")
gr.Markdown("This AI assistant can help you with product information, store policies, technical support, and more. Just type your question in the chat box or click on any of the example questions to get started.")
gr.Markdown("### ✅ What I Can Help With")
gr.Markdown("""
• Product information, specifications, and pricing
• Store hours, location, and contact information
• Shipping options and return policies
• Technical support and troubleshooting
• Product comparisons and recommendations
• Service information and repair options
""")
gr.Markdown("### ⚠️ Limitations")
gr.Markdown("""
• I can't process orders or payments directly
• I don't have access to your personal account information
• For complex issues, I may connect you with a human specialist
• My knowledge is based on information available up to my last training
""")
with gr.Row():
with gr.Column(scale=2):
gr.Markdown("### 🏪 Store Information")
gr.Markdown(f"""
**Hours**: {BUSINESS_CONFIG['hours']}
**Address**: {BUSINESS_CONFIG['address']}
**Phone**: {BUSINESS_CONFIG['phone']}
**Email**: {BUSINESS_CONFIG['email']}
**Shipping**: {BUSINESS_CONFIG['shipping']}
""")
gr.Markdown("---")
with gr.Row():
with gr.Column(scale=2):
chatbot = gr.Chatbot(
label="Conversation",
elem_id="chatbot",
type="messages",
show_copy_button=True
)
with gr.Row():
msg = gr.Textbox(
label="Type your message here...",
placeholder="Ask me about products, services, or anything else...",
lines=1,
scale=4
)
send_btn = gr.Button("Send", variant="primary", elem_classes="send-button", scale=1)
clear = gr.Button("Clear Conversation", variant="stop", elem_classes="clear-button")
with gr.Column(scale=1):
gr.Markdown("### 💡 Common Questions")
examples = gr.Examples(
examples=[
["What products do you have?"],
["Do you offer free shipping?"],
["What are your store hours?"],
["What's your return policy?"],
["Can you compare your laptop models?"],
["What services do you provide?"],
["What payment methods do you accept?"]
],
inputs=msg,
label="Click any question to try it!",
examples_per_page=7
)
# Event handlers
msg.submit(chat_with_bot, [msg, chatbot], [msg, chatbot])
send_btn.click(chat_with_bot, [msg, chatbot], [msg, chatbot])
clear.click(lambda: None, None, chatbot, queue=False)
if __name__ == "__main__":
demo.launch(share=True)