Spaces:
Running

axeronis commited on
Commit
7756d2d
·
1 Parent(s): 3fc8a71

feat: Smart correction with full settings analysis, detailed change report

Browse files
backend/app/api/demo.py CHANGED
@@ -113,12 +113,14 @@ async def demo_chat(
113
 
114
  class SmartCorrectionRequest(BaseModel):
115
  correction: str
 
116
 
117
 
118
  class SmartCorrectionResponse(BaseModel):
119
  success: bool
120
  changes: List[dict]
121
  message: str
 
122
 
123
 
124
  @router.post("/smart-correct", response_model=SmartCorrectionResponse)
@@ -128,8 +130,8 @@ async def smart_correct(
128
  session = Depends(get_async_session)
129
  ):
130
  """
131
- AI-powered correction that modifies actual tenant settings.
132
- Analyzes the correction text and determines which fields to update.
133
  """
134
  try:
135
  from google import genai
@@ -140,38 +142,72 @@ async def smart_correct(
140
  if not tenant:
141
  raise HTTPException(status_code=404, detail="Tenant not found")
142
 
143
- # Current settings for context
144
  ai_settings = tenant.ai_settings or {}
145
  ai_identity = ai_settings.get("ai_identity", {})
 
146
 
147
- # Ask AI to parse the correction
148
- parse_prompt = f"""Проанализируй правку пользователя и определи какие настройки AI нужно изменить.
149
-
150
- ПРАВКА ПОЛЬЗОВАТЕЛЯ: "{request.correction}"
151
-
152
- ТЕКУЩИЕ НАСТРОЙКИ:
153
- - bot_name: {ai_identity.get('bot_name', 'AI Assistant')}
154
- - bot_role: {ai_identity.get('bot_role', 'Менеджер')}
155
- - bot_gender: {ai_identity.get('bot_gender', 'female')}
156
- - banned_words: {ai_settings.get('banned_words', [])}
157
- - custom_instructions: {ai_settings.get('custom_instructions', '')[:200]}...
158
-
159
- ВОЗМОЖНЫЕ ИЗМЕНЕНИЯ:
160
- 1. "set_bot_name" - изменить имя бота
161
- 2. "set_bot_role" - изменить роль бота
162
- 3. "set_bot_gender" - изменить пол (male/female)
163
- 4. "add_banned_word" - добавить запрещённое слово
164
- 5. "remove_banned_word" - убрать запрещённое слово
165
- 6. "add_instruction" - добавить инструкцию
166
- 7. "set_tone" - изменить тон (Professional/Friendly/Empathetic/Bold)
167
-
168
- Верни ТОЛЬКО JSON массив изменений. Примеры:
169
- - "не говори бот" → [{{"action": "add_banned_word", "value": "бот"}}]
170
- - "ты Нова а не менеджер" → [{{"action": "set_bot_name", "value": "Нова"}}, {{"action": "set_bot_role", "value": "AI-ассистент"}}]
171
- - "будь женского пола" → [{{"action": "set_bot_gender", "value": "female"}}]
172
- - "не используй слово дёшево" → [{{"action": "add_banned_word", "value": "дёшево"}}]
173
-
174
- ВАЖНО: Верни ТОЛЬКО валидный JSON массив, без markdown и пояснений.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  """
176
 
177
  client = genai.Client(api_key=settings.GEMINI_API_KEY)
@@ -180,28 +216,31 @@ async def smart_correct(
180
  contents=parse_prompt
181
  )
182
 
183
- ai_response = response.text.strip() if response.text else "[]"
184
 
185
- # Clean markdown if present
186
  ai_response = re.sub(r'```json\s*', '', ai_response)
187
  ai_response = re.sub(r'```\s*', '', ai_response)
188
 
189
  # Parse JSON
190
  try:
191
- changes = json.loads(ai_response)
192
  except json.JSONDecodeError:
193
- # Try to extract JSON array
194
- match = re.search(r'\[.*\]', ai_response, re.DOTALL)
195
  if match:
196
- changes = json.loads(match.group())
197
  else:
198
- changes = []
 
 
 
199
 
200
  if not changes:
201
  return SmartCorrectionResponse(
202
  success=False,
203
  changes=[],
204
- message="Не удалось определить какие настройки изменить"
 
205
  )
206
 
207
  # Apply changes
@@ -210,47 +249,87 @@ async def smart_correct(
210
  for change in changes:
211
  action = change.get("action", "")
212
  value = change.get("value", "")
 
213
 
214
  if action == "set_bot_name" and value:
 
215
  if "ai_identity" not in ai_settings:
216
  ai_settings["ai_identity"] = {}
217
  ai_settings["ai_identity"]["bot_name"] = value
218
- applied_changes.append({"field": "Имя бота", "value": value})
 
 
 
 
 
 
219
 
220
  elif action == "set_bot_role" and value:
 
221
  if "ai_identity" not in ai_settings:
222
  ai_settings["ai_identity"] = {}
223
  ai_settings["ai_identity"]["bot_role"] = value
224
- applied_changes.append({"field": "Роль бот", "value": value})
 
 
 
 
 
 
225
 
226
  elif action == "set_bot_gender" and value in ["male", "female"]:
 
227
  if "ai_identity" not in ai_settings:
228
  ai_settings["ai_identity"] = {}
229
  ai_settings["ai_identity"]["bot_gender"] = value
230
- gender_text = "Женский" if value == "female" else "Мужской"
231
- applied_changes.append({"field": "Пол бота", "value": gender_text})
 
 
 
 
 
232
 
233
  elif action == "add_banned_word" and value:
234
  banned = ai_settings.get("banned_words", []) or []
235
  if value.lower() not in [w.lower() for w in banned]:
236
  banned.append(value)
237
  ai_settings["banned_words"] = banned
238
- applied_changes.append({"field": "Запрещённые слова", "value": f"+{value}"})
 
 
 
 
 
 
239
 
240
  elif action == "remove_banned_word" and value:
241
  banned = ai_settings.get("banned_words", []) or []
242
- ai_settings["banned_words"] = [w for w in banned if w.lower() != value.lower()]
243
- applied_changes.append({"field": "Запрещённые слова", "value": f"-{value}"})
 
 
 
 
 
 
 
244
 
245
  elif action == "add_instruction" and value:
246
  current = ai_settings.get("custom_instructions", "") or ""
247
  if value not in current:
248
- ai_settings["custom_instructions"] = current + "\n" + value if current else value
249
- applied_changes.append({"field": "Инструкции", "value": value[:50] + "..."})
 
 
 
 
 
 
 
250
 
251
  elif action == "set_tone" and value:
252
  valid_tones = ["Professional", "Friendly", "Empathetic", "Bold"]
253
- # Map Russian to English
254
  tone_map = {
255
  "профессиональный": "Professional",
256
  "дружелюбный": "Friendly",
@@ -259,29 +338,57 @@ async def smart_correct(
259
  }
260
  mapped = tone_map.get(value.lower(), value)
261
  if mapped in valid_tones:
 
262
  ai_settings["tone_of_voice"] = mapped
263
- applied_changes.append({"field": "Тон", "value": mapped})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
264
 
265
  if applied_changes:
266
- # Save to database
267
  tenant.ai_settings = ai_settings
268
  session.add(tenant)
269
  await session.commit()
270
 
271
- # Invalidate AI cache so changes take effect
272
  await memory_manager.invalidate_memory(session, tenant)
273
 
274
- changes_text = ", ".join([f"{c['field']}: {c['value']}" for c in applied_changes])
 
 
 
 
 
 
 
 
275
  return SmartCorrectionResponse(
276
  success=True,
277
  changes=applied_changes,
278
- message=f"Изменено: {changes_text}"
 
279
  )
280
  else:
281
  return SmartCorrectionResponse(
282
  success=False,
283
  changes=[],
284
- message="Изменения не применены"
 
285
  )
286
 
287
  except Exception as e:
 
113
 
114
  class SmartCorrectionRequest(BaseModel):
115
  correction: str
116
+ last_ai_response: Optional[str] = None # What AI said that was wrong
117
 
118
 
119
  class SmartCorrectionResponse(BaseModel):
120
  success: bool
121
  changes: List[dict]
122
  message: str
123
+ analysis: Optional[str] = None # Why AI was wrong
124
 
125
 
126
  @router.post("/smart-correct", response_model=SmartCorrectionResponse)
 
130
  session = Depends(get_async_session)
131
  ):
132
  """
133
+ AI-powered correction that analyzes WHY the bot responded incorrectly
134
+ and modifies the appropriate tenant settings to fix it.
135
  """
136
  try:
137
  from google import genai
 
142
  if not tenant:
143
  raise HTTPException(status_code=404, detail="Tenant not found")
144
 
145
+ # Get FULL settings context
146
  ai_settings = tenant.ai_settings or {}
147
  ai_identity = ai_settings.get("ai_identity", {})
148
+ playbook = tenant.playbook or {}
149
 
150
+ # Build comprehensive context
151
+ current_config = f"""
152
+ === ТЕКУЩИЕ НАСТРОЙКИ AI (tenant: {tenant.id}) ===
153
+
154
+ [ЛИЧНОСТЬ БОТА]
155
+ - Имя бота: {ai_identity.get('bot_name', 'AI Assistant')}
156
+ - Роль: {ai_identity.get('bot_role', 'Менеджер по продажам')}
157
+ - Пол: {ai_identity.get('bot_gender', 'female')}
158
+
159
+ [ТОН И СТИЛЬ]
160
+ - Тон общения: {ai_settings.get('tone_of_voice', 'Professional')}
161
+ - Методология продаж: {ai_settings.get('sales_methodology', 'Consultative')}
162
+
163
+ [ЗАПРЕТЫ]
164
+ - Запрещённые слова: {ai_settings.get('banned_words', [])}
165
+
166
+ [ИНСТРУКЦИИ]
167
+ {ai_settings.get('custom_instructions', '(пусто)')[:500]}
168
+
169
+ [PLAYBOOK - ЭТАПЫ ВОРОНКИ]
170
+ {json.dumps(playbook.get('stages', []), ensure_ascii=False, indent=2)[:800] if playbook.get('stages') else '(нет этапов)'}
171
+
172
+ [ДРУГОЕ]
173
+ - Идеальный клиент: {ai_settings.get('ideal_customer_profile', '(не задано)')[:200]}
174
+ - Описание бизнеса: {tenant.business_description[:200] if tenant.business_description else '(не задано)'}
175
+ """
176
+
177
+ # Build the analysis prompt
178
+ parse_prompt = f"""Ты эксперт по настройке AI-ассистентов. Пользователь указал проблему с ответом бота.
179
+
180
+ {current_config}
181
+
182
+ === ПРОБЛЕМА ПОЛЬЗОВАТЕЛЯ ===
183
+ "{request.correction}"
184
+ {f'Ответ бота который не понравился: "{request.last_ai_response}"' if request.last_ai_response else ''}
185
+
186
+ === ТВОЯ ЗАДАЧА ===
187
+ 1. Проанализируй ПОЧЕМУ бот мог ответить неправильно (какие настройки влияют)
188
+ 2. Определи какие КОНКРЕТНЫЕ настройки нужно изменить
189
+ 3. Верни JSON с изменениями
190
+
191
+ === ДОСТУПНЫЕ ДЕЙСТВИЯ ===
192
+ - "set_bot_name": изменить имя бота (value: нов��е имя)
193
+ - "set_bot_role": изменить роль (value: новая роль)
194
+ - "set_bot_gender": изменить пол (value: "male" или "female")
195
+ - "add_banned_word": добавить запрет (value: слово)
196
+ - "remove_banned_word": убрать запрет (value: слово)
197
+ - "add_instruction": добавить инструкцию (value: текст инструкции)
198
+ - "set_tone": изменить тон (value: Professional/Friendly/Empathetic/Bold)
199
+ - "update_ideal_customer": обновить профиль клиента (value: описание)
200
+
201
+ === ФОРМАТ ОТВЕТА ===
202
+ Верни JSON объект:
203
+ {{
204
+ "analysis": "Краткое объяснение почему бот отвечал неправильно",
205
+ "changes": [
206
+ {{"action": "действие", "value": "значение", "reason": "почему это исправит проблему"}}
207
+ ]
208
+ }}
209
+
210
+ ВАЖНО: Верни ТОЛЬКО валидный JSON, без ```json и без пояснений снаружи JSON.
211
  """
212
 
213
  client = genai.Client(api_key=settings.GEMINI_API_KEY)
 
216
  contents=parse_prompt
217
  )
218
 
219
+ ai_response = response.text.strip() if response.text else "{}"
220
 
221
+ # Clean markdown
222
  ai_response = re.sub(r'```json\s*', '', ai_response)
223
  ai_response = re.sub(r'```\s*', '', ai_response)
224
 
225
  # Parse JSON
226
  try:
227
+ result = json.loads(ai_response)
228
  except json.JSONDecodeError:
229
+ match = re.search(r'\{.*\}', ai_response, re.DOTALL)
 
230
  if match:
231
+ result = json.loads(match.group())
232
  else:
233
+ result = {"analysis": "", "changes": []}
234
+
235
+ analysis = result.get("analysis", "")
236
+ changes = result.get("changes", [])
237
 
238
  if not changes:
239
  return SmartCorrectionResponse(
240
  success=False,
241
  changes=[],
242
+ message="Не удалось определить какие настройки изменить",
243
+ analysis=analysis
244
  )
245
 
246
  # Apply changes
 
249
  for change in changes:
250
  action = change.get("action", "")
251
  value = change.get("value", "")
252
+ reason = change.get("reason", "")
253
 
254
  if action == "set_bot_name" and value:
255
+ old_value = ai_identity.get('bot_name', 'AI Assistant')
256
  if "ai_identity" not in ai_settings:
257
  ai_settings["ai_identity"] = {}
258
  ai_settings["ai_identity"]["bot_name"] = value
259
+ applied_changes.append({
260
+ "field": "Имя бота",
261
+ "section": "AI Мозг → Личность",
262
+ "old": old_value,
263
+ "new": value,
264
+ "reason": reason
265
+ })
266
 
267
  elif action == "set_bot_role" and value:
268
+ old_value = ai_identity.get('bot_role', 'Менеджер')
269
  if "ai_identity" not in ai_settings:
270
  ai_settings["ai_identity"] = {}
271
  ai_settings["ai_identity"]["bot_role"] = value
272
+ applied_changes.append({
273
+ "field": "Роль бота",
274
+ "section": "AI Мозг → Личность",
275
+ "old": old_value,
276
+ "new": value,
277
+ "reason": reason
278
+ })
279
 
280
  elif action == "set_bot_gender" and value in ["male", "female"]:
281
+ old_value = ai_identity.get('bot_gender', 'female')
282
  if "ai_identity" not in ai_settings:
283
  ai_settings["ai_identity"] = {}
284
  ai_settings["ai_identity"]["bot_gender"] = value
285
+ applied_changes.append({
286
+ "field": "Пол бота",
287
+ "section": "AI Мозг → Личность",
288
+ "old": "Женский" if old_value == "female" else "Мужской",
289
+ "new": "Ж��нский" if value == "female" else "Мужской",
290
+ "reason": reason
291
+ })
292
 
293
  elif action == "add_banned_word" and value:
294
  banned = ai_settings.get("banned_words", []) or []
295
  if value.lower() not in [w.lower() for w in banned]:
296
  banned.append(value)
297
  ai_settings["banned_words"] = banned
298
+ applied_changes.append({
299
+ "field": "Запрещённые слова",
300
+ "section": "AI Мозг → Фильтры",
301
+ "old": "(не было)",
302
+ "new": f"+{value}",
303
+ "reason": reason
304
+ })
305
 
306
  elif action == "remove_banned_word" and value:
307
  banned = ai_settings.get("banned_words", []) or []
308
+ if value.lower() in [w.lower() for w in banned]:
309
+ ai_settings["banned_words"] = [w for w in banned if w.lower() != value.lower()]
310
+ applied_changes.append({
311
+ "field": "Запрещённые слова",
312
+ "section": "AI Мозг → Фильтры",
313
+ "old": value,
314
+ "new": "(удалено)",
315
+ "reason": reason
316
+ })
317
 
318
  elif action == "add_instruction" and value:
319
  current = ai_settings.get("custom_instructions", "") or ""
320
  if value not in current:
321
+ new_instructions = current + "\n" + value if current else value
322
+ ai_settings["custom_instructions"] = new_instructions
323
+ applied_changes.append({
324
+ "field": "Инструкции",
325
+ "section": "AI Мозг → Глобальный промпт",
326
+ "old": "(добавлено новое)",
327
+ "new": value[:100] + ("..." if len(value) > 100 else ""),
328
+ "reason": reason
329
+ })
330
 
331
  elif action == "set_tone" and value:
332
  valid_tones = ["Professional", "Friendly", "Empathetic", "Bold"]
 
333
  tone_map = {
334
  "профессиональный": "Professional",
335
  "дружелюбный": "Friendly",
 
338
  }
339
  mapped = tone_map.get(value.lower(), value)
340
  if mapped in valid_tones:
341
+ old_value = ai_settings.get("tone_of_voice", "Professional")
342
  ai_settings["tone_of_voice"] = mapped
343
+ applied_changes.append({
344
+ "field": "Тон общения",
345
+ "section": "AI Мозг → Стиль",
346
+ "old": old_value,
347
+ "new": mapped,
348
+ "reason": reason
349
+ })
350
+
351
+ elif action == "update_ideal_customer" and value:
352
+ old_value = ai_settings.get("ideal_customer_profile", "")
353
+ ai_settings["ideal_customer_profile"] = value
354
+ applied_changes.append({
355
+ "field": "Идеальный клиент",
356
+ "section": "AI Мозг → Таргетинг",
357
+ "old": old_value[:50] + "..." if old_value else "(пусто)",
358
+ "new": value[:50] + "...",
359
+ "reason": reason
360
+ })
361
 
362
  if applied_changes:
363
+ # Save to database (tenant-specific)
364
  tenant.ai_settings = ai_settings
365
  session.add(tenant)
366
  await session.commit()
367
 
368
+ # Invalidate AI cache
369
  await memory_manager.invalidate_memory(session, tenant)
370
 
371
+ # Build detailed message
372
+ changes_lines = []
373
+ for c in applied_changes:
374
+ changes_lines.append(f"• {c['field']} ({c['section']}): {c['old']} → {c['new']}")
375
+
376
+ message = f"✅ Настройки обновлены:\n" + "\n".join(changes_lines)
377
+
378
+ logger.info(f"🔧 Smart correction for tenant {tenant.id}: {len(applied_changes)} changes")
379
+
380
  return SmartCorrectionResponse(
381
  success=True,
382
  changes=applied_changes,
383
+ message=message,
384
+ analysis=analysis
385
  )
386
  else:
387
  return SmartCorrectionResponse(
388
  success=False,
389
  changes=[],
390
+ message="Изменения не применены",
391
+ analysis=analysis
392
  )
393
 
394
  except Exception as e:
frontend/app/demo-chat/page.tsx CHANGED
@@ -227,17 +227,30 @@ export default function DemoChatPage() {
227
  )}
228
  >
229
  {msg.role === 'system' ? (
230
- <div className="px-3 py-2 bg-violet-500/10 border border-violet-500/20 rounded-xl max-w-[90%]">
231
- <div className="flex items-center gap-2 text-violet-300 text-xs">
232
- <CheckCircle className="w-3.5 h-3.5 flex-shrink-0" />
233
- <span>{msg.content}</span>
234
  </div>
235
  {msg.changes && msg.changes.length > 0 && (
236
- <div className="mt-1.5 flex flex-wrap gap-1">
237
- {msg.changes.map((c, i) => (
238
- <span key={i} className="px-1.5 py-0.5 bg-violet-500/20 text-violet-200 text-[10px] rounded-full">
239
- {c.field}: {c.value}
240
- </span>
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  ))}
242
  </div>
243
  )}
 
227
  )}
228
  >
229
  {msg.role === 'system' ? (
230
+ <div className="px-3 py-2 bg-violet-500/10 border border-violet-500/20 rounded-xl max-w-[95%]">
231
+ <div className="flex items-start gap-2 text-violet-300 text-xs">
232
+ <CheckCircle className="w-3.5 h-3.5 flex-shrink-0 mt-0.5" />
233
+ <div className="whitespace-pre-wrap">{msg.content}</div>
234
  </div>
235
  {msg.changes && msg.changes.length > 0 && (
236
+ <div className="mt-2 space-y-1 text-[11px]">
237
+ {msg.changes.map((c: any, i: number) => (
238
+ <div key={i} className="bg-violet-500/10 rounded-lg px-2 py-1.5">
239
+ <div className="text-violet-200 font-medium">{c.field}</div>
240
+ {c.section && (
241
+ <div className="text-violet-400/60 text-[10px]">{c.section}</div>
242
+ )}
243
+ {(c.old || c.new) && (
244
+ <div className="text-violet-300 mt-0.5">
245
+ <span className="text-red-400/70">{c.old}</span>
246
+ <span className="text-violet-400 mx-1">→</span>
247
+ <span className="text-green-400">{c.new}</span>
248
+ </div>
249
+ )}
250
+ {c.value && !c.new && (
251
+ <div className="text-violet-300">{c.value}</div>
252
+ )}
253
+ </div>
254
  ))}
255
  </div>
256
  )}