LucidMinds3ye commited on
Commit
d3ad66a
·
verified ·
1 Parent(s): 4f84f4f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -145
app.py CHANGED
@@ -1,102 +1,10 @@
1
  import gradio as gr
2
  import time
3
- import requests
4
- import json
5
-
6
- # ==================== CONFIGURATION MODULE ====================
7
- # Customize this section for your specific business
8
-
9
- BUSINESS_CONFIG = {
10
- "name": "TechGadget Store",
11
- "industry": "technology retail",
12
- "hours": "9AM-6PM Monday to Saturday",
13
- "products": "smartphones, laptops, tablets, and accessories",
14
- "address": "123 Main Street, Tech City",
15
- "phone": "(555) 123-4567",
16
- "email": "[email protected]",
17
- "return_policy": "30-day money-back guarantee on all products",
18
- "shipping": "Free shipping on orders over $50",
19
- "values": "Quality products, excellent customer service, and competitive prices",
20
- "key_people": "John Smith (CEO), Sarah Johnson (Head of Sales)"
21
- }
22
-
23
- PRODUCTS = {
24
- "smartphone": {
25
- "basic": {"name": "BasicPhone", "price": "$199", "features": "6.1\" display, 128GB storage"},
26
- "pro": {"name": "ProPhone X", "price": "$899", "features": "6.7\" OLED, 512GB, 5G"}
27
- },
28
- "laptop": {
29
- "standard": {"name": "WorkBook Lite", "price": "$699", "features": "15\" display, 8GB RAM, 256GB SSD"},
30
- "premium": {"name": "WorkBook Pro", "price": "$1499", "features": "16\" display, 16GB RAM, 1TB SSD"}
31
- }
32
- }
33
-
34
- # ==================== AI MODULE ====================
35
- # This module handles complex questions using business context
36
-
37
- class BusinessAIAssistant:
38
- def __init__(self, business_config):
39
- self.business_config = business_config
40
- self.context = self._create_context_prompt()
41
-
42
- def _create_context_prompt(self):
43
- """Create a detailed context prompt for the AI"""
44
- prompt = f"""You are a customer service representative for {self.business_config['name']},
45
- a {self.business_config['industry']} business. Your role is to assist customers with questions
46
- about products, policies, and services while maintaining a friendly and professional tone.
47
-
48
- BUSINESS INFORMATION:
49
- - Name: {self.business_config['name']}
50
- - Industry: {self.business_config['industry']}
51
- - Hours: {self.business_config['hours']}
52
- - Address: {self.business_config['address']}
53
- - Phone: {self.business_config['phone']}
54
- - Email: {self.business_config['email']}
55
- - Products: {self.business_config['products']}
56
- - Return Policy: {self.business_config['return_policy']}
57
- - Shipping: {self.business_config['shipping']}
58
- - Values: {self.business_config['values']}
59
- - Key People: {self.business_config['key_people']}
60
-
61
- GUIDELINES:
62
- 1. Always be helpful, friendly, and professional
63
- 2. Stay on topic related to the business and its products/services
64
- 3. If asked about unrelated topics, politely steer back to business matters
65
- 4. For technical questions, provide accurate information based on product specs
66
- 5. If unsure about something, offer to connect the customer with a human representative
67
-
68
- CURRENT CONVERSATION:
69
- """
70
- return prompt
71
-
72
- def generate_response(self, user_message, conversation_history=""):
73
- """
74
- Generate a response to user message using business context
75
- In a real implementation, this would connect to an AI API
76
- """
77
- # Simulated AI response - in practice, you would call an AI API here
78
- # For example: Hugging Face, OpenAI, or another LLM provider
79
-
80
- # This is a simplified simulation - real implementation would use API calls
81
- if "technical" in user_message.lower() or "spec" in user_message.lower():
82
- return "I'd be happy to help with technical questions! Based on our product specifications, I can provide detailed information about features and compatibility."
83
-
84
- elif "recommend" in user_message.lower() or "suggest" in user_message.lower():
85
- return "Based on your needs, I'd recommend considering our premium lineup for the best performance, or our standard options for great value."
86
-
87
- elif "compare" in user_message.lower():
88
- return "I can help you compare our products! Our premium options generally offer better performance, more storage, and higher quality displays than our standard models."
89
-
90
- elif "problem" in user_message.lower() or "issue" in user_message.lower():
91
- return "I'm sorry to hear you're experiencing an issue. Let me help you troubleshoot, or I can connect you with our technical support team if needed."
92
-
93
- else:
94
- return "Thank you for your question. As a representative of {business_name}, I'll do my best to provide accurate information about our products and services. How else can I assist you today?".format(business_name=self.business_config['name'])
95
 
96
  # Initialize the AI assistant
97
- ai_assistant = BusinessAIAssistant(BUSINESS_CONFIG)
98
-
99
- # ==================== CHATBOT LOGIC ====================
100
 
101
  # Predefined responses for common queries
102
  def get_business_response(intent):
@@ -105,32 +13,36 @@ def get_business_response(intent):
105
  "location": f"We're located at {BUSINESS_CONFIG['address']}. Come visit us!",
106
  "contact": f"You can reach us at {BUSINESS_CONFIG['phone']} or email {BUSINESS_CONFIG['email']}.",
107
  "products": f"We offer a wide range of {BUSINESS_CONFIG['products']}. What specifically are you interested in?",
 
108
  "returns": f"Our return policy: {BUSINESS_CONFIG['return_policy']}.",
109
  "shipping": f"Yes! We offer {BUSINESS_CONFIG['shipping'].lower()}",
110
- "greeting": "Hello! Welcome to {name}. How can I help you today?".format(name=BUSINESS_CONFIG['name']),
111
  "thanks": "You're welcome! Is there anything else I can help you with?",
112
- "goodbye": "Thank you for contacting {name}. Have a great day!".format(name=BUSINESS_CONFIG['name']),
113
  "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?",
114
- "capabilities": "I'm your virtual assistant for {name}! I can: \n• Answer questions about our products \n• Provide store information and hours \n• Explain our shipping and return policies \n• Help you compare different tech products \n• Assist with basic technical advice \n\nWhat would you like to know?".format(name=BUSINESS_CONFIG['name']),
115
  "values": f"Our company values: {BUSINESS_CONFIG['values']}",
116
- "people": f"Key people at our company: {BUSINESS_CONFIG['key_people']}"
 
117
  }
118
- return responses.get(intent, "I'm not sure how to help with that. Can you please rephrase?")
119
 
120
  # Function to handle product inquiries
121
  def handle_product_inquiry(product_type, model=None):
122
  if product_type not in PRODUCTS:
123
- return f"We don't carry that product. We mainly offer {', '.join(PRODUCTS.keys())}."
 
124
 
125
  if model:
126
  if model in PRODUCTS[product_type]:
127
  product = PRODUCTS[product_type][model]
128
  return f"Our {model} {product_type} is the {product['name']}, priced at {product['price']}. Features: {product['features']}"
129
  else:
130
- return f"We don't have a {model} model for {product_type}. We have {', '.join(PRODUCTS[product_type].keys())}."
 
131
  else:
132
  models = PRODUCTS[product_type]
133
- response = f"For {product_type}, we have: "
134
  for model_name, details in models.items():
135
  response += f"\n- {model_name}: {details['name']} ({details['price']})"
136
  return response
@@ -157,29 +69,37 @@ def chat_with_bot(message, chat_history):
157
  bot_response = get_business_response("returns")
158
 
159
  # Check for products
160
- elif any(word in user_message for word in ["product", "sell", "offer", "item"]):
161
  bot_response = get_business_response("products")
162
 
 
 
 
 
163
  # Check for contact info
164
- elif any(word in user_message for word in ["contact", "phone", "call", "email"]):
165
  bot_response = get_business_response("contact")
166
 
167
  # Check for location
168
- elif any(word in user_message for word in ["where", "location", "address", "find"]):
169
  bot_response = get_business_response("location")
170
 
171
  # Check for business hours
172
- elif any(word in user_message for word in ["hour", "time", "open", "close"]):
173
  bot_response = get_business_response("hours")
174
 
175
  # Check for company values
176
- elif any(word in user_message for word in ["value", "mission", "believe"]):
177
  bot_response = get_business_response("values")
178
 
179
  # Check for people
180
- elif any(word in user_message for word in ["who", "people", "team", "owner", "ceo"]):
181
  bot_response = get_business_response("people")
182
 
 
 
 
 
183
  # Check for help or capabilities
184
  elif any(word in user_message for word in ["help", "what can you do", "how can you help", "capabilities", "what do you know"]):
185
  bot_response = get_business_response("capabilities")
@@ -189,33 +109,45 @@ def chat_with_bot(message, chat_history):
189
  bot_response = get_business_response("thanks")
190
 
191
  # Check for goodbye
192
- elif any(word in user_message for word in ["bye", "goodbye", "see you"]):
193
  bot_response = get_business_response("goodbye")
194
 
195
  # Check for greetings (moved to end to avoid conflicts)
196
- elif any(word in user_message for word in ["hi", "hello", "hey", "greetings"]):
197
  bot_response = get_business_response("greeting")
198
 
199
  # Handle product inquiries
200
- elif any(word in user_message for word in ["smartphone", "phone"]):
201
- if "pro" in user_message or "premium" in user_message:
202
  bot_response = handle_product_inquiry("smartphone", "pro")
203
- elif "basic" in user_message or "cheap" in user_message:
204
  bot_response = handle_product_inquiry("smartphone", "basic")
205
  else:
206
  bot_response = handle_product_inquiry("smartphone")
207
 
208
- elif any(word in user_message for word in ["laptop", "computer"]):
209
- if "pro" in user_message or "premium" in user_message:
210
  bot_response = handle_product_inquiry("laptop", "premium")
211
- elif "standard" in user_message or "basic" in user_message:
212
  bot_response = handle_product_inquiry("laptop", "standard")
213
  else:
214
  bot_response = handle_product_inquiry("laptop")
215
 
 
 
 
 
 
 
216
  # For all other questions, use the AI module
217
  else:
218
  bot_response = ai_assistant.generate_response(user_message, conversation_history)
 
 
 
 
 
 
219
 
220
  # Add a small delay to make it feel more natural
221
  time.sleep(0.3)
@@ -226,8 +158,7 @@ def chat_with_bot(message, chat_history):
226
 
227
  return "", chat_history
228
 
229
- # ==================== GRADIO INTERFACE ====================
230
-
231
  custom_css = """
232
  #chatbot {
233
  font-family: 'Arial', sans-serif;
@@ -264,7 +195,7 @@ h1 {
264
  }
265
  """
266
 
267
- with gr.Blocks(css=custom_css, title="TechGadget Store Support") as demo:
268
  with gr.Column(elem_id="container"):
269
  gr.Markdown(f"# 🤖 {BUSINESS_CONFIG['name']} Support Chat")
270
  gr.Markdown("### How can I help you with our products and services today?")
@@ -280,7 +211,7 @@ with gr.Blocks(css=custom_css, title="TechGadget Store Support") as demo:
280
  with gr.Row():
281
  msg = gr.Textbox(
282
  label="Type your message here...",
283
- placeholder="Ask me about products, shipping, or technical details...",
284
  lines=1,
285
  scale=4
286
  )
@@ -292,13 +223,13 @@ with gr.Blocks(css=custom_css, title="TechGadget Store Support") as demo:
292
 
293
  examples = gr.Examples(
294
  examples=[
 
295
  ["Do you offer free shipping?"],
296
  ["What are your store hours?"],
297
  ["What's your return policy?"],
298
  ["Can you compare your laptop models?"],
299
- ["What technical specifications do your phones have?"],
300
- ["Who are the key people at your company?"],
301
- ["What values does your company uphold?"]
302
  ],
303
  inputs=msg,
304
  label="Click any question to try it!"
@@ -318,26 +249,5 @@ with gr.Blocks(css=custom_css, title="TechGadget Store Support") as demo:
318
  send_btn.click(chat_with_bot, [msg, chatbot], [msg, chatbot])
319
  clear.click(lambda: None, None, chatbot, queue=False)
320
 
321
- # ==================== INSTRUCTIONS ====================
322
-
323
- gr.Markdown("""
324
- ### Implementation Notes:
325
-
326
- 1. **AI Integration**: The `BusinessAIAssistant` class is designed to connect to any AI API. Currently, it uses simulated responses, but you can easily extend it to use:
327
- - Hugging Face Inference API
328
- - OpenAI GPT models
329
- - Anthropic Claude
330
- - Or any other LLM provider
331
-
332
- 2. **Customization**: Modify the `BUSINESS_CONFIG` dictionary at the top to match any business. The AI module will automatically adapt to the new context.
333
-
334
- 3. **Extending Functionality**: To add more capabilities:
335
- - Add new patterns to the response logic in `chat_with_bot()`
336
- - Extend the `BusinessAIAssistant` class with specialized methods
337
- - Add more products to the `PRODUCTS` dictionary
338
-
339
- 4. **API Integration**: To connect to a real AI API, replace the `generate_response` method with actual API calls to your preferred provider.
340
- """)
341
-
342
  if __name__ == "__main__":
343
  demo.launch(share=True)
 
1
  import gradio as gr
2
  import time
3
+ from business_ai import BusinessAIAssistant
4
+ from business_config import BUSINESS_CONFIG, PRODUCTS, SERVICES
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  # Initialize the AI assistant
7
+ ai_assistant = BusinessAIAssistant(BUSINESS_CONFIG, PRODUCTS, SERVICES)
 
 
8
 
9
  # Predefined responses for common queries
10
  def get_business_response(intent):
 
13
  "location": f"We're located at {BUSINESS_CONFIG['address']}. Come visit us!",
14
  "contact": f"You can reach us at {BUSINESS_CONFIG['phone']} or email {BUSINESS_CONFIG['email']}.",
15
  "products": f"We offer a wide range of {BUSINESS_CONFIG['products']}. What specifically are you interested in?",
16
+ "services": f"We provide these services: {BUSINESS_CONFIG['services']}.",
17
  "returns": f"Our return policy: {BUSINESS_CONFIG['return_policy']}.",
18
  "shipping": f"Yes! We offer {BUSINESS_CONFIG['shipping'].lower()}",
19
+ "greeting": f"Hello! Welcome to {BUSINESS_CONFIG['name']}. How can I help you today?",
20
  "thanks": "You're welcome! Is there anything else I can help you with?",
21
+ "goodbye": f"Thank you for contacting {BUSINESS_CONFIG['name']}. Have a great day!",
22
  "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?",
23
+ "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?",
24
  "values": f"Our company values: {BUSINESS_CONFIG['values']}",
25
+ "people": f"Key people at our company: {BUSINESS_CONFIG['key_people']}",
26
+ "payment": f"We accept these payment methods: {BUSINESS_CONFIG['payment_methods']}."
27
  }
28
+ return responses.get(intent, "")
29
 
30
  # Function to handle product inquiries
31
  def handle_product_inquiry(product_type, model=None):
32
  if product_type not in PRODUCTS:
33
+ available_products = ", ".join(PRODUCTS.keys())
34
+ return f"We don't carry that product. We mainly offer {available_products}."
35
 
36
  if model:
37
  if model in PRODUCTS[product_type]:
38
  product = PRODUCTS[product_type][model]
39
  return f"Our {model} {product_type} is the {product['name']}, priced at {product['price']}. Features: {product['features']}"
40
  else:
41
+ available_models = ", ".join(PRODUCTS[product_type].keys())
42
+ return f"We don't have a {model} model for {product_type}. We have {available_models}."
43
  else:
44
  models = PRODUCTS[product_type]
45
+ response = f"For {product_type}, we have these models:"
46
  for model_name, details in models.items():
47
  response += f"\n- {model_name}: {details['name']} ({details['price']})"
48
  return response
 
69
  bot_response = get_business_response("returns")
70
 
71
  # Check for products
72
+ elif any(word in user_message for word in ["product", "sell", "offer", "item", "inventory", "have", "stock"]):
73
  bot_response = get_business_response("products")
74
 
75
+ # Check for services
76
+ elif any(word in user_message for word in ["service", "support", "repair", "maintenance", "warranty"]):
77
+ bot_response = get_business_response("services")
78
+
79
  # Check for contact info
80
+ elif any(word in user_message for word in ["contact", "phone", "call", "email", "reach"]):
81
  bot_response = get_business_response("contact")
82
 
83
  # Check for location
84
+ elif any(word in user_message for word in ["where", "location", "address", "find", "directions"]):
85
  bot_response = get_business_response("location")
86
 
87
  # Check for business hours
88
+ elif any(word in user_message for word in ["hour", "time", "open", "close", "when"]):
89
  bot_response = get_business_response("hours")
90
 
91
  # Check for company values
92
+ elif any(word in user_message for word in ["value", "mission", "believe", "principle"]):
93
  bot_response = get_business_response("values")
94
 
95
  # Check for people
96
+ elif any(word in user_message for word in ["who", "people", "team", "owner", "ceo", "manager"]):
97
  bot_response = get_business_response("people")
98
 
99
+ # Check for payment methods
100
+ elif any(word in user_message for word in ["pay", "payment", "credit", "debit", "cash", "finance"]):
101
+ bot_response = get_business_response("payment")
102
+
103
  # Check for help or capabilities
104
  elif any(word in user_message for word in ["help", "what can you do", "how can you help", "capabilities", "what do you know"]):
105
  bot_response = get_business_response("capabilities")
 
109
  bot_response = get_business_response("thanks")
110
 
111
  # Check for goodbye
112
+ elif any(word in user_message for word in ["bye", "goodbye", "see you", "farewell"]):
113
  bot_response = get_business_response("goodbye")
114
 
115
  # Check for greetings (moved to end to avoid conflicts)
116
+ elif any(word in user_message for word in ["hi", "hello", "hey", "greetings", "howdy"]):
117
  bot_response = get_business_response("greeting")
118
 
119
  # Handle product inquiries
120
+ elif any(word in user_message for word in ["smartphone", "phone", "iphone", "android"]):
121
+ if "pro" in user_message or "premium" in user_message or "high-end" in user_message:
122
  bot_response = handle_product_inquiry("smartphone", "pro")
123
+ elif "basic" in user_message or "cheap" in user_message or "budget" in user_message:
124
  bot_response = handle_product_inquiry("smartphone", "basic")
125
  else:
126
  bot_response = handle_product_inquiry("smartphone")
127
 
128
+ elif any(word in user_message for word in ["laptop", "computer", "notebook", "macbook", "pc"]):
129
+ if "pro" in user_message or "premium" in user_message or "high-end" in user_message:
130
  bot_response = handle_product_inquiry("laptop", "premium")
131
+ elif "standard" in user_message or "basic" in user_message or "budget" in user_message:
132
  bot_response = handle_product_inquiry("laptop", "standard")
133
  else:
134
  bot_response = handle_product_inquiry("laptop")
135
 
136
+ elif any(word in user_message for word in ["tablet", "ipad", "android tablet"]):
137
+ bot_response = "We offer a variety of tablets from leading brands. Would you like information about Apple iPads or Android tablets?"
138
+
139
+ elif any(word in user_message for word in ["accessory", "accessories", "case", "charger", "headphone"]):
140
+ bot_response = "We carry a wide range of accessories including cases, chargers, headphones, and more. Is there a specific accessory you're interested in?"
141
+
142
  # For all other questions, use the AI module
143
  else:
144
  bot_response = ai_assistant.generate_response(user_message, conversation_history)
145
+ # If the AI module returns a generic response, try to provide something more specific
146
+ if "thank you for your question" in bot_response.lower():
147
+ if "?" in user_message or "what" in user_message or "how" in user_message:
148
+ 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?"
149
+ else:
150
+ bot_response = "How can I assist you today? I can help with product information, store details, or technical support."
151
 
152
  # Add a small delay to make it feel more natural
153
  time.sleep(0.3)
 
158
 
159
  return "", chat_history
160
 
161
+ # Custom CSS for styling
 
162
  custom_css = """
163
  #chatbot {
164
  font-family: 'Arial', sans-serif;
 
195
  }
196
  """
197
 
198
+ with gr.Blocks(css=custom_css, title=f"{BUSINESS_CONFIG['name']} Support") as demo:
199
  with gr.Column(elem_id="container"):
200
  gr.Markdown(f"# 🤖 {BUSINESS_CONFIG['name']} Support Chat")
201
  gr.Markdown("### How can I help you with our products and services today?")
 
211
  with gr.Row():
212
  msg = gr.Textbox(
213
  label="Type your message here...",
214
+ placeholder="Ask me about products, services, or anything else...",
215
  lines=1,
216
  scale=4
217
  )
 
223
 
224
  examples = gr.Examples(
225
  examples=[
226
+ ["What products do you have?"],
227
  ["Do you offer free shipping?"],
228
  ["What are your store hours?"],
229
  ["What's your return policy?"],
230
  ["Can you compare your laptop models?"],
231
+ ["What services do you provide?"],
232
+ ["What payment methods do you accept?"]
 
233
  ],
234
  inputs=msg,
235
  label="Click any question to try it!"
 
249
  send_btn.click(chat_with_bot, [msg, chatbot], [msg, chatbot])
250
  clear.click(lambda: None, None, chatbot, queue=False)
251
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
  if __name__ == "__main__":
253
  demo.launch(share=True)