Spaces:
Runtime error
Runtime error
RollBack
Browse filesFiles changed (12)
125 unmodified lines126127128129130131132133129130131132137133134135136125 unmodified lines "expanded_queries": queries } logger.info( "Phân loại: %s | Số truy vấn: %s", final_result["question_type"], len(final_result["expanded_queries"]), ) print(f"Phân loại: {final_result['question_type']} | Queries: {len(final_result['expanded_queries'])}") return final_result
except Exception as e: logger.warning("Lỗi phân tích (%s). Mặc định chuyển sang tìm kiếm.", e) print(f" Lỗi phân tích ({e}). Mặc định chuyển sang tìm kiếm.") return { "question_type": "simple", "answer": None,27 unmodified lines28293031313233346 unmodified lines41424344444546477 unmodified lines5556575858596061626364656566676822 unmodified lines919293949495969727 unmodified lines (r"(?m)^\s*•\s+", "<LIST_BULLET>"),]
# Tách và thêm các thẻ <table> để bảo vệ cấu trúc bảng khỏi bị chia cắt trong quá trình chunking.
def extract_and_protect_tables(text: str) -> Tuple[str, dict]: table_pattern = re.compile(r"(?:\|.*\|[\r\n]+)+") tables = {}6 unmodified lines protected_text = re.sub(table_pattern, replace_table, text) return protected_text, tables
# Bảo vệ các phần tử của danh sách khỏi bị chia cắt trong quá trình chunking
def protect_lists(text: str) -> Tuple[str, dict]: placeholders = {} protected = text7 unmodified lines
return protected, placeholders
# Khôi phục các phần từ được bảo vệ về nội dung gốc bằng cách thay thế các placeholder
def restore_placeholders(text: str, placeholders: dict) -> str: restored = text for placeholder, original in placeholders.items(): restored = restored.replace(placeholder, original) return restored
# Tách văn bản dựa trên cấu trúc được xây dựng từ đầu
def split_by_structure(text: str) -> List[str]: parts = [text]
22 unmodified lines
return [part for part in parts if part.strip()]
# Hàm chính thực hiện chunking thông minh
def smart_chunking(docs: List) -> List: logger.info("Chunking theo cau truc + do dai...") length_splitter = RecursiveCharacterTextSplitter(123434576781 unmodified line101112151617181920212223242526272829303132333435363738394041424344454647484950515253545513141545 unmodified lines616263107646566673 unmodified lines7172731171181191201217475762 unmodified lines7980811308213213383848586877 unmodified lines959697147989910015110110210322 unmodified lines126127128180129130131import hashlibimport loggingimport refrom typing import List, Optionalfrom typing import List
from langchain_core.documents import Document as LangChainDocumentfrom qdrant_client.models import Filter, FieldCondition, HasIdCondition, MatchAny
from .collection_utils import collection_matches_yearfrom .document_db import SessionLocal, list_active_collection_names1 unmodified linelogger = logging.getLogger(__name__)
def _build_year_filter(year_scope: Optional[str]) -> Optional[Filter]: """Tạo Qdrant Filter từ year_scope (ví dụ: '2023-2024' hoặc '2023').""" if not year_scope: return None year_targets = [] year_scope = year_scope.strip() # Parse year_scope: có thể là "2023-2024" hoặc "2023" if "-" in year_scope: parts = year_scope.split("-") for p in parts: try: year_targets.append(int(p.strip())) except ValueError: pass else: try: year_targets.append(int(year_scope)) except ValueError: pass if not year_targets: return None # Sử dụng MatchAny để filter theo danh sách years from qdrant_client.models import HasIdCondition as QdrantHasId try: return Filter( must=[ FieldCondition( key="years", match=MatchAny(any=year_targets), ) ] ) except Exception: # Fallback nếu MatchAny không work return None
class CollectionRouterRetriever: def __init__( self,45 unmodified lines
return active_collections[: self.top_n_collections]
def _search_target_collections(self, query: str, collections: List[str], limit: int, year_scope: Optional[str] = None) -> List: def _search_target_collections(self, query: str, collections: List[str], limit: int) -> List: if not collections: return []
3 unmodified lines logger.exception("Failed to embed query for collection routing") return []
# Tạo filter Qdrant nếu có year_scope year_filter = _build_year_filter(year_scope) if year_filter: logger.info(f"Áp dụng Qdrant Filter cho year_scope: {year_scope}")
scored_docs = [] for collection_name in collections: try:2 unmodified lines query_vector=query_vector, limit=limit, with_payload=True, query_filter=year_filter, # NEW: Áp dụng Qdrant Filter native ) except Exception as e: logger.exception(f"Qdrant search failed for collection={collection_name}: {e}") except Exception: logger.exception("Qdrant search failed for collection=%s", collection_name) continue
for point in points:7 unmodified lines "source_file": payload.get("filename") or payload.get("stored_name") or "", "source_relpath": payload.get("object_path") or payload.get("path") or "", "object_path": payload.get("object_path") or "", "source_url": payload.get("source_url") or "", # NEW: Thêm source_url "folder_key": payload.get("folder_key") or "", "collection_name": collection_name, "academic_year": payload.get("academic_year") or "", "years": payload.get("years") or [], # NEW: Thêm years array "chunk_index": payload.get("chunk_index"), "page_number": payload.get("page_number"), }22 unmodified lines query=query, collections=target_collections, limit=candidate_k, year_scope=year_scope, # NEW: Pass year_scope để Qdrant Filter )
if year_scoped:13 unmodified lines141516171819202122231718192021222313 unmodified lines
def build_collection_name(folder_key: str, prefix: str = "rag") -> str: """ OPTIMIZED: Always return single collection name regardless of folder_key. This ensures all documents go into ONE collection for deduplication and efficient querying. Folder structure is preserved in payload metadata (folder_key), not as separate collections. """ # ✅ Force single collection: always return "rag_docs" return f"{prefix}_docs" normalized = normalize_folder_key(folder_key) base = f"{prefix}_{normalized}" # Qdrant collection names should stay short and simple. return base[:63]
def extract_year_tokens(value: str) -> Set[str]:38 unmodified lines39404142434243444546474849484950515238 unmodified lines# Name modelsLLM_MODEL = os.getenv('LLM_MODEL', 'llama-3.1-70b-versatile')FAST_LLM_MODEL = os.getenv('FAST_LLM_MODEL', 'llama-3.1-8b-instant')EMBED_MODEL = os.getenv('EMBED_MODEL', 'bkai-foundation-models/vietnamese-bi-encoder')CROSS_ENCODER_MODEL = os.getenv('CROSS_ENCODER_MODEL', 'itdainb/PhoRanker')EMBED_MODEL = os.getenv('EMBED_MODEL', 'BAAI/bge-m3')CROSS_ENCODER_MODEL = os.getenv('CROSS_ENCODER_MODEL', 'BAAI/bge-reranker-v2-m3')
# Chunking and retrieval settingsCHUNK_SIZE = int(os.getenv('CHUNK_SIZE', '800'))CHUNK_OVERLAP = int(os.getenv('CHUNK_OVERLAP', '150'))TOP_K_RESULTS = int(os.getenv('TOP_K_RESULTS', '15'))FINAL_TOP_K = int(os.getenv('FINAL_TOP_K', '3'))TOP_K_RESULTS = int(os.getenv('TOP_K_RESULTS', '10'))FINAL_TOP_K = int(os.getenv('FINAL_TOP_K', '5'))
QDRANT_COLLECTION = os.getenv('QDRANT_COLLECTION', 'rag_docs')DOCUMENTS_DATABASE_URL = os.getenv('DOCUMENTS_DATABASE_URL', _default_documents_db_url())112434512 unmodified lines18192023212223241 unmodified line26272831293334353637383940414243444546474849505152535455565758596030313274 unmodified lines1071081091411421431441451101461471481491501511521531541551561571111121601611131141151161641651661671171181191 unmodified line12112212317517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932012412512633 unmodified lines16016116236016316416569 unmodified lines23523623743643743843944044144244344444544644744844923823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227345145245327427527645645745845927727827928077 unmodified lines358359360543361362363import hashlibimport loggingimport osimport reimport uuidfrom datetime import datetime, timezonefrom typing import List, Optional12 unmodified lines)
from .chunking import smart_chunkingfrom .config import QDRANT_API_KEY, QDRANT_COLLECTION, QDRANT_URL, SUPABASE_URL, SUPABASE_STORAGE_BUCKETfrom .config import QDRANT_API_KEY, QDRANT_COLLECTION, QDRANT_URLfrom .document_db import Document, DocumentChunk, SessionLocalfrom .models import embeddingsfrom .text_utils import clean_text1 unmodified line
logger = logging.getLogger(__name__)
ACTIVE_CODE_PATTERN = re.compile(r"(20\d{2})\s*[-_/]\s*(20\d{2})")_ALLOWED_EXTENSIONS = {".pdf", ".docx", ".txt"}_ENSURED_PAYLOAD_INDEX_COLLECTIONS = set()
def _build_supabase_file_url(object_path: str) -> str: """Tạo URL đầy đủ cho tài liệu từ Supabase Storage.""" if not SUPABASE_URL or not SUPABASE_STORAGE_BUCKET or not object_path: return "" clean_path = object_path.lstrip("/") return f"{SUPABASE_URL}/storage/v1/object/public/{SUPABASE_STORAGE_BUCKET}/{clean_path}"
def _extract_years_from_academic_year(academic_year: str) -> List[int]: """Trích xuất danh sách năm từ chuỗi năm học (ví dụ '2023-2024' -> [2023, 2024]).""" if not academic_year or academic_year == "ALL": return [] years = [] match = ACTIVE_CODE_PATTERN.search(academic_year) if match: try: start_year = int(match.group(1)) end_year = int(match.group(2)) years = [start_year, end_year] except (ValueError, IndexError): pass return years
def _load_documents_for_ingest(path: str, extension: str) -> List[LangChainDocument]:74 unmodified lines
def _ensure_payload_indexes(client: QdrantClient, collection_name: str) -> None: if collection_name in _ENSURED_PAYLOAD_INDEX_COLLECTIONS: return
# KEYWORD indexes cho filtering nhanh for field_name in ("object_path", "document_id", "content_hash"): for field_name in ("object_path", "document_id"): try: client.create_payload_index( collection_name=collection_name, field_name=field_name, field_schema=PayloadSchemaType.KEYWORD, wait=True, ) except Exception as e: logger.warning(f"Failed to create KEYWORD index for {field_name}: {e}") # INTEGER array index cho years try: client.create_payload_index( collection_name=collection_name, field_name="years", field_schema=PayloadSchemaType.INTEGER, field_name=field_name, field_schema=PayloadSchemaType.KEYWORD, wait=True, ) except Exception as e: logger.warning(f"Failed to create INTEGER index for years: {e}")
_ENSURED_PAYLOAD_INDEX_COLLECTIONS.add(collection_name)
def _is_missing_payload_index_error(error: Exception) -> bool:1 unmodified line return "Index required but not found" in message
def _get_or_create_deduplicated_points( client: QdrantClient, collection_name: str, chunk_docs: List[LangChainDocument], vectors: List, source_object_ref: str, document: Document, source_updated_at: Optional[str], source_etag: Optional[str], created_at: str, effective_source_path: Optional[str] = None,) -> tuple[List[PointStruct], List[DocumentChunk]]: """ Tích hợp MD5 deduplication: nếu content hash trùng, cập nhật years array thay vì tạo mới. """ points: List[PointStruct] = [] db_chunk_rows: List[DocumentChunk] = [] for index, (chunk_doc, vector) in enumerate(zip(chunk_docs, vectors)): chunk_text = chunk_doc.page_content metadata = chunk_doc.metadata if isinstance(chunk_doc.metadata, dict) else {} # Tính content hash content_hash = hashlib.md5(chunk_text.encode('utf-8')).hexdigest() # Trích académie năm học academic_year = metadata.get("academic_year") or "ALL" years = _extract_years_from_academic_year(academic_year) # Tạo source URL source_url = _build_supabase_file_url(source_object_ref) # Kiểm tra xem content_hash đã tồn tại existing_point_id = None try: existing_points = client.scroll( collection_name=collection_name, limit=1, scroll_filter=Filter( must=[ FieldCondition( key="content_hash", match=MatchValue(value=content_hash), ) ] ), ) if existing_points and existing_points[0]: # Nếu tìm thấy point với hash trùng existing_point_id = existing_points[0][0].id logger.info(f"Tìm thấy content đã tồn tại hash={content_hash[:8]}..., sẽ cập nhật years") except Exception as e: logger.debug(f"Không thể tìm kiếm existing points: {e}") if existing_point_id: # Merge years array try: existing_payload = client.retrieve(collection_name, [existing_point_id])[0].payload existing_years = set(existing_payload.get("years", [])) merged_years = sorted(list(set(years) | existing_years)) # Update payload với years mới updated_payload = { **existing_payload, "years": merged_years, "document_id": document.id, # Update document_id nếu tài liệu mới "source_updated_at": source_updated_at or existing_payload.get("source_updated_at"), } # ✅ Dùng set_payload để cập nhật payload client.set_payload( collection_name=collection_name, payload=updated_payload, points=[existing_point_id], ) logger.info(f"Đã cập nhật years cho hash {content_hash[:8]}...: {merged_years}") # ✅ QUAN TRỌNG: Bỏ qua tạo point mới - vì đã cập nhật point đã tồn tại continue except Exception as e: logger.warning(f"Lỗi cập nhật years cho point đã tồn tại: {e}, sẽ tạo point mới") # Fallback: tạo point mới nếu cập nhật thất bại pass # Tạo point mới point_id = str(uuid.uuid4()) payload = _build_payload( document, source_object_ref, chunk_text, index, metadata, academic_year, years, content_hash, source_url, source_updated_at, source_etag, created_at, effective_source_path ) points.append(PointStruct(id=point_id, vector=vector, payload=payload)) db_chunk_rows.append( DocumentChunk( document_id=document.id, chunk_index=index, content_preview=chunk_text[:200], qdrant_point_id=point_id, ) ) return points, db_chunk_rows
def _build_payload( document: Document, source_object_ref: str, chunk_text: str, index: int, metadata: dict, academic_year: str, years: List[int], content_hash: str, source_url: str, source_updated_at: Optional[str], source_etag: Optional[str], created_at: str, effective_source_path: Optional[str] = None,) -> dict: """Xây dựng payload dictionary cho point.""" source_name = os.path.basename(source_object_ref) if source_object_ref else document.stored_name source_relpath = source_object_ref or source_name return { "document_id": document.id, "filename": document.original_name, "stored_effective_source_path or name": document.stored_name, "path": document.path, "object_path": source_object_ref, "folder_key": document.folder_key, "collection_name": document.collection_name or "", "source_file": metadata.get("source_file") or source_name, "source_relpath": metadata.get("source_relpath") or source_relpath, "source_url": source_url, "academic_year": academic_year, "years": years, "content_hash": content_hash, "page_number": metadata.get("page_number"), "source_updated_at": source_updated_at, "source_etag": source_etag, "chunk_index": index, "created_at": created_at, "content": chunk_text, }
def _delete_existing_document_points( client: QdrantClient, collection_name: str,33 unmodified lines "Missing payload index detected while deleting old points in collection=%s. Rebuilding indexes and retrying once.", collection_name, ) _ENSURED_PAYLOAD_INDEX_COLLECTIONS.discard(collection_name) _ensure_payload_indexes(client, collection_name) client.delete( collection_name=collection_name,69 unmodified lines _delete_existing_document_points(client, target_collection, source_object_ref, document.id)
created_at = datetime.now(timezone.utc).isoformat() # NEW: Sử dụng deduplication logic points, db_chunk_rows = _get_or_create_deduplicated_points( client=client, collection_name=target_collection, chunk_docs=chunk_docs, vectors=vectors, source_object_ref=source_object_ref, document=document, source_updated_at=source_updated_at, source_etag=source_etag, created_at=created_at, effective_source_path=effective_source_path, ) points: List[PointStruct] = [] db_chunk_rows: List[DocumentChunk] = []
for index, (chunk_doc, vector) in enumerate(zip(chunk_docs, vectors)): chunk_text = chunk_doc.page_content metadata = chunk_doc.metadata if isinstance(chunk_doc.metadata, dict) else {} point_id = str(uuid.uuid4()) payload = { "document_id": document.id, "filename": document.original_name, "stored_name": document.stored_name, "path": effective_source_path or document.path, "object_path": source_object_ref, "folder_key": document.folder_key, "collection_name": target_collection, "source_file": metadata.get("source_file") or source_name, "source_relpath": metadata.get("source_relpath") or source_relpath, "academic_year": metadata.get("academic_year") or "ALL", "page_number": metadata.get("page_number"), "source_updated_at": source_updated_at, "source_etag": source_etag, "chunk_index": index, "created_at": created_at, "content": chunk_text, }
points.append(PointStruct(id=point_id, vector=vector, payload=payload)) db_chunk_rows.append( DocumentChunk( document_id=document.id, chunk_index=index, content_preview=chunk_text[:200], qdrant_point_id=point_id, ) )
# ✅ Chỉ upsert nếu có points mới (không phải cập nhật existing) if points: client.upsert(collection_name=target_collection, points=points, wait=True) client.upsert(collection_name=target_collection, points=points, wait=True)
db.query(DocumentChunk).filter(DocumentChunk.document_id == document.id).delete() # ✅ Chỉ bulk save nếu có chunks mới if db_chunk_rows: db.bulk_save_objects(db_chunk_rows) db.bulk_save_objects(db_chunk_rows)
if effective_source_path: document.path = effective_source_path77 unmodified lines "Missing payload index detected while deleting object_path in collection=%s. Rebuilding indexes and retrying once.", target_collection, ) _ENSURED_PAYLOAD_INDEX_COLLECTIONS.discard(target_collection) _ensure_payload_indexes(client, target_collection) client.delete( collection_name=target_collection,84 unmodified lines85868788888990915 unmodified lines97989910010110210210310410510310410510610710810911011111011211311411584 unmodified lines # Lấy ví dụ phù hợp (Fallback về simple nếu không khớp) example = examples.get(question_type, examples['simple'])
# TOPIC INSTRUCTION: Rào chắn ngữ cảnh (Context Guardrail) # 3. TOPIC INSTRUCTION: Rào chắn ngữ cảnh (Context Guardrail) if topic: topic_instr = ( f"\n\n **LƯU Ý ĐẶC BIỆT VỀ CHỦ ĐỀ MỞ RỘNG:**\n"5 unmodified lines else: topic_instr = ""
# [YEAR-AWARE CHANGE] Rang buoc cau tra loi theo nam hoc duoc hoi. if year_scope: year_instr = ( f"\n\n **RÀNG BUỘC NĂM HỌC (LƯU Ý QUAN TRỌNG):**\n" f"- Người dùng đang hỏi cho năm học: **{year_scope}**.\n" f"- Nếu trong `TÀI LIỆU THAM KHẢO` có nội dung khớp với năm này, hãy dùng nó làm đáp án chính.\n" f"- Nếu KHÔNG CÓ nội dung đúng năm, BẮT BUỘC SỬ DỤNG tài liệu có nhãn 'Áp dụng nhiều năm' hoặc quy chế gần nhất có trong context. Khi trả lời, hãy rào trước một câu thân thiện: *'Hệ thống hiện ghi nhận quy chế dùng chung/năm [Năm của tài liệu] quy định như sau...'*. TUYỆT ĐỐI KHÔNG TỪ CHỐI trả lời nếu vẫn có bản dùng chung.\n" f"\n\n **RÀNG BUỘC NĂM HỌC (BẮT BUỘC):**\n" f"- Người dùng đang hỏi trong phạm vi năm: **{year_scope}**.\n" f"- Ưu tiên các đoạn có nhãn nguồn cùng năm trong context (ví dụ: [Năm 2022-2023 | ...]).\n" f"- Nếu chưa đủ bằng chứng đúng năm, được phép dùng đoạn có nhãn 'Áp dụng nhiều năm' hoặc quy định gần nhất và phải ghi chú rõ phạm vi áp dụng.\n" f"- Không kết luận 'không có dữ liệu' chỉ vì thiếu đúng nhãn năm nếu vẫn có quy định bao quát liên quan.\n" ) else: year_instr = ""
# Gộp Prompt # 4. Gộp Prompt full_prompt = f"""{base_system}----------------{example}11234567789101 unmodified line121314151516174 unmodified lines222324262728293031323334252627102 unmodified lines13013113214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318413313413595 unmodified lines2312322332862342882352362372912922932942952382392402412982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363372422432442453392462472482492502512522532544 unmodified lines2592602613503513523533543553563573583593603613623633643653663673683693703713723733743753763773782622632642652662672682692702712722732742752762772782792803813822813842822832843872852862872882892902912922932942952962972982993003013023033903043053063073083963093103113124003133143153 unmodified lines31932032141041132232332432532641641732732832933015 unmodified lines34634734843934935035135210 unmodified lines363364365456366458367from typing import List, Generator, Optionalfrom typing import List, Generatorimport os, re, hashlibimport logging import groqimport google.generativeai as genaiimport json import unicodedata
from .models import llmfrom .config import TOP_K_RESULTS, FINAL_TOP_Kfrom .rerank import advanced_rerank1 unmodified linefrom .retriever import HybridRetrieverfrom .analyze_and_expand import analyze_and_expand_queryfrom .llm_utils import safe_invoke, safe_streamimport concurrent.futures
logger = logging.getLogger(__name__)
4 unmodified lines# [YEAR-AWARE CHANGE] Pattern nhan dien nam hoc trong cau hoi.ACADEMIC_YEAR_PATTERN = re.compile(r"\b(20\d{2})\s*[-_/]\s*(20\d{2})\b")SINGLE_YEAR_PATTERN = re.compile(r"\b(20\d{2})\b")_SOCIAL_KEYWORDS = { "hello", "hi", "xin chao", "chao", "alo", "hey", "thanks", "cam on", "tam biet", "bye"}_PERSONAL_NON_DOMAIN_PATTERNS = [ re.compile(r"\bb(ạn|an)\s+c[oó]\s+bi[eế]t\s+t[oô]i\s+l[aà]\s+ai\b", re.IGNORECASE), re.compile(r"\bb(ạn|an)\s+l[aà]\s+ai\b", re.IGNORECASE), re.compile(r"\bai\s+t[aạ]o\s+ra\s+b(ạn|an)\b", re.IGNORECASE), re.compile(r"\b(ăn|an)\s+c[oơ]m\s+ch(ưa|ua)\b", re.IGNORECASE),]
# Quản lý API Keys cho Groq và Gemini với xoay tua tự động khi gặp lỗi hoặc hết hạnclass AIProviderManager:102 unmodified lines text = re.sub(r"\b\d{8,12}\b", "[ID]", text) return text.strip()
def remove_accents(input_str: str) -> str: s1 = unicodedata.normalize('NFKD', input_str).encode('ASCII', 'ignore').decode('utf-8') return s1.lower()
def _normalize_for_router(message: str) -> str: compact = remove_accents(message or "") compact = re.sub(r"[^\w\s]", " ", compact, flags=re.UNICODE) return re.sub(r"\s+", " ", compact).strip()
def _quick_non_domain_reply(message: str) -> Optional[str]: normalized = _normalize_for_router(message) if not normalized: return None
if normalized in _SOCIAL_KEYWORDS: return "Chào bạn. Mình hỗ trợ tra cứu quy chế đào tạo, bạn cần hỏi nội dung nào?"
for pattern in _PERSONAL_NON_DOMAIN_PATTERNS: if pattern.search(normalized): return "Mình không có thông tin cá nhân của bạn. Mình chỉ hỗ trợ giải đáp về quy chế đào tạo."
return None
def _was_recently_prompted_for_year(history: List) -> bool: if not history: return False
reminder_snippet = "Vui lòng nhập kèm năm học để tra cứu nhanh hơn" for item in reversed(history[-6:]): if not isinstance(item, dict): continue if str(item.get("role") or "").strip().lower() != "assistant": continue content = str(item.get("content") or "") if reminder_snippet in content: return True
return False
def generate_standalone_query(message: str, history: List) -> str: """Tái tạo câu hỏi từ lịch sử """ if not history:95 unmodified lines yield full_response
def ask_ai_stream_delta(message: str, history: List, hybrid_retriever) -> Generator[str, None, None]: # Kiểm tra rỗng if not message.strip(): yield "Bạn chưa nhập câu hỏi." yield " Bạn chưa nhập câu hỏi." return
# Xử lý các câu giao tiếp/xã giao nhanh (đã được sửa lỗi dấu tiếng Việt) quick_reply = _quick_non_domain_reply(message) if quick_reply: logger.info("Bỏ qua truy xuất tài liệu cho câu hỏi giao tiếp/ngoài phạm vi") yield quick_reply if message.strip().lower() in {"hello", "hi", "xin chào", "chào"}: yield "Chào bạn 👋 Mình hỗ trợ tra cứu quy chế đào tạo. Bạn cần hỏi điều gì?" return
# Song song : generate_standalone_query + analyze_and_expand_query cùng 1 lúc, không chờ đợi lẫn nhau, giảm độ trễ tổng thể logger.info(f"CÂU HỎI GỐC: {message}") try: with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: # Call 1: Tạo standalone question từ history future_standalone = executor.submit( generate_standalone_query, message, history ) # Call 2: Phân loại & mở rộng (song parallel) # Dùng message gốc luôn, LLM sẽ handle context từ message future_classify = executor.submit( analyze_and_expand_query, message # ✅ Dùng message gốc, không chờ standalone xong ) # Chờ cả 2 xong (timeout 15s) question = future_standalone.result(timeout=15) processed_data = future_classify.result(timeout=15) except concurrent.futures.TimeoutError: logger.warning("Timeout khi gọi LLM song parallel, fallback...") question = message processed_data = { "question_type": "simple", "answer": None, "expanded_queries": [message] } except Exception as e: logger.warning(f"Lỗi parallel execution: {e}, fallback...") question = message processed_data = { "question_type": "simple", "answer": None, "expanded_queries": [message] } logger.info(f" CÂU HỎI GỐC: {message}") question = generate_standalone_query(message, history) # [YEAR-AWARE CHANGE] Xac dinh pham vi nam ma nguoi dung yeu cau. requested_year_range, mentioned_years = detect_requested_year(f"{message}\n{question}") year_scope_hint = requested_year_range or (", ".join(sorted(mentioned_years)) if mentioned_years else None) if requested_year_range: logger.info(f"Lọc theo năm học yêu cầu: {requested_year_range}") elif mentioned_years: logger.info(f"Lọc theo năm được nhắc tới: {sorted(mentioned_years)}")
processed_data = analyze_and_expand_query(question)
if processed_data.get("question_type") == "normal": ans = processed_data.get("answer") or "Chào bạn 👋 Mình hỗ trợ tra cứu quy chế đào tạo."4 unmodified lines queries = processed_data['expanded_queries'] logger.info(f"Các truy vấn tìm kiếm: {queries}")
def fetch_docs(year_hint): docs_temp = [] seen_temp = set() def single_search(query): current_alpha = 0.4 if "CNTT" in query.upper() else 0.5 return hybrid_retriever.search(query, k=TOP_K_RESULTS, alpha=current_alpha, year_scope=year_hint) # Bắn đồng loạt các truy vấn cùng 1 lúc with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor: results = executor.map(single_search, queries) for retrieved in results: for doc in retrieved: # Tối ưu: Dùng id của Qdrant (nếu có) hoặc hash nội dung content_hash = hashlib.sha256(doc.page_content.encode("utf-8")).hexdigest() if content_hash not in seen_temp: docs_temp.append(doc) seen_temp.add(content_hash) return docs_temp # Tìm tài liệu # Cố gắng tìm tài liệu khớp chính xác với năm học người dùng nhắc đến all_docs = fetch_docs(year_scope_hint)
# Nếu lớp 1 tìm không ra hoặc người dùng hoàn toàn không nhập năm, hệ thống sẽ tự động hạ chuẩn, tìm trên toàn bộ cơ sở dữ liệu chung (ALL) if not all_docs and year_scope_hint: logger.info(f"Bộ lọc năm '{year_scope_hint}' quá gắt không ra kết quả. Tự động Fallback tìm trên bản chung...") year_scope_hint = None # Reset lại biến hint để quét toàn bộ VectorDB all_docs = fetch_docs(None) all_docs: List = [] seen = set() year_scope_hint = requested_year_range or (", ".join(sorted(mentioned_years)) if mentioned_years else None) for query in queries: #Giữ nguyên logic alpha ngành CNTT của Minh current_alpha = 0.4 if "CNTT" in query.upper() else 0.5 docs = hybrid_retriever.search( query, k=TOP_K_RESULTS, alpha=current_alpha, year_scope=year_scope_hint, ) for doc in docs: content_hash = hashlib.sha256(doc.page_content.encode("utf-8")).hexdigest() if content_hash not in seen: all_docs.append(doc) seen.add(content_hash)
logger.info(f"Tìm thấy tổng {len(all_docs)} documents.") # Xử lý lịch sự nếu Vector DB thực sự "bó tay" if not all_docs: yield f"Dạ, hiện tại hệ thống không tìm thấy quy định nào liên quan đến vấn đề này. Bạn có thể dùng các từ khóa mang tính hành chính hơn được không ạ?" yield "Không tìm thấy thông tin liên quan trong tài liệu." return
# Rerank lại kết quả để chống ảo giác # [YEAR-AWARE CHANGE] Lọc theo năm nhưng vẫn fallback nếu không có tài liệu đúng năm. year_scope = None year_filter_requested = bool(requested_year_range or mentioned_years) year_filtered_docs = filter_docs_by_year(all_docs, requested_year_range, mentioned_years)
if year_filter_requested: if year_filtered_docs: if len(year_filtered_docs) != len(all_docs): logger.info(f"Đã lọc theo năm: còn {len(year_filtered_docs)}/{len(all_docs)} documents") all_docs = year_filtered_docs if requested_year_range: year_scope = requested_year_range elif mentioned_years: year_scope = ", ".join(sorted(mentioned_years)) else: logger.warning("Không tìm thấy tài liệu đúng năm yêu cầu, fallback sang tập tài liệu tổng quát")
final_docs = advanced_rerank(question, all_docs, top_k=FINAL_TOP_K)
# Gắn nhãn năm học vào Context cho LLM đọc context_parts = [] total_chars = 0 for doc in final_docs: page = doc.metadata.get('page_number', 'N/A') file_name = doc.metadata.get('source_file') or doc.metadata.get('source') # [YEAR-AWARE CHANGE] Gan nhan nam trong context de LLM bam dung nguon. doc_year = infer_doc_academic_year(doc) year_label = f"Năm {doc_year}" if doc_year != "ALL" else "Áp dụng nhiều năm" source = f"[{year_label} | {os.path.basename(file_name)} | Trang {page}]" if file_name else f"[{year_label} | Trang {page}]" block = f"{source}\n{doc.page_content}" if total_chars + len(block) > MAX_CONTEXT_CHARS: break3 unmodified lines context = "\n\n---\n\n".join(context_parts) topic_hint = processed_data.get('topic') or processed_data.get('root_question') or question
# Truyền year_scope_hint vào prompt để LLM biết đường rào đón prompt = create_advanced_prompt(question, context, question_type, topic_hint, year_scope=year_scope_hint) prompt = create_advanced_prompt(question, context, question_type, topic_hint, year_scope=year_scope)
logger.info("Đang tạo câu trả lời cuối cùng ...") success = False # Streaming qua Groq (Có xoay tua khi gặp lỗi 429) # Thử với Groq for _ in range(len(api_manager.groq_keys)): try: client = api_manager.get_groq_client()15 unmodified lines logger.error(f"Lỗi Groq: {e}") break # Streaming dự phòng qua Gemini # Dự phòng sang Gemini (nếu Groq lỗi hoặc hết key) if not success: logger.warning("Chuyển sang Gemini ...") for _ in range(max(1, len(api_manager.gemini_keys))):10 unmodified lines api_manager.rotate_gemini() logger.error(f"Lỗi Gemini: {e}")
# Báo lỗi khi cả 2 API đều sập if not success: yield "Đã xảy ra lỗi hệ thống hoặc quá tải API. Vui lòng thử lại sau giây lát!" yield "Đã xảy ra lỗi hệ thống hoặc quá tải. Vui lòng thử lại sau giây lát!"12235645678111213141516171819209101112131415from typing import Listimport loggingfrom .models import cross_encoder
MAX_RERANK_CHARS = 800logger = logging.getLogger(__name__)MAX_RERANK_CHARS = 1200
def advanced_rerank(question: str, docs: List, top_k: int = 5) -> List: if not docs: return [] MAX_DOCS_TO_RERANK = 15 pruned_docs = docs[:MAX_DOCS_TO_RERANK] logger.info("Đang rerank %s tài liệu với Cross-Encoder...", len(pruned_docs)) pairs = [(question, (doc.page_content or "")[:MAX_RERANK_CHARS]) for doc in pruned_docs] scores = cross_encoder.predict(pairs, show_progress_bar=False) ranked = sorted(zip(scores, pruned_docs), key=lambda x: x[0], reverse=True) logger.info("Top 3 điểm: %s", [f"{s:.3f}" for s, _ in ranked[:3]]) print(f"Đang rerank {len(docs)} documents với Cross-Encoder...") pairs = [(question, (doc.page_content or "")[:MAX_RERANK_CHARS]) for doc in docs] scores = cross_encoder.predict(pairs) ranked = sorted(zip(scores, docs), key=lambda x: x[0], reverse=True) print(f" Top 3 scores: {[f'{s:.3f}' for s, _ in ranked[:3]]}") return [doc for score, doc in ranked[:top_k]]
12 unmodified lines1314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465661617184 unmodified lines232425262728294 unmodified lines3435368788899091929394953738394012 unmodified lines self.rrf_c = 60 print(" BM25 sẵn sàng!")
@staticmethod def _filter_by_year_scope(documents: List, year_scope: str | None) -> List: """Filter documents theo year_scope (ví dụ: '2023-2024' hoặc '2023').""" if not year_scope: return documents filtered = [] year_targets = set() # Parse year_scope: có thể là "2023-2024" hoặc "2023" if "-" in year_scope: parts = year_scope.split("-") try: year_targets = {int(p.strip()) for p in parts if p.strip()} except ValueError: return documents else: try: year_targets = {int(year_scope.strip())} except ValueError: return documents for doc in documents: metadata = doc.metadata if isinstance(doc.metadata, dict) else {} # Check years array (mới) doc_years = metadata.get("years", []) if isinstance(doc_years, list) and any(y in year_targets for y in doc_years): filtered.append(doc) continue # Check academic_year string (cũ, để backwards compatibility) academic_year = metadata.get("academic_year", "") if academic_year and academic_year != "ALL": doc_year_tokens = set() for potential_year in academic_year.split("-"): try: doc_year_tokens.add(int(potential_year.strip())) except ValueError: pass if doc_year_tokens.intersection(year_targets): filtered.append(doc) continue # Include ALL documents không có year info if not doc_years and academic_year == "ALL": filtered.append(doc) return filtered if filtered else documents
@staticmethod def _doc_key(doc) -> str: metadata = doc.metadata if isinstance(doc.metadata, dict) else {}4 unmodified lines return f"{source}|{page}|{digest}"
def search(self, query: str, k: int = 10, alpha: float = 0.6, year_scope: str | None = None) -> List: del year_scope if not self.documents or k <= 0: return []
4 unmodified lines # Lấy top k từ BM25 tokenized_query = query.lower().split() candidate_k = min(max(k * 4, k), len(self.documents)) # Filter documents theo year_scope nếu có docs_to_search = self.documents if year_scope: docs_to_search = self._filter_by_year_scope(self.documents, year_scope) if not docs_to_search: docs_to_search = self.documents # Fallback nếu không có doc match year bm25_top_docs = self.bm25.get_top_n(tokenized_query, docs_to_search, n=candidate_k) bm25_top_docs = self.bm25.get_top_n(tokenized_query, self.documents, n=candidate_k)
bm25_ranked = {} all_retrieved = {}123456789101112345671889102111121324252614151617182919202132222324import re
#Compile regex patterns một lần toàn cục - tránh recompile mỗi lần gọi_HYPHENATED_WORD_PATTERN = re.compile(r'(\w+)-\s*\n\s*(\w+)')_INVALID_CHARS_PATTERN = re.compile(r'[^\w\s\.,;:!?\-$$\"\'\À-ỹ\n\|<>]')_MULTIPLE_SPACES_PATTERN = re.compile(r'[ \t]+')_SPACE_BEFORE_NEWLINE_PATTERN = re.compile(r' +\n')_SPACE_AFTER_NEWLINE_PATTERN = re.compile(r'\n +')_MULTIPLE_NEWLINES_PATTERN = re.compile(r'\n{3,}')_SPACE_BEFORE_PUNCTUATION_PATTERN = re.compile(r'\s+([.,;:!?])')
def clean_text(text: str) -> str: if not text or not text.strip(): return "" # Nối các từ bị gãy ngang do xuống dòng text = _HYPHENATED_WORD_PATTERN.sub(r'\1\2', text) text = re.sub(r'(\w+)-\s*\n\s*(\w+)', r'\1\2', text) # \| và < > vào để bảo vệ khung Bảng Markdown và các Placeholder text = _INVALID_CHARS_PATTERN.sub(' ', text) text = re.sub(r'[^\w\s\.,;:!?\-$$\"\'\À-ỹ\n\|<>]', ' ', text) # Chuẩn hóa khoảng trắng text = _MULTIPLE_SPACES_PATTERN.sub(' ', text) text = _SPACE_BEFORE_NEWLINE_PATTERN.sub('\n', text) text = _SPACE_AFTER_NEWLINE_PATTERN.sub('\n', text) text = re.sub(r'[ \t]+', ' ', text) text = re.sub(r' +\n', '\n', text) text = re.sub(r'\n +', '\n', text) # Giới hạn tối đa 2 dòng trống liên tiếp text = _MULTIPLE_NEWLINES_PATTERN.sub('\n\n', text) text = re.sub(r'\n{3,}', '\n\n', text) # Sửa lỗi dư khoảng trắng trước dấu câu text = _SPACE_BEFORE_PUNCTUATION_PATTERN.sub(r'\1', text) text = re.sub(r'\s+([.,;:!?])', r'\1', text) return text.strip()36 unmodified lines3738394041424340414236 unmodified lines# Hàm log lỗi an toànlogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)logging.getLogger("httpx").setLevel(logging.WARNING)logging.getLogger("httpcore").setLevel(logging.WARNING)logging.getLogger("qdrant_client").setLevel(logging.WARNING)logging.getLogger("sentence_transformers").setLevel(logging.WARNING)MAX_HISTORY_MESSAGES = int(os.getenv("MAX_HISTORY_MESSAGES", "20"))POOL_MIN_SIZE = int(os.getenv("DB_POOL_MIN_SIZE", "1"))POOL_MAX_SIZE = int(os.getenv("DB_POOL_MAX_SIZE", "10"))core/analyze_and_expand.py+2-6
core/chunking.py+5-5
core/collection_router_retriever.py+4-56
core/collection_utils.py+4-7
core/config.py+4-4
core/document_ingest_service.py+41-224
core/prompting.py+8-6
core/qa_pipeline.py+54-145
core/rerank.py+6-13
core/retriever.py+2-60
core/text_utils.py+7-17
main.py-4