Spaces:
Building
Building
File size: 14,908 Bytes
67cc066 e1ef72d 67cc066 e1ef72d ccdbef1 a22ac01 e1ef72d 67cc066 e1ef72d 3bd94e0 e1ef72d a22ac01 e1ef72d a22ac01 e1ef72d 3bd94e0 e1ef72d a22ac01 3bd94e0 037f971 ec80e4b 037f971 2167be3 037f971 7285c41 e1ef72d e47265d 847112a e1ef72d 847112a c22dfdb 7285c41 847112a e1ef72d 7285c41 e1ef72d 7285c41 ec80e4b 037f971 c22dfdb 724a384 e7addaf e1ef72d c22dfdb ec80e4b 724a384 ec80e4b 037f971 ec80e4b 037f971 2167be3 037f971 847112a 2167be3 847112a 037f971 2167be3 847112a 2167be3 add2298 037f971 c31edec 2167be3 724a384 2167be3 a22ac01 c22dfdb e1ef72d a22ac01 c22dfdb a22ac01 3bd94e0 c22dfdb 037f971 a22ac01 3bd94e0 c31edec 6506311 c31edec dbe0aa3 c31edec 2167be3 6506311 c22dfdb c31edec 724a384 c22dfdb e1ef72d 3bd94e0 a22ac01 3bd94e0 c22dfdb 6506311 c22dfdb c31edec c22dfdb 6506311 c22dfdb 6506311 c22dfdb 6506311 c22dfdb 060c625 a22ac01 e1ef72d a22ac01 e1ef72d a22ac01 e1ef72d 060c625 c22dfdb e1ef72d 060c625 c22dfdb 060c625 e1ef72d 060c625 e1ef72d c22dfdb e1ef72d c22dfdb 060c625 c22dfdb 060c625 e1ef72d c22dfdb 060c625 c22dfdb 060c625 c22dfdb e1ef72d c22dfdb 060c625 c22dfdb 060c625 c22dfdb e1ef72d 060c625 c22dfdb 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d |
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 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 |
"""
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>", 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>", 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 ""
# 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":"<param>","value":"<val>"},...],"missing":["<param>",...]}"""
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 |