ciyidogan commited on
Commit
8e23367
Β·
verified Β·
1 Parent(s): acba2e1

Update prompt_builder.py

Browse files
Files changed (1) hide show
  1. prompt_builder.py +96 -78
prompt_builder.py CHANGED
@@ -91,12 +91,10 @@ def _build_locale_aware_date_prompt(param, date_ctx: Dict, locale_data: Dict, lo
91
  # ─────────────────────────────────────────────────────────────────────────────
92
  # INTENT PROMPT
93
  # ─────────────────────────────────────────────────────────────────────────────
94
- def build_intent_prompt(general_prompt: str,
95
- conversation: List[Dict[str, str]],
96
- user_input: str,
97
- intents: List,
98
- project_name: str = None,
99
- project_locale: str = "tr") -> str:
100
 
101
  # Get config
102
  cfg = ConfigProvider.get()
@@ -107,12 +105,13 @@ def build_intent_prompt(general_prompt: str,
107
  internal_prompt = cfg.global_config.llm_provider.settings.get("internal_prompt", "")
108
 
109
  # Extract intent names and captions
110
- intent_names = [it.name for it in intents]
111
- intent_captions = [it.caption or it.name for it in intents]
112
 
113
  # Get project language name
114
  locale_data = LocaleManager.get_locale(project_locale)
115
  project_language = locale_data.get("name", "Turkish")
 
116
 
117
  # Replace placeholders in internal prompt
118
  if internal_prompt:
@@ -126,21 +125,28 @@ def build_intent_prompt(general_prompt: str,
126
 
127
  # Project language
128
  internal_prompt = internal_prompt.replace("<project language>", project_language)
 
 
129
 
130
- # === INTENT INDEX ===
131
- lines = ["### INTENT INDEX ###"]
132
- for it in intents:
133
- # IntentConfig object attribute access
134
- det = it.detection_prompt.strip() if it.detection_prompt else ""
135
- det_part = f' β€’ detection_prompt β†’ "{det}"' if det else ""
136
 
137
- # Get examples for project locale
 
 
 
 
138
  examples = it.get_examples_for_locale(project_locale)
139
- exs = " | ".join(examples) if examples else ""
140
- ex_part = f" β€’ examples β†’ {exs}" if exs else ""
141
-
142
- newline_between = "\n" if det_part and ex_part else ""
143
- lines.append(f"{it.name}:{det_part}{newline_between}{ex_part}")
 
 
 
144
 
145
  intent_index = "\n".join(lines)
146
 
@@ -150,7 +156,10 @@ def build_intent_prompt(general_prompt: str,
150
  )
151
 
152
  # Combine prompts
153
- combined_prompt = internal_prompt + "\n\n" + general_prompt if internal_prompt else general_prompt
 
 
 
154
 
155
  prompt = (
156
  f"{combined_prompt}\n\n"
@@ -158,7 +167,8 @@ def build_intent_prompt(general_prompt: str,
158
  f"Conversation so far:\n{history_block}\n\n"
159
  f"USER: {user_input.strip()}"
160
  )
161
- log("βœ… Intent prompt built (with internal prompt and locale support)")
 
162
  return prompt
163
 
164
  # ─────────────────────────────────────────────────────────────────────────────
@@ -166,65 +176,73 @@ def build_intent_prompt(general_prompt: str,
166
  # ─────────��───────────────────────────────────────────────────────────────────
167
  _FMT = """#PARAMETERS:{"extracted":[{"name":"<param>","value":"<val>"},...],"missing":["<param>",...]}"""
168
 
169
- def build_parameter_prompt(intent_cfg,
170
- missing_params: List[str],
171
- user_input: str,
172
- conversation: List[Dict[str, str]],
173
- locale_code: str = "tr") -> str:
174
-
175
- date_ctx = _get_date_context(locale_code)
176
- locale_data = LocaleManager.get_locale(locale_code)
177
-
178
- parts: List[str] = [
179
- f"You are extracting parameters from user messages in {locale_data.get('name', 'the target language')}.",
180
- f"Today is {date_ctx['today']} ({date_ctx['today_weekday']}). Tomorrow is {date_ctx['tomorrow']}.",
181
- "Extract ONLY the parameters listed below from the conversation.",
182
- "Look at BOTH the current message AND previous messages to find parameter values.",
183
- "If a parameter cannot be found, is invalid, or wasn't provided, keep it in the \"missing\" list.",
184
- "Never guess or make up values. Only extract values explicitly given by the user.",
185
- "",
186
- "IMPORTANT: If the user is NOT providing the requested parameter but instead:",
187
- "- Asking for recommendations or advice (e.g. 'nereye gitsem?', 'ΓΆnerin var mΔ±?')",
188
- "- Expressing uncertainty (e.g. 'tam net değil', 'emin değilim', 'bilmiyorum')",
189
- "- Changing the subject or asking something else",
190
- "Then DO NOT extract any value for that parameter. Keep it in the 'missing' list.",
191
- ""
192
- ]
193
-
194
- # Add parameter descriptions
195
- parts.append("Parameters to extract:")
196
- for p in intent_cfg.parameters:
197
- if p.name in missing_params:
198
- # Get localized caption
199
- caption = p.get_caption_for_locale(locale_code)
200
-
201
- # Special handling for date type parameters
202
- if p.type == "date":
203
- date_prompt = _build_locale_aware_date_prompt(
204
- p, date_ctx, locale_data, locale_code
205
- )
206
- parts.append(date_prompt)
207
- else:
208
- parts.append(f"β€’ {p.name}: {p.extraction_prompt} (Display: {caption})")
 
 
 
 
 
 
 
 
 
 
 
209
 
210
- # Add format instruction
211
- parts.append("")
212
- parts.append("IMPORTANT: Your response must start with '#PARAMETERS:' followed by the JSON.")
213
- parts.append("Return ONLY this format with no extra text before or after:")
214
- parts.append(_FMT)
215
 
216
- # Add conversation history
217
- history_block = "\n".join(
218
- f"{m['role'].upper()}: {m['content']}" for m in conversation[-10:]
219
- )
220
-
221
- prompt = (
222
- "\n".join(parts) +
223
- "\n\nConversation so far:\n" + history_block +
224
- "\n\nUSER: " + user_input.strip()
225
- )
 
226
 
227
- log(f"πŸ“ Parameter prompt built for missing: {missing_params} in locale: {locale_code}")
228
  return prompt
229
 
230
  # ─────────────────────────────────────────────────────────────────────────────
 
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()
 
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:
 
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
 
 
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"
 
167
  f"Conversation so far:\n{history_block}\n\n"
168
  f"USER: {user_input.strip()}"
169
  )
170
+
171
+ log("βœ… Intent prompt built with enhanced detection prompts and examples")
172
  return prompt
173
 
174
  # ─────────────────────────────────────────────────────────────────────────────
 
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
  # ─────────────────────────────────────────────────────────────────────────────