Spaces:
Sleeping
Sleeping
Updated the PROMPT_ENTRY_CLASSIFIER function to simplify query formation without clinical context. Added easy logging for dynamic queries in the EnhancedMainLifestyleAssistant class, including markers for successful use and Fallback. Fixed time formatting to UTC in the EntryClassifier class. Removed unnecessary comments and improved code structure.
Browse filesFiles changed (3)
83 unmodified lines84858687888990919293949596290 unmodified lines38738838939083 unmodified lines# ===== PROMPT FUNCTIONS =====def PROMPT_ENTRY_CLASSIFIER(clinical_background, user_message):return f"""PATIENT CLINICAL CONTEXT:Patient name: {clinical_background.patient_name}Active problems: {"; ".join(clinical_background.active_problems[:5]) if clinical_background.active_problems else "none"}Current medications: {"; ".join(clinical_background.current_medications[:5]) if clinical_background.current_medications else "none"}Critical alerts: {"; ".join(clinical_background.critical_alerts) if clinical_background.critical_alerts else "none"}PATIENT MESSAGE: "{user_message}"ANALYSIS REQUIRED:Classify this patient communication and determine the appropriate system mode based on content analysis and safety considerations."""290 unmodified linesANALYSIS REQUIRED:Analyze the situation and determine the best action for this lifestyle coaching session."""# ===== DEPRECATED: Old lifestyle assistant prompt =====83 unmodified lines8485868788899091290 unmodified lines38238338438583 unmodified lines# ===== PROMPT FUNCTIONS =====def PROMPT_ENTRY_CLASSIFIER(clinical_background, user_message):"""Build minimal prompt for entry classification without clinical context."""return f"""PATIENT MESSAGE: "{user_message}"ANALYSIS REQUIRED:Classify this patient communication and determine the appropriate system mode based on content analysis and safety considerations."""290 unmodified linesANALYSIS REQUIRED:Analyze the situation and determine the best action for this lifestyle coaching session."""# ===== DEPRECATED: Old lifestyle assistant prompt =====
142 unmodified lines143144145146147148149150151152288 unmodified lines441442443444142 unmodified lines):if chunk.text:response_text += chunk.text# Log the interactionself._log_interaction(system_prompt, user_prompt, response_text, "gemini")return response_textexcept Exception as e:288 unmodified linesprint(f" Test response: {response[:100]}...")except Exception as e:print(f" Error: {e}")142 unmodified lines143144145146147148149288 unmodified lines438439440441142 unmodified lines):if chunk.text:response_text += chunk.textreturn response_textexcept Exception as e:288 unmodified linesprint(f" Test response: {response[:100]}...")except Exception as e:print(f" Error: {e}")
303 unmodified lines30430530630730830948 unmodified lines35835936036136236310 unmodified lines37437537637737837985 unmodified lines465466467468469470471677 unmodified lines1149115011511152115311541155115611571158115911601161469 unmodified lines1631163216331634303 unmodified linesself.composition_performance_tracker = FailsafeTracker()print("🔄 Fallback to static prompt mode activated")# === EXISTING METHODS PRESERVED UNCHANGED ===def set_custom_system_prompt(self, custom_prompt: str):48 unmodified linesself.composition_performance_tracker.record_success()if DynamicPromptConfig.DEBUG_MODE:print("🧠 Using dynamically composed prompt")return dynamic_promptexcept Exception as e:10 unmodified linesattempted = self._should_attempt_dynamic_composition(session_context, lifestyle_profile)if attempted and lifestyle_profile is not None and not isinstance(self.composition_performance_tracker, FailsafeTracker):suffix = f"\n\n[Dynamic Context]\nPatient: {getattr(lifestyle_profile, 'patient_name', 'Пацієнт')}\nMode: static-fallback"return (self.default_system_prompt or "") + suffixreturn self.default_system_prompt85 unmodified linesprint(f"✅ Dynamic prompt composed using: {', '.join(assembly_result.components_used)}")if assembly_result.assembly_notes:print(f"📝 Assembly notes: {'; '.join(assembly_result.assembly_notes)}")return assembly_result.assembled_promptexcept Exception as e:677 unmodified linesif classification["V"] not in ["on", "off", "hybrid"]:classification["V"] = "off" # fallbackreturn classificationexcept:from datetime import datetimereturn {"K": "Lifestyle Mode","V": "off","T": datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")}class TriageExitClassifier:469 unmodified lines'LifestyleSessionManager','DynamicPromptSystemMonitor','get_enhanced_architecture_summary']303 unmodified lines30430530630730830931031131231331431531631731831932032132232332432532632732832948 unmodified lines37837938038138238338438510 unmodified lines39639739839940040140240385 unmodified lines489490491492493494495496497498499500677 unmodified lines11781179118011811182118311841185118611871188118911901191119211931194469 unmodified lines1664166516661667303 unmodified linesself.composition_performance_tracker = FailsafeTracker()print("🔄 Fallback to static prompt mode activated")# --- Lightweight logging for dynamic prompt transparency ---def _log_dynamic_marker(self, message: str):"""Write a short marker to dynamic prompts log when enabled.Respects LOG_PROMPTS env var; creates a simple file handler once."""try:import logging, osif os.getenv("LOG_PROMPTS", "false").lower() != "true":returnlogger = logging.getLogger("dynamic_prompts")if not logger.handlers:logger.setLevel(logging.INFO)fh = logging.FileHandler('dynamic_prompts.log', encoding='utf-8')fh.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))logger.addHandler(fh)logger.info(message)except Exception:# Never break flow due to loggingpass# === EXISTING METHODS PRESERVED UNCHANGED ===def set_custom_system_prompt(self, custom_prompt: str):48 unmodified linesself.composition_performance_tracker.record_success()if DynamicPromptConfig.DEBUG_MODE:print("🧠 Using dynamically composed prompt")# Marker: dynamic prompt successfully usedself._log_dynamic_marker("[DYNAMIC_PROMPT] used=success")return dynamic_promptexcept Exception as e:10 unmodified linesattempted = self._should_attempt_dynamic_composition(session_context, lifestyle_profile)if attempted and lifestyle_profile is not None and not isinstance(self.composition_performance_tracker, FailsafeTracker):suffix = f"\n\n[Dynamic Context]\nPatient: {getattr(lifestyle_profile, 'patient_name', 'Пацієнт')}\nMode: static-fallback"# Marker: dynamic attempted but fell back to staticself._log_dynamic_marker("[DYNAMIC_PROMPT] fallback=static")return (self.default_system_prompt or "") + suffixreturn self.default_system_prompt85 unmodified linesprint(f"✅ Dynamic prompt composed using: {', '.join(assembly_result.components_used)}")if assembly_result.assembly_notes:print(f"📝 Assembly notes: {'; '.join(assembly_result.assembly_notes)}")# Minimal marker without PHItry:comps = ','.join(assembly_result.components_used)self._log_dynamic_marker(f"[DYNAMIC_PROMPT] components={comps}")except Exception:passreturn assembly_result.assembled_promptexcept Exception as e:677 unmodified linesif classification["V"] not in ["on", "off", "hybrid"]:classification["V"] = "off" # fallback# Переважно підставляємо серверний timestamp (UTC), ігноруючи T з LLMfrom datetime import datetime, timezoneclassification["T"] = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")return classificationexcept:from datetime import datetimereturn {"K": "Lifestyle Mode","V": "off",# Використовуємо UTC timestamp у fallback"T": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")}class TriageExitClassifier:469 unmodified lines'LifestyleSessionManager','DynamicPromptSystemMonitor','get_enhanced_architecture_summary']
prompts.py+3-8
src/core/ai_client.py+2-5
src/core/core_classes.py+36-3