{ "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 }