File size: 6,188 Bytes
f91eed4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
from fastapi import Request
from fastapi.responses import JSONResponse
import traceback, random
from intent import extract_parameters, validate_variable_formats, execute_intent, detect_intent
from llm_model import generate_response, model, tokenizer, Message
from log import log

DEBUG = True

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."}

        # === INTENT TESPİTİ ===
        detected_intent, intent_conf = None, 0.0
        if s_config.INTENT_MODEL:
            detected_intent, intent_conf = await detect_intent(user_input)
            if DEBUG:
                log(f"🎯 Intent tespiti: {detected_intent}, Confidence: {intent_conf:.2f}")

        current_intent = session.get("last_intent")
        awaiting_variable = session.get("awaiting_variable")

        if DEBUG:
            log(f"📦 Session: {session}")
            log(f"🧩 Awaiting: {awaiting_variable}, Last Intent: {current_intent}")

        # === KONU DEĞİŞİKLİĞİ TESPİTİ ===
        if (
            awaiting_variable and
            detected_intent and
            detected_intent != current_intent and
            intent_conf > s_config.INTENT_CONFIDENCE_THRESHOLD
        ):
            log("🧹 Konu değişikliği algılandı → context sıfırlanıyor")
            session["awaiting_variable"] = None
            session["variables"] = {}
            session["last_intent"] = detected_intent
            current_intent = detected_intent

        # === INTENT GEÇERLİ Mİ? ===
        intent_is_valid = (
            detected_intent and
            intent_conf > s_config.INTENT_CONFIDENCE_THRESHOLD and
            detected_intent in s_config.INTENT_DEFINITIONS
        )
        if DEBUG:
            log(f"✅ Intent geçerli mi?: {intent_is_valid}")

        if intent_is_valid:
            session["last_intent"] = detected_intent
            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", {})

            # === AWAITING PARAMETRE TAMAMLANDI MI? ===
            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

            # === TÜM PARAMETRELERİ TOPLA ===
            extracted = extract_parameters(pattern_list, user_input)
            variables = {p["key"]: p["value"] for p in extracted}
            session.setdefault("variables", {}).update(variables)

            if DEBUG:
                log(f"🧪 Tespit edilen parametreler: {variables}")

            # === VALIDASYON ===
            is_valid, validation_errors = validate_variable_formats(
                session["variables"],
                variable_format_map,
                data_formats
            )
            if DEBUG:
                log(f"📛 Validasyon hataları: {validation_errors}")

            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]}

            # === EKSİK VAR MI? ===
            expected_vars = list(variable_format_map.keys())
            missing_vars = [v for v in expected_vars if v not in session["variables"]]
            if DEBUG:
                log(f"📌 Beklenen parametreler: {expected_vars}, Eksik: {missing_vars}")

            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?"}

            # === INTENT ÇALIŞTIR ===
            log("🚀 execute_intent() çağrılıyor...")
            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)}

        # === LLM FALLBACK ===
        log("🤖 execute_intent çağrılmadı → LLM fallback devrede")
        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)