ciyidogan commited on
Commit
fe450e1
·
verified ·
1 Parent(s): e25edcf

Update chat_handler.py

Browse files
Files changed (1) hide show
  1. 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 intent_utils import extract_parameters, validate_variable_formats, detect_intent
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
- log("🚀 execute_intent() çağrılıyor...")
62
- result = execute_intent(
63
- current_intent,
64
- user_input,
65
- session.__dict__,
66
- {i["name"]: i for i in project_intents},
67
- data_formats,
68
- project_name,
69
- service_config
70
- )
71
- if "reply" in result:
72
- return {"reply": result["reply"]}
73
- elif "errors" in result:
74
- return {"response": list(result["errors"].values())[0]}
75
- else:
76
- return {"response": random.choice(project_config["fallback_answers"])}
77
- else:
78
- # Parametre yine çıkarılamadı konu değişmiş olabilir
79
- log("⚠️ Parametre bulunamadı → intent detect tetikleniyor")
80
- session.awaiting_variable = None
81
- session.variables = {}
82
-
83
- # 🧩 2. NORMAL INTENT DEĞERLENDİRMESİ
84
- detected_intent, intent_conf = await detect_intent(user_input, project_name)
85
- log(f"🎯 Intent tespit edildi: {detected_intent}, Confidence: {intent_conf:.2f}")
86
-
87
- intent_is_valid = (
88
- detected_intent and
89
- intent_conf > intent_conf_threshold and
90
- any(i["name"] == detected_intent for i in project_intents)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- log("🤖 execute_intent çağrılmadı → LLM fallback devrede")
142
- session.awaiting_variable = None
143
- session.variables = {}
144
- response, response_conf = await llm_model.generate_response(user_input, project_config)
145
- if response_conf is not None and response_conf < project_config["llm_confidence_treshold"]:
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 yokhavadan 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()