Spaces:
Running
Running
Update chat_handler.py
Browse files- chat_handler.py +62 -129
chat_handler.py
CHANGED
@@ -2,10 +2,11 @@ from fastapi import Request
|
|
2 |
from fastapi.responses import JSONResponse
|
3 |
import traceback
|
4 |
import random
|
5 |
-
from
|
6 |
from intent_api import execute_intent
|
|
|
|
|
7 |
from log import log
|
8 |
-
from llm_model import Message, LLMModel
|
9 |
|
10 |
async def handle_chat(msg: Message, request: Request, app, service_config, session, llm_model: LLMModel):
|
11 |
try:
|
@@ -14,137 +15,69 @@ async def handle_chat(msg: Message, request: Request, app, service_config, sessi
|
|
14 |
|
15 |
project_name = session.project_name
|
16 |
project_config = service_config.get_project_llm_config(project_name)
|
17 |
-
project_intents = service_config.get_project_intents(project_name)
|
18 |
-
intent_conf_threshold = project_config["intent_confidence_treshold"]
|
19 |
-
|
20 |
-
if llm_model.model is None or llm_model.tokenizer is None:
|
21 |
-
return {"error": f"{project_name} için model yüklenmedi."}
|
22 |
-
|
23 |
-
current_intent = session.last_intent
|
24 |
-
awaiting_variable = session.awaiting_variable
|
25 |
-
|
26 |
-
# 🧩 1. PARAMETRE TAMAMLAMA MODU
|
27 |
-
if awaiting_variable and current_intent:
|
28 |
-
log(f"🔄 Parametre tamamlama modu: intent={current_intent}, beklenen={awaiting_variable}")
|
29 |
-
intent_def = next(i for i in project_intents if i["name"] == current_intent)
|
30 |
-
pattern_list = intent_def.get("variables", [])
|
31 |
-
variable_format_map = intent_def.get("variable_formats", {})
|
32 |
-
data_formats = service_config.data_formats
|
33 |
-
|
34 |
-
extracted = extract_parameters(pattern_list, user_input)
|
35 |
-
if extracted:
|
36 |
-
for p in extracted:
|
37 |
-
session.variables[p["key"]] = p["value"]
|
38 |
-
log(f"✅ Parametre dolduruldu: {p['key']} = {p['value']}")
|
39 |
-
session.awaiting_variable = None
|
40 |
-
|
41 |
-
# Doğrulama + execute_intent’e geçiş
|
42 |
-
is_valid, validation_errors = validate_variable_formats(session.variables, variable_format_map, data_formats)
|
43 |
-
log(f"📛 Validasyon hataları: {validation_errors}")
|
44 |
-
|
45 |
-
expected_vars = list(variable_format_map.keys())
|
46 |
-
missing_vars = [v for v in expected_vars if v not in session.variables]
|
47 |
-
log(f"📌 Beklenen parametreler: {expected_vars}, Eksik: {missing_vars}")
|
48 |
-
|
49 |
-
if not is_valid:
|
50 |
-
session.awaiting_variable = list(validation_errors.keys())[0]
|
51 |
-
return {"response": list(validation_errors.values())[0]}
|
52 |
-
|
53 |
-
if missing_vars:
|
54 |
-
if len(missing_vars) > 1:
|
55 |
-
ordered_list = ", ".join(missing_vars)
|
56 |
-
return {"response": f"Lütfen şu bilgileri sırayla belirtir misiniz: {ordered_list}."}
|
57 |
-
else:
|
58 |
-
session.awaiting_variable = missing_vars[0]
|
59 |
-
return {"response": f"Lütfen {missing_vars[0]} bilgisini belirtir misiniz?"}
|
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 |
-
log(f"✅ Intent geçerli mi?: {intent_is_valid}")
|
93 |
-
|
94 |
-
if intent_is_valid:
|
95 |
-
session.last_intent = detected_intent
|
96 |
-
intent_def = next(i for i in project_intents if i["name"] == detected_intent)
|
97 |
-
pattern_list = intent_def.get("variables", [])
|
98 |
-
variable_format_map = intent_def.get("variable_formats", {})
|
99 |
-
data_formats = service_config.data_formats
|
100 |
-
|
101 |
-
extracted = extract_parameters(pattern_list, user_input)
|
102 |
-
variables = {p["key"]: p["value"] for p in extracted}
|
103 |
-
session.variables.update(variables)
|
104 |
-
|
105 |
-
is_valid, validation_errors = validate_variable_formats(session.variables, variable_format_map, data_formats)
|
106 |
-
log(f"📛 Validasyon hataları: {validation_errors}")
|
107 |
-
|
108 |
-
expected_vars = list(variable_format_map.keys())
|
109 |
-
missing_vars = [v for v in expected_vars if v not in session.variables]
|
110 |
-
log(f"📌 Beklenen parametreler: {expected_vars}, Eksik: {missing_vars}")
|
111 |
-
|
112 |
-
if not is_valid:
|
113 |
-
session.awaiting_variable = list(validation_errors.keys())[0]
|
114 |
-
return {"response": list(validation_errors.values())[0]}
|
115 |
-
|
116 |
-
if missing_vars:
|
117 |
-
if len(missing_vars) > 1:
|
118 |
-
ordered_list = ", ".join(missing_vars)
|
119 |
-
return {"response": f"Lütfen şu bilgileri sırayla belirtir misiniz: {ordered_list}."}
|
120 |
-
else:
|
121 |
-
session.awaiting_variable = missing_vars[0]
|
122 |
-
return {"response": f"Lütfen {missing_vars[0]} bilgisini belirtir misiniz?"}
|
123 |
-
|
124 |
-
log("🚀 execute_intent() çağrılıyor...")
|
125 |
-
result = execute_intent(
|
126 |
-
detected_intent,
|
127 |
-
user_input,
|
128 |
-
session.__dict__,
|
129 |
-
{i["name"]: i for i in project_intents},
|
130 |
-
data_formats,
|
131 |
-
project_name,
|
132 |
-
service_config
|
133 |
-
)
|
134 |
-
if "reply" in result:
|
135 |
-
return {"reply": result["reply"]}
|
136 |
-
elif "errors" in result:
|
137 |
-
return {"response": list(result["errors"].values())[0]}
|
138 |
-
else:
|
139 |
-
return {"response": random.choice(project_config["fallback_answers"])}
|
140 |
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
return {"response": random.choice(project_config["fallback_answers"])}
|
147 |
-
return {"response": response}
|
148 |
|
149 |
except Exception as e:
|
150 |
traceback.print_exc()
|
|
|
2 |
from fastapi.responses import JSONResponse
|
3 |
import traceback
|
4 |
import random
|
5 |
+
from llm_model import Message, LLMModel
|
6 |
from intent_api import execute_intent
|
7 |
+
from intent_utils import validate_variable_formats
|
8 |
+
from parse_llm_blocks import parse_llm_blocks
|
9 |
from log import log
|
|
|
10 |
|
11 |
async def handle_chat(msg: Message, request: Request, app, service_config, session, llm_model: LLMModel):
|
12 |
try:
|
|
|
15 |
|
16 |
project_name = session.project_name
|
17 |
project_config = service_config.get_project_llm_config(project_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
+
# Chat history'ye user mesajını ekle
|
20 |
+
session.chat_history.append({"role": "user", "content": user_input})
|
21 |
+
|
22 |
+
# === LLM çağrısı
|
23 |
+
llm_response = await llm_model.generate_response_with_messages(session.chat_history, project_config)
|
24 |
+
log(f"🤖 LLM cevabı: {llm_response}")
|
25 |
+
|
26 |
+
# === LLM cevabını parse et
|
27 |
+
parsed = parse_llm_blocks(llm_response)
|
28 |
+
intent = parsed["intent"]
|
29 |
+
params = parsed["params"]
|
30 |
+
missing = parsed["missing"]
|
31 |
+
action_json = parsed["action_json"]
|
32 |
+
|
33 |
+
# Chat history'ye assistant cevabını ekle
|
34 |
+
session.chat_history.append({"role": "assistant", "content": llm_response})
|
35 |
+
|
36 |
+
# === INTENT yok → havadan sudan konuşma
|
37 |
+
if intent == "NONE":
|
38 |
+
session.awaiting_variable = None
|
39 |
+
session.last_intent = None
|
40 |
+
session.variables.clear()
|
41 |
+
return {"response": llm_response}
|
42 |
+
|
43 |
+
# === INTENT varsa
|
44 |
+
session.last_intent = intent
|
45 |
+
session.variables.update(params)
|
46 |
+
|
47 |
+
# Eksik parametre varsa
|
48 |
+
if missing:
|
49 |
+
session.awaiting_variable = missing[0]
|
50 |
+
return {"response": f"Lütfen {', '.join(missing)} bilgisini belirtir misiniz?"}
|
51 |
+
|
52 |
+
# === API çağrısı yap
|
53 |
+
intent_definitions = {i["name"]: i for i in service_config.get_project_intents(project_name)}
|
54 |
+
data_formats = service_config.data_formats
|
55 |
+
|
56 |
+
# Parametreleri validasyonla kontrol et (backend güvenlik katmanı)
|
57 |
+
variable_format_map = intent_definitions[intent].get("variable_formats", {})
|
58 |
+
is_valid, validation_errors = validate_variable_formats(session.variables, variable_format_map, data_formats)
|
59 |
+
|
60 |
+
if not is_valid:
|
61 |
+
session.awaiting_variable = list(validation_errors.keys())[0]
|
62 |
+
return {"response": list(validation_errors.values())[0]}
|
63 |
+
|
64 |
+
log("🚀 execute_intent() çağrılıyor...")
|
65 |
+
result = execute_intent(
|
66 |
+
intent,
|
67 |
+
user_input,
|
68 |
+
session.__dict__,
|
69 |
+
intent_definitions,
|
70 |
+
data_formats,
|
71 |
+
project_name,
|
72 |
+
service_config
|
73 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
|
75 |
+
if "reply" in result:
|
76 |
+
return {"reply": result["reply"]}
|
77 |
+
elif "errors" in result:
|
78 |
+
return {"response": list(result["errors"].values())[0]}
|
79 |
+
else:
|
80 |
return {"response": random.choice(project_config["fallback_answers"])}
|
|
|
81 |
|
82 |
except Exception as e:
|
83 |
traceback.print_exc()
|