-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1627 lines (1363 loc) · 68.6 KB
/
Copy pathmain.py
File metadata and controls
1627 lines (1363 loc) · 68.6 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
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect, BackgroundTasks
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from typing import Dict, List, Optional, Any, Set
import json
import uuid
import asyncio
import logging
from datetime import datetime, timedelta, timezone
from pathlib import Path
import os
from enum import Enum
from dataclasses import dataclass
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI(title="Citizen Voice AI", description="Government Accountability System with AI Agents")
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# =============================================================================
# ENUMS AND STATUS SYSTEM
# =============================================================================
class ComplaintStatus(str, Enum):
RED = "RED" # Complaint received, under AI processing
ORANGE = "ORANGE" # Routed by AI to department with deadline
BLUE = "BLUE" # Acknowledged by department
GREEN = "GREEN" # In progress, officials working
BLACK = "BLACK" # Resolved and verified
class ComplaintType(str, Enum):
PUBLIC = "PUBLIC" # Visible to community, can be upvoted
PRIVATE = "PRIVATE" # Only citizen and department can see
class UrgencyLevel(str, Enum):
LOW = "LOW"
MEDIUM = "MEDIUM"
HIGH = "HIGH"
CRITICAL = "CRITICAL"
class AgentStatus(str, Enum):
IDLE = "IDLE"
PROCESSING = "PROCESSING"
WAITING = "WAITING"
COMPLETED = "COMPLETED"
ERROR = "ERROR"
# =============================================================================
# PYDANTIC MODELS
# =============================================================================
class ComplaintInput(BaseModel):
citizenName: str = Field(..., min_length=2, max_length=100)
phone: str = Field(..., pattern=r'^\+?[1-9]\d{1,14}$')
location: str = Field(..., min_length=3, max_length=200)
complaintText: str = Field(..., min_length=10, max_length=2000)
complaintType: ComplaintType = ComplaintType.PRIVATE
area: Optional[str] = None
class ChatMessage(BaseModel):
message: str = Field(..., min_length=1, max_length=1000)
user_id: Optional[str] = None
class ComplaintChatMessage(BaseModel):
message: str = Field(..., min_length=1, max_length=500)
user_type: str = Field(..., pattern="^(citizen|government)$")
complaint_id: str
class ComplaintResponse(BaseModel):
complaint_id: str
status: ComplaintStatus
category: str
urgency: UrgencyLevel
department: str
deadlines: Dict[str, str]
is_public: bool = False
upvotes: int = 0
area: Optional[str] = None
processing_steps: List[Dict[str, Any]] = []
class ChatResponse(BaseModel):
message: str
complaint_id: Optional[str] = None
current_status: Optional[ComplaintStatus] = None
processing_steps: List[Dict[str, Any]] = []
class GovernmentResponse(BaseModel):
status: ComplaintStatus
message: str = Field(..., min_length=5, max_length=1000)
estimated_completion: Optional[str] = None
department: str
officer_name: str
class UpvoteRequest(BaseModel):
user_id: str
class PublicComplaint(BaseModel):
complaint_id: str
category: str
location: str
area: str
urgency: UrgencyLevel
status: ComplaintStatus
upvotes: int
created_at: datetime
anonymized_text: str
# =============================================================================
# WATSON INTEGRATION
# =============================================================================
@dataclass
class WatsonConfig:
region_code: str = os.getenv("WATSON_REGION_CODE", "us-south")
jwt_token: str = os.getenv("WATSON_JWT_TOKEN", "")
instance_id: str = os.getenv("WATSON_INSTANCE_ID", "")
base_url: str = "dl.watsonx.ai"
def is_configured(self) -> bool:
return bool(self.jwt_token and self.instance_id and self.region_code)
class WatsonIntegration:
def __init__(self, config: WatsonConfig):
self.config = config
async def analyze_text(self, text: str) -> Dict:
"""Analyze text using Watson (or fallback to local processing)"""
if not self.config.is_configured():
return self._local_text_analysis(text)
# TODO: Implement Watson API calls here
return self._local_text_analysis(text)
def _local_text_analysis(self, text: str) -> Dict:
"""Local text analysis fallback"""
text_lower = text.lower()
# Category detection
categories = {
"electricity": ["electricity", "power", "light", "transformer", "outage", "blackout"],
"water": ["water", "tap", "supply", "pipeline", "pressure", "leak"],
"road": ["road", "pothole", "traffic", "signal", "street", "highway"],
"sanitation": ["garbage", "waste", "clean", "drain", "toilet", "sewage"],
"health": ["health", "hospital", "doctor", "medicine", "ambulance"],
"general": []
}
category = "general"
for cat, keywords in categories.items():
if any(keyword in text_lower for keyword in keywords):
category = cat
break
# Urgency detection
urgent_keywords = ["emergency", "urgent", "critical", "immediate", "dangerous"]
high_keywords = ["days", "week", "problem", "issue", "not working", "broken"]
low_keywords = ["sometime", "when possible", "eventually", "convenience"]
if any(keyword in text_lower for keyword in urgent_keywords):
urgency = "CRITICAL"
elif any(keyword in text_lower for keyword in high_keywords):
urgency = "HIGH"
elif any(keyword in text_lower for keyword in low_keywords):
urgency = "LOW"
else:
urgency = "MEDIUM"
# Language detection
hindi_chars = any('\u0900' <= char <= '\u097F' for char in text)
language = "Hindi" if hindi_chars else "English"
return {
"category": category.title(),
"urgency": urgency,
"language": language,
"confidence": 0.85,
"keywords_found": [kw for cat, keywords in categories.items()
if cat == category for kw in keywords
if kw in text_lower][:5]
}
watson_config = WatsonConfig()
watson = WatsonIntegration(watson_config)
# =============================================================================
# ENHANCED SHARED MEMORY SYSTEM
# =============================================================================
class SharedMemory:
def __init__(self):
self.complaints: Dict[str, Dict] = {}
self.agent_states: Dict[str, Dict] = {}
self.analytics_data: Dict[str, Any] = {}
self.websocket_connections: Dict[str, WebSocket] = {}
self.dashboard_connections: List[WebSocket] = []
self.public_complaints: Dict[str, Dict] = {} # Area-based public complaints
self.upvotes: Dict[str, Set[str]] = {} # complaint_id -> set of user_ids
self.agent_message_queue: List[Dict] = [] # Inter-agent communication
self.processing_history: Dict[str, List[Dict]] = {} # complaint_id -> history
def save_complaint(self, complaint_id: str, complaint_data: Dict):
"""Save complaint and handle public/private logic"""
self.complaints[complaint_id] = complaint_data
# If public, add to area-based feed
if complaint_data.get('complaint_type') == ComplaintType.PUBLIC:
area = complaint_data.get('area', 'Unknown')
if area not in self.public_complaints:
self.public_complaints[area] = {}
self.public_complaints[area][complaint_id] = {
'category': complaint_data.get('category'),
'location': complaint_data.get('location'),
'urgency': complaint_data.get('urgency'),
'status': complaint_data.get('status'),
'upvotes': len(self.upvotes.get(complaint_id, set())),
'created_at': complaint_data.get('timestamp'),
'anonymized_text': self._anonymize_text(complaint_data.get('text', ''))
}
logger.info(f"💾 Saved complaint {complaint_id} - Type: {complaint_data.get('complaint_type', 'PRIVATE')}")
def _anonymize_text(self, text: str) -> str:
"""Remove sensitive info for public viewing"""
import re
text = re.sub(r'\b[A-Z][a-z]+ [A-Z][a-z]+\b', 'RESIDENT', text) # Names
text = re.sub(r'\b\d{10,}\b', 'XXXX-XXXX', text) # Phone numbers
text = re.sub(r'\b\d{1,4}[,.]?\s*[A-Za-z]+\s+[A-Za-z]+\b', 'ADDRESS', text) # Addresses
return text[:150] + "..." if len(text) > 150 else text
def get_complaint(self, complaint_id: str) -> Dict:
return self.complaints.get(complaint_id, {})
def update_complaint_status(self, complaint_id: str, status: ComplaintStatus,
agent_name: str = "", message: str = ""):
"""Update complaint status and broadcast changes"""
if complaint_id in self.complaints:
self.complaints[complaint_id]['status'] = status.value
self.complaints[complaint_id]['last_updated'] = datetime.now(timezone.utc).isoformat()
# Add to processing history
if complaint_id not in self.processing_history:
self.processing_history[complaint_id] = []
self.processing_history[complaint_id].append({
'status': status.value,
'agent': agent_name,
'message': message,
'timestamp': datetime.now(timezone.utc).isoformat()
})
logger.info(f"📊 Status Update: {complaint_id} → {status.value} by {agent_name}")
def upvote_complaint(self, complaint_id: str, user_id: str) -> bool:
"""Add upvote to a public complaint"""
if complaint_id not in self.complaints:
return False
complaint = self.complaints[complaint_id]
if complaint.get('complaint_type') != ComplaintType.PUBLIC:
return False
if complaint_id not in self.upvotes:
self.upvotes[complaint_id] = set()
if user_id in self.upvotes[complaint_id]:
return False # Already upvoted
self.upvotes[complaint_id].add(user_id)
# Update public complaints data
area = complaint.get('area', 'Unknown')
if area in self.public_complaints and complaint_id in self.public_complaints[area]:
self.public_complaints[area][complaint_id]['upvotes'] = len(self.upvotes[complaint_id])
return True
def get_public_complaints_by_area(self, area: str) -> List[Dict]:
"""Get public complaints for a specific area, sorted by upvotes"""
area_complaints = self.public_complaints.get(area, {})
complaints = []
for complaint_id, data in area_complaints.items():
complaints.append({
'complaint_id': complaint_id,
**data
})
return sorted(complaints, key=lambda x: x.get('upvotes', 0), reverse=True)
def send_agent_message(self, sender: str, receiver: str, message_type: str,
content: Dict, priority: str = "normal"):
"""Send message between agents"""
message = {
"id": str(uuid.uuid4()),
"sender": sender,
"receiver": receiver,
"type": message_type,
"content": content,
"priority": priority,
"timestamp": datetime.now(timezone.utc).isoformat(),
"processed": False
}
self.agent_message_queue.append(message)
logger.info(f"📨 Agent Message: {sender} → {receiver} [{message_type}]")
def get_agent_messages(self, agent_name: str) -> List[Dict]:
"""Get unprocessed messages for an agent"""
return [msg for msg in self.agent_message_queue
if msg['receiver'] == agent_name and not msg['processed']]
def mark_message_processed(self, message_id: str):
"""Mark message as processed"""
for msg in self.agent_message_queue:
if msg['id'] == message_id:
msg['processed'] = True
break
async def broadcast_to_users(self, message: Dict, user_id: Optional[str] = None):
"""Broadcast message to user WebSocket connections"""
if user_id and user_id in self.websocket_connections:
try:
await self.websocket_connections[user_id].send_text(json.dumps(message))
except Exception as e:
logger.error(f"Error sending to user {user_id}: {e}")
self.websocket_connections.pop(user_id, None)
elif not user_id:
# Broadcast to all users
for uid, connection in list(self.websocket_connections.items()):
try:
await connection.send_text(json.dumps(message))
except Exception:
self.websocket_connections.pop(uid, None)
async def broadcast_to_dashboards(self, message: Dict):
"""Broadcast message to government dashboard connections"""
for connection in self.dashboard_connections[:]:
try:
await connection.send_text(json.dumps(message))
except Exception as e:
logger.error(f"Error sending to dashboard: {e}")
self.dashboard_connections.remove(connection)
async def broadcast_status_update(self, complaint_id: str, status: ComplaintStatus,
agent_name: str = "", message: str = ""):
"""Broadcast status update with color coding to all clients"""
update = {
"type": "status_update",
"complaint_id": complaint_id,
"status": status.value,
"status_color": self._get_status_color(status),
"status_message": self._get_status_message(status),
"agent": agent_name,
"message": message,
"timestamp": datetime.now(timezone.utc).isoformat()
}
await self.broadcast_to_users(update)
await self.broadcast_to_dashboards(update)
logger.info(f"📡 Status Broadcast: {complaint_id} → {status.value}")
def _get_status_color(self, status: ComplaintStatus) -> str:
color_map = {
ComplaintStatus.RED: "#dc2626",
ComplaintStatus.ORANGE: "#ea580c",
ComplaintStatus.BLUE: "#2563eb",
ComplaintStatus.GREEN: "#16a34a",
ComplaintStatus.BLACK: "#1f2937"
}
return color_map.get(status, "#6b7280")
def _get_status_message(self, status: ComplaintStatus) -> str:
messages = {
ComplaintStatus.RED: "Complaint received, under AI processing",
ComplaintStatus.ORANGE: "Routed to department with deadline",
ComplaintStatus.BLUE: "Acknowledged by department",
ComplaintStatus.GREEN: "In progress, officials are working",
ComplaintStatus.BLACK: "Resolved and verified"
}
return messages.get(status, "Status unknown")
def add_chat_message(self, complaint_id: str, message: str, user_type: str, timestamp: str) -> bool:
"""Add a chat message to a complaint"""
if complaint_id in self.complaints:
complaint = self.complaints[complaint_id]
if "chat_messages" not in complaint:
complaint["chat_messages"] = []
chat_message = {
"message": message,
"user_type": user_type,
"timestamp": timestamp
}
complaint["chat_messages"].append(chat_message)
return True
return False
# Initialize shared memory
shared_memory = SharedMemory()
# =============================================================================
# AI AGENT SYSTEM WITH REAL COLLABORATION
# =============================================================================
class BaseAgent:
def __init__(self, name: str, description: str, icon: str = "🤖"):
self.name = name
self.description = description
self.icon = icon
self.status = AgentStatus.IDLE
self.last_activity = datetime.now(timezone.utc)
async def update_status(self, status: AgentStatus, message: str = "", complaint_id: str = ""):
"""Update agent status and broadcast to clients"""
self.status = status
self.last_activity = datetime.now(timezone.utc)
shared_memory.agent_states[self.name] = {
"status": status.value,
"message": message,
"timestamp": self.last_activity.isoformat(),
"complaint_id": complaint_id
}
# Broadcast agent update
update = {
"type": "agent_update",
"agent": self.name,
"status": status.value,
"message": message,
"complaint_id": complaint_id,
"timestamp": self.last_activity.isoformat()
}
await shared_memory.broadcast_to_users(update)
logger.info(f"🤖 {self.name}: {status.value} - {message}")
async def process_messages(self):
"""Process incoming messages from other agents"""
messages = shared_memory.get_agent_messages(self.name)
for message in messages:
await self.handle_message(message)
shared_memory.mark_message_processed(message['id'])
async def handle_message(self, message: Dict):
"""Override in subclasses to handle specific message types"""
pass
class ChatAgent(BaseAgent):
def __init__(self):
super().__init__("Chat_Agent", "Processes citizen complaints and initiates workflow", "💬")
async def process_complaint(self, complaint_data: Dict, complaint_id: str) -> Dict:
"""Process initial complaint - RED status"""
await self.update_status(AgentStatus.PROCESSING, "Analyzing citizen complaint...", complaint_id)
# Update complaint status to RED
shared_memory.update_complaint_status(complaint_id, ComplaintStatus.RED, self.name,
"Starting AI analysis of complaint")
await shared_memory.broadcast_status_update(complaint_id, ComplaintStatus.RED, self.name,
"AI is analyzing your complaint...")
# Simulate processing steps
await asyncio.sleep(1)
await self.update_status(AgentStatus.PROCESSING, "Extracting keywords and entities...", complaint_id)
await asyncio.sleep(1)
await self.update_status(AgentStatus.PROCESSING, "Determining category and urgency...", complaint_id)
# Analyze with Watson
analysis = await watson.analyze_text(complaint_data["complaintText"])
# Create processed complaint
processed_complaint = {
"id": complaint_id,
"user_id": complaint_data.get("user_id"),
"text": complaint_data["complaintText"],
"citizen_name": complaint_data["citizenName"],
"phone": complaint_data["phone"],
"location": complaint_data["location"],
"area": complaint_data.get("area", "Unknown"),
"complaint_type": complaint_data.get("complaintType", ComplaintType.PRIVATE),
"language": analysis.get("language", "English"),
"category": analysis.get("category", "General"),
"urgency": analysis.get("urgency", "MEDIUM"),
"confidence": analysis.get("confidence", 0.0),
"keywords": analysis.get("keywords_found", []),
"status": ComplaintStatus.RED.value,
"timestamp": datetime.now(timezone.utc).isoformat(),
"watson_analysis": analysis
}
shared_memory.save_complaint(complaint_id, processed_complaint)
# Send message to Router Agent
shared_memory.send_agent_message(
self.name, "Router_Agent", "new_complaint",
{"complaint_id": complaint_id}, priority="high"
)
await self.update_status(AgentStatus.COMPLETED,
f"Complaint classified as {analysis.get('category')} - {analysis.get('urgency')} urgency",
complaint_id)
return {
"complaint_id": complaint_id,
"category": analysis.get("category", "General"),
"urgency": analysis.get("urgency", "MEDIUM"),
"language": analysis.get("language", "English"),
"confidence": analysis.get("confidence", 0.0)
}
class RouterAgent(BaseAgent):
def __init__(self):
super().__init__("Router_Agent", "Routes complaints to correct departments", "🎯")
self.department_mapping = {
"Electricity": "Delhi Electricity Regulatory Commission (DERC)",
"Water": "Delhi Jal Board (DJB)",
"Road": "Public Works Department (PWD)",
"Sanitation": "Municipal Corporation of Delhi (MCD)",
"Health": "Department of Health & Family Welfare",
"General": "District Collector Office"
}
async def handle_message(self, message: Dict):
if message['type'] == 'new_complaint':
await self.route_complaint(message['content']['complaint_id'])
async def route_complaint(self, complaint_id: str) -> Dict:
"""Route complaint to department - ORANGE status"""
complaint = shared_memory.get_complaint(complaint_id)
if not complaint:
return {"error": "Complaint not found"}
await self.update_status(AgentStatus.PROCESSING, "Finding correct department...", complaint_id)
# Update to ORANGE status
shared_memory.update_complaint_status(complaint_id, ComplaintStatus.ORANGE, self.name,
"Routing to appropriate department")
await shared_memory.broadcast_status_update(complaint_id, ComplaintStatus.ORANGE, self.name,
"Finding the right department for your complaint...")
await asyncio.sleep(1)
category = complaint.get('category', 'General')
department = self.department_mapping.get(category, self.department_mapping['General'])
urgency = complaint.get('urgency', 'MEDIUM')
# Calculate deadlines based on urgency
deadlines = self.calculate_deadlines(urgency)
# Update complaint with routing info
complaint['department'] = department
complaint['deadlines'] = deadlines
complaint['routed_at'] = datetime.now(timezone.utc).isoformat()
shared_memory.save_complaint(complaint_id, complaint)
# Send to Tracker Agent
shared_memory.send_agent_message(
self.name, "Tracker_Agent", "setup_tracking",
{"complaint_id": complaint_id, "department": department, "deadlines": deadlines}
)
await self.update_status(AgentStatus.COMPLETED,
f"Routed to {department} with {deadlines['acknowledgment']} deadline",
complaint_id)
return {
"department": department,
"deadlines": deadlines,
"urgency": urgency
}
def calculate_deadlines(self, urgency: str) -> Dict[str, str]:
"""Calculate response and resolution deadlines"""
now = datetime.now(timezone.utc)
if urgency == "CRITICAL":
ack_hours = 2
resolution_days = 1
elif urgency == "HIGH":
ack_hours = 6
resolution_days = 3
elif urgency == "MEDIUM":
ack_hours = 24
resolution_days = 7
else: # LOW
ack_hours = 48
resolution_days = 15
acknowledgment = (now + timedelta(hours=ack_hours)).isoformat()
resolution = (now + timedelta(days=resolution_days)).isoformat()
return {
"acknowledgment": acknowledgment,
"resolution": resolution
}
class TrackerAgent(BaseAgent):
def __init__(self):
super().__init__("Tracker_Agent", "Monitors government responses and deadlines", "⏰")
async def handle_message(self, message: Dict):
if message['type'] == 'setup_tracking':
await self.setup_tracking(message['content']['complaint_id'])
elif message['type'] == 'government_response':
await self.process_government_response(message['content']['complaint_id'],
message['content']['response_data'])
async def setup_tracking(self, complaint_id: str) -> Dict:
"""Setup tracking for complaint deadlines"""
complaint = shared_memory.get_complaint(complaint_id)
if not complaint:
return {"error": "Complaint not found"}
await self.update_status(AgentStatus.PROCESSING, "Setting up deadline tracking...", complaint_id)
# Add tracking data
complaint['tracking'] = {
'setup_at': datetime.now(timezone.utc).isoformat(),
'acknowledgment_deadline': complaint.get('deadlines', {}).get('acknowledgment'),
'resolution_deadline': complaint.get('deadlines', {}).get('resolution'),
'status_checks': []
}
shared_memory.save_complaint(complaint_id, complaint)
# Send to Follow Agent to schedule reminders
shared_memory.send_agent_message(
self.name, "Follow_Agent", "schedule_reminders",
{"complaint_id": complaint_id, "deadlines": complaint.get('deadlines', {})}
)
await self.update_status(AgentStatus.COMPLETED, "Tracking setup complete", complaint_id)
return {"tracking_setup": True}
async def process_government_response(self, complaint_id: str, response_data: Dict):
"""Process government response - move to BLUE/GREEN/BLACK"""
complaint = shared_memory.get_complaint(complaint_id)
if not complaint:
return
await self.update_status(AgentStatus.PROCESSING, f"Processing government response for {complaint_id}", complaint_id)
new_status = ComplaintStatus(response_data.get('status', ComplaintStatus.BLUE))
government_message = response_data.get('message', 'Government has responded to your complaint')
department = response_data.get('department', complaint.get('department', 'Department'))
officer_name = response_data.get('officer_name', 'Government Official')
# Update complaint with government response
complaint['government_response'] = {
'message': government_message,
'status': new_status.value,
'department': department,
'officer_name': officer_name,
'timestamp': datetime.now(timezone.utc).isoformat(),
'estimated_completion': response_data.get('estimated_completion')
}
shared_memory.save_complaint(complaint_id, complaint)
# Update complaint status
shared_memory.update_complaint_status(complaint_id, new_status, self.name,
f"Government response: {government_message}")
# Broadcast status update to all clients
await shared_memory.broadcast_status_update(complaint_id, new_status, self.name,
f"{department} says: {government_message}")
# Send direct message to the citizen who filed the complaint
citizen_message = {
"type": "government_response",
"complaint_id": complaint_id,
"status": new_status.value,
"status_color": shared_memory._get_status_color(new_status),
"message": government_message,
"department": department,
"officer_name": officer_name,
"estimated_completion": response_data.get('estimated_completion'),
"timestamp": datetime.now(timezone.utc).isoformat()
}
# Try to send to specific user if available
user_id = complaint.get('user_id')
if user_id:
await shared_memory.broadcast_to_users(citizen_message, user_id)
else:
# Broadcast to all users if user_id not available
await shared_memory.broadcast_to_users(citizen_message)
# Update tracking
if 'tracking' in complaint:
complaint['tracking']['status_checks'].append({
'timestamp': datetime.now(timezone.utc).isoformat(),
'status': new_status.value,
'response': response_data
})
shared_memory.save_complaint(complaint_id, complaint)
await self.update_status(AgentStatus.COMPLETED,
f"Government response processed: {new_status.value}", complaint_id)
logger.info(f"🏛️ Government Response Processed: {complaint_id} → {new_status.value}")
# If resolved, send to Analytics for completion analysis
if new_status == ComplaintStatus.BLACK:
shared_memory.send_agent_message(
self.name, "Analytics_Agent", "complaint_resolved",
{"complaint_id": complaint_id, "resolution_data": response_data}
)
class FollowAgent(BaseAgent):
def __init__(self):
super().__init__("Follow_Agent", "Sends reminders and ensures accountability", "🔔")
async def handle_message(self, message: Dict):
if message['type'] == 'schedule_reminders':
await self.schedule_reminders(message['content']['complaint_id'])
async def schedule_reminders(self, complaint_id: str) -> Dict:
"""Schedule automatic reminders to government departments"""
complaint = shared_memory.get_complaint(complaint_id)
if not complaint:
return {"error": "Complaint not found"}
await self.update_status(AgentStatus.PROCESSING, "Scheduling reminders...", complaint_id)
# Add reminder schedule
reminder_schedule = {
'created_at': datetime.now(timezone.utc).isoformat(),
'reminders': []
}
deadlines = complaint.get('deadlines', {})
if 'acknowledgment' in deadlines:
reminder_time = datetime.fromisoformat(deadlines['acknowledgment']) - timedelta(hours=2)
reminder_schedule['reminders'].append({
'type': 'acknowledgment_reminder',
'scheduled_for': reminder_time.isoformat(),
'sent': False
})
if 'resolution' in deadlines:
reminder_time = datetime.fromisoformat(deadlines['resolution']) - timedelta(days=1)
reminder_schedule['reminders'].append({
'type': 'resolution_reminder',
'scheduled_for': reminder_time.isoformat(),
'sent': False
})
complaint['reminders'] = reminder_schedule
shared_memory.save_complaint(complaint_id, complaint)
# Send to Analytics Agent
shared_memory.send_agent_message(
self.name, "Analytics_Agent", "analyze_complaint",
{"complaint_id": complaint_id}
)
await self.update_status(AgentStatus.COMPLETED, "Reminders scheduled", complaint_id)
return {"reminders_scheduled": len(reminder_schedule['reminders'])}
class AnalyticsAgent(BaseAgent):
def __init__(self):
super().__init__("Analytics_Agent", "Analyzes patterns and generates insights", "📊")
async def handle_message(self, message: Dict):
if message['type'] == 'analyze_complaint':
await self.analyze_complaint(message['content']['complaint_id'])
async def analyze_complaint(self, complaint_id: str) -> Dict:
"""Analyze complaint patterns and generate insights"""
complaint = shared_memory.get_complaint(complaint_id)
if not complaint:
return {"error": "Complaint not found"}
await self.update_status(AgentStatus.PROCESSING, "Analyzing complaint patterns...", complaint_id)
# Generate analytics
analytics = {
'analyzed_at': datetime.now(timezone.utc).isoformat(),
'category_frequency': self._get_category_stats(complaint.get('category', 'General')),
'area_analysis': self._get_area_stats(complaint.get('area', 'Unknown')),
'urgency_distribution': self._get_urgency_stats(),
'resolution_predictions': self._predict_resolution_time(complaint)
}
# Update complaint with analytics
complaint['analytics'] = analytics
shared_memory.save_complaint(complaint_id, complaint)
# Update global analytics
shared_memory.analytics_data[complaint_id] = analytics
# Send to Escalate Agent for escalation check
shared_memory.send_agent_message(
self.name, "Escalate_Agent", "check_escalation",
{"complaint_id": complaint_id}
)
await self.update_status(AgentStatus.COMPLETED, "Analysis complete", complaint_id)
return analytics
def _get_category_stats(self, category: str) -> Dict:
"""Get statistics for this complaint category"""
category_complaints = [c for c in shared_memory.complaints.values()
if c.get('category') == category]
return {
'total_complaints': len(category_complaints),
'avg_resolution_time': 5.2, # Mock data
'success_rate': 0.85
}
def _get_area_stats(self, area: str) -> Dict:
"""Get statistics for this area"""
area_complaints = [c for c in shared_memory.complaints.values()
if c.get('area') == area]
return {
'total_complaints': len(area_complaints),
'most_common_category': 'Electricity', # Mock data
'response_time': 'Average'
}
def _get_urgency_stats(self) -> Dict:
"""Get overall urgency distribution"""
return {
'CRITICAL': 5,
'HIGH': 15,
'MEDIUM': 60,
'LOW': 20
}
def _predict_resolution_time(self, complaint: Dict) -> Dict:
"""Predict resolution time based on patterns"""
urgency = complaint.get('urgency', 'MEDIUM')
category = complaint.get('category', 'General')
base_days = {'CRITICAL': 1, 'HIGH': 3, 'MEDIUM': 7, 'LOW': 15}
predicted_days = base_days.get(urgency, 7)
return {
'estimated_days': predicted_days,
'confidence': 0.78,
'factors': ['urgency', 'category', 'historical_data']
}
class AutoGovernmentAgent(BaseAgent):
"""Simulates automatic government responses for demo purposes"""
def __init__(self):
super().__init__("Auto_Government", "Simulates government department responses", "🏛️")
self.response_templates = {
"Water": {
"acknowledgment": "Water complaint received. Technical team will inspect the area within 24 hours.",
"progress": "Our maintenance crew is working on the water supply issue. Expected resolution in 2-3 days.",
"resolution": "Water supply issue has been resolved. New pipeline installed and tested."
},
"Electricity": {
"acknowledgment": "Power outage complaint noted. Dispatch team sent to check transformers.",
"progress": "Electrical fault identified. Repair work in progress. Power should be restored soon.",
"resolution": "Electrical repairs completed. Power supply fully restored and stabilized."
},
"Road": {
"acknowledgment": "Road maintenance request received. Survey team will assess the damage.",
"progress": "Pothole repair work started. Road closure may be needed for safety during repairs.",
"resolution": "Road repairs completed. Surface leveled and traffic flow normalized."
},
"Sanitation": {
"acknowledgment": "Sanitation complaint registered. Cleaning team will be dispatched immediately.",
"progress": "Garbage collection in progress. Additional cleaning staff deployed to the area.",
"resolution": "Area cleaned thoroughly. Regular cleaning schedule updated for this location."
},
"General": {
"acknowledgment": "Your complaint has been forwarded to the appropriate department for action.",
"progress": "Department is reviewing your complaint and working on a resolution.",
"resolution": "Your complaint has been resolved. Thank you for bringing this to our attention."
}
}
async def handle_message(self, message: Dict):
if message['type'] == 'simulate_response':
content = message['content']
complaint_id = content['complaint_id']
department_category = content['department_category']
# Start simulation in background
asyncio.create_task(self.simulate_government_workflow(complaint_id, department_category))
async def simulate_government_workflow(self, complaint_id: str, department_category: str):
"""Simulate realistic government response workflow"""
try:
complaint = shared_memory.get_complaint(complaint_id)
if not complaint:
return
templates = self.response_templates.get(department_category, self.response_templates["General"])
urgency = complaint.get('urgency', 'MEDIUM')
# Calculate delays based on urgency
if urgency == 'CRITICAL':
ack_delay = 2 * 60 # 2 minutes for demo
progress_delay = 5 * 60 # 5 minutes
resolution_delay = 10 * 60 # 10 minutes
elif urgency == 'HIGH':
ack_delay = 3 * 60 # 3 minutes
progress_delay = 8 * 60 # 8 minutes
resolution_delay = 15 * 60 # 15 minutes
elif urgency == 'MEDIUM':
ack_delay = 5 * 60 # 5 minutes
progress_delay = 10 * 60 # 10 minutes
resolution_delay = 20 * 60 # 20 minutes
else: # LOW
ack_delay = 8 * 60 # 8 minutes
progress_delay = 15 * 60 # 15 minutes
resolution_delay = 30 * 60 # 30 minutes
await self.update_status(AgentStatus.PROCESSING, f"Simulating {department_category} department responses", complaint_id)
# Step 1: Acknowledgment (ORANGE → BLUE)
await asyncio.sleep(ack_delay)
await self._send_government_response(complaint_id, {
"status": "BLUE",
"message": templates["acknowledgment"],
"department": complaint.get('department', 'Government Department'),
"officer_name": f"{department_category} Officer"
})
# Step 2: Progress Update (BLUE → GREEN)
await asyncio.sleep(progress_delay - ack_delay)
await self._send_government_response(complaint_id, {
"status": "GREEN",
"message": templates["progress"],
"department": complaint.get('department', 'Government Department'),
"officer_name": f"{department_category} Officer",
"estimated_completion": (datetime.now(timezone.utc) + timedelta(minutes=resolution_delay//60)).isoformat()
})
# Step 3: Resolution (GREEN → BLACK)
await asyncio.sleep(resolution_delay - progress_delay)
await self._send_government_response(complaint_id, {
"status": "BLACK",
"message": templates["resolution"],
"department": complaint.get('department', 'Government Department'),
"officer_name": f"{department_category} Department Head"
})
await self.update_status(AgentStatus.COMPLETED, f"Government simulation completed for {complaint_id}", complaint_id)
except Exception as e:
logger.error(f"Error in government simulation: {e}")
await self.update_status(AgentStatus.ERROR, f"Simulation error: {str(e)}", complaint_id)
async def _send_government_response(self, complaint_id: str, response_data: Dict):
"""Send government response through Tracker Agent"""
shared_memory.send_agent_message(
self.name, "Tracker_Agent", "government_response",
{"complaint_id": complaint_id, "response_data": response_data},
priority="high"
)
logger.info(f"🏛️ Auto-Government Response: {complaint_id} → {response_data['status']}")
class EscalateAgent(BaseAgent):
def __init__(self):
super().__init__("Escalate_Agent", "Escalates complaints when departments don't respond", "⚠️")
async def handle_message(self, message: Dict):
if message['type'] == 'check_escalation':
await self.check_escalation(message['content']['complaint_id'])
async def check_escalation(self, complaint_id: str) -> Dict:
"""Check if complaint needs escalation"""
complaint = shared_memory.get_complaint(complaint_id)
if not complaint:
return {"error": "Complaint not found"}
await self.update_status(AgentStatus.PROCESSING, "Checking escalation criteria...", complaint_id)
# Check if escalation is needed
needs_escalation = self._should_escalate(complaint)
escalation_data = {