Spaces:
Paused
Paused
update
Browse files- rag_pipeline.py +11 -32
rag_pipeline.py
CHANGED
@@ -82,17 +82,14 @@ def initialize_components(data_path):
|
|
82 |
|
83 |
def generate_response(query: str, components: dict) -> str:
|
84 |
"""
|
85 |
-
Tạo câu trả lời (single-turn)
|
86 |
-
Phiên bản
|
87 |
-
- Tương thích với mô hình Vision bằng cách sử dụng chat template.
|
88 |
-
- Nhận và sử dụng thông tin `matched_vehicle` từ retriever.
|
89 |
-
- Định dạng context với tóm tắt thông minh từ metadata.
|
90 |
"""
|
91 |
print("--- Bắt đầu quy trình RAG cho query mới ---")
|
92 |
|
93 |
-
# === THAY ĐỔI 1:
|
94 |
-
# 1. Truy xuất ngữ cảnh
|
95 |
-
retrieved_results
|
96 |
query_text=query,
|
97 |
embedding_model=components["embedding_model"],
|
98 |
faiss_index=components["faiss_index"],
|
@@ -102,35 +99,25 @@ def generate_response(query: str, components: dict) -> str:
|
|
102 |
initial_k_multiplier=15
|
103 |
)
|
104 |
|
105 |
-
# 2
|
|
|
106 |
if not retrieved_results:
|
107 |
context = "Không tìm thấy thông tin luật liên quan trong cơ sở dữ liệu."
|
108 |
else:
|
109 |
context_parts = []
|
110 |
for i, res in enumerate(retrieved_results):
|
111 |
metadata = res.get('metadata', {})
|
|
|
112 |
header = f"Trích dẫn {i+1}: Điều {metadata.get('article', 'N/A')}, Khoản {metadata.get('clause_number', 'N/A')} (Nguồn: {metadata.get('source_document', 'N/A')})"
|
113 |
text = res.get('text', '*Nội dung không có*')
|
114 |
-
|
115 |
-
# === THAY ĐỔI 2: Thêm gợi ý về loại xe vào header ===
|
116 |
-
if matched_vehicle:
|
117 |
-
vehicle_keywords = {
|
118 |
-
"ô tô": ["ô tô", "xe con"], "xe máy": ["xe máy", "xe mô tô"],
|
119 |
-
"xe đạp": ["xe đạp", "xe thô sơ"], "máy kéo": ["máy kéo", "xe chuyên dùng"]
|
120 |
-
}
|
121 |
-
article_title_lower = metadata.get("article_title", "").lower()
|
122 |
-
if any(keyword in article_title_lower for keyword in vehicle_keywords.get(matched_vehicle, [])):
|
123 |
-
header += f" [GỢI Ý: Thông tin này áp dụng cho {matched_vehicle.upper()}]"
|
124 |
-
|
125 |
context_parts.append(f"{header}\n{text}")
|
126 |
context = "\n\n---\n\n".join(context_parts)
|
127 |
|
128 |
-
# 3. Xây dựng Prompt bằng Chat Template
|
129 |
print("--- Xây dựng prompt bằng chat template ---")
|
130 |
llm_model = components["llm_model"]
|
131 |
tokenizer = components["tokenizer"]
|
132 |
|
133 |
-
# Tạo cấu trúc tin nhắn theo chuẩn
|
134 |
messages = [
|
135 |
{
|
136 |
"role": "system",
|
@@ -149,19 +136,11 @@ def generate_response(query: str, components: dict) -> str:
|
|
149 |
}
|
150 |
]
|
151 |
|
152 |
-
|
153 |
-
# Phương thức này sẽ tạo ra chuỗi prompt hoàn chỉnh với các token đặc biệt,
|
154 |
-
# tương thích với cả mô hình text và vision (khi không có ảnh).
|
155 |
-
prompt = tokenizer.apply_chat_template(
|
156 |
-
messages,
|
157 |
-
tokenize=False,
|
158 |
-
add_generation_prompt=True
|
159 |
-
)
|
160 |
|
161 |
# 4. Tạo câu trả lời từ LLM
|
162 |
print("--- Bắt đầu tạo câu trả lời từ LLM ---")
|
163 |
|
164 |
-
# Tokenize chuỗi prompt đã được định dạng đúng
|
165 |
inputs = tokenizer([prompt], return_tensors="pt").to(llm_model.device)
|
166 |
|
167 |
generation_config = dict(
|
@@ -176,4 +155,4 @@ def generate_response(query: str, components: dict) -> str:
|
|
176 |
response_text = tokenizer.decode(output_ids[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
|
177 |
|
178 |
print("--- Tạo câu trả lời hoàn tất ---")
|
179 |
-
return response_text
|
|
|
82 |
|
83 |
def generate_response(query: str, components: dict) -> str:
|
84 |
"""
|
85 |
+
Tạo câu trả lời (single-turn).
|
86 |
+
Phiên bản đơn giản hóa, không có logic vehicle_type.
|
|
|
|
|
|
|
87 |
"""
|
88 |
print("--- Bắt đầu quy trình RAG cho query mới ---")
|
89 |
|
90 |
+
# === THAY ĐỔI 1: Chỉ nhận 1 giá trị trả về ===
|
91 |
+
# 1. Truy xuất ngữ cảnh
|
92 |
+
retrieved_results = search_relevant_laws(
|
93 |
query_text=query,
|
94 |
embedding_model=components["embedding_model"],
|
95 |
faiss_index=components["faiss_index"],
|
|
|
99 |
initial_k_multiplier=15
|
100 |
)
|
101 |
|
102 |
+
# === THAY ĐỔI 2: Loại bỏ logic vehicle_type trong context ===
|
103 |
+
# 2. Định dạng Context
|
104 |
if not retrieved_results:
|
105 |
context = "Không tìm thấy thông tin luật liên quan trong cơ sở dữ liệu."
|
106 |
else:
|
107 |
context_parts = []
|
108 |
for i, res in enumerate(retrieved_results):
|
109 |
metadata = res.get('metadata', {})
|
110 |
+
# Tạo header đơn giản, không có gợi ý
|
111 |
header = f"Trích dẫn {i+1}: Điều {metadata.get('article', 'N/A')}, Khoản {metadata.get('clause_number', 'N/A')} (Nguồn: {metadata.get('source_document', 'N/A')})"
|
112 |
text = res.get('text', '*Nội dung không có*')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
113 |
context_parts.append(f"{header}\n{text}")
|
114 |
context = "\n\n---\n\n".join(context_parts)
|
115 |
|
116 |
+
# 3. Xây dựng Prompt bằng Chat Template (giữ nguyên logic tương thích Vision)
|
117 |
print("--- Xây dựng prompt bằng chat template ---")
|
118 |
llm_model = components["llm_model"]
|
119 |
tokenizer = components["tokenizer"]
|
120 |
|
|
|
121 |
messages = [
|
122 |
{
|
123 |
"role": "system",
|
|
|
136 |
}
|
137 |
]
|
138 |
|
139 |
+
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
|
141 |
# 4. Tạo câu trả lời từ LLM
|
142 |
print("--- Bắt đầu tạo câu trả lời từ LLM ---")
|
143 |
|
|
|
144 |
inputs = tokenizer([prompt], return_tensors="pt").to(llm_model.device)
|
145 |
|
146 |
generation_config = dict(
|
|
|
155 |
response_text = tokenizer.decode(output_ids[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
|
156 |
|
157 |
print("--- Tạo câu trả lời hoàn tất ---")
|
158 |
+
return response_text
|