Spaces:
Building
Building
Delete prompt_builder.py
Browse files- prompt_builder.py +0 -354
prompt_builder.py
DELETED
@@ -1,354 +0,0 @@
|
|
1 |
-
"""
|
2 |
-
Flare – Prompt Builder (Refactored with Multi-language Support)
|
3 |
-
==============================================================
|
4 |
-
"""
|
5 |
-
|
6 |
-
from typing import List, Dict, Any
|
7 |
-
from datetime import datetime, timedelta
|
8 |
-
from config_provider import ConfigProvider
|
9 |
-
from logger import log_info, log_error, log_warning, log_debug
|
10 |
-
from locale_manager import LocaleManager
|
11 |
-
|
12 |
-
# Date helper for locale-aware date expressions
|
13 |
-
def _get_date_context(locale_code: str = "tr") -> Dict[str, str]:
|
14 |
-
"""Generate date context for date expressions"""
|
15 |
-
now = datetime.now()
|
16 |
-
|
17 |
-
# Get locale data
|
18 |
-
locale_data = LocaleManager.get_locale(locale_code)
|
19 |
-
weekdays = locale_data.get("weekdays", ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
|
20 |
-
|
21 |
-
today_weekday = weekdays[now.weekday()]
|
22 |
-
|
23 |
-
# Calculate various dates
|
24 |
-
dates = {
|
25 |
-
"today": now.strftime("%Y-%m-%d"),
|
26 |
-
"tomorrow": (now + timedelta(days=1)).strftime("%Y-%m-%d"),
|
27 |
-
"day_after_tomorrow": (now + timedelta(days=2)).strftime("%Y-%m-%d"),
|
28 |
-
"this_weekend_saturday": (now + timedelta(days=(5-now.weekday())%7)).strftime("%Y-%m-%d"),
|
29 |
-
"this_weekend_sunday": (now + timedelta(days=(6-now.weekday())%7)).strftime("%Y-%m-%d"),
|
30 |
-
"next_week_same_day": (now + timedelta(days=7)).strftime("%Y-%m-%d"),
|
31 |
-
"two_weeks_later": (now + timedelta(days=14)).strftime("%Y-%m-%d"),
|
32 |
-
"today_weekday": today_weekday,
|
33 |
-
"today_day": now.day,
|
34 |
-
"today_month": now.month,
|
35 |
-
"today_year": now.year,
|
36 |
-
"locale_code": locale_code
|
37 |
-
}
|
38 |
-
|
39 |
-
return dates
|
40 |
-
|
41 |
-
def _build_locale_aware_date_prompt(param, date_ctx: Dict, locale_data: Dict, locale_code: str) -> str:
|
42 |
-
"""Build locale-aware date extraction prompt"""
|
43 |
-
|
44 |
-
# Get locale-specific date patterns
|
45 |
-
date_patterns = locale_data.get("date_patterns", {})
|
46 |
-
months = locale_data.get("months", [])
|
47 |
-
|
48 |
-
prompt_parts = [f"• {param.name}: {param.extraction_prompt}"]
|
49 |
-
prompt_parts.append(f" IMPORTANT DATE RULES for {locale_data.get('name', 'this language')}:")
|
50 |
-
|
51 |
-
# Add locale-specific patterns
|
52 |
-
if locale_code == "tr":
|
53 |
-
prompt_parts.extend([
|
54 |
-
f" - 'bugün' = {date_ctx['today']}",
|
55 |
-
f" - 'yarın' = {date_ctx['tomorrow']}",
|
56 |
-
f" - 'öbür gün' = {date_ctx['day_after_tomorrow']}",
|
57 |
-
f" - 'bu hafta sonu' = {date_ctx['this_weekend_saturday']} or {date_ctx['this_weekend_sunday']}",
|
58 |
-
f" - 'bu cumartesi' = {date_ctx['this_weekend_saturday']}",
|
59 |
-
f" - 'bu pazar' = {date_ctx['this_weekend_sunday']}",
|
60 |
-
f" - 'haftaya' or 'gelecek hafta' = add 7 days to current date",
|
61 |
-
f" - 'haftaya bugün' = {date_ctx['next_week_same_day']}",
|
62 |
-
f" - 'iki hafta sonra' = {date_ctx['two_weeks_later']}",
|
63 |
-
f" - '15 gün sonra' = add 15 days to today",
|
64 |
-
f" - '10 Temmuz' = {date_ctx['today_year']}-07-10",
|
65 |
-
f" - Turkish months: Ocak=01, Şubat=02, Mart=03, Nisan=04, Mayıs=05, Haziran=06, "
|
66 |
-
f"Temmuz=07, Ağustos=08, Eylül=09, Ekim=10, Kasım=11, Aralık=12"
|
67 |
-
])
|
68 |
-
elif locale_code == "en":
|
69 |
-
prompt_parts.extend([
|
70 |
-
f" - 'today' = {date_ctx['today']}",
|
71 |
-
f" - 'tomorrow' = {date_ctx['tomorrow']}",
|
72 |
-
f" - 'day after tomorrow' = {date_ctx['day_after_tomorrow']}",
|
73 |
-
f" - 'this weekend' = {date_ctx['this_weekend_saturday']} or {date_ctx['this_weekend_sunday']}",
|
74 |
-
f" - 'this Saturday' = {date_ctx['this_weekend_saturday']}",
|
75 |
-
f" - 'this Sunday' = {date_ctx['this_weekend_sunday']}",
|
76 |
-
f" - 'next week' = add 7 days to current date",
|
77 |
-
f" - 'next {date_ctx['today_weekday']}' = {date_ctx['next_week_same_day']}",
|
78 |
-
f" - 'in two weeks' = {date_ctx['two_weeks_later']}",
|
79 |
-
f" - 'July 10' or '10th of July' = {date_ctx['today_year']}-07-10",
|
80 |
-
f" - English months: January=01, February=02, March=03, April=04, May=05, June=06, "
|
81 |
-
f"July=07, August=08, September=09, October=10, November=11, December=12"
|
82 |
-
])
|
83 |
-
|
84 |
-
# Add month mappings if available
|
85 |
-
if months:
|
86 |
-
month_mapping = [f"{month}={i+1:02d}" for i, month in enumerate(months)]
|
87 |
-
prompt_parts.append(f" - Month names: {', '.join(month_mapping)}")
|
88 |
-
|
89 |
-
return "\n".join(prompt_parts)
|
90 |
-
|
91 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
92 |
-
# INTENT PROMPT
|
93 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
94 |
-
def build_intent_prompt(version: Any, # VersionConfig
|
95 |
-
conversation: List[Dict[str, str]],
|
96 |
-
project_locale: str) -> str:
|
97 |
-
"""Build intent detection prompt with enhanced detection prompts and examples"""
|
98 |
-
|
99 |
-
# Get config
|
100 |
-
cfg = ConfigProvider.get()
|
101 |
-
|
102 |
-
# Get internal prompt from LLM provider settings
|
103 |
-
internal_prompt = ""
|
104 |
-
if cfg.global_config.llm_provider and cfg.global_config.llm_provider.settings:
|
105 |
-
internal_prompt = cfg.global_config.llm_provider.settings.get("internal_prompt", "")
|
106 |
-
|
107 |
-
# Extract intent names and captions
|
108 |
-
intent_names = [it.name for it in version.intents]
|
109 |
-
intent_captions = [str(it.caption) if it.caption else it.name for it in version.intents]
|
110 |
-
|
111 |
-
# Get project language name
|
112 |
-
locale_data = LocaleManager.get_locale(project_locale)
|
113 |
-
project_language = locale_data.get("name", "Turkish")
|
114 |
-
current_language_name = project_language
|
115 |
-
|
116 |
-
# Replace placeholders in internal prompt
|
117 |
-
if internal_prompt:
|
118 |
-
# Intent names - quoted and comma-separated
|
119 |
-
intent_names_str = ', '.join([f'"{name}"' for name in intent_names])
|
120 |
-
internal_prompt = internal_prompt.replace("<intent names>", intent_names_str)
|
121 |
-
|
122 |
-
# Intent captions - quoted and comma-separated
|
123 |
-
intent_captions_str = ', '.join([f'"{caption}"' for caption in intent_captions])
|
124 |
-
internal_prompt = internal_prompt.replace("<intent captions>", intent_captions_str)
|
125 |
-
|
126 |
-
# Project language
|
127 |
-
internal_prompt = internal_prompt.replace("<project language>", project_language)
|
128 |
-
internal_prompt = internal_prompt.replace("{{current_language_name}}", current_language_name)
|
129 |
-
internal_prompt = internal_prompt.replace("{{project_language}}", project_language)
|
130 |
-
|
131 |
-
# === ENHANCED INTENT INDEX WITH DETECTION PROMPTS AND EXAMPLES ===
|
132 |
-
lines = ["### INTENT DETECTION RULES ###"]
|
133 |
-
for it in version.intents:
|
134 |
-
lines.append(f"\n{it.name}:")
|
135 |
-
|
136 |
-
# Add detection prompt
|
137 |
-
if it.detection_prompt:
|
138 |
-
lines.append(f" Detection Rule: {it.detection_prompt}")
|
139 |
-
|
140 |
-
# Add examples to enhance detection
|
141 |
-
examples = it.get_examples_for_locale(project_locale)
|
142 |
-
if examples:
|
143 |
-
# Combine detection prompt with examples
|
144 |
-
examples_str = " | ".join([f'"{ex}"' for ex in examples[:5]]) # Max 5 examples
|
145 |
-
lines.append(f" Examples that match this intent: {examples_str}")
|
146 |
-
|
147 |
-
# If we have both detection prompt and examples, make it clear
|
148 |
-
if it.detection_prompt and examples:
|
149 |
-
lines.append(f" → This intent should be detected when user says something similar to the examples above AND matches the detection rule.")
|
150 |
-
|
151 |
-
intent_index = "\n".join(lines)
|
152 |
-
|
153 |
-
# === HISTORY ===
|
154 |
-
history_block = "\n".join(
|
155 |
-
f"{m['role'].upper()}: {m['content']}" for m in conversation[-10:]
|
156 |
-
)
|
157 |
-
|
158 |
-
# Combine prompts
|
159 |
-
combined_prompt = internal_prompt + "\n\n" + version.general_prompt if internal_prompt else version.general_prompt
|
160 |
-
|
161 |
-
# Get last user message
|
162 |
-
user_input = conversation[-1]['content'] if conversation else ""
|
163 |
-
|
164 |
-
prompt = (
|
165 |
-
f"{combined_prompt}\n\n"
|
166 |
-
f"{intent_index}\n\n"
|
167 |
-
f"Conversation so far:\n{history_block}\n\n"
|
168 |
-
f"USER: {user_input.strip()}"
|
169 |
-
)
|
170 |
-
|
171 |
-
log_info("✅ Intent prompt built with enhanced detection prompts and examples")
|
172 |
-
return prompt
|
173 |
-
|
174 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
175 |
-
# PARAMETER PROMPT
|
176 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
177 |
-
_FMT = """#PARAMETERS:{"extracted":[{"name":"<param>","value":"<val>"},...],"missing":["<param>",...]}"""
|
178 |
-
|
179 |
-
def build_parameter_prompt(
|
180 |
-
version: Any, # VersionConfig
|
181 |
-
intent_config: Any, # IntentConfig
|
182 |
-
chat_history: List[Dict[str, str]],
|
183 |
-
collected_params: Dict[str, Any],
|
184 |
-
missing_params: List[str],
|
185 |
-
params_to_ask: List[str],
|
186 |
-
max_params: int,
|
187 |
-
project_locale: str,
|
188 |
-
unanswered_params: List[str] = None
|
189 |
-
) -> str:
|
190 |
-
"""Build parameter collection prompt with approval support"""
|
191 |
-
|
192 |
-
# Check if we're asking for approval parameter
|
193 |
-
is_approval_question = len(params_to_ask) == 1 and params_to_ask[0] == "is_approved"
|
194 |
-
|
195 |
-
if is_approval_question:
|
196 |
-
# For approval, use special format without LLM collection prompt
|
197 |
-
# This will be handled in chat_handler with custom approval_question
|
198 |
-
return "" # Return empty, chat_handler will use custom question
|
199 |
-
|
200 |
-
# Normal parameter collection
|
201 |
-
cfg = ConfigProvider.get()
|
202 |
-
collection_config = cfg.global_config.llm_provider.settings.get("parameter_collection_config", {})
|
203 |
-
collection_prompt = collection_config.get("collection_prompt", "")
|
204 |
-
|
205 |
-
if not collection_prompt:
|
206 |
-
# Fallback prompt
|
207 |
-
collection_prompt = "Ask for the missing parameters naturally."
|
208 |
-
|
209 |
-
# Build conversation history string
|
210 |
-
history_str = "\n".join([
|
211 |
-
f"{msg['role'].upper()}: {msg['content']}"
|
212 |
-
for msg in chat_history[-5:] # Last 5 messages
|
213 |
-
])
|
214 |
-
|
215 |
-
# Build collected params string
|
216 |
-
collected_str = "\n".join([
|
217 |
-
f"- {k}: {v}" for k, v in collected_params.items()
|
218 |
-
])
|
219 |
-
|
220 |
-
# Build missing params string with captions
|
221 |
-
missing_str = []
|
222 |
-
for param_name in missing_params:
|
223 |
-
param = next((p for p in intent_config.parameters if p.name == param_name), None)
|
224 |
-
if param:
|
225 |
-
caption = param.get_caption_for_locale(project_locale) if hasattr(param, 'get_caption_for_locale') else param_name
|
226 |
-
missing_str.append(f"- {param_name} ({caption})")
|
227 |
-
else:
|
228 |
-
missing_str.append(f"- {param_name}")
|
229 |
-
missing_str = "\n".join(missing_str)
|
230 |
-
|
231 |
-
# Build unanswered params string
|
232 |
-
unanswered_str = "\n".join([f"- {p}" for p in (unanswered_params or [])])
|
233 |
-
|
234 |
-
# Replace placeholders
|
235 |
-
prompt = collection_prompt
|
236 |
-
prompt = prompt.replace("{{conversation_history}}", history_str)
|
237 |
-
prompt = prompt.replace("{{intent_name}}", intent_config.name)
|
238 |
-
prompt = prompt.replace("{{intent_caption}}", str(intent_config.caption))
|
239 |
-
prompt = prompt.replace("{{collected_params}}", collected_str)
|
240 |
-
prompt = prompt.replace("{{missing_params}}", missing_str)
|
241 |
-
prompt = prompt.replace("{{unanswered_params}}", unanswered_str)
|
242 |
-
prompt = prompt.replace("{{max_params}}", str(max_params))
|
243 |
-
prompt = prompt.replace("{{project_language}}", project_locale)
|
244 |
-
prompt = prompt.replace("{{current_language_name}}", project_locale) # For compatibility
|
245 |
-
|
246 |
-
return prompt
|
247 |
-
|
248 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
249 |
-
# SMART PARAMETER COLLECTION PROMPT
|
250 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
251 |
-
def build_smart_parameter_question_prompt(intent_cfg,
|
252 |
-
missing_params: List[str],
|
253 |
-
conversation: List[Dict[str, str]],
|
254 |
-
collection_config: Dict[str, Any],
|
255 |
-
project_language: str) -> str:
|
256 |
-
"""Build prompt for smart parameter collection"""
|
257 |
-
|
258 |
-
# Get the collection prompt template
|
259 |
-
template = collection_config.get("collection_prompt", "Ask for the missing parameters.")
|
260 |
-
|
261 |
-
# Replace placeholders
|
262 |
-
prompt = template.replace("{{max_params}}", str(collection_config.get("max_params_per_question", 2)))
|
263 |
-
prompt = prompt.replace("{{project_language}}", project_language)
|
264 |
-
|
265 |
-
# Add parameter information
|
266 |
-
param_info = []
|
267 |
-
for param_name in missing_params[:collection_config.get("max_params_per_question", 2)]:
|
268 |
-
param = next((p for p in intent_cfg.parameters if p.name == param_name), None)
|
269 |
-
if param:
|
270 |
-
# Get caption for default locale (first supported locale)
|
271 |
-
caption = param.get_caption_for_locale("tr") # Default to Turkish
|
272 |
-
param_info.append(f"- {param_name}: {caption}")
|
273 |
-
|
274 |
-
# Add context
|
275 |
-
parts = [
|
276 |
-
prompt,
|
277 |
-
"",
|
278 |
-
"Missing parameters:",
|
279 |
-
"\n".join(param_info),
|
280 |
-
"",
|
281 |
-
"Recent conversation:"
|
282 |
-
]
|
283 |
-
|
284 |
-
# Add recent conversation
|
285 |
-
for msg in conversation[-5:]:
|
286 |
-
parts.append(f"{msg['role'].upper()}: {msg['content']}")
|
287 |
-
|
288 |
-
return "\n".join(parts)
|
289 |
-
|
290 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
291 |
-
# PARAMETER EXTRACTION FROM QUESTION
|
292 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
293 |
-
def extract_params_from_question(question: str, param_names: List[str]) -> Dict[str, str]:
|
294 |
-
"""Extract parameters that might be embedded in the question itself"""
|
295 |
-
extracted = {}
|
296 |
-
|
297 |
-
# Simple pattern matching for common cases
|
298 |
-
# This is a basic implementation - can be enhanced with NLP
|
299 |
-
|
300 |
-
# Example: "İstanbul'dan Ankara'ya ne zaman gitmek istiyorsunuz?"
|
301 |
-
# Could extract origin=İstanbul, destination=Ankara
|
302 |
-
|
303 |
-
# For now, return empty dict
|
304 |
-
# This function can be enhanced based on specific use cases
|
305 |
-
|
306 |
-
return extracted
|
307 |
-
|
308 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
309 |
-
# API RESPONSE PROMPT
|
310 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
311 |
-
def build_api_response_prompt(api_config, api_response: Dict) -> str:
|
312 |
-
"""Build prompt for API response with mappings"""
|
313 |
-
|
314 |
-
response_prompt = api_config.response_prompt
|
315 |
-
if not response_prompt:
|
316 |
-
return "İşlem başarıyla tamamlandı."
|
317 |
-
|
318 |
-
# Apply response mappings if available
|
319 |
-
mapped_data = {}
|
320 |
-
if hasattr(api_config, 'response_mappings'):
|
321 |
-
for mapping in api_config.response_mappings:
|
322 |
-
field_path = mapping.get('field_path', '')
|
323 |
-
display_name = mapping.get('display_name', field_path)
|
324 |
-
|
325 |
-
# Extract value from response
|
326 |
-
value = _extract_value_from_path(api_response, field_path)
|
327 |
-
if value is not None:
|
328 |
-
mapped_data[display_name] = value
|
329 |
-
|
330 |
-
# Replace placeholders in response prompt
|
331 |
-
for key, value in mapped_data.items():
|
332 |
-
response_prompt = response_prompt.replace(f"{{{key}}}", str(value))
|
333 |
-
|
334 |
-
# Also try direct field replacement
|
335 |
-
for key, value in api_response.items():
|
336 |
-
response_prompt = response_prompt.replace(f"{{{key}}}", str(value))
|
337 |
-
|
338 |
-
return response_prompt
|
339 |
-
|
340 |
-
def _extract_value_from_path(data: Dict, path: str) -> Any:
|
341 |
-
"""Extract value from nested dict using dot notation"""
|
342 |
-
try:
|
343 |
-
parts = path.split('.')
|
344 |
-
value = data
|
345 |
-
for part in parts:
|
346 |
-
if isinstance(value, dict):
|
347 |
-
value = value.get(part)
|
348 |
-
elif isinstance(value, list) and part.isdigit():
|
349 |
-
value = value[int(part)]
|
350 |
-
else:
|
351 |
-
return None
|
352 |
-
return value
|
353 |
-
except:
|
354 |
-
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|