flare / prompt_builder.py
ciyidogan's picture
Update prompt_builder.py
e1ef72d verified
raw
history blame
15 kB
"""
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