AumCoreAI commited on
Commit
ba4f273
·
verified ·
1 Parent(s): f49923c

Update modules/prompt_manager.py

Browse files
Files changed (1) hide show
  1. modules/prompt_manager.py +396 -0
modules/prompt_manager.py CHANGED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Prompt Management System for AumCore AI
3
+ Version: 4.0.0
4
+ Author: AumCore AI
5
+ Location: /app/modules/prompt_manager.py
6
+ """
7
+
8
+ import json
9
+ import os
10
+ from typing import Dict, List, Optional, Any
11
+ from datetime import datetime
12
+ from enum import Enum
13
+ from dataclasses import dataclass, field
14
+ import hashlib
15
+
16
+ class ConversationStyle(Enum):
17
+ """Different conversation styles"""
18
+ CONCISE = "concise" # Short, direct answers
19
+ DETAILED = "detailed" # Thorough explanations
20
+ TECHNICAL = "technical" # Code-focused, precise
21
+ FRIENDLY = "friendly" # Casual, conversational
22
+ PROFESSIONAL = "professional" # Formal, business-like
23
+
24
+ class LanguageCode(Enum):
25
+ """Supported language codes"""
26
+ ENGLISH = "en"
27
+ HINDI = "hi"
28
+ SPANISH = "es"
29
+ FRENCH = "fr"
30
+ GERMAN = "de"
31
+ JAPANESE = "ja"
32
+
33
+ @dataclass
34
+ class PromptConfig:
35
+ """Configuration for generating prompts"""
36
+ language: LanguageCode = LanguageCode.ENGLISH
37
+ style: ConversationStyle = ConversationStyle.CONCISE
38
+ username: Optional[str] = None
39
+ context_length: int = 5 # Number of previous messages to include
40
+ include_code_examples: bool = False
41
+ temperature: float = 0.7
42
+ max_response_length: int = 1000
43
+
44
+ class AumCorePromptManager:
45
+ """
46
+ Advanced Prompt Management System
47
+ Handles multi-language prompts, conversation context, and response optimization
48
+ """
49
+
50
+ def __init__(self, prompts_dir: str = "data/prompts"):
51
+ self.prompts_dir = prompts_dir
52
+ self._prompt_cache: Dict[str, str] = {}
53
+ self._conversation_history: List[Dict] = []
54
+ self._load_base_prompts()
55
+
56
+ # Create prompts directory if it doesn't exist
57
+ os.makedirs(self.prompts_dir, exist_ok=True)
58
+
59
+ def _load_base_prompts(self):
60
+ """Load base system prompts for all languages and styles"""
61
+ self._base_prompts = {
62
+ "system": {
63
+ "en": {
64
+ "concise": """You are {name}, an AI assistant. Answer directly and clearly.""",
65
+ "detailed": """You are {name}, an advanced AI assistant. Provide comprehensive, well-explained responses with examples when helpful.""",
66
+ "technical": """You are {name}, an AI specializing in programming and technology. Provide precise, code-focused answers with best practices.""",
67
+ "friendly": """You are {name}, a friendly AI assistant. Be conversational, helpful, and approachable in your responses.""",
68
+ "professional": """You are {name}, a professional AI assistant. Maintain formal tone, accuracy, and clarity in all responses."""
69
+ },
70
+ "hi": {
71
+ "concise": """आप {name} हैं, एक AI सहायक। सीधे और स्पष्ट उत्तर दें।""",
72
+ "detailed": """आप {name} हैं, एक उन्नत AI सहायक। विस्तृत, समझदार उत्तर दें और आवश्यक होने पर उदाहरण दें।""",
73
+ "technical": """आप {name} हैं, प्रोग्रामिंग और तकनीक में विशेषज्ञ AI। सटीक, कोड-केंद्रित उत्तर दें और बेस्ट प्रैक्टिस बताएं।""",
74
+ "friendly": """आप {name} हैं, एक मित्रवत AI सहायक। बातचीत के अंदाज में, सहायक और आसानी से संपर्क करने योग्य रहें।""",
75
+ "professional": """आप {name} हैं, एक पेशेवर AI सहायक। औपचारिक शैली, सटीकता और स्पष्टता बनाए रखें।"""
76
+ }
77
+ },
78
+ "greeting": {
79
+ "en": {
80
+ "morning": "Good morning! I'm {name}. How can I assist you today?",
81
+ "afternoon": "Good afternoon! I'm {name}. What can I help you with?",
82
+ "evening": "Good evening! I'm {name}. How may I be of service?",
83
+ "general": "Hello! I'm {name}. How can I help you?"
84
+ },
85
+ "hi": {
86
+ "morning": "सुप्रभात! मैं {name} हूँ। आज आपकी कैसे सहायता कर सकता हूँ?",
87
+ "afternoon": "नमस्ते! मैं {name} हूँ। आपकी क्या सहायता कर सकता हूँ?",
88
+ "evening": "शुभ संध्या! मैं {name} हूँ। मैं आपकी कैसे सेवा कर सकता हूँ?",
89
+ "general": "नमस्ते! मैं {name} हूँ। मैं आपकी कैसे सहाय���ा कर सकता हूँ?"
90
+ }
91
+ },
92
+ "error_responses": {
93
+ "en": {
94
+ "no_code_request": "I don't see a specific code request. Could you clarify what you need?",
95
+ "confused_context": "I want to make sure I understand correctly. Could you rephrase your question?",
96
+ "technical_help": "I'd be happy to help with technical questions. What specifically do you need?"
97
+ },
98
+ "hi": {
99
+ "no_code_request": "मुझे कोई विशिष्ट कोड अनुरोध नहीं दिख रहा। क्या आप स्पष्ट कर सकते हैं कि आपको क्या चाहिए?",
100
+ "confused_context": "मैं सुनिश्चित करना चाहता हूँ कि मैं सही समझ रहा हूँ। क्या आप अपना प्रश्न दोबारा कह सकते हैं?",
101
+ "technical_help": "मैं तकनीकी प्रश्नों में मदद करने में खुशी होगी। आपको विशेष रूप से क्या चाहिए?"
102
+ }
103
+ }
104
+ }
105
+
106
+ def _get_cache_key(self, config: PromptConfig, category: str) -> str:
107
+ """Generate cache key for prompt"""
108
+ key_data = f"{category}:{config.language.value}:{config.style.value}:{config.username}"
109
+ return hashlib.md5(key_data.encode()).hexdigest()
110
+
111
+ def get_system_prompt(self,
112
+ language: str = "en",
113
+ username: str = None,
114
+ style: str = "concise") -> str:
115
+ """
116
+ Get system prompt for AI interaction
117
+
118
+ Args:
119
+ language: Language code (en, hi, etc.)
120
+ username: Optional username for personalization
121
+ style: Conversation style (concise, detailed, technical, friendly, professional)
122
+
123
+ Returns:
124
+ System prompt string
125
+ """
126
+ # Normalize inputs
127
+ lang = language.lower() if language else "en"
128
+ style_key = style.lower() if style else "concise"
129
+
130
+ # Get name part
131
+ name_part = f"{username}'s AI" if username else "AumCore AI"
132
+
133
+ # Get base prompt
134
+ try:
135
+ base_prompt = self._base_prompts["system"][lang][style_key]
136
+ except KeyError:
137
+ # Fallback to English concise
138
+ base_prompt = self._base_prompts["system"]["en"]["concise"]
139
+
140
+ # Format with name
141
+ return base_prompt.format(name=name_part)
142
+
143
+ def get_context_aware_prompt(self,
144
+ user_message: str,
145
+ language: str = "en",
146
+ username: str = None,
147
+ previous_messages: List[Dict] = None) -> str:
148
+ """
149
+ Get prompt with conversation context awareness
150
+
151
+ Args:
152
+ user_message: Current user message
153
+ language: Language code
154
+ username: Optional username
155
+ previous_messages: List of previous conversation messages
156
+
157
+ Returns:
158
+ Context-aware prompt string
159
+ """
160
+ system_prompt = self.get_system_prompt(language, username, "friendly")
161
+
162
+ # Build context if available
163
+ context_part = ""
164
+ if previous_messages and len(previous_messages) > 0:
165
+ context_part = "\n\nPrevious conversation:\n"
166
+ for msg in previous_messages[-5:]: # Last 5 messages
167
+ role = msg.get("role", "user")
168
+ content = msg.get("content", "")
169
+ context_part += f"{role}: {content}\n"
170
+
171
+ # Analyze message for special handling
172
+ message_lower = user_message.lower()
173
+
174
+ if "code" in message_lower or "program" in message_lower or "python" in message_lower:
175
+ style = "technical"
176
+ elif len(user_message.split()) < 4: # Very short message
177
+ style = "concise"
178
+ else:
179
+ style = "detailed"
180
+
181
+ # Add style instruction
182
+ style_instruction = ""
183
+ if style == "technical":
184
+ style_instruction = "Focus on providing accurate code and technical explanations."
185
+ elif style == "concise":
186
+ style_instruction = "Keep the response brief and to the point."
187
+
188
+ final_prompt = f"""{system_prompt}
189
+ {style_instruction}
190
+ {context_part}
191
+
192
+ Current user message: {user_message}
193
+
194
+ Please respond appropriately based on the context and message."""
195
+
196
+ return final_prompt
197
+
198
+ def get_greeting(self,
199
+ language: str = "en",
200
+ username: str = None,
201
+ time_of_day: str = None) -> str:
202
+ """
203
+ Get appropriate greeting based on time of day
204
+
205
+ Args:
206
+ language: Language code
207
+ username: Optional username
208
+ time_of_day: Specific time of day (morning, afternoon, evening)
209
+
210
+ Returns:
211
+ Greeting message
212
+ """
213
+ lang = language.lower() if language else "en"
214
+
215
+ # Determine time of day if not provided
216
+ if not time_of_day:
217
+ hour = datetime.now().hour
218
+ if 5 <= hour < 12:
219
+ time_of_day = "morning"
220
+ elif 12 <= hour < 17:
221
+ time_of_day = "afternoon"
222
+ elif 17 <= hour < 22:
223
+ time_of_day = "evening"
224
+ else:
225
+ time_of_day = "general"
226
+
227
+ # Get greeting template
228
+ try:
229
+ greeting_templates = self._base_prompts["greeting"][lang]
230
+ template = greeting_templates.get(time_of_day, greeting_templates["general"])
231
+ except KeyError:
232
+ # Fallback to English
233
+ greeting_templates = self._base_prompts["greeting"]["en"]
234
+ template = greeting_templates.get(time_of_day, greeting_templates["general"])
235
+
236
+ name_part = f"{username}'s AI" if username else "AumCore AI"
237
+ return template.format(name=name_part)
238
+
239
+ def detect_response_style_needed(self, user_message: str) -> Dict:
240
+ """
241
+ Analyze user message to determine appropriate response style
242
+
243
+ Args:
244
+ user_message: User's input text
245
+
246
+ Returns:
247
+ Dictionary with style recommendations
248
+ """
249
+ message_lower = user_message.lower()
250
+ words = user_message.split()
251
+
252
+ analysis = {
253
+ "language": "en", # Default, will be detected elsewhere
254
+ "style": "detailed",
255
+ "needs_code": False,
256
+ "is_technical": False,
257
+ "is_casual": False,
258
+ "word_count": len(words)
259
+ }
260
+
261
+ # Check for technical/code requests
262
+ code_keywords = ["code", "program", "function", "script", "algorithm",
263
+ "python", "javascript", "java", "html", "css", "sql",
264
+ "error", "bug", "debug", "compile", "syntax"]
265
+
266
+ if any(keyword in message_lower for keyword in code_keywords):
267
+ analysis["needs_code"] = True
268
+ analysis["is_technical"] = True
269
+ analysis["style"] = "technical"
270
+
271
+ # Check for casual conversation
272
+ casual_keywords = ["hi", "hello", "hey", "how are you", "what's up",
273
+ "thanks", "thank you", "please", "ok", "okay"]
274
+
275
+ if any(keyword in message_lower for keyword in casual_keywords):
276
+ analysis["is_casual"] = True
277
+ analysis["style"] = "friendly"
278
+
279
+ # Check for very short messages
280
+ if len(words) <= 3:
281
+ analysis["style"] = "concise"
282
+
283
+ # Check for complex questions
284
+ question_words = ["how", "what", "why", "when", "where", "which", "explain", "describe"]
285
+ if any(user_message.strip().startswith(word) for word in question_words):
286
+ analysis["style"] = "detailed"
287
+
288
+ return analysis
289
+
290
+ def save_custom_prompt(self,
291
+ category: str,
292
+ language: str,
293
+ style: str,
294
+ prompt_text: str):
295
+ """
296
+ Save custom prompt to file
297
+
298
+ Args:
299
+ category: Prompt category (system, greeting, error_responses)
300
+ language: Language code
301
+ style: Prompt style
302
+ prompt_text: Custom prompt text
303
+ """
304
+ custom_file = os.path.join(self.prompts_dir, "custom_prompts.json")
305
+
306
+ # Load existing or create new
307
+ if os.path.exists(custom_file):
308
+ with open(custom_file, 'r', encoding='utf-8') as f:
309
+ custom_prompts = json.load(f)
310
+ else:
311
+ custom_prompts = {}
312
+
313
+ # Update structure
314
+ if category not in custom_prompts:
315
+ custom_prompts[category] = {}
316
+ if language not in custom_prompts[category]:
317
+ custom_prompts[category][language] = {}
318
+
319
+ custom_prompts[category][language][style] = prompt_text
320
+
321
+ # Save back
322
+ with open(custom_file, 'w', encoding='utf-8') as f:
323
+ json.dump(custom_prompts, f, indent=2, ensure_ascii=False)
324
+
325
+ # Clear cache
326
+ self._prompt_cache.clear()
327
+
328
+ def add_to_conversation_history(self, role: str, content: str):
329
+ """
330
+ Add message to conversation history
331
+
332
+ Args:
333
+ role: 'user' or 'assistant'
334
+ content: Message content
335
+ """
336
+ self._conversation_history.append({
337
+ "role": role,
338
+ "content": content,
339
+ "timestamp": datetime.now().isoformat()
340
+ })
341
+
342
+ # Keep only last 20 messages
343
+ if len(self._conversation_history) > 20:
344
+ self._conversation_history = self._conversation_history[-20:]
345
+
346
+ def get_conversation_summary(self) -> str:
347
+ """
348
+ Get summary of recent conversation
349
+
350
+ Returns:
351
+ Conversation summary string
352
+ """
353
+ if not self._conversation_history:
354
+ return "No recent conversation."
355
+
356
+ summary = f"Recent conversation ({len(self._conversation_history)} messages):\n"
357
+ for msg in self._conversation_history[-5:]: # Last 5 messages
358
+ role = msg["role"]
359
+ content_preview = msg["content"][:50] + "..." if len(msg["content"]) > 50 else msg["content"]
360
+ summary += f"{role}: {content_preview}\n"
361
+
362
+ return summary
363
+
364
+ def clear_conversation_history(self):
365
+ """Clear all conversation history"""
366
+ self._conversation_history = []
367
+
368
+ # Global instance for easy import
369
+ prompt_manager = AumCorePromptManager()
370
+
371
+ # Backward compatibility functions
372
+ def get_system_prompt(language: str = "en", username: str = None) -> str:
373
+ """
374
+ Legacy compatibility function
375
+
376
+ Args:
377
+ language: Language code
378
+ username: Optional username
379
+
380
+ Returns:
381
+ System prompt string
382
+ """
383
+ return prompt_manager.get_system_prompt(language, username)
384
+
385
+ # Module exports
386
+ __all__ = [
387
+ 'AumCorePromptManager',
388
+ 'PromptConfig',
389
+ 'ConversationStyle',
390
+ 'LanguageCode',
391
+ 'prompt_manager',
392
+ 'get_system_prompt'
393
+ ]
394
+
395
+ __version__ = "4.0.0"
396
+ __author__ = "AumCore AI"