from fastapi import Request from fastapi.responses import JSONResponse import traceback, random from intent import extract_parameters, validate_variable_formats, detect_intent from intent_api import execute_intent from llm_model import generate_response, model, tokenizer, Message from log import log async def handle_chat(msg: Message, request: Request, app, s_config): user_input = msg.user_input.strip() session_id = request.headers.get("X-Session-ID", "demo-session") if not hasattr(app.state, "session_store"): app.state.session_store = {} session_store = getattr(app.state, "session_store", {}) session = session_store.get(session_id, { "session_id": session_id, "variables": {}, "auth_tokens": {}, "last_intent": None, "awaiting_variable": None }) try: if model is None or tokenizer is None: return {"error": "Model yüklenmedi."} detected_intent, intent_conf = None, 0.0 if s_config.INTENT_MODEL: detected_intent, intent_conf = await detect_intent(user_input) log(f"🎯 Intent tespit edildi: {detected_intent} (conf={intent_conf:.2f})") current_intent = session.get("last_intent") awaiting_variable = session.get("awaiting_variable") if ( awaiting_variable and detected_intent and detected_intent != current_intent and intent_conf > s_config.INTENT_CONFIDENCE_THRESHOLD ): log(f"🧹 Yeni intent: {detected_intent}, önceki: {current_intent} — awaiting sıfırlanıyor.") session["awaiting_variable"] = None session["variables"] = {} session["last_intent"] = detected_intent current_intent = detected_intent if ( detected_intent and intent_conf > s_config.INTENT_CONFIDENCE_THRESHOLD and detected_intent in s_config.INTENT_DEFINITIONS ): definition = s_config.INTENT_DEFINITIONS[detected_intent] pattern_list = definition.get("variables", []) data_formats = s_config.DATA_FORMATS variable_format_map = definition.get("variable_formats", {}) if awaiting_variable: extracted = extract_parameters(pattern_list, user_input) for p in extracted: if p["key"] == awaiting_variable: session["variables"][awaiting_variable] = p["value"] session["awaiting_variable"] = None log(f"✅ Awaiting parametre tamamlandı: {awaiting_variable} = {p['value']}") break extracted = extract_parameters(pattern_list, user_input) variables = {p["key"]: p["value"] for p in extracted} session.setdefault("variables", {}).update(variables) is_valid, validation_errors = validate_variable_formats(session["variables"], variable_format_map, data_formats) if not is_valid: session["awaiting_variable"] = list(validation_errors.keys())[0] session_store[session_id] = session app.state.session_store = session_store return {"response": list(validation_errors.values())[0]} expected_vars = list(variable_format_map.keys()) missing_vars = [v for v in expected_vars if v not in session["variables"]] if missing_vars: session["awaiting_variable"] = missing_vars[0] session_store[session_id] = session app.state.session_store = session_store return {"response": f"Lütfen {missing_vars[0]} bilgisini belirtir misiniz?"} result = execute_intent( detected_intent, user_input, session, s_config.INTENT_DEFINITIONS, s_config.DATA_FORMATS ) if "reply" in result: session_store[session_id] = result["session"] app.state.session_store = session_store return {"reply": result["reply"]} elif "errors" in result: session_store[session_id] = result["session"] app.state.session_store = session_store return {"response": list(result["errors"].values())[0]} else: return {"response": random.choice(s_config.FALLBACK_ANSWERS)} session["awaiting_variable"] = None session["variables"] = {} response, response_conf = await generate_response(user_input, s_config) if response_conf is not None and response_conf < s_config.LLM_CONFIDENCE_THRESHOLD: return {"response": random.choice(s_config.FALLBACK_ANSWERS)} return {"response": response} except Exception as e: traceback.print_exc() return JSONResponse(content={"error": str(e)}, status_code=500)