truglpk3 commited on
Commit
49ffc6f
·
verified ·
1 Parent(s): 59e6b8b

Update chatbot/agents/tools/food_retriever.py

Browse files
Files changed (1) hide show
  1. chatbot/agents/tools/food_retriever.py +362 -362
chatbot/agents/tools/food_retriever.py CHANGED
@@ -1,362 +1,362 @@
1
- # ========================================
2
- # 🥗 FOOD RETRIEVER - ElasticSearch Retriever
3
- # ========================================
4
-
5
- import os
6
- from langchain.chains.query_constructor.base import (
7
- AttributeInfo,
8
- get_query_constructor_prompt,
9
- StructuredQueryOutputParser,
10
- )
11
- from langchain_deepseek import ChatDeepSeek
12
- from langchain_elasticsearch import ElasticsearchStore
13
- from langchain.retrievers.self_query.elasticsearch import ElasticsearchTranslator
14
- from langchain.retrievers.self_query.base import SelfQueryRetriever
15
-
16
- from chatbot.models.embeddings import embeddings_model as embeddings # Import embeddings đã khởi tạo sẵn
17
- from chatbot.models.llm_setup import llm
18
- from chatbot.config import ELASTIC_CLOUD_URL, ELASTIC_API_KEY
19
-
20
-
21
- # ========================================
22
- # 1️⃣ Định nghĩa metadata field info
23
- # ========================================
24
- metadata_field_info = [
25
-
26
- # Thông tin chung về món ăn
27
- AttributeInfo(
28
- name="meal_id",
29
- description="ID duy nhất của món ăn",
30
- type="integer"
31
- ),
32
- AttributeInfo(
33
- name="name",
34
- description="Tên món ăn",
35
- type="string"
36
- ),
37
- AttributeInfo(
38
- name="servings",
39
- description="Số khẩu phần ăn",
40
- type="integer"
41
- ),
42
- AttributeInfo(
43
- name="difficulty",
44
- description="Độ khó chế biến",
45
- type="string"
46
- ),
47
- AttributeInfo(
48
- name="cooking_time_minutes",
49
- description="Thời gian nấu (phút)",
50
- type="integer"
51
- ),
52
-
53
- # Nguyên liệu
54
- AttributeInfo(
55
- name="ingredients",
56
- description="Danh sách nguyên liệu (list string), ví dụ: ['cà rốt', 'rong biển', 'trứng gà']",
57
- type="string"
58
- ),
59
- AttributeInfo(
60
- name="ingredients_text",
61
- description="Nguyên liệu ở dạng chuỗi nối, ví dụ: 'cà rốt, rong biển, trứng gà'",
62
- type="string"
63
- ),
64
-
65
- # Năng lượng & chất đa lượng
66
- AttributeInfo(
67
- name="kcal",
68
- description="Năng lượng của món ăn (kcal)",
69
- type="float"
70
- ),
71
- AttributeInfo(
72
- name="protein",
73
- description="Hàm lượng protein (g)",
74
- type="float"
75
- ),
76
- AttributeInfo(
77
- name="carbohydrate",
78
- description="Hàm lượng carbohydrate (g)",
79
- type="float"
80
- ),
81
- AttributeInfo(
82
- name="sugar",
83
- description="Hàm lượng đường tổng (g)",
84
- type="float"
85
- ),
86
- AttributeInfo(
87
- name="fiber",
88
- description="Hàm lượng chất xơ (g)",
89
- type="float"
90
- ),
91
- AttributeInfo(
92
- name="lipid",
93
- description="Tổng chất béo (g)",
94
- type="float"
95
- ),
96
- AttributeInfo(
97
- name="saturated_fat",
98
- description="Chất béo bão hòa (g)",
99
- type="float"
100
- ),
101
- AttributeInfo(
102
- name="monounsaturated_fat",
103
- description="Chất béo không bão hòa đơn (g)",
104
- type="float"
105
- ),
106
- AttributeInfo(
107
- name="polyunsaturated_fat",
108
- description="Chất béo không bão hòa đa (g)",
109
- type="float"
110
- ),
111
- AttributeInfo(
112
- name="trans_fat",
113
- description="Chất béo chuyển hóa (g)",
114
- type="float"
115
- ),
116
- AttributeInfo(
117
- name="cholesterol",
118
- description="Hàm lượng cholesterol (mg)",
119
- type="float"
120
- ),
121
-
122
- # Vitamin
123
- AttributeInfo(
124
- name="vit_a",
125
- description="Vitamin A (mg)",
126
- type="float"
127
- ),
128
- AttributeInfo(
129
- name="vit_d",
130
- description="Vitamin D (mg)",
131
- type="float"
132
- ),
133
- AttributeInfo(
134
- name="vit_c",
135
- description="Vitamin C (mg)",
136
- type="float"
137
- ),
138
- AttributeInfo(
139
- name="vit_b6",
140
- description="Vitamin B6 (mg)",
141
- type="float"
142
- ),
143
- AttributeInfo(
144
- name="vit_b12",
145
- description="Vitamin B12 (mg)",
146
- type="float"
147
- ),
148
- AttributeInfo(
149
- name="vit_b12_added",
150
- description="Vitamin B12 bổ sung (mg)",
151
- type="float"
152
- ),
153
- AttributeInfo(
154
- name="vit_e",
155
- description="Vitamin E (mg)",
156
- type="float"
157
- ),
158
- AttributeInfo(
159
- name="vit_e_added",
160
- description="Vitamin E bổ sung (mg)",
161
- type="float"
162
- ),
163
- AttributeInfo(
164
- name="vit_k",
165
- description="Vitamin K (mg)",
166
- type="float"
167
- ),
168
- AttributeInfo(
169
- name="choline",
170
- description="Choline (mg)",
171
- type="float"
172
- ),
173
-
174
- # Khoáng chất
175
- AttributeInfo(
176
- name="canxi",
177
- description="Canxi (mg)",
178
- type="float"
179
- ),
180
- AttributeInfo(
181
- name="sat",
182
- description="Sắt (mg)",
183
- type="float"
184
- ),
185
- AttributeInfo(
186
- name="magie",
187
- description="Magie (mg)",
188
- type="float"
189
- ),
190
- AttributeInfo(
191
- name="photpho",
192
- description="Phốt pho (mg)",
193
- type="float"
194
- ),
195
- AttributeInfo(
196
- name="kali",
197
- description="Kali (mg)",
198
- type="float"
199
- ),
200
- AttributeInfo(
201
- name="natri",
202
- description="Natri (mg)",
203
- type="float"
204
- ),
205
- AttributeInfo(
206
- name="kem",
207
- description="Kẽm (mg)",
208
- type="float"
209
- ),
210
-
211
- # Thành phần khác
212
- AttributeInfo(
213
- name="water",
214
- description="Hàm lượng nước (g)",
215
- type="float"
216
- ),
217
- AttributeInfo(
218
- name="caffeine",
219
- description="Caffeine (mg)",
220
- type="float"
221
- ),
222
- AttributeInfo(
223
- name="alcohol",
224
- description="Cồn (g)",
225
- type="float"
226
- ),
227
- ]
228
-
229
- document_content_description = "Mô tả ngắn gọn về món ăn"
230
-
231
-
232
- # ========================================
233
- # 2️⃣ Định nghĩa toán tử hỗ trợ và ví dụ
234
- # ========================================
235
- allowed_comparators = [
236
- "$eq",
237
- "$gt",
238
- "$gte",
239
- "$lt",
240
- "$lte",
241
- "$contain",
242
- "$like",
243
- ]
244
-
245
- examples = [
246
- (
247
- "Gợi ý các món ăn có trứng và ít hơn 500 kcal.",
248
- {
249
- "query": "món ăn có trứng",
250
- "filter": 'and(lt("kcal", 500), contain("ingredients", "trứng"))',
251
- },
252
- ),
253
- (
254
- "Tìm món ăn không chứa trứng nhưng có nhiều protein hơn 30g.",
255
- {
256
- "query": "món ăn không có trứng",
257
- "filter": 'and(gt("protein", 30), not(contain("ingredients", "trứng")))',
258
- },
259
- ),
260
- (
261
- "Món ăn chay dễ nấu trong vòng 20 phút.",
262
- {
263
- "query": "món ăn chay",
264
- "filter": 'and(lte("cooking_time_minutes", 20), eq("difficulty", "easy"), not(contain("ingredients", "thịt")), not(contain("ingredients", "cá")))',
265
- },
266
- ),
267
- (
268
- "Món ăn giàu chất xơ, trên 10g, ít đường dưới 5g.",
269
- {
270
- "query": "món ăn giàu chất xơ",
271
- "filter": 'and(gt("fiber", 10), lt("sugar", 5))',
272
- },
273
- ),
274
- (
275
- "Món ăn có vitamin C trên 50mg và ít chất béo dưới 10g.",
276
- {
277
- "query": "món ăn nhiều vitamin C",
278
- "filter": 'and(gt("vit_c", 50), lt("lipid", 10))',
279
- },
280
- ),
281
- (
282
- "Gợi ý các món ăn keto với nhiều chất béo nhưng ít carb.",
283
- {
284
- "query": "món ăn keto",
285
- "filter": 'and(gt("lipid", 20), lt("carbohydrate", 5))',
286
- },
287
- ),
288
- (
289
- "Món ăn có cà rốt, rong biển và trên 300 kcal.",
290
- {
291
- "query": "món ăn có cà rốt và rong biển",
292
- "filter": 'and(gt("kcal", 300), contain("ingredients", "cà rốt"), contain("ingredients", "rong biển"))',
293
- },
294
- ),
295
- (
296
- "Tìm món có khoảng 500 kcal và 20g protein",
297
- {
298
- "query": "món ăn có năng lượng trung bình",
299
- "filter": 'and(gte("kcal", 450), lte("kcal", 450), gte("protein", 15), lte("protein", 25))',
300
- },
301
- )
302
- ]
303
-
304
-
305
- # ========================================
306
- # 3️⃣ Tạo Query Constructor
307
- # ========================================
308
- prompt_query = get_query_constructor_prompt(
309
- document_content_description,
310
- metadata_field_info,
311
- allowed_comparators=allowed_comparators,
312
- examples=examples,
313
- )
314
-
315
- llm = ChatDeepSeek(
316
- model="deepseek-chat",
317
- temperature=0,
318
- max_tokens=None,
319
- timeout=None,
320
- max_retries=2,
321
- )
322
-
323
- output_parser = StructuredQueryOutputParser.from_components()
324
- query_constructor = prompt_query | llm | output_parser
325
-
326
-
327
- # ========================================
328
- # 4️⃣ Kết nối Elasticsearch
329
- # ========================================
330
- docsearch = ElasticsearchStore(
331
- es_url=ELASTIC_CLOUD_URL,
332
- es_api_key=ELASTIC_API_KEY,
333
- index_name="food_vdb",
334
- embedding=embeddings,
335
- )
336
-
337
-
338
- # ========================================
339
- # 5️⃣ Tạo retrievers (nhiều cấu hình)
340
- # ========================================
341
-
342
- # Truy vấn rộng hơn, trả về nhiều kết quả để lọc sau
343
- food_retriever = SelfQueryRetriever(
344
- query_constructor=query_constructor,
345
- vectorstore=docsearch,
346
- structured_query_translator=ElasticsearchTranslator(),
347
- search_kwargs={"k": 20},
348
- )
349
-
350
- # Truy vấn ngắn gọn hơn, trả về top-3 kết quả
351
- food_retriever_top3 = SelfQueryRetriever(
352
- query_constructor=query_constructor,
353
- vectorstore=docsearch,
354
- structured_query_translator=ElasticsearchTranslator(),
355
- search_kwargs={"k": 3},
356
- )
357
-
358
-
359
- # ========================================
360
- # 6️⃣ EXPORT
361
- # ========================================
362
- __all__ = ["food_retriever", "food_retriever_top3", "docsearch", "query_constructor"]
 
1
+ # ========================================
2
+ # 🥗 FOOD RETRIEVER - ElasticSearch Retriever
3
+ # ========================================
4
+
5
+ import os
6
+ from langchain.chains.query_constructor.base import (
7
+ AttributeInfo,
8
+ get_query_constructor_prompt,
9
+ StructuredQueryOutputParser,
10
+ )
11
+ from langchain_deepseek import ChatDeepSeek
12
+ from langchain_elasticsearch import ElasticsearchStore
13
+ from langchain.retrievers.self_query.elasticsearch import ElasticsearchTranslator
14
+ from langchain.retrievers.self_query.base import SelfQueryRetriever
15
+
16
+ from chatbot.models.embeddings import embeddings # Import embeddings đã khởi tạo sẵn
17
+ from chatbot.models.llm_setup import llm
18
+ from chatbot.config import ELASTIC_CLOUD_URL, ELASTIC_API_KEY
19
+
20
+
21
+ # ========================================
22
+ # 1️⃣ Định nghĩa metadata field info
23
+ # ========================================
24
+ metadata_field_info = [
25
+
26
+ # Thông tin chung về món ăn
27
+ AttributeInfo(
28
+ name="meal_id",
29
+ description="ID duy nhất của món ăn",
30
+ type="integer"
31
+ ),
32
+ AttributeInfo(
33
+ name="name",
34
+ description="Tên món ăn",
35
+ type="string"
36
+ ),
37
+ AttributeInfo(
38
+ name="servings",
39
+ description="Số khẩu phần ăn",
40
+ type="integer"
41
+ ),
42
+ AttributeInfo(
43
+ name="difficulty",
44
+ description="Độ khó chế biến",
45
+ type="string"
46
+ ),
47
+ AttributeInfo(
48
+ name="cooking_time_minutes",
49
+ description="Thời gian nấu (phút)",
50
+ type="integer"
51
+ ),
52
+
53
+ # Nguyên liệu
54
+ AttributeInfo(
55
+ name="ingredients",
56
+ description="Danh sách nguyên liệu (list string), ví dụ: ['cà rốt', 'rong biển', 'trứng gà']",
57
+ type="string"
58
+ ),
59
+ AttributeInfo(
60
+ name="ingredients_text",
61
+ description="Nguyên liệu ở dạng chuỗi nối, ví dụ: 'cà rốt, rong biển, trứng gà'",
62
+ type="string"
63
+ ),
64
+
65
+ # Năng lượng & chất đa lượng
66
+ AttributeInfo(
67
+ name="kcal",
68
+ description="Năng lượng của món ăn (kcal)",
69
+ type="float"
70
+ ),
71
+ AttributeInfo(
72
+ name="protein",
73
+ description="Hàm lượng protein (g)",
74
+ type="float"
75
+ ),
76
+ AttributeInfo(
77
+ name="carbohydrate",
78
+ description="Hàm lượng carbohydrate (g)",
79
+ type="float"
80
+ ),
81
+ AttributeInfo(
82
+ name="sugar",
83
+ description="Hàm lượng đường tổng (g)",
84
+ type="float"
85
+ ),
86
+ AttributeInfo(
87
+ name="fiber",
88
+ description="Hàm lượng chất xơ (g)",
89
+ type="float"
90
+ ),
91
+ AttributeInfo(
92
+ name="lipid",
93
+ description="Tổng chất béo (g)",
94
+ type="float"
95
+ ),
96
+ AttributeInfo(
97
+ name="saturated_fat",
98
+ description="Chất béo bão hòa (g)",
99
+ type="float"
100
+ ),
101
+ AttributeInfo(
102
+ name="monounsaturated_fat",
103
+ description="Chất béo không bão hòa đơn (g)",
104
+ type="float"
105
+ ),
106
+ AttributeInfo(
107
+ name="polyunsaturated_fat",
108
+ description="Chất béo không bão hòa đa (g)",
109
+ type="float"
110
+ ),
111
+ AttributeInfo(
112
+ name="trans_fat",
113
+ description="Chất béo chuyển hóa (g)",
114
+ type="float"
115
+ ),
116
+ AttributeInfo(
117
+ name="cholesterol",
118
+ description="Hàm lượng cholesterol (mg)",
119
+ type="float"
120
+ ),
121
+
122
+ # Vitamin
123
+ AttributeInfo(
124
+ name="vit_a",
125
+ description="Vitamin A (mg)",
126
+ type="float"
127
+ ),
128
+ AttributeInfo(
129
+ name="vit_d",
130
+ description="Vitamin D (mg)",
131
+ type="float"
132
+ ),
133
+ AttributeInfo(
134
+ name="vit_c",
135
+ description="Vitamin C (mg)",
136
+ type="float"
137
+ ),
138
+ AttributeInfo(
139
+ name="vit_b6",
140
+ description="Vitamin B6 (mg)",
141
+ type="float"
142
+ ),
143
+ AttributeInfo(
144
+ name="vit_b12",
145
+ description="Vitamin B12 (mg)",
146
+ type="float"
147
+ ),
148
+ AttributeInfo(
149
+ name="vit_b12_added",
150
+ description="Vitamin B12 bổ sung (mg)",
151
+ type="float"
152
+ ),
153
+ AttributeInfo(
154
+ name="vit_e",
155
+ description="Vitamin E (mg)",
156
+ type="float"
157
+ ),
158
+ AttributeInfo(
159
+ name="vit_e_added",
160
+ description="Vitamin E bổ sung (mg)",
161
+ type="float"
162
+ ),
163
+ AttributeInfo(
164
+ name="vit_k",
165
+ description="Vitamin K (mg)",
166
+ type="float"
167
+ ),
168
+ AttributeInfo(
169
+ name="choline",
170
+ description="Choline (mg)",
171
+ type="float"
172
+ ),
173
+
174
+ # Khoáng chất
175
+ AttributeInfo(
176
+ name="canxi",
177
+ description="Canxi (mg)",
178
+ type="float"
179
+ ),
180
+ AttributeInfo(
181
+ name="sat",
182
+ description="Sắt (mg)",
183
+ type="float"
184
+ ),
185
+ AttributeInfo(
186
+ name="magie",
187
+ description="Magie (mg)",
188
+ type="float"
189
+ ),
190
+ AttributeInfo(
191
+ name="photpho",
192
+ description="Phốt pho (mg)",
193
+ type="float"
194
+ ),
195
+ AttributeInfo(
196
+ name="kali",
197
+ description="Kali (mg)",
198
+ type="float"
199
+ ),
200
+ AttributeInfo(
201
+ name="natri",
202
+ description="Natri (mg)",
203
+ type="float"
204
+ ),
205
+ AttributeInfo(
206
+ name="kem",
207
+ description="Kẽm (mg)",
208
+ type="float"
209
+ ),
210
+
211
+ # Thành phần khác
212
+ AttributeInfo(
213
+ name="water",
214
+ description="Hàm lượng nước (g)",
215
+ type="float"
216
+ ),
217
+ AttributeInfo(
218
+ name="caffeine",
219
+ description="Caffeine (mg)",
220
+ type="float"
221
+ ),
222
+ AttributeInfo(
223
+ name="alcohol",
224
+ description="Cồn (g)",
225
+ type="float"
226
+ ),
227
+ ]
228
+
229
+ document_content_description = "Mô tả ngắn gọn về món ăn"
230
+
231
+
232
+ # ========================================
233
+ # 2️⃣ Định nghĩa toán tử hỗ trợ và ví dụ
234
+ # ========================================
235
+ allowed_comparators = [
236
+ "$eq",
237
+ "$gt",
238
+ "$gte",
239
+ "$lt",
240
+ "$lte",
241
+ "$contain",
242
+ "$like",
243
+ ]
244
+
245
+ examples = [
246
+ (
247
+ "Gợi ý các món ăn có trứng và ít hơn 500 kcal.",
248
+ {
249
+ "query": "món ăn có trứng",
250
+ "filter": 'and(lt("kcal", 500), contain("ingredients", "trứng"))',
251
+ },
252
+ ),
253
+ (
254
+ "Tìm món ăn không chứa trứng nhưng có nhiều protein hơn 30g.",
255
+ {
256
+ "query": "món ăn không có trứng",
257
+ "filter": 'and(gt("protein", 30), not(contain("ingredients", "trứng")))',
258
+ },
259
+ ),
260
+ (
261
+ "Món ăn chay dễ nấu trong vòng 20 phút.",
262
+ {
263
+ "query": "món ăn chay",
264
+ "filter": 'and(lte("cooking_time_minutes", 20), eq("difficulty", "easy"), not(contain("ingredients", "thịt")), not(contain("ingredients", "cá")))',
265
+ },
266
+ ),
267
+ (
268
+ "Món ăn giàu chất xơ, trên 10g, ít đường dưới 5g.",
269
+ {
270
+ "query": "món ăn giàu chất xơ",
271
+ "filter": 'and(gt("fiber", 10), lt("sugar", 5))',
272
+ },
273
+ ),
274
+ (
275
+ "Món ăn có vitamin C trên 50mg và ít chất béo dưới 10g.",
276
+ {
277
+ "query": "món ăn nhiều vitamin C",
278
+ "filter": 'and(gt("vit_c", 50), lt("lipid", 10))',
279
+ },
280
+ ),
281
+ (
282
+ "Gợi ý các món ăn keto với nhiều chất béo nhưng ít carb.",
283
+ {
284
+ "query": "món ăn keto",
285
+ "filter": 'and(gt("lipid", 20), lt("carbohydrate", 5))',
286
+ },
287
+ ),
288
+ (
289
+ "Món ăn có cà rốt, rong biển và trên 300 kcal.",
290
+ {
291
+ "query": "món ăn có cà rốt và rong biển",
292
+ "filter": 'and(gt("kcal", 300), contain("ingredients", "cà rốt"), contain("ingredients", "rong biển"))',
293
+ },
294
+ ),
295
+ (
296
+ "Tìm món có khoảng 500 kcal và 20g protein",
297
+ {
298
+ "query": "món ăn có năng lượng trung bình",
299
+ "filter": 'and(gte("kcal", 450), lte("kcal", 450), gte("protein", 15), lte("protein", 25))',
300
+ },
301
+ )
302
+ ]
303
+
304
+
305
+ # ========================================
306
+ # 3️⃣ Tạo Query Constructor
307
+ # ========================================
308
+ prompt_query = get_query_constructor_prompt(
309
+ document_content_description,
310
+ metadata_field_info,
311
+ allowed_comparators=allowed_comparators,
312
+ examples=examples,
313
+ )
314
+
315
+ llm = ChatDeepSeek(
316
+ model="deepseek-chat",
317
+ temperature=0,
318
+ max_tokens=None,
319
+ timeout=None,
320
+ max_retries=2,
321
+ )
322
+
323
+ output_parser = StructuredQueryOutputParser.from_components()
324
+ query_constructor = prompt_query | llm | output_parser
325
+
326
+
327
+ # ========================================
328
+ # 4️⃣ Kết nối Elasticsearch
329
+ # ========================================
330
+ docsearch = ElasticsearchStore(
331
+ es_url=ELASTIC_CLOUD_URL,
332
+ es_api_key=ELASTIC_API_KEY,
333
+ index_name="food_vdb",
334
+ embedding=embeddings,
335
+ )
336
+
337
+
338
+ # ========================================
339
+ # 5️⃣ Tạo retrievers (nhiều cấu hình)
340
+ # ========================================
341
+
342
+ # Truy vấn rộng hơn, trả về nhiều kết quả để lọc sau
343
+ food_retriever = SelfQueryRetriever(
344
+ query_constructor=query_constructor,
345
+ vectorstore=docsearch,
346
+ structured_query_translator=ElasticsearchTranslator(),
347
+ search_kwargs={"k": 20},
348
+ )
349
+
350
+ # Truy vấn ngắn gọn hơn, trả về top-3 kết quả
351
+ food_retriever_top3 = SelfQueryRetriever(
352
+ query_constructor=query_constructor,
353
+ vectorstore=docsearch,
354
+ structured_query_translator=ElasticsearchTranslator(),
355
+ search_kwargs={"k": 3},
356
+ )
357
+
358
+
359
+ # ========================================
360
+ # 6️⃣ EXPORT
361
+ # ========================================
362
+ __all__ = ["food_retriever", "food_retriever_top3", "docsearch", "query_constructor"]