ciyidogan commited on
Commit
a38473c
·
verified ·
1 Parent(s): 77d0d4f

Update chat_handler.py

Browse files
Files changed (1) hide show
  1. chat_handler.py +104 -104
chat_handler.py CHANGED
@@ -1,105 +1,105 @@
1
- from fastapi import Request
2
- from fastapi.responses import JSONResponse
3
- import traceback
4
- import random
5
- from intent 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:
12
- user_input = msg.user_input.strip()
13
- project_name = session.project_name
14
- project_config = service_config.get_project_llm_config(project_name)
15
- project_intents = service_config.get_project_intents(project_name)
16
-
17
- if llm_model.model is None or llm_model.tokenizer is None:
18
- return {"error": f"{project_name} için model yüklenmedi."}
19
-
20
- detected_intent, intent_conf = await detect_intent(user_input)
21
- log(f"🎯 Intent tespit edildi: {detected_intent}, Confidence: {intent_conf:.2f}")
22
-
23
- current_intent = session.last_intent
24
- awaiting_variable = session.awaiting_variable
25
-
26
- if (
27
- awaiting_variable and
28
- detected_intent and
29
- detected_intent != current_intent and
30
- intent_conf > project_config["intent_confidence_treshold"]
31
- ):
32
- log("🧹 Konu değişikliği algılandı → context sıfırlanıyor")
33
- session.awaiting_variable = None
34
- session.variables = {}
35
- session.last_intent = detected_intent
36
- current_intent = detected_intent
37
-
38
- intent_is_valid = (
39
- detected_intent and
40
- intent_conf > project_config["intent_confidence_treshold"] and
41
- any(i["name"] == detected_intent for i in project_intents)
42
- )
43
- log(f"✅ Intent geçerli mi?: {intent_is_valid}")
44
-
45
- if intent_is_valid:
46
- session.last_intent = detected_intent
47
- intent_def = next(i for i in project_intents if i["name"] == detected_intent)
48
- pattern_list = intent_def.get("variables", [])
49
- variable_format_map = intent_def.get("variable_formats", {})
50
- data_formats = service_config.data_formats
51
-
52
- if awaiting_variable:
53
- extracted = extract_parameters(pattern_list, user_input)
54
- for p in extracted:
55
- if p["key"] == awaiting_variable:
56
- session.variables[awaiting_variable] = p["value"]
57
- session.awaiting_variable = None
58
- log(f"✅ Awaiting parametre tamamlandı: {awaiting_variable} = {p['value']}")
59
- break
60
-
61
- extracted = extract_parameters(pattern_list, user_input)
62
- variables = {p["key"]: p["value"] for p in extracted}
63
- session.variables.update(variables)
64
-
65
- is_valid, validation_errors = validate_variable_formats(session.variables, variable_format_map, data_formats)
66
- log(f"📛 Validasyon hataları: {validation_errors}")
67
-
68
- if not is_valid:
69
- session.awaiting_variable = list(validation_errors.keys())[0]
70
- return {"response": list(validation_errors.values())[0]}
71
-
72
- expected_vars = list(variable_format_map.keys())
73
- missing_vars = [v for v in expected_vars if v not in session.variables]
74
- log(f"📌 Beklenen parametreler: {expected_vars}, Eksik: {missing_vars}")
75
-
76
- if missing_vars:
77
- session.awaiting_variable = missing_vars[0]
78
- return {"response": f"Lütfen {missing_vars[0]} bilgisini belirtir misiniz?"}
79
-
80
- log("🚀 execute_intent() çağrılıyor...")
81
- result = execute_intent(
82
- detected_intent,
83
- user_input,
84
- session.__dict__,
85
- {i["name"]: i for i in project_intents},
86
- data_formats
87
- )
88
- if "reply" in result:
89
- return {"reply": result["reply"]}
90
- elif "errors" in result:
91
- return {"response": list(result["errors"].values())[0]}
92
- else:
93
- return {"response": random.choice(project_config["fallback_answers"])}
94
-
95
- log("🤖 execute_intent çağrılmadı → LLM fallback devrede")
96
- session.awaiting_variable = None
97
- session.variables = {}
98
- response, response_conf = await llm_model.generate_response(user_input, project_config)
99
- if response_conf is not None and response_conf < project_config["llm_confidence_treshold"]:
100
- return {"response": random.choice(project_config["fallback_answers"])}
101
- return {"response": response}
102
-
103
- except Exception as e:
104
- traceback.print_exc()
105
  return JSONResponse(content={"error": str(e)}, status_code=500)
 
1
+ from fastapi import Request
2
+ from fastapi.responses import JSONResponse
3
+ import traceback
4
+ import random
5
+ from intent 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:
12
+ user_input = msg.user_input.strip()
13
+ project_name = session.project_name
14
+ project_config = service_config.get_project_llm_config(project_name)
15
+ project_intents = service_config.get_project_intents(project_name)
16
+
17
+ if llm_model.model is None or llm_model.tokenizer is None:
18
+ return {"error": f"{project_name} için model yüklenmedi."}
19
+
20
+ detected_intent, intent_conf = await detect_intent(user_input, project_name)
21
+ log(f"🎯 Intent tespit edildi: {detected_intent}, Confidence: {intent_conf:.2f}")
22
+
23
+ current_intent = session.last_intent
24
+ awaiting_variable = session.awaiting_variable
25
+
26
+ if (
27
+ awaiting_variable and
28
+ detected_intent and
29
+ detected_intent != current_intent and
30
+ intent_conf > project_config["intent_confidence_treshold"]
31
+ ):
32
+ log("🧹 Konu değişikliği algılandı → context sıfırlanıyor")
33
+ session.awaiting_variable = None
34
+ session.variables = {}
35
+ session.last_intent = detected_intent
36
+ current_intent = detected_intent
37
+
38
+ intent_is_valid = (
39
+ detected_intent and
40
+ intent_conf > project_config["intent_confidence_treshold"] and
41
+ any(i["name"] == detected_intent for i in project_intents)
42
+ )
43
+ log(f"✅ Intent geçerli mi?: {intent_is_valid}")
44
+
45
+ if intent_is_valid:
46
+ session.last_intent = detected_intent
47
+ intent_def = next(i for i in project_intents if i["name"] == detected_intent)
48
+ pattern_list = intent_def.get("variables", [])
49
+ variable_format_map = intent_def.get("variable_formats", {})
50
+ data_formats = service_config.data_formats
51
+
52
+ if awaiting_variable:
53
+ extracted = extract_parameters(pattern_list, user_input)
54
+ for p in extracted:
55
+ if p["key"] == awaiting_variable:
56
+ session.variables[awaiting_variable] = p["value"]
57
+ session.awaiting_variable = None
58
+ log(f"✅ Awaiting parametre tamamlandı: {awaiting_variable} = {p['value']}")
59
+ break
60
+
61
+ extracted = extract_parameters(pattern_list, user_input)
62
+ variables = {p["key"]: p["value"] for p in extracted}
63
+ session.variables.update(variables)
64
+
65
+ is_valid, validation_errors = validate_variable_formats(session.variables, variable_format_map, data_formats)
66
+ log(f"📛 Validasyon hataları: {validation_errors}")
67
+
68
+ if not is_valid:
69
+ session.awaiting_variable = list(validation_errors.keys())[0]
70
+ return {"response": list(validation_errors.values())[0]}
71
+
72
+ expected_vars = list(variable_format_map.keys())
73
+ missing_vars = [v for v in expected_vars if v not in session.variables]
74
+ log(f"📌 Beklenen parametreler: {expected_vars}, Eksik: {missing_vars}")
75
+
76
+ if missing_vars:
77
+ session.awaiting_variable = missing_vars[0]
78
+ return {"response": f"Lütfen {missing_vars[0]} bilgisini belirtir misiniz?"}
79
+
80
+ log("🚀 execute_intent() çağrılıyor...")
81
+ result = execute_intent(
82
+ detected_intent,
83
+ user_input,
84
+ session.__dict__,
85
+ {i["name"]: i for i in project_intents},
86
+ data_formats
87
+ )
88
+ if "reply" in result:
89
+ return {"reply": result["reply"]}
90
+ elif "errors" in result:
91
+ return {"response": list(result["errors"].values())[0]}
92
+ else:
93
+ return {"response": random.choice(project_config["fallback_answers"])}
94
+
95
+ log("🤖 execute_intent çağrılmadı → LLM fallback devrede")
96
+ session.awaiting_variable = None
97
+ session.variables = {}
98
+ response, response_conf = await llm_model.generate_response(user_input, project_config)
99
+ if response_conf is not None and response_conf < project_config["llm_confidence_treshold"]:
100
+ return {"response": random.choice(project_config["fallback_answers"])}
101
+ return {"response": response}
102
+
103
+ except Exception as e:
104
+ traceback.print_exc()
105
  return JSONResponse(content={"error": str(e)}, status_code=500)