""" Flare – Prompt Builder (v6 · date handling) ============================================================== """ from typing import List, Dict from datetime import datetime, timedelta from utils import log # Date helper for Turkish date expressions def _get_date_context() -> Dict[str, str]: """Generate date context for Turkish date expressions""" now = datetime.now() # Weekday names in Turkish weekdays_tr = ["Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi", "Pazar"] today_weekday = weekdays_tr[now.weekday()] # Calculate various dates dates = { "today": now.strftime("%Y-%m-%d"), "tomorrow": (now + timedelta(days=1)).strftime("%Y-%m-%d"), "day_after_tomorrow": (now + timedelta(days=2)).strftime("%Y-%m-%d"), "this_weekend_saturday": (now + timedelta(days=(5-now.weekday())%7)).strftime("%Y-%m-%d"), "this_weekend_sunday": (now + timedelta(days=(6-now.weekday())%7)).strftime("%Y-%m-%d"), "next_week_same_day": (now + timedelta(days=7)).strftime("%Y-%m-%d"), "two_weeks_later": (now + timedelta(days=14)).strftime("%Y-%m-%d"), "today_weekday": today_weekday, "today_day": now.day, "today_month": now.month, "today_year": now.year } return dates # ───────────────────────────────────────────────────────────────────────────── # INTENT PROMPT # ───────────────────────────────────────────────────────────────────────────── def build_intent_prompt(general_prompt: str, conversation: List[Dict[str, str]], user_input: str, intents: List) -> str: # === 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 "" exs = " | ".join(it.examples) if it.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:] ) prompt = ( f"{general_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 (index with detection_prompt)") return prompt # ───────────────────────────────────────────────────────────────────────────── # PARAMETER PROMPT - Improved version # ───────────────────────────────────────────────────────────────────────────── _FMT = """#PARAMETERS:{"extracted":[{"name":"","value":""},...],"missing":["",...]}""" def build_parameter_prompt(intent_cfg, missing_params: List[str], user_input: str, conversation: List[Dict[str, str]]) -> str: date_ctx = _get_date_context() parts: List[str] = [ "You are extracting parameters from user messages in TURKISH.", 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.", "" ] # Add parameter descriptions parts.append("Parameters to extract:") for p in intent_cfg.parameters: if p.name in missing_params: # Special handling for date type parameters if p.type == "date": date_prompt = ( f"• {p.name}: {p.extraction_prompt}\n" f" IMPORTANT DATE RULES:\n" f" - 'bugün' = {date_ctx['today']}\n" f" - 'yarın' = {date_ctx['tomorrow']}\n" f" - 'öbür gün' = {date_ctx['day_after_tomorrow']}\n" f" - 'bu hafta sonu' = {date_ctx['this_weekend_saturday']} or {date_ctx['this_weekend_sunday']}\n" f" - 'bu cumartesi' = {date_ctx['this_weekend_saturday']}\n" f" - 'bu pazar' = {date_ctx['this_weekend_sunday']}\n" f" - 'haftaya' or 'gelecek hafta' = add 7 days to current date\n" f" - 'haftaya bugün' = {date_ctx['next_week_same_day']}\n" f" - 'iki hafta sonra' = {date_ctx['two_weeks_later']}\n" f" - '15 gün sonra' = add 15 days to today\n" f" - '10 Temmuz' = {date_ctx['today_year']}-07-10\n" f" - Turkish months: Ocak=01, Şubat=02, Mart=03, Nisan=04, Mayıs=05, Haziran=06, " f"Temmuz=07, Ağustos=08, Eylül=09, Ekim=10, Kasım=11, Aralık=12" ) parts.append(date_prompt) else: parts.append(f"• {p.name}: {p.extraction_prompt}") # Add format instruction 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) # Add conversation history 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