Spaces:
Building
Building
File size: 15,027 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 e1ef72d 7285c41 847112a e1ef72d 7285c41 e1ef72d 7285c41 ec80e4b 037f971 e1ef72d 724a384 e7addaf e1ef72d ec80e4b 724a384 ec80e4b 037f971 ec80e4b 037f971 2167be3 037f971 847112a 2167be3 847112a 037f971 2167be3 847112a 2167be3 add2298 037f971 c31edec 2167be3 724a384 2167be3 a22ac01 e1ef72d a22ac01 e1ef72d a22ac01 e1ef72d a22ac01 3bd94e0 037f971 a22ac01 3bd94e0 c31edec 6506311 c31edec dbe0aa3 c31edec 2167be3 6506311 e1ef72d c31edec 724a384 e1ef72d 3bd94e0 a22ac01 3bd94e0 e1ef72d 6506311 c31edec e1ef72d 6506311 c31edec e1ef72d 6506311 e1ef72d 6506311 e1ef72d 060c625 a22ac01 e1ef72d a22ac01 e1ef72d a22ac01 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 060c625 e1ef72d 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 |
"""
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_name: str = None,
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 project language name from locale
locale_info = LocaleManager.get_locale(project_locale)
project_language = locale_info.get("name", "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:
# Get examples for project locale
locale_examples = it.get_examples_for_locale(project_locale)
det = it.detection_prompt.strip() if it.detection_prompt else ""
det_part = f' β’ detection_prompt β "{det}"' if det else ""
ex_part = ""
if locale_examples:
exs = " | ".join(locale_examples)
ex_part = f" β’ examples β {exs}"
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,
project_locale: str = "tr") -> str:
# Use project locale if not specified
if not locale_code:
locale_code = project_locale
date_ctx = _get_date_context(locale_code)
locale_data = LocaleManager.get_locale(locale_code)
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 with localized captions
parts.append("Parameters to extract:")
for p in intent_cfg.parameters:
if p.name in missing_params:
# Get localized caption
caption = p.get_caption_for_locale(locale_code, project_locale)
# 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:
extraction = p.extraction_prompt or f"Extract {p.name}"
parts.append(f"β’ {p.name} ({caption}): {extraction}")
# Add format instruction
parts.append("")
parts.append("IMPORTANT: Your response must start with '#PARAMETERS:' followed by the JSON.")
parts.append(f"Format: {_FMT}")
parts.append("No other text before or after.")
# Add conversation history
parts.append("")
parts.append("Recent conversation:")
for msg in conversation[-5:]:
parts.append(f"{msg['role'].upper()}: {msg['content']}")
# Add current input
parts.append(f"USER: {user_input}")
return "\n".join(parts)
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(
intent_config,
missing_params: List[str],
collected_params: Dict[str, str],
conversation: List[Dict[str, str]],
project_locale: str = "tr",
unanswered_params: List[str] = None
) -> str:
"""Build prompt for smart parameter collection"""
cfg = ConfigProvider.get()
# Get parameter collection config from LLM provider settings
collection_config = {}
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", {})
# Get collection prompt template
collection_prompt = collection_config.get("collection_prompt", """
You are a helpful assistant collecting information from the user.
Intent: {{intent_name}} - {{intent_caption}}
Still needed: {{missing_params}}
Ask for the missing parameters in a natural, conversational way in {{project_language}}.
Generate ONLY the question, nothing else.
""")
# Get locale info
locale_info = LocaleManager.get_locale(project_locale)
project_language = locale_info.get("name", "Turkish")
# Build missing params description with localized captions
missing_param_descriptions = []
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(project_locale)
missing_param_descriptions.append(f"{param_name} ({caption})")
# Build collected params description
collected_descriptions = []
for param_name, value in collected_params.items():
param = next((p for p in intent_config.parameters if p.name == param_name), None)
if param:
caption = param.get_caption_for_locale(project_locale)
collected_descriptions.append(f"{param_name} ({caption}): {value}")
# Build conversation history
conv_history = "\n".join([f"{msg['role']}: {msg['content']}" for msg in conversation[-5:]])
# Replace placeholders
prompt = collection_prompt
prompt = prompt.replace("{{conversation_history}}", conv_history)
prompt = prompt.replace("{{intent_name}}", intent_config.name)
prompt = prompt.replace("{{intent_caption}}", intent_config.caption or intent_config.name)
prompt = prompt.replace("{{collected_params}}", "\n".join(collected_descriptions) if collected_descriptions else "None")
prompt = prompt.replace("{{missing_params}}", ", ".join(missing_param_descriptions))
prompt = prompt.replace("{{unanswered_params}}", ", ".join(unanswered_params) if unanswered_params else "None")
prompt = prompt.replace("{{max_params}}", str(collection_config.get("max_params_per_question", 2)))
prompt = prompt.replace("{{project_language}}", project_language)
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 |