SmokeyBandit commited on
Commit
fead20a
Β·
verified Β·
1 Parent(s): 195663c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -30
app.py CHANGED
@@ -3,6 +3,7 @@ from huggingface_hub import InferenceClient
3
  import json
4
  from typing import Dict, List, Any
5
  import time
 
6
 
7
  # Initialize the client with retries
8
  MAX_RETRIES = 3
@@ -13,7 +14,7 @@ def create_client(retries=MAX_RETRIES):
13
  for attempt in range(retries):
14
  try:
15
  return InferenceClient(
16
- "HuggingFaceH4/zephyr-7b-beta",
17
  timeout=30
18
  )
19
  except Exception as e:
@@ -35,6 +36,26 @@ def load_site_content() -> Dict[str, Any]:
35
  print(f"Error loading JSON: {e}")
36
  return {}
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def get_relevant_context(query: str, data: Dict[str, Any]) -> str:
39
  """Get relevant context based on the query keywords."""
40
  query = query.lower()
@@ -94,8 +115,19 @@ Company Information:
94
  Features: {', '.join(spec_data.get('core_features', []))}
95
  Technologies: {', '.join(spec_data.get('key_technologies', []))}""")
96
 
 
 
 
 
 
 
 
 
 
 
 
97
  # Add payment information for relevant queries
98
- if any(word in query for word in ['payment', 'pay', 'cost', 'pricing', 'bank', 'bitcoin', 'eth', 'btc']):
99
  info = data.get('company_info', {})
100
  context_parts.append(f"\nPayment Information: {info.get('payment', '')}")
101
 
@@ -135,19 +167,19 @@ def respond(
135
  # Get relevant context
136
  context = get_relevant_context(message, content)
137
 
138
- # Enhanced system message with strict instructions
139
  enhanced_system_message = f"""{system_message}
140
  IMPORTANT CONTEXT - USE THIS INFORMATION ONLY:
141
  {context}
142
- STRICT INSTRUCTIONS:
143
- 1. ONLY use information from the context provided above
144
- 2. If information isn't in the context, say "I don't have that specific information"
145
- 3. NEVER make assumptions about location - we are a proudly South African company
146
- 4. NEVER invent services or capabilities not listed
147
- 5. Be accurate about our AI and educational technology focus
148
- 6. Acknowledge our cryptocurrency acceptance when relevant
149
- 7. Use exact statistics when they're provided in the context
150
- 8. Always acknowledge Wayne Sletcher as CEO and Founder when relevant"""
151
 
152
  try:
153
  # Format conversation history
@@ -177,24 +209,76 @@ STRICT INSTRUCTIONS:
177
  client = create_client()
178
  yield "I apologize, but I encountered an error. Please try your question again."
179
 
180
- # Create the Gradio interface
181
- demo = gr.ChatInterface(
182
- respond,
183
- additional_inputs=[
184
- gr.Textbox(
185
- value="You are the official AI assistant for SletcherSystems, a proudly South African technology company. Provide accurate, specific information based only on the provided context.",
186
- label="System message"
187
- ),
188
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
189
- gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.1, label="Temperature"),
190
- gr.Slider(
191
- minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"
192
- ),
193
- ],
194
- title="SletcherSystems AI Assistant",
195
- description="Welcome! I'm here to help you learn about SletcherSystems, a proudly South African technology company.",
196
- theme=gr.themes.Soft()
197
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
  if __name__ == "__main__":
 
200
  demo.launch()
 
3
  import json
4
  from typing import Dict, List, Any
5
  import time
6
+ import random
7
 
8
  # Initialize the client with retries
9
  MAX_RETRIES = 3
 
14
  for attempt in range(retries):
15
  try:
16
  return InferenceClient(
17
+ "mistralai/Mistral-7B-Instruct-v0.2", # Updated to a more capable model
18
  timeout=30
19
  )
20
  except Exception as e:
 
36
  print(f"Error loading JSON: {e}")
37
  return {}
38
 
39
+ def get_engagement_prompt(content):
40
+ """Generate a random friendly greeting."""
41
+ prompts = [
42
+ "πŸ‘‹ Welcome to SletcherSystems! How can I assist you today?",
43
+ "πŸ‡ΏπŸ‡¦ Hello from SletcherSystems in South Africa! How may I help you?",
44
+ "πŸ‘¨β€πŸ’» Need help with AI solutions or educational technology? I'm here to assist!",
45
+ "πŸš€ Looking to transform your business with AI? Let me know what you're interested in!",
46
+ "🌍 Greetings! I'm your SletcherSystems virtual assistant. What can I help you with?"
47
+ ]
48
+
49
+ # Add product-specific prompts if available
50
+ products = content.get('products', [])
51
+ if products and isinstance(products, list):
52
+ product_count = min(2, len(products)) # Get up to 2 products
53
+ for i in range(product_count):
54
+ product = products[i]
55
+ prompts.append(f"πŸ” Interested in our {product.get('name', '')}? Feel free to ask about it!")
56
+
57
+ return random.choice(prompts)
58
+
59
  def get_relevant_context(query: str, data: Dict[str, Any]) -> str:
60
  """Get relevant context based on the query keywords."""
61
  query = query.lower()
 
115
  Features: {', '.join(spec_data.get('core_features', []))}
116
  Technologies: {', '.join(spec_data.get('key_technologies', []))}""")
117
 
118
+ # Products information
119
+ if any(word in query for word in ['product', 'pricing', 'cost', 'buy', 'purchase', 'student', 'enterprise', 'personal']):
120
+ products = data.get('products', [])
121
+ context_parts.append("\nOur Products:")
122
+ for product in products:
123
+ context_parts.append(f"""
124
+ - {product.get('name', '')}
125
+ Description: {product.get('description', '')}
126
+ Price: {product.get('price', 'Contact for pricing')}
127
+ Features: {', '.join(product.get('features', []))}""")
128
+
129
  # Add payment information for relevant queries
130
+ if any(word in query for word in ['payment', 'pay', 'cost', 'pricing', 'bank', 'bitcoin', 'eth', 'btc', 'crypto']):
131
  info = data.get('company_info', {})
132
  context_parts.append(f"\nPayment Information: {info.get('payment', '')}")
133
 
 
167
  # Get relevant context
168
  context = get_relevant_context(message, content)
169
 
170
+ # Enhanced system message with conversation guidance
171
  enhanced_system_message = f"""{system_message}
172
  IMPORTANT CONTEXT - USE THIS INFORMATION ONLY:
173
  {context}
174
+ CONVERSATION GUIDELINES:
175
+ 1. Be warm, friendly, and conversational - feel free to use emoji occasionally πŸ‡ΏπŸ‡¦
176
+ 2. ONLY use information from the context provided above
177
+ 3. If information isn't in the context, politely say you don't have that specific information
178
+ 4. We are a proudly South African company - incorporate this identity naturally
179
+ 5. Avoid technical jargon unless directly relevant to the question
180
+ 6. Keep responses concise and focused on helping the user
181
+ 7. For product inquiries, mention relevant features and pricing
182
+ 8. Acknowledge Wayne Sletcher as CEO and Founder when contextually appropriate"""
183
 
184
  try:
185
  # Format conversation history
 
209
  client = create_client()
210
  yield "I apologize, but I encountered an error. Please try your question again."
211
 
212
+ def create_chat_interface():
213
+ content = load_site_content()
214
+
215
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
216
+ with gr.Row():
217
+ with gr.Column(scale=3):
218
+ chatbot = gr.Chatbot(
219
+ label="SletcherSystems Assistant",
220
+ height=500,
221
+ avatar_images=["https://api.dicebear.com/7.x/bottts/svg?seed=user", "https://api.dicebear.com/7.x/bottts/svg?seed=sletcher"]
222
+ )
223
+
224
+ with gr.Row():
225
+ msg = gr.Textbox(
226
+ placeholder="Ask me about SletcherSystems...",
227
+ label="Your message",
228
+ scale=8
229
+ )
230
+ submit = gr.Button("Send", variant="primary", scale=1)
231
+ clear = gr.Button("Clear", variant="secondary", scale=1)
232
+
233
+ with gr.Accordion("Advanced Settings", open=False):
234
+ system_message = gr.Textbox(
235
+ value="You are the official AI assistant for SletcherSystems, a proudly South African technology company. Provide helpful, friendly information based on the context provided.",
236
+ label="System message"
237
+ )
238
+ max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max tokens")
239
+ temperature = gr.Slider(minimum=0.1, maximum=1.0, value=0.8, step=0.1, label="Temperature")
240
+ top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p")
241
+
242
+ # Add initial greeting
243
+ def show_greeting():
244
+ greeting = "πŸ‘‹ Welcome to SletcherSystems! How can I assist you today?"
245
+ try:
246
+ if content:
247
+ greeting = get_engagement_prompt(content)
248
+ except Exception as e:
249
+ print(f"Error generating greeting: {e}")
250
+ return [[None, greeting]]
251
+
252
+ def user_submit(message, chat_history):
253
+ return "", chat_history + [[message, None]]
254
+
255
+ def bot_response(chat_history, system_msg, max_tok, temp, top_probability):
256
+ if chat_history and chat_history[-1][1] is None:
257
+ user_message = chat_history[-1][0]
258
+ chat_history[-1][1] = "" # Initialize bot response
259
+
260
+ for chunk in respond(user_message, chat_history[:-1], system_msg, max_tok, temp, top_probability):
261
+ chat_history[-1][1] = chunk
262
+ yield chat_history
263
+ else:
264
+ yield chat_history
265
+
266
+ # Set up event handlers
267
+ msg.submit(user_submit, [msg, chatbot], [msg, chatbot]).then(
268
+ bot_response, [chatbot, system_message, max_tokens, temperature, top_p], [chatbot]
269
+ )
270
+
271
+ submit.click(user_submit, [msg, chatbot], [msg, chatbot]).then(
272
+ bot_response, [chatbot, system_message, max_tokens, temperature, top_p], [chatbot]
273
+ )
274
+
275
+ clear.click(lambda: (None, []), None, [msg, chatbot], queue=False)
276
+
277
+ # Show initial greeting on load
278
+ demo.load(show_greeting, None, chatbot)
279
+
280
+ return demo
281
 
282
  if __name__ == "__main__":
283
+ demo = create_chat_interface()
284
  demo.launch()