-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1767 lines (1476 loc) · 69.2 KB
/
app.py
File metadata and controls
1767 lines (1476 loc) · 69.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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import smtplib
import chromadb
import pandas as pd
from datetime import datetime
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
from sentence_transformers import SentenceTransformer
import google.generativeai as genai
from chromadb.config import Settings
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from dotenv import load_dotenv
from sql_connector import SQLConnector
from database import IncidentDatabase
from ai_client import create_ai_client
from email_service import send_incident_report_email
# Load environment variables
load_dotenv()
# Initialize database
db = IncidentDatabase()
# Initialize Flask app
app = Flask(__name__)
CORS(app, resources={
r"/*": {
"origins": "*",
"methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
"allow_headers": ["Content-Type"]
}
})
# Global variables for models and data
sentence_transformer = None
chroma_client = None
collections = {} # Dictionary to store module-based collections
contacts_data = None
sql_connector = None
historical_data = None # Global DataFrame for historical case logs
# Enhanced LLM Prompts for Multi-Agent Architecture
TRIAGE_AGENT_PROMPT = """
You are a specialized Triage Agent for PSA (Port System Alert) processing.
Your task is to analyze ANY alert text format and extract key information in JSON format.
IMPORTANT: Return ONLY valid JSON, no markdown, no explanations, no additional text.
{{
"module": "CNTR|VSL|EDI/API|Infra/SRE",
"entities": ["entity1", "entity2", "entity3"],
"alert_type": "error|warning|info",
"severity": "critical|high|medium|low",
"urgency": "immediate|high|medium|low"
}}
MODULE DETECTION RULES:
- CNTR (Container): Look for "container", "CMAU", "MSCU", "cntr_no", "duplicate", "identical containers", "bay", "slots"
- VSL (Vessel): Look for "vessel", "MV", "vessel advice", "VESSEL_ERR_4", "System Vessel Name", "BAPLIE", "COARRI", "terminal", "load completed"
- EDI/API: Look for "EDI", "message", "REF-IFT", "stuck in ERROR", "acknowledgment", "ack_at is NULL", "correlation_id", "httpStatus"
- Infra/SRE: Look for "database", "connection", "timeout", "service", "system", "infrastructure"
ENTITY EXTRACTION:
- Extract container numbers (CMAU, MSCU patterns)
- Extract vessel names (MV patterns)
- Extract error codes (VESSEL_ERR_4, EDI_ERR_1, etc.)
- Extract message references (REF-IFT-0007, etc.)
- Extract terminal/port names
- Extract any technical identifiers
SEVERITY ASSESSMENT:
- critical: System down, data corruption, security breach
- high: Service degradation, multiple users affected
- medium: Single user issues, minor errors
- low: Informational, warnings
URGENCY ASSESSMENT:
- immediate: Production down, data loss risk
- high: Customer impact, SLA breach
- medium: Operational impact
- low: Non-critical issues
Alert text: {alert_text}
Return ONLY the JSON object above, nothing else.
"""
ANALYST_AGENT_PROMPT = """
You are an expert Technical Analyst Agent for PSA support. You have been provided with an alert and 3 candidate SOP documents.
Your task is to select the single best SOP that matches the alert.
ALERT TO ANALYZE:
{alert_text}
CANDIDATE SOPs:
{sop_candidates}
INSTRUCTIONS:
1. Analyze the alert and identify the core problem
2. Select the single best SOP that directly addresses this problem
3. Provide concise reasoning for your choice (no comparisons with other SOPs)
4. Generate a clear problem statement and actionable resolution steps
IMPORTANT: Return ONLY valid JSON, no markdown, no explanations, no additional text.
{{
"best_sop_id": "sop_X",
"reasoning": "Brief explanation of why this SOP is the best match for the alert",
"problem_statement": "Clear, concise description of the issue",
"resolution_summary": "Step-by-step resolution approach with specific actions to take"
}}
Return ONLY the JSON object above, nothing else.
"""
def initialize_models():
"""Initialize all required models and load data"""
global sentence_transformer, chroma_client, collections, contacts_data, sql_connector, historical_data
try:
# Initialize SentenceTransformer
print("Loading SentenceTransformer model...")
sentence_transformer = SentenceTransformer('all-MiniLM-L6-v2')
# Initialize ChromaDB with module-based collections
print("Connecting to ChromaDB...")
script_dir = os.path.dirname(os.path.abspath(__file__))
chroma_client = chromadb.PersistentClient(
path=os.path.join(script_dir, "chroma_db"),
settings=Settings(anonymized_telemetry=False)
)
# Load module-based collections
modules = ["CNTR", "VSL", "EDI/API", "Infra/SRE", "Container Report", "Container Booking", "IMPORT/EXPORT"]
for module in modules:
collection_name = f"psa_{module.lower().replace('/', '_').replace(' ', '_')}_collection"
try:
collection = chroma_client.get_collection(collection_name)
collections[module] = collection
print(f"Loaded collection: {collection_name}")
except Exception as e:
print(f"Warning: Could not load collection {collection_name}: {e}")
# Initialize SQL Connector
print("Initializing SQL connector...")
sql_connector = SQLConnector()
if not sql_connector.connect():
print("Warning: Could not connect to SQL database")
sql_connector = None
# Load contacts
print("Loading contacts data...")
contacts_file = os.path.join(script_dir, "contacts.json")
with open(contacts_file, 'r', encoding='utf-8') as f:
contacts_data = json.load(f)
# Load historical case log data
print("Loading historical case log data...")
case_log_file = os.path.join(script_dir, "Case Log.xlsx")
try:
# Read the Excel file, assuming the data is in the first sheet
historical_data = pd.read_excel(case_log_file)
print(f"Loaded {len(historical_data)} historical case logs")
print(f"Columns: {list(historical_data.columns)}")
except Exception as e:
print(f"Warning: Could not load historical data from {case_log_file}: {e}")
# Create empty DataFrame with expected columns if file doesn't exist
historical_data = pd.DataFrame(columns=['Module', 'Problem Statement', 'Solution', 'Timestamp'])
# Initialize Gemini
print("Initializing Gemini API...")
api_key = os.getenv('GOOGLE_API_KEY')
print(f"DEBUG: API Key loaded: {api_key[:10]}..." if api_key else "DEBUG: No API key found")
if not api_key or api_key == 'your-google-api-key-here':
raise ValueError("Please set GOOGLE_API_KEY in your .env file")
genai.configure(api_key=api_key)
print("DEBUG: Gemini configured successfully")
print("All models and data loaded successfully!")
except Exception as e:
print(f"Error initializing models: {e}")
raise e
def triage_agent(alert_text, ai_client=None):
"""Layer 1: Triage Agent - Parse alert text to extract entities and module"""
print("=" * 50)
print("TRIAGE AGENT CALLED!")
print(f"Alert text: {alert_text}")
print("=" * 50)
# Force flush output
import sys
sys.stdout.flush()
try:
print(f"TRIAGE AGENT: Processing alert: {alert_text[:100]}...")
# Use provided AI client or create default one
if ai_client is None:
print("TRIAGE AGENT: Creating default AI client...")
ai_client = create_ai_client()
print("TRIAGE AGENT: AI client ready")
prompt = TRIAGE_AGENT_PROMPT.format(alert_text=alert_text)
print(f"TRIAGE AGENT: Prompt created, length: {len(prompt)}")
print(f"TRIAGE AGENT: Calling AI API...")
response_text = ai_client.generate_content(prompt)
print(f"TRIAGE AGENT: AI response received")
# Extract JSON from response with better parsing
response_text = response_text.strip()
print(f"Raw AI response: {response_text}")
# Remove ALL markdown code blocks (handle multiple formats)
response_text = response_text.replace('```json', '').replace('```', '')
response_text = response_text.strip()
# Try to find JSON object boundaries
start_idx = response_text.find('{')
end_idx = response_text.rfind('}')
if start_idx != -1 and end_idx != -1 and end_idx > start_idx:
response_text = response_text[start_idx:end_idx + 1]
# Clean up whitespace and newlines
response_text = response_text.replace('\n', ' ').replace('\r', ' ')
response_text = ' '.join(response_text.split()) # Remove extra whitespace
print(f"Extracted JSON: {response_text}")
# Try to parse JSON with fallback
try:
parsed = json.loads(response_text)
print(f"Successfully parsed JSON: {parsed}")
except json.JSONDecodeError as e:
print(f"JSON decode error in triage: {e}")
# Try to fix common JSON issues
response_text = response_text.replace("'", '"') # Replace single quotes with double quotes
try:
parsed = json.loads(response_text)
print(f"Successfully parsed JSON after fix: {parsed}")
except json.JSONDecodeError as e2:
print(f"Second JSON decode attempt failed: {e2}")
# Try fallback extraction using simple pattern matching
return fallback_triage_agent(alert_text)
# Ensure required fields exist
if 'module' not in parsed:
parsed['module'] = 'Unknown'
if 'entities' not in parsed:
parsed['entities'] = []
if 'alert_type' not in parsed:
parsed['alert_type'] = 'error'
if 'severity' not in parsed:
parsed['severity'] = 'medium'
if 'urgency' not in parsed:
parsed['urgency'] = 'medium'
return parsed
except json.JSONDecodeError as e:
print(f"Triage JSON decode error: {e}")
print(f"Response text: {response_text}")
return {"module": "Unknown", "entities": [], "alert_type": "error", "severity": "medium", "urgency": "medium"}
except Exception as e:
print(f"Error in triage agent: {e}")
return {"module": "Unknown", "entities": [], "alert_type": "error", "severity": "medium", "urgency": "medium"}
def fallback_triage_agent(alert_text):
"""Fallback triage agent using simple pattern matching when LLM fails"""
print("Using fallback triage agent")
# Convert to lowercase for pattern matching
text_lower = alert_text.lower()
# Determine module based on keywords
module = "Unknown"
entities = []
# Container patterns
if any(keyword in text_lower for keyword in ["container", "cmau", "mscu", "cntr_no", "duplicate", "identical containers", "bay", "slots"]):
module = "CNTR"
# Extract container numbers
import re
container_matches = re.findall(r'[CM]MAU\d+|[CM]SCU\d+', alert_text)
entities.extend(container_matches)
# Vessel patterns
elif any(keyword in text_lower for keyword in ["vessel", "mv", "vessel advice", "vessel_err_4", "system vessel name", "baplie", "coarri", "terminal", "load completed"]):
module = "VSL"
# Extract vessel names
import re
vessel_matches = re.findall(r'MV\s+[A-Z\s]+', alert_text)
entities.extend(vessel_matches)
# EDI/API patterns
elif any(keyword in text_lower for keyword in ["edi", "message", "ref-ift", "stuck in error", "acknowledgment", "ack_at is null", "correlation_id", "httpstatus"]):
module = "EDI/API"
# Extract message references
import re
message_matches = re.findall(r'REF-[A-Z]+-\d+', alert_text)
entities.extend(message_matches)
# Infrastructure patterns
elif any(keyword in text_lower for keyword in ["database", "connection", "timeout", "service", "system", "infrastructure"]):
module = "Infra/SRE"
# Extract other entities
import re
error_codes = re.findall(r'[A-Z_]+_ERR_\d+', alert_text)
entities.extend(error_codes)
# Determine severity and urgency based on keywords
severity = "medium"
urgency = "medium"
if any(keyword in text_lower for keyword in ["critical", "urgent", "immediate", "down", "failed", "error"]):
severity = "high"
urgency = "high"
elif any(keyword in text_lower for keyword in ["warning", "issue", "problem"]):
severity = "medium"
urgency = "medium"
elif any(keyword in text_lower for keyword in ["info", "information", "notice"]):
severity = "low"
urgency = "low"
return {
"module": module,
"entities": entities[:5], # Limit to 5 entities
"alert_type": "error" if "error" in text_lower else "warning" if "warning" in text_lower else "info",
"severity": severity,
"urgency": urgency
}
def retrieve_candidate_sops(alert_text, parsed_entities):
"""Retrieve top 3-4 SOPs and top 4-5 case logs from ChromaDB based on module"""
try:
print("Retrieving candidate documents...")
# Get the module from parsed entities
module = parsed_entities.get('module', 'Unknown')
print(f"Searching for module: {module}")
# Map module to collection name
module_mapping = {
'CNTR': 'CNTR',
'VSL': 'VSL',
'Vessel': 'VSL', # Map Vessel to VSL collection
'EDI/API': 'EDI/API',
'Infra/SRE': 'Infra/SRE',
'Container Report': 'Container Report',
'Container Booking': 'Container Booking',
'IMPORT/EXPORT': 'IMPORT/EXPORT'
}
target_module = module_mapping.get(module, 'Unknown')
print(f"Target module: {target_module}")
print(f"Available collections: {list(collections.keys())}")
if target_module not in collections:
print(f"No collection found for module: {target_module}")
return {"sops": [], "case_logs": [], "module": "Unknown"}
collection = collections[target_module]
# Retrieve SOPs (top 3-4)
print("Retrieving SOPs...")
sop_results = collection.query(
query_texts=[alert_text],
n_results=4,
where={"doc_type": "SOP"} if target_module != 'Unknown' else None
)
# Retrieve Case Logs (top 4-5)
print("Retrieving case logs...")
case_log_results = collection.query(
query_texts=[alert_text],
n_results=5,
where={"doc_type": "Case Log"} if target_module != 'Unknown' else None
)
sops = []
if sop_results['documents'] and sop_results['documents'][0]:
for i in range(len(sop_results['documents'][0])):
sops.append({
'id': sop_results['ids'][0][i],
'document': sop_results['documents'][0][i],
'metadata': sop_results['metadatas'][0][i],
'distance': sop_results['distances'][0][i]
})
case_logs = []
if case_log_results['documents'] and case_log_results['documents'][0]:
for i in range(len(case_log_results['documents'][0])):
case_logs.append({
'id': case_log_results['ids'][0][i],
'document': case_log_results['documents'][0][i],
'metadata': case_log_results['metadatas'][0][i],
'distance': case_log_results['distances'][0][i]
})
print(f"Found {len(sops)} SOPs and {len(case_logs)} case logs")
return {
"sops": sops,
"case_logs": case_logs,
"module": target_module
}
except Exception as e:
print(f"Error retrieving documents: {e}")
return {"sops": [], "case_logs": [], "module": "Unknown"}
def analyst_agent(alert_text, candidate_sops, sql_data=None, ai_client=None):
"""Layer 2: Enhanced Analyst Agent - Analyze SOPs, case logs, and SQL data"""
try:
# Use provided AI client or create default one
if ai_client is None:
ai_client = create_ai_client()
sops = candidate_sops.get('sops', [])
case_logs = candidate_sops.get('case_logs', [])
if not sops and not case_logs:
return {
"best_sop_id": "none",
"reasoning": "No candidate documents available for analysis",
"problem_statement": "Unable to analyze the alert due to lack of relevant documentation",
"resolution_summary": "Manual review and escalation required"
}
# Format candidate SOPs for the prompt
sop_candidates_text = ""
for i, sop in enumerate(sops, 1):
sop_candidates_text += f"\n--- SOP {i} (ID: {sop['id']}) ---\n"
sop_candidates_text += f"Title: {sop['metadata'].get('title', 'Unknown')}\n"
sop_candidates_text += f"Module: {sop['metadata'].get('module', 'Unknown')}\n"
sop_candidates_text += f"Content: {sop['document'][:1000]}...\n"
sop_candidates_text += f"Relevance Score: {(1 - sop['distance']):.3f}\n"
# Format case logs for the prompt
case_logs_text = ""
for i, case_log in enumerate(case_logs, 1):
case_logs_text += f"\n--- Case Log {i} (ID: {case_log['id']}) ---\n"
case_logs_text += f"Problem: {case_log['metadata'].get('problem_statement', 'Unknown')}\n"
case_logs_text += f"Solution: {case_log['metadata'].get('solution', 'Unknown')}\n"
case_logs_text += f"Content: {case_log['document'][:1000]}...\n"
case_logs_text += f"Relevance Score: {(1 - case_log['distance']):.3f}\n"
# Prepare SQL data context
sql_context = ""
if sql_data:
sql_context = f"\n\nSQL DATABASE CONTEXT:\n"
if sql_data.get('vessel_data'):
sql_context += f"Vessel Data: {len(sql_data['vessel_data'])} records\n"
if sql_data.get('container_data'):
sql_context += f"Container Data: {len(sql_data['container_data'])} records\n"
if sql_data.get('edi_data'):
sql_context += f"EDI Data: {len(sql_data['edi_data'])} records\n"
if sql_data.get('api_events'):
sql_context += f"API Events: {len(sql_data['api_events'])} records\n"
if sql_data.get('vessel_advice'):
sql_context += f"Vessel Advice: {len(sql_data['vessel_advice'])} records\n"
# Create enhanced prompt
enhanced_prompt = f"""
You are an expert Technical Analyst Agent for PSA support. You have been provided with an alert, candidate SOPs, case logs, and SQL database context.
Your task is to select the single best SOP that matches the alert and provide comprehensive analysis.
ALERT TO ANALYZE:
{alert_text}
CANDIDATE SOPs:
{sop_candidates_text}
CASE LOGS (Historical Similar Issues):
{case_logs_text}
{sql_context}
INSTRUCTIONS:
1. Analyze the alert and identify the core problem
2. Consider both SOPs and case logs to understand the issue
3. Select the single best SOP that directly addresses this problem
4. Provide concise reasoning for your choice (no comparisons with other SOPs)
5. Generate a clear problem statement and actionable resolution steps
6. Consider SQL database context if relevant
IMPORTANT: Return ONLY valid JSON, no markdown, no explanations, no additional text.
{{
"best_sop_id": "sop_X",
"reasoning": "Brief explanation of why this SOP is the best match for the alert",
"problem_statement": "Clear, concise description of the issue",
"resolution_summary": "Step-by-step resolution approach with specific actions to take"
}}
Return ONLY the JSON object above, nothing else.
"""
response_text = ai_client.generate_content(enhanced_prompt)
# Extract JSON from response with better parsing
response_text = response_text.strip()
print(f"Raw Analyst response: {response_text}")
# Remove ALL markdown code blocks (handle multiple formats)
response_text = response_text.replace('```json', '').replace('```', '')
response_text = response_text.strip()
# Try to find JSON object boundaries
start_idx = response_text.find('{')
end_idx = response_text.rfind('}')
if start_idx != -1 and end_idx != -1 and end_idx > start_idx:
response_text = response_text[start_idx:end_idx + 1]
# Clean up whitespace and newlines aggressively
response_text = response_text.replace('\n', ' ').replace('\r', ' ')
response_text = ' '.join(response_text.split()) # Remove extra whitespace
print(f"Extracted Analyst JSON: {response_text}")
# Try to parse JSON with fallback
try:
analysis = json.loads(response_text)
# Convert SOP ID to title for display
if analysis.get('best_sop_id') and analysis['best_sop_id'] != 'none':
sop_title = get_sop_title_by_id(analysis['best_sop_id'], candidate_sops)
analysis['best_sop_name'] = sop_title
# Keep the ID for internal reference but use name for display
analysis['best_sop_id'] = sop_title
return analysis
except json.JSONDecodeError as e:
print(f"JSON decode error in analyst: {e}")
# Try to fix common JSON issues
response_text = response_text.replace("'", '"') # Replace single quotes with double quotes
try:
analysis = json.loads(response_text)
# Convert SOP ID to title for display
if analysis.get('best_sop_id') and analysis['best_sop_id'] != 'none':
sop_title = get_sop_title_by_id(analysis['best_sop_id'], candidate_sops)
analysis['best_sop_name'] = sop_title
# Keep the ID for internal reference but use name for display
analysis['best_sop_id'] = sop_title
return analysis
except json.JSONDecodeError as e2:
print(f"Second JSON decode attempt failed: {e2}")
# Return default values if JSON parsing completely fails
# Use fallback analyst agent
return fallback_analyst_agent(alert_text, candidate_sops)
except json.JSONDecodeError as e:
print(f"JSON decode error: {e}")
print(f"Response text: {response_text}")
return {
"best_sop_id": "error",
"reasoning": f"JSON parsing failed: {str(e)}",
"problem_statement": "Unable to parse AI analysis response",
"resolution_summary": "Manual review and escalation required"
}
except Exception as e:
print(f"Error in analyst agent: {e}")
return {
"best_sop_id": "error",
"reasoning": f"Analysis failed: {str(e)}",
"problem_statement": "Unable to analyze the alert due to processing error",
"resolution_summary": "Manual review and escalation required"
}
def fallback_analyst_agent(alert_text, candidate_sops):
"""Fallback analyst agent when LLM fails"""
print("Using fallback analyst agent")
if not candidate_sops:
return {
"best_sop_id": "none",
"reasoning": "No candidate SOPs available for analysis",
"problem_statement": "Unable to find relevant SOP for this alert",
"resolution_summary": "Manual investigation and escalation required"
}
# Simple keyword matching to select best SOP
alert_lower = alert_text.lower()
best_sop = candidate_sops[0] # Default to first SOP
best_score = 0
for sop in candidate_sops:
score = 0
title = sop['metadata'].get('title', '').lower()
content = sop['document'].lower()
# Score based on keyword matches
keywords = ['error', 'issue', 'problem', 'failed', 'stuck', 'duplicate', 'inconsistent']
for keyword in keywords:
if keyword in alert_lower and keyword in content:
score += 1
# Score based on module match
if 'container' in alert_lower and 'container' in content:
score += 2
elif 'vessel' in alert_lower and 'vessel' in content:
score += 2
elif 'edi' in alert_lower and 'edi' in content:
score += 2
if score > best_score:
best_score = score
best_sop = sop
# Get SOP title for display
sop_title = best_sop['metadata'].get('title', best_sop['id'])
return {
"best_sop_id": sop_title, # Use title instead of ID
"best_sop_name": sop_title,
"reasoning": f"Selected based on keyword matching (score: {best_score})",
"problem_statement": f"Alert requires analysis: {alert_text[:100]}...",
"resolution_summary": f"Follow SOP: {sop_title}"
}
def run_predictive_agent(problem_statement, entities, ai_client=None):
"""Layer 3: Predictive Agent - Predict downstream impacts using historical data"""
global historical_data
try:
print("=" * 50)
print("PREDICTIVE AGENT CALLED!")
print(f"Problem statement: {problem_statement}")
print(f"Entities: {entities}")
print("=" * 50)
# Use provided AI client or create default one
if ai_client is None:
ai_client = create_ai_client()
if historical_data is None or len(historical_data) == 0:
return {
"predictive_insight": "No historical data available for prediction",
"confidence": "low"
}
# Pre-filtering Logic: Find relevant historical cases
print("Filtering historical data for relevant cases...")
filtered_cases = pd.DataFrame()
# Convert entities to lowercase for matching
entities_lower = [str(entity).lower() for entity in entities if entity]
problem_lower = str(problem_statement).lower()
# Filter by entities in Module or Problem Statement columns
for idx, row in historical_data.iterrows():
is_relevant = False
# Check if any entity appears in the row data
row_text = ' '.join([str(val).lower() for val in row.values if pd.notna(val)])
for entity in entities_lower:
if entity in row_text:
is_relevant = True
break
# Also check if problem statement keywords match
problem_keywords = ['error', 'issue', 'failed', 'stuck', 'duplicate', 'timeout', 'connection']
for keyword in problem_keywords:
if keyword in problem_lower and keyword in row_text:
is_relevant = True
break
if is_relevant:
filtered_cases = pd.concat([filtered_cases, row.to_frame().T], ignore_index=True)
print(f"Found {len(filtered_cases)} relevant historical cases")
if len(filtered_cases) == 0:
return {
"predictive_insight": "No similar historical cases found for prediction",
"confidence": "low"
}
# Convert filtered cases to concise text format
historical_summary = ""
for idx, row in filtered_cases.head(10).iterrows(): # Limit to top 10 most relevant
case_text = f"Case {idx + 1}: "
if 'Module' in row and pd.notna(row['Module']):
case_text += f"Module: {row['Module']}, "
if 'Problem Statement' in row and pd.notna(row['Problem Statement']):
case_text += f"Problem: {str(row['Problem Statement'])[:200]}..., "
if 'Solution' in row and pd.notna(row['Solution']):
case_text += f"Solution: {str(row['Solution'])[:200]}..."
historical_summary += case_text + "\n"
# Create the predictive prompt
predictive_prompt = f"""
You are a predictive systems analyst with access to historical incident data.
Given the current problem: {problem_statement}
And this curated list of highly similar past incidents:
{historical_summary}
What was the most common downstream impact or related failure mentioned in these cases?
Your prediction must be a single, concise sentence that describes the most likely downstream impact based on the historical patterns.
IMPORTANT: Return ONLY valid JSON, no markdown, no explanations, no additional text.
{{
"predictive_insight": "Your single sentence prediction here",
"confidence": "high|medium|low"
}}
Return ONLY the JSON object above, nothing else.
"""
print("Calling AI for predictive analysis...")
response_text = ai_client.generate_content(predictive_prompt)
# Extract JSON from response
response_text = response_text.strip()
print(f"Raw Predictive response: {response_text}")
# Remove markdown code blocks
response_text = response_text.replace('```json', '').replace('```', '')
response_text = response_text.strip()
# Find JSON object boundaries
start_idx = response_text.find('{')
end_idx = response_text.rfind('}')
if start_idx != -1 and end_idx != -1 and end_idx > start_idx:
response_text = response_text[start_idx:end_idx + 1]
# Clean up whitespace
response_text = response_text.replace('\n', ' ').replace('\r', ' ')
response_text = ' '.join(response_text.split())
print(f"Extracted Predictive JSON: {response_text}")
# Parse JSON
try:
result = json.loads(response_text)
print(f"Successfully parsed predictive JSON: {result}")
return result
except json.JSONDecodeError as e:
print(f"JSON decode error in predictive agent: {e}")
# Try to fix common JSON issues
response_text = response_text.replace("'", '"')
try:
result = json.loads(response_text)
return result
except json.JSONDecodeError as e2:
print(f"Second JSON decode attempt failed: {e2}")
return {
"predictive_insight": "Unable to generate prediction due to parsing error",
"confidence": "low"
}
except Exception as e:
print(f"Error in predictive agent: {e}")
return {
"predictive_insight": f"Prediction failed: {str(e)}",
"confidence": "low"
}
def get_escalation_contact(module):
"""Get escalation contact information for the specified module"""
if module in contacts_data:
return contacts_data[module]
else:
# Default contact if module not found
return {
"module": "General Support",
"primary_contact": {
"name": "General Support Team",
"email": "support@company.com",
"phone": "+1-555-SUPPORT",
"escalation_level": "L1"
},
"escalation_contact": {
"name": "Support Manager",
"email": "support-manager@company.com",
"phone": "+1-555-SUPPORT-MGR",
"escalation_level": "L2"
}
}
def get_sop_title_by_id(sop_id, candidate_sops):
"""Get SOP title by ID from candidate SOPs"""
try:
if not candidate_sops or not candidate_sops.get('sops'):
return sop_id # Return ID if no candidates available
# Search through candidate SOPs for matching ID
for sop in candidate_sops['sops']:
if sop.get('id') == sop_id:
return sop.get('metadata', {}).get('title', sop_id)
# If not found in candidates, return the ID
return sop_id
except Exception as e:
print(f"Error getting SOP title for {sop_id}: {e}")
return sop_id
def get_escalation_contact(module):
"""Get escalation contact for a module"""
try:
# Load contacts from JSON file
script_dir = os.path.dirname(os.path.abspath(__file__))
contacts_file = os.path.join(script_dir, "contacts.json")
if not os.path.exists(contacts_file):
return {
"primary_contact": {"name": "Support Manager", "email": "support-manager@company.com", "phone": "+1-555-SUPPORT-MGR"},
"escalation_contact": {"name": "Support Manager", "email": "support-manager@company.com", "phone": "+1-555-SUPPORT-MGR"}
}
with open(contacts_file, 'r') as f:
contacts_data = json.load(f)
# Get contact for the module
contact = contacts_data.get(module, contacts_data.get("default", {}))
return {
"primary_contact": contact.get("primary_contact", {"name": "Support Manager", "email": "support-manager@company.com", "phone": "+1-555-SUPPORT-MGR"}),
"escalation_contact": contact.get("escalation_contact", {"name": "Support Manager", "email": "support-manager@company.com", "phone": "+1-555-SUPPORT-MGR"})
}
except Exception as e:
print(f"Error loading contacts: {e}")
return {
"primary_contact": {"name": "Support Manager", "email": "support-manager@company.com", "phone": "+1-555-SUPPORT-MGR"},
"escalation_contact": {"name": "Support Manager", "email": "support-manager@company.com", "phone": "+1-555-SUPPORT-MGR"}
}
def create_escalation_email_content(alert_text, parsed_entities, analysis, contact_info):
"""Create escalation email content"""
email_subject = f"PSA Alert Escalation - {parsed_entities.get('module', 'Unknown')} Module - {parsed_entities.get('severity', 'Unknown').upper()}"
# Clean up the reasoning to remove SOP comparisons
reasoning = analysis.get('reasoning', 'N/A')
if 'SOP' in reasoning and 'best match' in reasoning:
# Extract just the relevant part without comparisons
lines = reasoning.split('\n')
relevant_lines = []
for line in lines:
if 'SOP' in line and ('best match' in line or 'selected' in line):
relevant_lines.append(line.strip())
break
if relevant_lines:
reasoning = relevant_lines[0]
email_body = f"""Dear {contact_info['escalation_contact']['name']},
We are escalating the following PSA alert for your immediate review and action:
ALERT DETAILS:
{alert_text}
PARSED INFORMATION:
• Module: {parsed_entities.get('module', 'Unknown')}
• Alert Type: {parsed_entities.get('alert_type', 'Unknown')}
• Severity: {parsed_entities.get('severity', 'Unknown').upper()}
• Urgency: {parsed_entities.get('urgency', 'Unknown').upper()}
• Key Entities: {', '.join(parsed_entities.get('entities', []))}
TECHNICAL ANALYSIS:
• Problem Statement: {analysis.get('problem_statement', 'N/A')}
• Resolution Summary: {analysis.get('resolution_summary', 'N/A')}
• Recommended SOP: {analysis.get('best_sop_id', 'N/A')}
ESCALATION CONTACTS:
• Primary: {contact_info['primary_contact']['name']} ({contact_info['primary_contact']['email']})
• Escalation: {contact_info['escalation_contact']['name']} ({contact_info['escalation_contact']['email']})
Please review and take appropriate action immediately.
Best regards,
PSA Support Agent
AI-Powered Multi-Agent RAG System
""".strip()
return email_subject, email_body
def send_email(to_email, subject, body):
"""Send email using SMTP"""
try:
sender_email = os.getenv('SENDER_EMAIL')
app_password = os.getenv('EMAIL_APP_PASSWORD')
if not sender_email or not app_password:
raise ValueError("Email credentials not configured in .env file")
# Create message
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = to_email
msg['Subject'] = subject
# Add body to email
msg.attach(MIMEText(body, 'plain'))
# Create SMTP session
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls() # Enable security
server.login(sender_email, app_password)
# Send email
text = msg.as_string()
server.sendmail(sender_email, to_email, text)
server.quit()
return True, "Email sent successfully"
except Exception as e:
return False, f"Failed to send email: {str(e)}"
@app.route('/')
def index():
"""Render the main page"""
return render_template('index.html')
@app.route('/process_alert', methods=['POST'])
def process_alert():
"""Process alert through the multi-agent RAG pipeline"""
try:
print("=== PROCESS ALERT ENDPOINT CALLED ===")
# Get alert text and AI settings from request
data = request.get_json()
print(f"Received data: {data}")
alert_text = data.get('alert_text', '')
ai_settings = data.get('ai_settings') # Optional AI settings from frontend
print(f"Alert text: {alert_text}")
print(f"AI settings: {ai_settings}")
if not alert_text:
print("ERROR: No alert text provided")
return jsonify({"error": "No alert text provided"}), 400
# Create AI client based on settings (or use default)
try:
if ai_settings and ai_settings.get('aiProvider'):
print(f"Creating AI client for {ai_settings.get('aiProvider')} with model {ai_settings.get('aiModel')}...")
# Use environment variables for API keys
ai_client = create_ai_client({
"aiProvider": ai_settings.get('aiProvider'),
"aiModel": ai_settings.get('aiModel'),
"apiKey": None # Will use environment variable
})
else:
print("Using default AI client from environment...")
ai_client = create_ai_client()
except Exception as e:
print(f"ERROR creating AI client: {e}")
return jsonify({"error": f"Failed to initialize AI client: {str(e)}"}), 500
# Step 1: Triage Agent
print("Triage Agent: Parsing alert...")
try:
parsed_entities = triage_agent(alert_text, ai_client)
print(f"Parsed entities: {parsed_entities}")
except Exception as e:
print(f"ERROR in triage_agent: {e}")
parsed_entities = {"module": "Unknown", "entities": [], "alert_type": "error", "severity": "medium", "urgency": "medium", "debug_error": str(e)}
# Step 2: Retrieve candidate SOPs and case logs
print("Retrieving candidate SOPs and case logs...")
candidate_sops = retrieve_candidate_sops(alert_text, parsed_entities)
# Step 3: Extract SQL data
print("Extracting SQL data...")
sql_data = {}
if sql_connector:
try:
sql_data = sql_connector.extract_relevant_data(parsed_entities)
print(f"Extracted SQL data: {len(sql_data)} categories")
except Exception as e:
print(f"Error extracting SQL data: {e}")
sql_data = {}
# Step 4: Enhanced Analyst Agent
print("Enhanced Analyst Agent: Analyzing candidates with SQL data...")
analysis = analyst_agent(alert_text, candidate_sops, sql_data, ai_client)
# Step 5: Predictive Agent
print("Predictive Agent: Analyzing downstream impacts...")
predictive_insight = run_predictive_agent(
analysis.get('problem_statement', ''),
parsed_entities.get('entities', []),
ai_client
)
# Step 6: Get escalation contact
print("Getting escalation contact...")
contact_info = get_escalation_contact(parsed_entities.get('module', 'Unknown'))
# Step 7: Create escalation email content