SmokeyBandit commited on
Commit
f8ae9b6
Β·
verified Β·
1 Parent(s): 7c56c28

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -128
app.py CHANGED
@@ -3,7 +3,6 @@ from huggingface_hub import InferenceClient
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,7 +13,7 @@ def create_client(retries=MAX_RETRIES):
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,26 +35,6 @@ def load_site_content() -> Dict[str, Any]:
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,19 +94,8 @@ Company Information:
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
 
@@ -155,117 +123,78 @@ def respond(
155
  if client is None:
156
  client = create_client()
157
  if client is None:
158
- return "I apologize, but I'm having trouble connecting to the language model."
 
159
 
160
- try:
161
- # Load content
162
- content = load_site_content()
163
- if not content:
164
- return "I apologize, but I'm having trouble accessing the company information."
165
-
166
- # Get relevant context
167
- context = get_relevant_context(message, content)
168
-
169
- # Enhanced system message
170
- enhanced_system_message = f"""You are the official AI assistant for SletcherSystems.
 
171
  {context}
172
- GUIDELINES:
173
- - Be friendly and professional
174
- - Only use information from the context above
175
- - Keep responses concise and helpful"""
 
 
 
 
 
176
 
 
177
  # Format conversation history
178
  messages = [{"role": "system", "content": enhanced_system_message}]
179
  for user_msg, assistant_msg in history:
180
- messages.append({"role": "user", "content": user_msg})
 
181
  if assistant_msg:
182
  messages.append({"role": "assistant", "content": assistant_msg})
183
  messages.append({"role": "user", "content": message})
184
 
185
- # Get response without streaming
186
- response = client.chat_completion(
 
187
  messages,
188
  max_tokens=max_tokens,
 
189
  temperature=temperature,
190
  top_p=top_p,
191
- stream=False
192
- )
193
-
194
- return response.choices[0].message.content
195
-
196
  except Exception as e:
197
  print(f"Error in chat completion: {e}")
 
198
  client = create_client()
199
- return "I apologize, but I encountered an error. Please try again."
200
-
201
- def create_chat_interface():
202
- content = load_site_content()
203
-
204
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
205
- with gr.Row():
206
- with gr.Column(scale=3):
207
- chatbot = gr.Chatbot(
208
- label="SletcherSystems Assistant",
209
- height=500,
210
- avatar_images=["https://api.dicebear.com/7.x/bottts/svg?seed=user", "https://api.dicebear.com/7.x/bottts/svg?seed=sletcher"]
211
- )
212
-
213
- with gr.Row():
214
- msg = gr.Textbox(
215
- placeholder="Ask me about SletcherSystems...",
216
- label="Your message",
217
- scale=8
218
- )
219
- submit = gr.Button("Send", variant="primary", scale=1)
220
- clear = gr.Button("Clear", variant="secondary", scale=1)
221
-
222
- with gr.Accordion("Advanced Settings", open=False):
223
- system_message = gr.Textbox(
224
- value="You are the official AI assistant for SletcherSystems, a proudly South African technology company. Provide helpful, friendly information based on the context provided.",
225
- label="System message"
226
- )
227
- max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max tokens")
228
- temperature = gr.Slider(minimum=0.1, maximum=1.0, value=0.8, step=0.1, label="Temperature")
229
- top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p")
230
-
231
- # Add initial greeting
232
- def show_greeting():
233
- greeting = "πŸ‘‹ Welcome to SletcherSystems! How can I assist you today?"
234
- try:
235
- if content:
236
- greeting = get_engagement_prompt(content)
237
- except Exception as e:
238
- print(f"Error generating greeting: {e}")
239
- return [[None, greeting]]
240
-
241
- def user_submit(message, chat_history):
242
- return "", chat_history + [[message, None]]
243
-
244
- def bot_response(chat_history, system_msg, max_tok, temp, top_probability):
245
- if chat_history and chat_history[-1][1] is None:
246
- user_message = chat_history[-1][0]
247
- response = respond(user_message, chat_history[:-1], system_msg, max_tok, temp, top_probability)
248
- chat_history[-1][1] = response
249
- yield chat_history
250
- else:
251
- yield chat_history
252
-
253
- # Set up event handlers
254
- msg.submit(user_submit, [msg, chatbot], [msg, chatbot]).then(
255
- bot_response, [chatbot, system_message, max_tokens, temperature, top_p], [chatbot]
256
- )
257
-
258
- submit.click(user_submit, [msg, chatbot], [msg, chatbot]).then(
259
- bot_response, [chatbot, system_message, max_tokens, temperature, top_p], [chatbot]
260
- )
261
-
262
- clear.click(lambda: (None, []), None, [msg, chatbot], queue=False)
263
-
264
- # Show initial greeting on load
265
- demo.load(show_greeting, None, chatbot)
266
-
267
- return demo
268
 
269
  if __name__ == "__main__":
270
- demo = create_chat_interface()
271
  demo.launch()
 
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
  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
  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
  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
 
 
123
  if client is None:
124
  client = create_client()
125
  if client is None:
126
+ yield "I apologize, but I'm having trouble connecting to the language model. Please try again in a moment."
127
+ return
128
 
129
+ # Load content
130
+ content = load_site_content()
131
+ if not content:
132
+ yield "I apologize, but I'm having trouble accessing the company information. Please try again in a moment."
133
+ return
134
+
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
154
  messages = [{"role": "system", "content": enhanced_system_message}]
155
  for user_msg, assistant_msg in history:
156
+ if user_msg:
157
+ messages.append({"role": "user", "content": user_msg})
158
  if assistant_msg:
159
  messages.append({"role": "assistant", "content": assistant_msg})
160
  messages.append({"role": "user", "content": message})
161
 
162
+ # Stream the response
163
+ response = ""
164
+ for msg in client.chat_completion(
165
  messages,
166
  max_tokens=max_tokens,
167
+ stream=True,
168
  temperature=temperature,
169
  top_p=top_p,
170
+ ):
171
+ token = msg.choices[0].delta.content
172
+ response += token
173
+ yield response
 
174
  except Exception as e:
175
  print(f"Error in chat completion: {e}")
176
+ # Try to recreate client on error
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()