davidtran999 commited on
Commit
dc32db8
·
verified ·
1 Parent(s): dd22707

Upload backend/chatbot/context_manager.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. backend/chatbot/context_manager.py +174 -0
backend/chatbot/context_manager.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Context manager for conversation sessions and messages.
3
+ """
4
+ from typing import List, Dict, Any, Optional
5
+ from uuid import UUID
6
+ from hue_portal.core.models import ConversationSession, ConversationMessage
7
+
8
+
9
+ class ConversationContext:
10
+ """Manages conversation sessions and context."""
11
+
12
+ @staticmethod
13
+ def get_session(session_id: Optional[str] = None, user_id: Optional[str] = None) -> ConversationSession:
14
+ """
15
+ Get or create a conversation session.
16
+
17
+ Args:
18
+ session_id: Optional session ID (UUID string). If None, creates new session.
19
+ user_id: Optional user ID for tracking.
20
+
21
+ Returns:
22
+ ConversationSession instance.
23
+ """
24
+ if session_id:
25
+ try:
26
+ # Try to get existing session
27
+ session = ConversationSession.objects.get(session_id=session_id)
28
+ # Update updated_at timestamp
29
+ session.save(update_fields=["updated_at"])
30
+ return session
31
+ except ConversationSession.DoesNotExist:
32
+ # Create new session with provided session_id
33
+ return ConversationSession.objects.create(
34
+ session_id=session_id,
35
+ user_id=user_id
36
+ )
37
+ else:
38
+ # Create new session
39
+ return ConversationSession.objects.create(user_id=user_id)
40
+
41
+ @staticmethod
42
+ def add_message(
43
+ session_id: str,
44
+ role: str,
45
+ content: str,
46
+ intent: Optional[str] = None,
47
+ entities: Optional[Dict[str, Any]] = None,
48
+ metadata: Optional[Dict[str, Any]] = None
49
+ ) -> ConversationMessage:
50
+ """
51
+ Add a message to a conversation session.
52
+
53
+ Args:
54
+ session_id: Session ID (UUID string).
55
+ role: Message role ('user' or 'bot').
56
+ content: Message content.
57
+ intent: Detected intent (optional).
58
+ entities: Extracted entities (optional).
59
+ metadata: Additional metadata (optional).
60
+
61
+ Returns:
62
+ ConversationMessage instance.
63
+ """
64
+ session = ConversationContext.get_session(session_id=session_id)
65
+
66
+ return ConversationMessage.objects.create(
67
+ session=session,
68
+ role=role,
69
+ content=content,
70
+ intent=intent or "",
71
+ entities=entities or {},
72
+ metadata=metadata or {}
73
+ )
74
+
75
+ @staticmethod
76
+ def get_recent_messages(session_id: str, limit: int = 10) -> List[ConversationMessage]:
77
+ """
78
+ Get recent messages from a session.
79
+
80
+ Args:
81
+ session_id: Session ID (UUID string).
82
+ limit: Maximum number of messages to return.
83
+
84
+ Returns:
85
+ List of ConversationMessage instances, ordered by timestamp (oldest first).
86
+ """
87
+ try:
88
+ session = ConversationSession.objects.get(session_id=session_id)
89
+ return list(session.messages.all()[:limit])
90
+ except ConversationSession.DoesNotExist:
91
+ return []
92
+
93
+ @staticmethod
94
+ def get_context_summary(session_id: str, max_messages: int = 5) -> Dict[str, Any]:
95
+ """
96
+ Create a summary of conversation context.
97
+
98
+ Args:
99
+ session_id: Session ID (UUID string).
100
+ max_messages: Maximum number of messages to include in summary.
101
+
102
+ Returns:
103
+ Dictionary with context summary including:
104
+ - recent_messages: List of recent messages
105
+ - entities: Aggregated entities from conversation
106
+ - intents: List of intents mentioned
107
+ - message_count: Total number of messages
108
+ """
109
+ messages = ConversationContext.get_recent_messages(session_id, limit=max_messages)
110
+
111
+ # Aggregate entities
112
+ all_entities = {}
113
+ intents = []
114
+
115
+ for msg in messages:
116
+ if msg.entities:
117
+ for key, value in msg.entities.items():
118
+ if key not in all_entities:
119
+ all_entities[key] = []
120
+ if value not in all_entities[key]:
121
+ all_entities[key].append(value)
122
+
123
+ if msg.intent:
124
+ if msg.intent not in intents:
125
+ intents.append(msg.intent)
126
+
127
+ return {
128
+ "recent_messages": [
129
+ {
130
+ "role": msg.role,
131
+ "content": msg.content,
132
+ "intent": msg.intent,
133
+ "timestamp": msg.timestamp.isoformat()
134
+ }
135
+ for msg in messages
136
+ ],
137
+ "entities": all_entities,
138
+ "intents": intents,
139
+ "message_count": len(messages)
140
+ }
141
+
142
+ @staticmethod
143
+ def extract_entities(query: str) -> Dict[str, Any]:
144
+ """
145
+ Extract entities from a query (basic implementation).
146
+ This is a placeholder - will be enhanced by entity_extraction.py
147
+
148
+ Args:
149
+ query: User query string.
150
+
151
+ Returns:
152
+ Dictionary with extracted entities.
153
+ """
154
+ entities = {}
155
+ query_lower = query.lower()
156
+
157
+ # Basic fine code extraction (V001, V002, etc.)
158
+ import re
159
+ fine_codes = re.findall(r'\bV\d{3}\b', query, re.IGNORECASE)
160
+ if fine_codes:
161
+ entities["fine_codes"] = fine_codes
162
+
163
+ # Basic procedure keywords
164
+ procedure_keywords = ["thủ tục", "hồ sơ", "giấy tờ"]
165
+ if any(kw in query_lower for kw in procedure_keywords):
166
+ entities["has_procedure"] = True
167
+
168
+ # Basic fine keywords
169
+ fine_keywords = ["phạt", "mức phạt", "vi phạm"]
170
+ if any(kw in query_lower for kw in fine_keywords):
171
+ entities["has_fine"] = True
172
+
173
+ return entities
174
+