ciyidogan commited on
Commit
aeddf52
·
verified ·
1 Parent(s): 38daa78

Update intent_api.py

Browse files
Files changed (1) hide show
  1. intent_api.py +197 -198
intent_api.py CHANGED
@@ -1,198 +1,197 @@
1
- import intent_utils as intent
2
- import requests
3
- import traceback
4
- from log import log
5
- from core import llm_models
6
-
7
- def auth_token_handler(api_name, auth_config, session):
8
- try:
9
- token_info = session.get("auth_tokens", {}).get(api_name)
10
- if token_info and "token" in token_info:
11
- return token_info["token"], session
12
-
13
- auth_endpoint = auth_config.get("auth_endpoint")
14
- auth_body = auth_config.get("auth_body", {})
15
- token_path = auth_config.get("auth_token_path")
16
-
17
- if not auth_endpoint or not token_path:
18
- raise Exception("auth_endpoint veya token_path tanımsız")
19
-
20
- resolved_body = {
21
- k: intent.resolve_placeholders(str(v), session, session.get("variables", {})) for k, v in auth_body.items()
22
- }
23
-
24
- response = requests.post(auth_endpoint, json=resolved_body, timeout=5)
25
- response.raise_for_status()
26
- json_resp = response.json()
27
-
28
- token_parts = token_path.split(".")
29
- token = json_resp
30
- for part in token_parts:
31
- token = token.get(part)
32
- if token is None:
33
- raise Exception(f"Token path çözülemedi: {token_path}")
34
-
35
- refresh_token = json_resp.get("refresh_token")
36
- session.setdefault("auth_tokens", {})[api_name] = {
37
- "token": token,
38
- "refresh_token": refresh_token
39
- }
40
-
41
- return token, session
42
-
43
- except Exception as e:
44
- log(f"❌ Auth token alınamadı: {e}")
45
- traceback.print_exc()
46
- raise e
47
-
48
- def refresh_auth_token(api_name, auth_config, session):
49
- try:
50
- refresh_endpoint = auth_config.get("auth_refresh_endpoint")
51
- refresh_body = auth_config.get("refresh_body", {})
52
- token_path = auth_config.get("auth_token_path")
53
-
54
- if not refresh_endpoint or not token_path:
55
- raise Exception("Refresh yapılandırması eksik")
56
-
57
- refresh_token = session.get("auth_tokens", {}).get(api_name, {}).get("refresh_token")
58
- if not refresh_token:
59
- raise Exception("Mevcut refresh token bulunamadı")
60
-
61
- resolved_body = {
62
- k: intent.resolve_placeholders(str(v), session, session.get("variables", {})) for k, v in refresh_body.items()
63
- }
64
-
65
- response = requests.post(refresh_endpoint, json=resolved_body, timeout=5)
66
- response.raise_for_status()
67
- json_resp = response.json()
68
-
69
- token_parts = token_path.split(".")
70
- token = json_resp
71
- for part in token_parts:
72
- token = token.get(part)
73
- if token is None:
74
- raise Exception(f"Token path çözülemedi: {token_path}")
75
-
76
- new_refresh_token = json_resp.get("refresh_token", refresh_token)
77
-
78
- session.setdefault("auth_tokens", {})[api_name] = {
79
- "token": token,
80
- "refresh_token": new_refresh_token
81
- }
82
-
83
- log(f"🔁 Token başarıyla yenilendi: {api_name}")
84
- return token, session
85
-
86
- except Exception as e:
87
- log(f"❌ Token yenileme başarısız: {e}")
88
- traceback.print_exc()
89
- raise e
90
-
91
- def execute_intent(intent_name, user_input, session_dict, intent_definitions, data_formats, project_name, service_config):
92
- try:
93
- session = session_dict
94
- intent_def = intent_definitions[intent_name]
95
- action_api_name = intent_def.get("action")
96
-
97
- if not action_api_name:
98
- raise Exception(f"Intent '{intent_name}' için action tanımı eksik.")
99
-
100
- api_def = service_config.get_api_config(action_api_name)
101
- if not api_def:
102
- raise Exception(f"API '{action_api_name}' tanımı bulunamadı.")
103
-
104
- variables_raw = intent.extract_parameters(intent_def.get("variables", []), user_input)
105
- variables = {item["key"]: item["value"] for item in variables_raw}
106
-
107
- log(f"🚀 execute_intent('{intent_name}')")
108
- log(f"🔍 Çıkarılan parametreler: {variables}")
109
-
110
- variable_format_map = intent_def.get("variable_formats", {})
111
- is_valid, validation_errors = intent.validate_variable_formats(variables, variable_format_map, data_formats)
112
- if not is_valid:
113
- log(f"⚠️ Validasyon hatası: {validation_errors}")
114
- return {
115
- "errors": validation_errors,
116
- "awaiting_variable": list(validation_errors.keys())[0],
117
- "session": session
118
- }
119
-
120
- headers = api_def.get("headers", [])
121
- body = api_def.get("body", {})
122
- method = api_def.get("method", "POST")
123
- url = api_def["url"]
124
- timeout = api_def.get("timeout", 5)
125
- retry_count = api_def.get("retry_count", 0)
126
- auth_config = api_def.get("auth")
127
- tls = api_def.get("tls", {})
128
- verify = tls.get("verify", True)
129
- verify_path = tls.get("ca_bundle") if verify and tls.get("ca_bundle") else verify
130
-
131
- # ✅ Düzeltilmiş auth çağrısı
132
- if auth_config:
133
- token, session = auth_token_handler(action_api_name, auth_config, session)
134
- else:
135
- token = None
136
-
137
- resolved_headers = {
138
- h["key"]: intent.resolve_placeholders(h["value"], session, variables)
139
- for h in headers
140
- }
141
- resolved_body = {
142
- k: intent.resolve_placeholders(str(v), session, variables)
143
- for k, v in body.items()
144
- }
145
-
146
- for attempt in range(retry_count + 1):
147
- try:
148
- response = requests.request(
149
- method=method,
150
- url=url,
151
- headers=resolved_headers,
152
- json=resolved_body,
153
- timeout=timeout,
154
- verify=verify_path
155
- )
156
- if response.status_code == 401 and auth_config and attempt < retry_count:
157
- log("🔁 Token expired. Yenileniyor...")
158
- token, session = refresh_auth_token(action_api_name, auth_config, session)
159
- continue
160
- response.raise_for_status()
161
- break
162
- except requests.HTTPError as e:
163
- if response.status_code != 401 or attempt == retry_count:
164
- raise e
165
-
166
- log("✅ API çağrısı başarılı")
167
- json_resp = response.json()
168
-
169
- field = api_def.get("response_parser", {}).get("field")
170
- value = json_resp.get(field) if field else json_resp
171
- template = api_def.get("reply_template", str(value))
172
-
173
- merged_variables = {**session.get("variables", {}), **variables}
174
- if field:
175
- merged_variables[field] = str(value)
176
-
177
- log(f"🧩 merged_variables: {merged_variables}")
178
- log(f"🧩 reply_template: {template}")
179
-
180
- reply = intent.resolve_placeholders(template, session, merged_variables)
181
-
182
- log(f"🛠 Final reply: {reply}")
183
-
184
- session.setdefault("variables", {}).update(merged_variables)
185
- session["last_intent"] = intent_name
186
-
187
- return {
188
- "reply": reply,
189
- "session": session
190
- }
191
-
192
- except Exception as e:
193
- log(f"❌ execute_intent() hatası: {e}")
194
- traceback.print_exc()
195
- return {
196
- "error": str(e),
197
- "session": session
198
- }
 
1
+ import intent_utils as intent
2
+ import requests
3
+ import traceback
4
+ from log import log
5
+
6
+ def auth_token_handler(api_name, auth_config, session):
7
+ try:
8
+ token_info = session.get("auth_tokens", {}).get(api_name)
9
+ if token_info and "token" in token_info:
10
+ return token_info["token"], session
11
+
12
+ auth_endpoint = auth_config.get("auth_endpoint")
13
+ auth_body = auth_config.get("auth_body", {})
14
+ token_path = auth_config.get("auth_token_path")
15
+
16
+ if not auth_endpoint or not token_path:
17
+ raise Exception("auth_endpoint veya token_path tanımsız")
18
+
19
+ resolved_body = {
20
+ k: intent.resolve_placeholders(str(v), session, session.get("variables", {})) for k, v in auth_body.items()
21
+ }
22
+
23
+ response = requests.post(auth_endpoint, json=resolved_body, timeout=5)
24
+ response.raise_for_status()
25
+ json_resp = response.json()
26
+
27
+ token_parts = token_path.split(".")
28
+ token = json_resp
29
+ for part in token_parts:
30
+ token = token.get(part)
31
+ if token is None:
32
+ raise Exception(f"Token path çözülemedi: {token_path}")
33
+
34
+ refresh_token = json_resp.get("refresh_token")
35
+ session.setdefault("auth_tokens", {})[api_name] = {
36
+ "token": token,
37
+ "refresh_token": refresh_token
38
+ }
39
+
40
+ return token, session
41
+
42
+ except Exception as e:
43
+ log(f"❌ Auth token alınamadı: {e}")
44
+ traceback.print_exc()
45
+ raise e
46
+
47
+ def refresh_auth_token(api_name, auth_config, session):
48
+ try:
49
+ refresh_endpoint = auth_config.get("auth_refresh_endpoint")
50
+ refresh_body = auth_config.get("refresh_body", {})
51
+ token_path = auth_config.get("auth_token_path")
52
+
53
+ if not refresh_endpoint or not token_path:
54
+ raise Exception("Refresh yapılandırması eksik")
55
+
56
+ refresh_token = session.get("auth_tokens", {}).get(api_name, {}).get("refresh_token")
57
+ if not refresh_token:
58
+ raise Exception("Mevcut refresh token bulunamadı")
59
+
60
+ resolved_body = {
61
+ k: intent.resolve_placeholders(str(v), session, session.get("variables", {})) for k, v in refresh_body.items()
62
+ }
63
+
64
+ response = requests.post(refresh_endpoint, json=resolved_body, timeout=5)
65
+ response.raise_for_status()
66
+ json_resp = response.json()
67
+
68
+ token_parts = token_path.split(".")
69
+ token = json_resp
70
+ for part in token_parts:
71
+ token = token.get(part)
72
+ if token is None:
73
+ raise Exception(f"Token path çözülemedi: {token_path}")
74
+
75
+ new_refresh_token = json_resp.get("refresh_token", refresh_token)
76
+
77
+ session.setdefault("auth_tokens", {})[api_name] = {
78
+ "token": token,
79
+ "refresh_token": new_refresh_token
80
+ }
81
+
82
+ log(f"🔁 Token başarıyla yenilendi: {api_name}")
83
+ return token, session
84
+
85
+ except Exception as e:
86
+ log(f"❌ Token yenileme başarısız: {e}")
87
+ traceback.print_exc()
88
+ raise e
89
+
90
+ def execute_intent(intent_name, user_input, session_dict, intent_definitions, data_formats, project_name, service_config):
91
+ try:
92
+ session = session_dict
93
+ intent_def = intent_definitions.get(intent_name)
94
+
95
+ if not intent_def:
96
+ raise Exception(f"'{intent_name}' için intent tanımı bulunamadı.")
97
+
98
+ action_api_name = intent_def.get("action")
99
+
100
+ if not action_api_name:
101
+ raise Exception(f"Intent '{intent_name}' için action tanımı eksik.")
102
+
103
+ api_def = service_config.get_api_config(action_api_name)
104
+ if not api_def:
105
+ raise Exception(f"API '{action_api_name}' tanımı bulunamadı.")
106
+
107
+ variables = session.get("variables", {})
108
+ log(f"🚀 execute_intent('{intent_name}')")
109
+ log(f"🔍 Kullanılan parametreler: {variables}")
110
+
111
+ variable_format_map = intent_def.get("variable_formats", {})
112
+ is_valid, validation_errors = intent.validate_variable_formats(variables, variable_format_map, data_formats)
113
+ if not is_valid:
114
+ log(f"⚠️ Validasyon hatası: {validation_errors}")
115
+ return {
116
+ "errors": validation_errors,
117
+ "awaiting_variable": list(validation_errors.keys())[0],
118
+ "session": session
119
+ }
120
+
121
+ headers = api_def.get("headers", [])
122
+ body = api_def.get("body", {})
123
+ method = api_def.get("method", "POST")
124
+ url = api_def["url"]
125
+ timeout = api_def.get("timeout", 5)
126
+ retry_count = api_def.get("retry_count", 0)
127
+ auth_config = api_def.get("auth")
128
+ tls = api_def.get("tls", {})
129
+ verify = tls.get("verify", True)
130
+ verify_path = tls.get("ca_bundle") if verify and tls.get("ca_bundle") else verify
131
+
132
+ if auth_config:
133
+ token, session = auth_token_handler(action_api_name, auth_config, session)
134
+ else:
135
+ token = None
136
+
137
+ resolved_headers = {
138
+ h["key"]: intent.resolve_placeholders(h["value"], session, variables)
139
+ for h in headers
140
+ }
141
+ resolved_body = {
142
+ k: intent.resolve_placeholders(str(v), session, variables)
143
+ for k, v in body.items()
144
+ }
145
+
146
+ for attempt in range(retry_count + 1):
147
+ try:
148
+ response = requests.request(
149
+ method=method,
150
+ url=url,
151
+ headers=resolved_headers,
152
+ json=resolved_body,
153
+ timeout=timeout,
154
+ verify=verify_path
155
+ )
156
+ if response.status_code == 401 and auth_config and attempt < retry_count:
157
+ log("🔁 Token expired. Yenileniyor...")
158
+ token, session = refresh_auth_token(action_api_name, auth_config, session)
159
+ continue
160
+ response.raise_for_status()
161
+ break
162
+ except requests.HTTPError as e:
163
+ if response.status_code != 401 or attempt == retry_count:
164
+ raise e
165
+
166
+ log("✅ API çağrısı başarılı")
167
+ json_resp = response.json()
168
+
169
+ field = api_def.get("response_parser", {}).get("field")
170
+ value = json_resp.get(field) if field else json_resp
171
+ template = api_def.get("reply_template", str(value))
172
+
173
+ merged_variables = {**session.get("variables", {}), **variables}
174
+ if field:
175
+ merged_variables[field] = str(value)
176
+
177
+ log(f"🧩 merged_variables: {merged_variables}")
178
+ log(f"🧩 reply_template: {template}")
179
+
180
+ reply = intent.resolve_placeholders(template, session, merged_variables)
181
+ log(f"🛠 Final reply: {reply}")
182
+
183
+ session.setdefault("variables", {}).update(merged_variables)
184
+ session["last_intent"] = intent_name
185
+
186
+ return {
187
+ "reply": reply,
188
+ "session": session
189
+ }
190
+
191
+ except Exception as e:
192
+ log(f"❌ execute_intent() hatası: {e}")
193
+ traceback.print_exc()
194
+ return {
195
+ "error": str(e),
196
+ "session": session
197
+ }