File size: 10,600 Bytes
5f1d259
 
 
 
c598e5f
5f1d259
 
 
 
 
 
 
c598e5f
5f1d259
 
c598e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f1d259
 
 
 
 
c598e5f
5f1d259
 
 
 
c598e5f
 
 
 
 
 
5f1d259
 
c598e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f1d259
 
 
 
c598e5f
 
5f1d259
 
 
c598e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f1d259
c598e5f
 
 
5f1d259
 
 
 
c598e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f1d259
 
c598e5f
 
 
 
 
 
 
 
5f1d259
 
 
 
c598e5f
 
 
 
 
5f1d259
 
 
 
c598e5f
 
5f1d259
 
 
 
c598e5f
 
5f1d259
 
c598e5f
5f1d259
 
 
 
c598e5f
5f1d259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "06013a58",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/anaconda3/envs/chatbot_env/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    }
   ],
   "source": [
    "from config import EMBEDDING_MODEL\n",
    "from langchain_huggingface import HuggingFaceEmbeddings\n",
    "\n",
    "embedding_model = HuggingFaceEmbeddings(model_name = EMBEDDING_MODEL)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "922bf9f7",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/16/yn17n1916z32xtfrqrq39zj00000gn/T/ipykernel_82857/248899337.py:25: DeprecationWarning: `recreate_collection` method is deprecated and will be removed in the future. Use `collection_exists` to check collection existence and `create_collection` instead.\n",
      "  client.recreate_collection(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✅ Đã upload toàn bộ câu hỏi từ FAQ.json vào Qdrant.\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import json\n",
    "from dotenv import load_dotenv\n",
    "from qdrant_client import QdrantClient\n",
    "from qdrant_client.http.models import Distance, VectorParams, PointStruct\n",
    "from langchain.embeddings import HuggingFaceEmbeddings\n",
    "from config import EMBEDDING_MODEL\n",
    "\n",
    "load_dotenv()\n",
    "QDRANT_HOST = os.getenv(\"QDRANT_HOST\")\n",
    "QDRANT_API_KEY = os.getenv(\"QDRANT_API_KEY\")\n",
    "\n",
    "embedding_model = HuggingFaceEmbeddings(model_name = EMBEDDING_MODEL)\n",
    "\n",
    "\n",
    "client = QdrantClient(\n",
    "    url=QDRANT_HOST,\n",
    "    api_key=QDRANT_API_KEY\n",
    ")\n",
    "\n",
    "client.recreate_collection(\n",
    "    collection_name=\"faq_collection\",\n",
    "    vectors_config=VectorParams(\n",
    "        size= 384,\n",
    "        distance=Distance.COSINE\n",
    "    )\n",
    ")\n",
    "\n",
    "with open(\"data/FAQ.json\", \"r\", encoding=\"utf-8\") as f:\n",
    "    faqs = json.load(f)\n",
    "\n",
    "points = []\n",
    "for idx, faq in enumerate(faqs):\n",
    "    vec = embedding_model.embed_query(faq[\"Question\"])\n",
    "    points.append(PointStruct(\n",
    "        id=idx,\n",
    "        vector=vec,\n",
    "        payload={\"Câu hỏi\": faq[\"Question\"], \"Câu trả lời\": faq[\"Answer\"]}\n",
    "    ))\n",
    "\n",
    "client.upsert(\n",
    "    collection_name=\"faq_collection\",\n",
    "    points=points\n",
    ")\n",
    "\n",
    "print(\"✅ Đã upload toàn bộ câu hỏi từ FAQ.json vào Qdrant.\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "6a7a4e49",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/16/yn17n1916z32xtfrqrq39zj00000gn/T/ipykernel_82857/1372710697.py:4: DeprecationWarning: `search` method is deprecated and will be removed in the future. Use `query_points` instead.\n",
      "  results = client.search(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "❓ Đèn bulb kẹp bình Rạng Đông có thể sử dụng dùng 24V không?\n",
      "💡 Các loại đèn kẹp bình DC Rạng đông có thể sử dụng bình có điện áp 1 chiều từ 12-24V, Tùy theo công bố dải điện áp của sản phẩm trên bao bì, khách hàng lựa chọn bình ắc quy phù hợp,nếu sử dụng bình có điện áp lớn hoặc nhỏ hơn dải điện áp công bố sẽ gây hư hỏng đèn và không được bảo hành của NSX\n",
      "📈 Score: 0.80096316\n",
      "-----\n",
      "❓ Rạng Đông có đèn kẹp bình không?\n",
      "💡 Rạng Đông có 1 số dòng led Bulb kẹp bình như sau: Model: LED A60N1 12-24VDC 9W Model: LED TR70N1 12-24VDC/12W Model: A60N1/9W.DCV2 Model: TR70N1/12W.DCV2\n",
      "📈 Score: 0.73507816\n",
      "-----\n",
      "❓ Đền LED có thể lắp trong chụp đèn gắn tường có kính IP65 không?\n",
      "💡 - Khuyến cáo của sản phẩm đèn led bulb là KH không sử dụng trong chao chụp vì sẽ gây om nhiệt ( nhiệt khi đèn hoạt động không tản đi được) - Khi om nhiệt sẽ làm hư hỏng chip LED làm giảm độ sáng, hư hỏng các linh kiện, gây nên hiện tượng đèn mờ, đèn chớp tắt hoặc không sáng. 1 số đèn để nguội bật lại thì không chớp nữa là do trong mạch có linh kiện cảnh báo quá nhiệt cho người sử dụng .Khi để nguội sử dụng lại thì lại bị quá nhiệt nên đèn chớp để cảnh báo.\n",
      "📈 Score: 0.702726\n",
      "-----\n"
     ]
    }
   ],
   "source": [
    "query = \"Đèn LED kẹp bình rạng ĐÔng tôi dùng loại 24V được không\"\n",
    "query_vector = embedding_model.embed_query(query)\n",
    "\n",
    "results = client.search(\n",
    "    collection_name=\"faq_collection\",\n",
    "    query_vector=query_vector,\n",
    "    limit=3\n",
    ")\n",
    "\n",
    "for res in results:\n",
    "    print(\"\", res.payload['Câu hỏi'])\n",
    "    print(\"💡\", res.payload['Câu trả lời'])\n",
    "    print(\"📈 Score:\", res.score)\n",
    "    print(\"-----\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "a028f015",
   "metadata": {},
   "outputs": [],
   "source": [
    "from chatbot.llm import gemini_llm  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "c80c4e25",
   "metadata": {},
   "outputs": [],
   "source": [
    "def retrieve_top_k_faqs(user_question, k=5):\n",
    "    query_vector = embedding_model.embed_query(user_question)\n",
    "    search_results = client.search(\n",
    "        collection_name=\"faq_collection\",\n",
    "        query_vector=query_vector,\n",
    "        limit=k\n",
    "    )\n",
    "    return [\n",
    "        {\n",
    "            \"question\": hit.payload[\"Câu hỏi\"],\n",
    "            \"answer\": hit.payload[\"Câu trả lời\"],\n",
    "            \"score\": hit.score\n",
    "        }\n",
    "        for hit in search_results\n",
    "    ]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "7a621084",
   "metadata": {},
   "outputs": [],
   "source": [
    "def find_best_match_llm(user_question, candidates):\n",
    "    options = \"\\n\".join(\n",
    "        f\"{i+1}. Q: {c['question']}\\n   A: {c['answer']}\"\n",
    "        for i, c in enumerate(candidates)\n",
    "    )\n",
    "\n",
    "    prompt = (\n",
    "        \"Bạn là một trợ lý thông minh. Câu hỏi của người dùng là:\\n\"\n",
    "        f\"\\\"{user_question}\\\"\\n\\n\"\n",
    "        \"Dưới đây là các câu hỏi và câu trả lời có thể phù hợp:\\n\"\n",
    "        f\"{options}\\n\\n\"\n",
    "        \"Trong số các câu hỏi trên, có câu hỏi nào giống về mặt ý nghĩa với câu hỏi của người dùng không?\\n\"\n",
    "        \"Nếu có, chỉ trả về một số (1, 2, 3, …) tương ứng với câu hỏi phù hợp nhất.\\n\"\n",
    "        \"Nếu không có, trả về đúng 'KHÔNG'.\"\n",
    "    )\n",
    "\n",
    "    response = gemini_llm.invoke(prompt)\n",
    "    print(response)\n",
    "    return response\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "id": "4d763177",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_faq_answer(user_question):\n",
    "    top_k = retrieve_top_k_faqs(user_question, k=5)\n",
    "    match_index = find_best_match_llm(user_question, top_k)\n",
    "    print(match_index)\n",
    "    if match_index.strip().upper() == \"KHÔNG\":\n",
    "        return \"Không có trong FAQ\"\n",
    "\n",
    "    try:\n",
    "        idx = int(match_index) - 1\n",
    "        matched = top_k[idx]\n",
    "    except (ValueError, IndexError):\n",
    "        return \"⚠️ Đã có lỗi khi xử lý kết quả. Vui lòng thử lại.\"\n",
    "    print(matched[\"question\"])\n",
    "    print(matched[\"answer\"])\n",
    "    final_prompt = (\n",
    "        'Câu hỏi của khách hàng: \"' + user_question + '\"\\n\\n'\n",
    "        'Dưới đây là câu hỏi đã khớp trong cơ sở dữ liệu:\\n'\n",
    "        f'\"{matched[\"question\"]}\"\\n\\n'\n",
    "        'Câu trả lời là:\\n'\n",
    "        f'\"{matched[\"answer\"]}\"\\n\\n'\n",
    "        'Hãy trả lời cho khách hàng một cách lịch sự và ngắn gọn nhất có thể.'\n",
    "    )\n",
    "\n",
    "    return gemini_llm.invoke(final_prompt)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "id": "df4d405d",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/16/yn17n1916z32xtfrqrq39zj00000gn/T/ipykernel_82857/149935573.py:3: DeprecationWarning: `search` method is deprecated and will be removed in the future. Use `query_points` instead.\n",
      "  search_results = client.search(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "KHÔNG\n",
      "\n",
      "KHÔNG\n",
      "\n",
      "Không có trong FAQ\n"
     ]
    }
   ],
   "source": [
    "q = \"Đèn học\"\n",
    "print(get_faq_answer(q))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "53ab51f6",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af23cb1c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "chatbot_py310",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}