Spaces:
Building
Building
File size: 11,560 Bytes
67cc066 3bd94e0 ec80e4b 67cc066 2167be3 3bd94e0 488c650 ccdbef1 67cc066 3bd94e0 037f971 ec80e4b 037f971 2167be3 037f971 7285c41 e47265d 847112a 7285c41 847112a 7285c41 ec80e4b 037f971 724a384 e7addaf 724a384 037f971 ec80e4b 724a384 ec80e4b 037f971 ec80e4b 037f971 2167be3 037f971 847112a 2167be3 847112a 037f971 2167be3 847112a 2167be3 037f971 add2298 037f971 c31edec 2167be3 724a384 2167be3 6506311 3bd94e0 037f971 3bd94e0 c31edec 6506311 c31edec dbe0aa3 c31edec 2167be3 6506311 c31edec 724a384 3bd94e0 6506311 c31edec 037f971 6506311 c31edec 037f971 2167be3 6506311 2167be3 6506311 037f971 2167be3 6506311 c31edec 724a384 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
"""
Flare β Prompt Builder (v6 Β· date handling)
==============================================================
"""
from typing import List, Dict
from datetime import datetime, timedelta
from utils import log
from config_provider import ConfigProvider
# 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,
project_name: str = None) -> str:
# Get config when needed
cfg = ConfigProvider.get()
# Get internal prompt from config
internal_prompt = cfg.global_config.internal_prompt or ""
# 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 project language
project_language = "Turkish" # Default
if project_name:
project = next((p for p in cfg.projects if p.name == project_name), None)
if project:
# Language code'u language name'e Γ§evir
lang_map = {
"tr": "Turkish",
"en": "English",
"de": "German",
"fr": "French",
"es": "Spanish"
}
project_language = lang_map.get(project.default_language, "Turkish")
# Replace placeholders in internal prompt
if internal_prompt:
# Intent names - tΔ±rnak iΓ§inde ve virgΓΌlle ayrΔ±lmΔ±Ε
intent_names_str = ', '.join([f'"{name}"' for name in intent_names])
internal_prompt = internal_prompt.replace("<intent names>", intent_names_str)
# Intent captions - tΔ±rnak iΓ§inde ve virgΓΌlle ayrΔ±lmΔ±Ε
intent_captions_str = ', '.join([f'"{caption}"' for caption in intent_captions])
internal_prompt = internal_prompt.replace("<intent captions>", intent_captions_str)
# Project language
internal_prompt = internal_prompt.replace("<project language>", 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 ""
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:]
)
# 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
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# RESPONSE PROMPT
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def build_api_response_prompt(api_config, api_response: Dict) -> str:
"""Build prompt for API response with mappings"""
response_prompt = api_config.response_prompt or "API yanΔ±tΔ±nΔ± kullanΔ±cΔ±ya aΓ§Δ±kla:"
# Response mappings varsa, mapping bilgilerini ekle
if api_config.response_mappings:
mapping_info = []
for mapping in api_config.response_mappings:
# JSON path'e gΓΆre deΔeri bul
value = extract_value_from_json_path(api_response, mapping.json_path)
if value is not None:
# Type'a gΓΆre formatlama
if mapping.type == "date":
# ISO date'i TΓΌrkΓ§e formata Γ§evir
try:
dt = datetime.fromisoformat(value.replace('Z', '+00:00'))
value = dt.strftime("%d %B %Y %H:%M")
except:
pass
elif mapping.type == "float":
try:
value = f"{float(value):,.2f}"
except:
pass
mapping_info.append(f"{mapping.caption}: {value}")
if mapping_info:
# Response prompt'a mapping bilgilerini ekle
mapping_text = "\n\nΓnemli Bilgiler:\n" + "\n".join(f"β’ {info}" for info in mapping_info)
response_prompt = response_prompt.replace("{{api_response}}", f"{{{{api_response}}}}{mapping_text}")
# API response'u JSON string olarak ekle
response_json = json.dumps(api_response, ensure_ascii=False, indent=2)
final_prompt = response_prompt.replace("{{api_response}}", response_json)
return final_prompt
def extract_value_from_json_path(data: Dict, path: str):
"""Extract value from JSON using dot notation path"""
try:
parts = path.split('.')
value = data
for part in parts:
if isinstance(value, dict):
value = value.get(part)
elif isinstance(value, list) and part.isdigit():
value = value[int(part)]
else:
return None
return value
except:
return None
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PARAMETER PROMPT
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_FMT = """#PARAMETERS:{"extracted":[{"name":"<param>","value":"<val>"},...],"missing":["<param>",...]}"""
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.",
"",
"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:
# 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 |