""" Flare – Prompt Builder """ from typing import Dict, List, Optional from datetime import datetime import json import re from config_provider import ConfigProvider from locale_manager import LocaleManager from utils import log # ───────────────────────────────────────────────────────────────────────────── # DATE CONTEXT # ───────────────────────────────────────────────────────────────────────────── def _get_date_context(locale_code: str = "tr") -> Dict[str, str]: """Get today/tomorrow dates with weekday names in target locale""" from datetime import timedelta today = datetime.now() tomorrow = today + timedelta(days=1) locale_data = LocaleManager.get_locale(locale_code) weekday_names = locale_data.get("weekdays", { "0": "Monday", "1": "Tuesday", "2": "Wednesday", "3": "Thursday", "4": "Friday", "5": "Saturday", "6": "Sunday" }) # Get localized date format date_format = locale_data.get("date_format", "%Y-%m-%d") dates = { "today": today.strftime(date_format), "tomorrow": tomorrow.strftime(date_format), "today_weekday": weekday_names.get(str(today.weekday()), ""), "tomorrow_weekday": weekday_names.get(str(tomorrow.weekday()), ""), "locale_code": locale_code } return dates # ───────────────────────────────────────────────────────────────────────────── # INTENT PROMPT # ───────────────────────────────────────────────────────────────────────────── def build_intent_prompt(general_prompt: str, conversation: List[Dict[str, str]], user_input: str, intents: List, project_locale: str = "tr") -> str: # Get config when needed cfg = ConfigProvider.get() # Get internal prompt from LLM provider settings internal_prompt = "" if cfg.global_config.llm_provider and cfg.global_config.llm_provider.settings: internal_prompt = cfg.global_config.llm_provider.settings.get("internal_prompt", "") # Extract intent names and captions intent_names = [it.name for it in intents] intent_captions = [it.caption or it.name for it in intents] # Get locale info from locale_manager import LocaleManager locale_data = LocaleManager.get_locale(project_locale) project_language = locale_data.get("name", "Turkish") if locale_data else "Turkish" # Replace placeholders in internal prompt if internal_prompt: # Intent names - quoted and comma-separated intent_names_str = ', '.join([f'"{name}"' for name in intent_names]) internal_prompt = internal_prompt.replace("", intent_names_str) # Intent captions - quoted and comma-separated intent_captions_str = ', '.join([f'"{caption}"' for caption in intent_captions]) internal_prompt = internal_prompt.replace("", intent_captions_str) # Project language internal_prompt = internal_prompt.replace("", project_language) # === INTENT INDEX === lines = ["### INTENT INDEX ###"] for it in intents: # IntentConfig object attribute access det = it.detection_prompt.strip() if it.detection_prompt else "" det_part = f' • detection_prompt → "{det}"' if det else "" # Get examples for project locale examples = it.get_examples_for_locale(project_locale) exs = " | ".join(examples) if examples else "" ex_part = f" • examples → {exs}" if exs else "" newline_between = "\n" if det_part and ex_part else "" lines.append(f"{it.name}:{det_part}{newline_between}{ex_part}") intent_index = "\n".join(lines) # === HISTORY === history_block = "\n".join( f"{m['role'].upper()}: {m['content']}" for m in conversation[-10:] ) # Combine prompts combined_prompt = internal_prompt + "\n\n" + general_prompt if internal_prompt else general_prompt prompt = ( f"{combined_prompt}\n\n" f"{intent_index}\n\n" f"Conversation so far:\n{history_block}\n\n" f"USER: {user_input.strip()}" ) log("✅ Intent prompt built (with internal prompt)") return prompt # ───────────────────────────────────────────────────────────────────────────── # PARAMETER PROMPT # ───────────────────────────────────────────────────────────────────────────── _FMT = """#PARAMETERS:{"extracted":[{"name":"","value":""},...],"missing":["",...]}""" def build_parameter_prompt(intent_cfg, missing_params: List[str], user_input: str, conversation: List[Dict[str, str]], locale_code: str = None) -> str: # Use project locale if not specified if not locale_code: locale_code = "tr" # Default # Get locale info from locale_manager import LocaleManager locale_data = LocaleManager.get_locale(locale_code) date_ctx = _get_date_context() parts: List[str] = [ f"You are extracting parameters from user messages in {locale_data.get('name', 'the target language')}.", f"Today is {date_ctx['today']} ({date_ctx['today_weekday']}). Tomorrow is {date_ctx['tomorrow']}.", "Extract ONLY the parameters listed below from the conversation.", "Look at BOTH the current message AND previous messages to find parameter values.", "If a parameter cannot be found, is invalid, or wasn't provided, keep it in the \"missing\" list.", "Never guess or make up values. Only extract values explicitly given by the user.", "", "IMPORTANT: If the user is NOT providing the requested parameter but instead:", "- Asking for recommendations or advice (e.g. 'nereye gitsem?', 'önerin var mı?')", "- Expressing uncertainty (e.g. 'tam net değil', 'emin değilim', 'bilmiyorum')", "- Changing the subject or asking something else", "Then DO NOT extract any value for that parameter. Keep it in the 'missing' list.", "" ] # Add parameter descriptions parts.append("Parameters to extract:") for p in intent_cfg.parameters: if p.name in missing_params: # Get caption for locale caption = p.get_caption_for_locale(locale_code) # Special handling for date type parameters if p.type == "date": date_prompt = _build_locale_aware_date_prompt( p, date_ctx, locale_data, locale_code ) parts.append(date_prompt) else: parts.append(f"• {p.name}: {p.extraction_prompt}") parts.append(f" Caption: {caption}") # Rest of the function remains the same... parts.append("") parts.append("IMPORTANT: Your response must start with '#PARAMETERS:' followed by the JSON.") parts.append("Return ONLY this format with no extra text before or after:") parts.append(_FMT) history_block = "\n".join( f"{m['role'].upper()}: {m['content']}" for m in conversation[-10:] ) prompt = ( "\n".join(parts) + "\n\nConversation so far:\n" + history_block + "\n\nUSER: " + user_input.strip() ) log(f"📝 Parameter prompt built for missing: {missing_params}") return prompt def _build_locale_aware_date_prompt(param, date_ctx: Dict, locale_data: Dict, locale_code: str) -> str: """Build date extraction prompt with locale awareness""" caption = param.get_caption_for_locale(locale_code) # Get locale-specific date info month_names = locale_data.get("months", {}) relative_dates = locale_data.get("relative_dates", { "today": "today", "tomorrow": "tomorrow", "yesterday": "yesterday", "this_week": "this week" }) parts = [ f"• {param.name} ({caption}): Extract date in YYYY-MM-DD format.", f" - Today is {date_ctx['today']} ({date_ctx['today_weekday']})", f" - '{relative_dates.get('today', 'today')}' → {date_ctx['today']}", f" - '{relative_dates.get('tomorrow', 'tomorrow')}' → {date_ctx['tomorrow']}" ] if param.extraction_prompt: parts.append(f" - {param.extraction_prompt}") return "\n".join(parts) # ───────────────────────────────────────────────────────────────────────────── # SMART PARAMETER QUESTION # ───────────────────────────────────────────────────────────────────────────── def build_smart_parameter_question_prompt( collection_config, intent_config, missing_params: List[str], session, project_language: str = "Turkish", locale_code: str = None ) -> str: """Build prompt for smart parameter collection""" # Get parameter collection config from LLM provider settings cfg = ConfigProvider.get() if cfg.global_config.llm_provider and cfg.global_config.llm_provider.settings: collection_config = cfg.global_config.llm_provider.settings.get("parameter_collection_config", collection_config) # Use locale if specified if not locale_code: locale_code = "tr" # Get locale info from locale_manager import LocaleManager locale_data = LocaleManager.get_locale(locale_code) if locale_data: project_language = locale_data.get("name", project_language) # Rest of the function implementation... template = collection_config.get("collection_prompt", "") # Format conversation history conversation_history = _format_conversation_history(session.chat_history) # Format collected parameters with locale-aware captions collected_params = "" if session.variables: params_list = [] for param_name, value in session.variables.items(): param = next((p for p in intent_config.parameters if p.name == param_name), None) if param: caption = param.get_caption_for_locale(locale_code) params_list.append(f"- {caption}: {value}") collected_params = "\n".join(params_list) # Format missing parameters with locale-aware captions missing_params_list = [] for param_name in missing_params: param = next((p for p in intent_config.parameters if p.name == param_name), None) if param: caption = param.get_caption_for_locale(locale_code) missing_params_list.append(f"- {caption} ({param.name})") missing_params_str = "\n".join(missing_params_list) # Rest of template replacement... prompt = template.replace("{{conversation_history}}", conversation_history) prompt = prompt.replace("{{intent_name}}", intent_config.name) prompt = prompt.replace("{{intent_caption}}", intent_config.caption) prompt = prompt.replace("{{collected_params}}", collected_params) prompt = prompt.replace("{{missing_params}}", missing_params_str) prompt = prompt.replace("{{max_params}}", str(collection_config.get("max_params_per_question", 2))) prompt = prompt.replace("{{project_language}}", project_language) log(f"📝 Smart parameter question prompt built for {len(missing_params)} params in {locale_code}") return prompt # ───────────────────────────────────────────────────────────────────────────── # PARAMETER EXTRACTION FROM QUESTION # ───────────────────────────────────────────────────────────────────────────── def extract_params_from_question(question: str, intent_config, project_locale: str = "tr") -> List[str]: """Extract which parameters are being asked in the question""" asked_params = [] question_lower = question.lower() # Check each missing parameter for param in intent_config.parameters: # Check all locale captions for caption_obj in param.caption: caption = caption_obj.caption.lower() # Check if caption appears in question if caption in question_lower: asked_params.append(param.name) break # Also check parameter name if param.name.lower() in question_lower: if param.name not in asked_params: asked_params.append(param.name) return asked_params # ───────────────────────────────────────────────────────────────────────────── # API RESPONSE PROMPT # ───────────────────────────────────────────────────────────────────────────── def build_api_response_prompt(api_config, api_response: Dict) -> str: """Build prompt for API response humanization""" response_prompt = api_config.response_prompt if not response_prompt: response_prompt = "Convert this API response to a friendly message: {{api_response}}" # Replace placeholders response_prompt = response_prompt.replace("{{api_response}}", json.dumps(api_response, ensure_ascii=False)) return response_prompt