# rag_router.py import os from typing import List, Dict, Any, Optional from fastapi import APIRouter, Query from pydantic import BaseModel from openai import OpenAI from rag_pipeline import build_index, search as rag_search router = APIRouter(prefix="/rag", tags=["RAG"]) OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") MODEL_NAME = os.environ.get("OPENAI_MODEL", "gpt-5") client = OpenAI(api_key=OPENAI_API_KEY) if OPENAI_API_KEY else None @router.get("/health") def health(): return {"ok": True} @router.post("/reindex") def reindex(scopes: Optional[List[str]] = Query(default=None), force: bool = Query(default=False)): """ POST /rag/reindex?scopes=Tai_lieu/&scopes=Bang_gia/&force=1 """ stats = build_index(scopes=scopes, force=force) return {"status": "ok", **stats} class SearchReq(BaseModel): q: str k: int = 8 scopes: Optional[List[str]] = None # ví dụ ["Tai_lieu/"] hoặc ["Bang_gia/"] @router.post("/search") def search(req: SearchReq): hits = rag_search(req.q, top_k=req.k, scopes=req.scopes) return {"data": hits} class ChatReq(BaseModel): question: str history: Optional[List[Dict[str, str]]] = None k: int = 6 scopes: Optional[List[str]] = None def _compose_prompt(question: str, hits: List[Dict[str, Any]], history: Optional[List[Dict[str, str]]]) -> str: ctx = "\n".join([f"- ({h['repo_path']}) {h['preview']}" for h in hits]) or "(không tìm thấy ngữ cảnh)" hist = "\n".join([f"[{m.get('role','user')}] {m.get('content','')}" for m in (history or [])][-8:]) return f"""Bạn là trợ lý nội bộ. Chỉ dùng NGỮ CẢNH dưới đây để trả lời. Nếu không đủ, hãy nói 'Không đủ thông tin trong dataset' và đề xuất thêm gì cần. NGỮ CẢNH: {ctx} LỊCH SỬ: {hist} YÊU CẦU: - Trả lời tiếng Việt, ngắn gọn, có căn cứ. - Cuối câu trả lời, thêm **Nguồn**: tối đa 5 repo_path. CÂU HỎI: {question}""" @router.post("/chat") def chat(req: ChatReq): hits = rag_search(req.question, top_k=req.k, scopes=req.scopes) if not client: return {"reply": "Chưa cấu hình OPENAI_API_KEY. Trả các đoạn liên quan nhất:\n" + "\n".join([f"- ({h['repo_path']}) {h['preview']}" for h in hits]), "sources": list({h["repo_path"] for h in hits})[:5], "hits": hits} prompt = _compose_prompt(req.question, hits, req.history) rsp = client.chat.completions.create(model=MODEL_NAME, temperature=0.2, messages=[{"role":"user","content":prompt}]) ans = rsp.choices[0].message.content.strip() sources = list({h["repo_path"] for h in hits})[:5] return {"reply": ans, "sources": sources, "hits": hits}