Spaces:
Paused
Paused
Create chat_handler.py
Browse files- chat_handler.py +113 -0
chat_handler.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import Request
|
| 2 |
+
from fastapi.responses import JSONResponse
|
| 3 |
+
import traceback, random
|
| 4 |
+
from intent import extract_parameters, validate_variable_formats, execute_intent, detect_intent
|
| 5 |
+
from llm_model import generate_response, model, tokenizer, Message
|
| 6 |
+
from log import log
|
| 7 |
+
|
| 8 |
+
async def handle_chat(msg: Message, request: Request, app, s_config):
|
| 9 |
+
user_input = msg.user_input.strip()
|
| 10 |
+
session_id = request.headers.get("X-Session-ID", "demo-session")
|
| 11 |
+
|
| 12 |
+
if not hasattr(app.state, "session_store"):
|
| 13 |
+
app.state.session_store = {}
|
| 14 |
+
|
| 15 |
+
session_store = getattr(app.state, "session_store", {})
|
| 16 |
+
session = session_store.get(session_id, {
|
| 17 |
+
"session_id": session_id,
|
| 18 |
+
"variables": {},
|
| 19 |
+
"auth_tokens": {},
|
| 20 |
+
"last_intent": None,
|
| 21 |
+
"awaiting_variable": None
|
| 22 |
+
})
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
if model is None or tokenizer is None:
|
| 26 |
+
return {"error": "Model yüklenmedi."}
|
| 27 |
+
|
| 28 |
+
detected_intent, intent_conf = None, 0.0
|
| 29 |
+
if s_config.INTENT_MODEL:
|
| 30 |
+
detected_intent, intent_conf = await detect_intent(user_input)
|
| 31 |
+
log(f"🎯 Intent tespit edildi: {detected_intent} (conf={intent_conf:.2f})")
|
| 32 |
+
|
| 33 |
+
current_intent = session.get("last_intent")
|
| 34 |
+
awaiting_variable = session.get("awaiting_variable")
|
| 35 |
+
|
| 36 |
+
if (
|
| 37 |
+
awaiting_variable and
|
| 38 |
+
detected_intent and
|
| 39 |
+
detected_intent != current_intent and
|
| 40 |
+
intent_conf > s_config.INTENT_CONFIDENCE_THRESHOLD
|
| 41 |
+
):
|
| 42 |
+
log(f"🧹 Yeni intent: {detected_intent}, önceki: {current_intent} — awaiting sıfırlanıyor.")
|
| 43 |
+
session["awaiting_variable"] = None
|
| 44 |
+
session["variables"] = {}
|
| 45 |
+
session["last_intent"] = detected_intent
|
| 46 |
+
current_intent = detected_intent
|
| 47 |
+
|
| 48 |
+
if (
|
| 49 |
+
detected_intent and
|
| 50 |
+
intent_conf > s_config.INTENT_CONFIDENCE_THRESHOLD and
|
| 51 |
+
detected_intent in s_config.INTENT_DEFINITIONS
|
| 52 |
+
):
|
| 53 |
+
definition = s_config.INTENT_DEFINITIONS[detected_intent]
|
| 54 |
+
pattern_list = definition.get("variables", [])
|
| 55 |
+
data_formats = s_config.DATA_FORMATS
|
| 56 |
+
variable_format_map = definition.get("variable_formats", {})
|
| 57 |
+
|
| 58 |
+
if awaiting_variable:
|
| 59 |
+
extracted = extract_parameters(pattern_list, user_input)
|
| 60 |
+
for p in extracted:
|
| 61 |
+
if p["key"] == awaiting_variable:
|
| 62 |
+
session["variables"][awaiting_variable] = p["value"]
|
| 63 |
+
session["awaiting_variable"] = None
|
| 64 |
+
log(f"✅ Awaiting parametre tamamlandı: {awaiting_variable} = {p['value']}")
|
| 65 |
+
break
|
| 66 |
+
|
| 67 |
+
extracted = extract_parameters(pattern_list, user_input)
|
| 68 |
+
variables = {p["key"]: p["value"] for p in extracted}
|
| 69 |
+
session.setdefault("variables", {}).update(variables)
|
| 70 |
+
|
| 71 |
+
is_valid, validation_errors = validate_variable_formats(session["variables"], variable_format_map, data_formats)
|
| 72 |
+
if not is_valid:
|
| 73 |
+
session["awaiting_variable"] = list(validation_errors.keys())[0]
|
| 74 |
+
session_store[session_id] = session
|
| 75 |
+
app.state.session_store = session_store
|
| 76 |
+
return {"response": list(validation_errors.values())[0]}
|
| 77 |
+
|
| 78 |
+
expected_vars = list(variable_format_map.keys())
|
| 79 |
+
missing_vars = [v for v in expected_vars if v not in session["variables"]]
|
| 80 |
+
if missing_vars:
|
| 81 |
+
session["awaiting_variable"] = missing_vars[0]
|
| 82 |
+
session_store[session_id] = session
|
| 83 |
+
app.state.session_store = session_store
|
| 84 |
+
return {"response": f"Lütfen {missing_vars[0]} bilgisini belirtir misiniz?"}
|
| 85 |
+
|
| 86 |
+
result = execute_intent(
|
| 87 |
+
detected_intent,
|
| 88 |
+
user_input,
|
| 89 |
+
session,
|
| 90 |
+
s_config.INTENT_DEFINITIONS,
|
| 91 |
+
s_config.DATA_FORMATS
|
| 92 |
+
)
|
| 93 |
+
if "reply" in result:
|
| 94 |
+
session_store[session_id] = result["session"]
|
| 95 |
+
app.state.session_store = session_store
|
| 96 |
+
return {"reply": result["reply"]}
|
| 97 |
+
elif "errors" in result:
|
| 98 |
+
session_store[session_id] = result["session"]
|
| 99 |
+
app.state.session_store = session_store
|
| 100 |
+
return {"response": list(result["errors"].values())[0]}
|
| 101 |
+
else:
|
| 102 |
+
return {"response": random.choice(s_config.FALLBACK_ANSWERS)}
|
| 103 |
+
|
| 104 |
+
session["awaiting_variable"] = None
|
| 105 |
+
session["variables"] = {}
|
| 106 |
+
response, response_conf = await generate_response(user_input, s_config)
|
| 107 |
+
if response_conf is not None and response_conf < s_config.LLM_CONFIDENCE_THRESHOLD:
|
| 108 |
+
return {"response": random.choice(s_config.FALLBACK_ANSWERS)}
|
| 109 |
+
return {"response": response}
|
| 110 |
+
|
| 111 |
+
except Exception as e:
|
| 112 |
+
traceback.print_exc()
|
| 113 |
+
return JSONResponse(content={"error": str(e)}, status_code=500)
|