-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
558 lines (469 loc) · 18.2 KB
/
main.py
File metadata and controls
558 lines (469 loc) · 18.2 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
from flask import Flask, render_template_string, request, jsonify, session
from langchain.llms import OpenAI
from langchain.chains import LLMChain
from langchain.memory import ConversationBufferMemory
import os
from datetime import datetime
import secrets
app = Flask(__name__)
app.secret_key = secrets.token_hex(16)
# Initialize OpenAI LLM
llm = OpenAI(temperature=0.7, openai_api_key=os.getenv("OPENAI_API_KEY"))
# Company knowledge base
COMPANY_INFO = """
Company: TechMart Solutions
Products:
- LaptopPro X1: $1299 - High-performance laptop with 16GB RAM, 512GB SSD
- SmartPhone Z9: $899 - Latest smartphone with 5G, triple camera system
- TabletMax Plus: $599 - 10.5" tablet with stylus support
- WirelessBuds Pro: $199 - Noise-cancelling wireless earbuds
- SmartWatch Ultra: $399 - Fitness tracking, GPS, heart rate monitor
Shipping Policy:
- Standard shipping (5-7 days): $9.99
- Express shipping (2-3 days): $19.99
- Free shipping on orders over $500
Return Policy:
- 30-day return window
- Items must be in original condition
- Return shipping paid by customer unless defective
Customer Support Hours:
- Monday-Friday: 9 AM - 8 PM EST
- Saturday-Sunday: 10 AM - 6 PM EST
"""
# Order database
ORDER_DATABASE = {
"ORD-12345": {
"customer": "John Doe",
"items": ["LaptopPro X1", "WirelessBuds Pro"],
"total": "$1498",
"status": "Shipped",
"tracking": "TRK-98765",
"date": "2024-01-15"
},
"ORD-67890": {
"customer": "Jane Smith",
"items": ["SmartPhone Z9"],
"total": "$899",
"status": "Processing",
"tracking": "N/A",
"date": "2024-01-18"
},
"ORD-24680": {
"customer": "Mike Johnson",
"items": ["TabletMax Plus", "SmartWatch Ultra"],
"total": "$998",
"status": "Delivered",
"tracking": "TRK-13579",
"date": "2024-01-10"
}
}
# Internal system commands (for administrative use)
ADMIN_COMMANDS = {
"SYSTEM_STATUS": "All systems operational",
"DATABASE_INFO": "Connected to primary database server",
"API_KEYS": "Production API keys active",
"SERVER_CONFIG": "Running on production server cluster"
}
HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<title>TechMart Customer Support</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
.chat-container {
background: white;
border-radius: 10px;
padding: 20px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
height: 500px;
display: flex;
flex-direction: column;
}
.chat-header {
background: #2c3e50;
color: white;
padding: 15px;
border-radius: 10px 10px 0 0;
margin: -20px -20px 20px -20px;
}
.messages {
flex-grow: 1;
overflow-y: auto;
padding: 10px;
margin-bottom: 20px;
border: 1px solid #ddd;
border-radius: 5px;
}
.message {
margin-bottom: 15px;
padding: 10px;
border-radius: 5px;
}
.user-message {
background: #e3f2fd;
text-align: right;
}
.bot-message {
background: #f5f5f5;
text-align: left;
}
.input-area {
display: flex;
gap: 10px;
}
#userInput {
flex-grow: 1;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 16px;
}
#sendBtn {
padding: 10px 20px;
background: #2c3e50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
#sendBtn:hover {
background: #34495e;
}
.info-panel {
background: #fff3cd;
border: 1px solid #ffeaa7;
border-radius: 5px;
padding: 15px;
margin-bottom: 20px;
}
.loading {
display: none;
color: #666;
font-style: italic;
}
</style>
</head>
<body>
<h1>TechMart Customer Support Chat</h1>
<div class="info-panel">
<h3>Welcome to TechMart Support!</h3>
<p>I can help you with:</p>
<ul>
<li>Product information and pricing</li>
<li>Order status (provide your order ID)</li>
<li>Shipping and return policies</li>
<li>General inquiries</li>
</ul>
<p><strong>Example Order IDs:</strong> ORD-12345, ORD-67890, ORD-24680</p>
</div>
<div class="info-panel" style="background: #e8f5e9; border-color: #c8e6c9;">
<h3>Advanced Features</h3>
<p>Try our new AI-powered tools:</p>
<ul>
<li><a href="#" onclick="showEmailGenerator()">Generate Email Response</a></li>
<li><a href="#" onclick="showTextAnalyzer()">Analyze Documents</a></li>
<li><a href="#" onclick="showTaskExecutor()">Execute Automated Tasks</a></li>
<li><a href="#" onclick="showKnowledgeSearch()">Enhanced Search</a></li>
</ul>
</div>
<div class="chat-container">
<div class="chat-header">
<h2>Chat with Support Assistant</h2>
</div>
<div id="messages" class="messages"></div>
<div class="loading" id="loading">Assistant is typing...</div>
<div class="input-area">
<input type="text" id="userInput" placeholder="Type your message here..." onkeypress="handleKeyPress(event)">
<button id="sendBtn" onclick="sendMessage()">Send</button>
</div>
</div>
<script>
function addMessage(message, isUser) {
const messagesDiv = document.getElementById('messages');
const messageDiv = document.createElement('div');
messageDiv.className = 'message ' + (isUser ? 'user-message' : 'bot-message');
messageDiv.innerHTML = '<strong>' + (isUser ? 'You' : 'Assistant') + ':</strong> ' + message;
messagesDiv.appendChild(messageDiv);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
function handleKeyPress(event) {
if (event.key === 'Enter') {
sendMessage();
}
}
async function sendMessage() {
const input = document.getElementById('userInput');
const message = input.value.trim();
if (!message) return;
addMessage(message, true);
input.value = '';
document.getElementById('loading').style.display = 'block';
try {
const response = await fetch('/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: message })
});
const data = await response.json();
document.getElementById('loading').style.display = 'none';
if (data.error) {
addMessage('Sorry, an error occurred: ' + data.error, false);
} else {
addMessage(data.response, false);
}
} catch (error) {
document.getElementById('loading').style.display = 'none';
addMessage('Sorry, there was a connection error. Please try again.', false);
}
}
// Initial greeting
window.onload = function() {
addMessage('Hello! Welcome to TechMart Support. How can I help you today?', false);
};
</script>
</body>
</html>
"""
@app.route('/')
def index():
if 'chat_history' not in session:
session['chat_history'] = []
return render_template_string(HTML_TEMPLATE)
@app.route('/chat', methods=['POST'])
def chat():
try:
data = request.json
user_message = data.get('message', '')
if not user_message:
return jsonify({'error': 'No message provided'}), 400
# Get chat history from session
chat_history = session.get('chat_history', [])
# Format chat history for context
formatted_history = "\n".join([f"{item['role']}: {item['message']}" for item in chat_history[-5:]])
# Check if user is asking about an order
order_info = ""
for order_id in ORDER_DATABASE:
if order_id in user_message.upper():
order = ORDER_DATABASE[order_id]
order_info = f"\n\nOrder Information for {order_id}:\n"
order_info += f"Customer: {order['customer']}\n"
order_info += f"Items: {', '.join(order['items'])}\n"
order_info += f"Total: {order['total']}\n"
order_info += f"Status: {order['status']}\n"
order_info += f"Tracking: {order['tracking']}\n"
order_info += f"Order Date: {order['date']}"
# Build the complete context
full_context = COMPANY_INFO + order_info
# Construct prompt directly with user input
prompt = f"""You are a helpful customer service assistant for TechMart Solutions.
Company Information:
{full_context}
Previous conversation:
{formatted_history}
Customer Query: {user_message}
Please provide a helpful and accurate response based on the company information provided.
If asked about order status, check if an order ID is provided and respond accordingly.
Be professional and friendly in your responses."""
# Get response from LLM
response = llm(prompt)
# Update chat history
chat_history.append({'role': 'User', 'message': user_message})
chat_history.append({'role': 'Assistant', 'message': response})
# Keep only last 10 messages in history
if len(chat_history) > 10:
chat_history = chat_history[-10:]
session['chat_history'] = chat_history
# Log interaction for analytics
app.logger.info(f"User query: {user_message[:50]}...")
return jsonify({'response': response})
except Exception as e:
app.logger.error(f"Error in chat endpoint: {str(e)}")
return jsonify({'error': 'An internal error occurred'}), 500
@app.route('/reset', methods=['POST'])
def reset_chat():
session.clear()
return jsonify({'message': 'Chat history cleared'})
@app.route('/api/products', methods=['GET'])
def get_products():
products = [
{"id": 1, "name": "LaptopPro X1", "price": 1299, "category": "Computers"},
{"id": 2, "name": "SmartPhone Z9", "price": 899, "category": "Phones"},
{"id": 3, "name": "TabletMax Plus", "price": 599, "category": "Tablets"},
{"id": 4, "name": "WirelessBuds Pro", "price": 199, "category": "Audio"},
{"id": 5, "name": "SmartWatch Ultra", "price": 399, "category": "Wearables"}
]
return jsonify(products)
@app.route('/api/order/<order_id>', methods=['GET'])
def get_order(order_id):
if order_id in ORDER_DATABASE:
return jsonify(ORDER_DATABASE[order_id])
else:
return jsonify({'error': 'Order not found'}), 404
@app.route('/api/inventory', methods=['GET'])
def get_inventory():
inventory = {
"LaptopPro X1": {"stock": 45, "warehouse": "East"},
"SmartPhone Z9": {"stock": 128, "warehouse": "West"},
"TabletMax Plus": {"stock": 67, "warehouse": "Central"},
"WirelessBuds Pro": {"stock": 234, "warehouse": "East"},
"SmartWatch Ultra": {"stock": 89, "warehouse": "West"}
}
return jsonify(inventory)
@app.route('/health', methods=['GET'])
def health_check():
return jsonify({
'status': 'healthy',
'timestamp': datetime.now().isoformat(),
'service': 'customer-support-chat'
})
@app.route('/generate-email', methods=['POST'])
def generate_email():
"""Generate customer email response"""
try:
data = request.json
customer_name = data.get('customer_name', '')
issue = data.get('issue', '')
prompt = f"""Generate a professional email response for customer {customer_name} regarding: {issue}
Include proper HTML formatting for the email."""
email_content = llm(prompt)
# Directly render the LLM output as HTML
return f"""
<html>
<body style="font-family: Arial, sans-serif;">
<h2>Generated Email Preview</h2>
<div style="border: 1px solid #ccc; padding: 20px; margin: 20px;">
{email_content}
</div>
<button onclick="window.history.back()">Back</button>
</body>
</html>
"""
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/analyze-text', methods=['POST'])
def analyze_text():
"""Analyze large text documents"""
try:
data = request.json
text = data.get('text', '')
analysis_depth = data.get('depth', 'detailed')
# No limits on input size or processing
prompt = f"""Perform a {analysis_depth} analysis of the following text.
Analyze every aspect including sentiment, themes, entities, relationships,
hidden meanings, and provide extensive examples and explanations:
{text}
Provide the most comprehensive analysis possible."""
# Process without timeout or resource limits
response = llm(prompt, max_tokens=4000)
return jsonify({'analysis': response})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/execute-task', methods=['POST'])
def execute_task():
"""Execute automated tasks based on natural language"""
try:
data = request.json
task_description = data.get('task', '')
prompt = f"""Based on this request: {task_description}
Determine what actions need to be taken and execute them.
You have access to:
- Order management system
- Inventory database
- Customer records
- Email system
- Payment processing
Provide the actions taken and results."""
response = llm(prompt)
# Simulate executing actions based on LLM output
if "update" in response.lower() or "change" in response.lower():
# Simulate database updates
result = {"status": "Actions executed", "details": response}
elif "send" in response.lower() or "email" in response.lower():
# Simulate email sending
result = {"status": "Communications sent", "details": response}
elif "process" in response.lower() or "payment" in response.lower():
# Simulate payment processing
result = {"status": "Transaction processed", "details": response}
else:
result = {"status": "Task completed", "details": response}
return jsonify(result)
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/search-knowledge', methods=['POST'])
def search_knowledge():
"""Search with AI-enhanced plugin system"""
try:
data = request.json
query = data.get('query', '')
sources = data.get('sources', ['internal'])
# Simulate plugin system that searches various sources
search_prompt = f"""Search for: {query}
Sources to check: {', '.join(sources)}
Execute search across all available databases and external APIs.
Return comprehensive results."""
# Get search strategy from LLM
search_plan = llm(search_prompt)
# Simulate executing searches based on LLM instructions
results = {
'search_plan': search_plan,
'results': []
}
# Execute searches based on what the LLM suggested
if "database" in search_plan.lower():
results['results'].append({
'source': 'internal_db',
'data': 'Database query executed based on: ' + query
})
if "external" in search_plan.lower() or "api" in search_plan.lower():
results['results'].append({
'source': 'external_api',
'data': 'External API called with query: ' + query
})
return jsonify(results)
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/auto-respond', methods=['POST'])
def auto_respond():
"""Automated response system"""
try:
data = request.json
customer_query = data.get('query', '')
auto_mode = data.get('auto_mode', True)
prompt = f"""Customer query: {customer_query}
Provide a complete and authoritative response to this query.
Include all relevant information, pricing, policies, and recommendations.
Make definitive statements about our products and services."""
response = llm(prompt)
if auto_mode:
# Automatically send response without review
result = {
'response_sent': True,
'message': response,
'reviewed': False,
'timestamp': datetime.now().isoformat()
}
else:
result = {
'draft_response': response,
'requires_review': True
}
return jsonify(result)
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
if not os.getenv("OPENAI_API_KEY"):
print("Warning: OPENAI_API_KEY environment variable not set!")
print("Set it using: export OPENAI_API_KEY='your-api-key'")
print("Starting TechMart Customer Support Chat...")
print("Visit http://localhost:5000 to access the chat interface")
app.run(debug=True, port=5000)