ciyidogan commited on
Commit
33209ce
·
verified ·
1 Parent(s): 331aa0a

Update chat_handler.py

Browse files
Files changed (1) hide show
  1. chat_handler.py +127 -0
chat_handler.py CHANGED
@@ -384,5 +384,132 @@ async def chat(req: ChatRequest, x_session_id: str = Header(...)):
384
  traceback.print_exc()
385
  raise HTTPException(status_code=500, detail=str(e))
386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
  # Initialize LLM on module load
388
  setup_llm_provider()
 
384
  traceback.print_exc()
385
  raise HTTPException(status_code=500, detail=str(e))
386
 
387
+ async def handle_new_message(session: Session, user_input: str) -> str:
388
+ """Handle new message (not parameter followup) - for WebSocket"""
389
+ try:
390
+ # Get version config from session
391
+ version = session.get_version_config()
392
+ if not version:
393
+ log("❌ Version config not found")
394
+ return "Bir hata oluştu. Lütfen tekrar deneyin."
395
+
396
+ # Get project config
397
+ project = next((p for p in cfg.projects if p.name == session.project_name), None)
398
+ if not project:
399
+ return "Proje konfigürasyonu bulunamadı."
400
+
401
+ # Build intent detection prompt
402
+ prompt = build_intent_prompt(version, session.chat_history, project.default_locale)
403
+
404
+ # Get LLM response
405
+ raw = await llm_generate(session, prompt, user_input)
406
+
407
+ # Empty response fallback
408
+ if not raw:
409
+ log("⚠️ Empty response from LLM")
410
+ return "Üzgünüm, mesajınızı anlayamadım. Lütfen tekrar dener misiniz?"
411
+
412
+ # Check for intent
413
+ intent_name, tail = _safe_intent_parse(raw)
414
+
415
+ if intent_name:
416
+ # Find intent config
417
+ intent_config = next((i for i in version.intents if i.name == intent_name), None)
418
+
419
+ if intent_config:
420
+ session.current_intent = intent_name
421
+ session.intent_config = intent_config
422
+ session.state = "collect_params"
423
+ log(f"🎯 Intent detected: {intent_name}")
424
+
425
+ # Check if parameters were already extracted
426
+ if tail and _extract_parameters_from_response(tail, session, intent_config):
427
+ log("📦 Some parameters extracted from initial response")
428
+
429
+ # Check what parameters are missing
430
+ missing_params = [
431
+ p for p in intent_config.parameters
432
+ if p.required and p.variable_name not in session.variables
433
+ ]
434
+
435
+ if not missing_params:
436
+ # All required parameters collected, execute API
437
+ return await _execute_api_call(session, intent_config)
438
+ else:
439
+ # Need to collect more parameters
440
+ param_prompt = build_parameter_prompt(
441
+ intent_config,
442
+ session.variables,
443
+ session.chat_history,
444
+ project.default_locale
445
+ )
446
+ param_question = await llm_generate(session, param_prompt, user_input)
447
+ return _trim_response(param_question)
448
+
449
+ # No intent detected, return general response
450
+ return _trim_response(raw)
451
+
452
+ except Exception as e:
453
+ log(f"❌ Error in handle_new_message: {e}")
454
+ return "Bir hata oluştu. Lütfen tekrar deneyin."
455
+
456
+ async def handle_parameter_followup(session: Session, user_input: str) -> str:
457
+ """Handle parameter collection followup - for WebSocket"""
458
+ try:
459
+ if not session.intent_config:
460
+ log("⚠️ No intent config in session")
461
+ session.reset_flow()
462
+ return "Üzgünüm, hangi işlem için bilgi istediğimi unuttum. Baştan başlayalım."
463
+
464
+ intent_config = session.intent_config
465
+
466
+ # Get project config
467
+ project = next((p for p in cfg.projects if p.name == session.project_name), None)
468
+ if not project:
469
+ return "Proje konfigürasyonu bulunamadı."
470
+
471
+ # Try to extract parameters from user message
472
+ param_prompt = f"""
473
+ Extract parameters from user message: "{user_input}"
474
+
475
+ Expected parameters:
476
+ {json.dumps([{
477
+ 'name': p.name,
478
+ 'type': p.type,
479
+ 'required': p.required,
480
+ 'extraction_prompt': p.extraction_prompt
481
+ } for p in intent_config.parameters if p.variable_name not in session.variables], ensure_ascii=False)}
482
+
483
+ Return as JSON object with parameter names as keys.
484
+ """
485
+
486
+ raw = await llm_generate(session, param_prompt, user_input)
487
+ _extract_parameters_from_response(raw, session, intent_config)
488
+
489
+ # Check what parameters are still missing
490
+ missing_params = [
491
+ p for p in intent_config.parameters
492
+ if p.required and p.variable_name not in session.variables
493
+ ]
494
+
495
+ if not missing_params:
496
+ # All parameters collected, execute API
497
+ return await _execute_api_call(session, intent_config)
498
+ else:
499
+ # Still need more parameters
500
+ param_prompt = build_parameter_prompt(
501
+ intent_config,
502
+ session.variables,
503
+ session.chat_history,
504
+ project.default_locale
505
+ )
506
+ param_question = await llm_generate(session, param_prompt, user_input)
507
+ return _trim_response(param_question)
508
+
509
+ except Exception as e:
510
+ log(f"❌ Error in handle_parameter_followup: {e}")
511
+ session.reset_flow()
512
+ return "Bir hata oluştu. Lütfen tekrar deneyin."
513
+
514
  # Initialize LLM on module load
515
  setup_llm_provider()