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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
@app.get("/")
|
| 48 |
def root():
|
| 49 |
return {"message": "✅ Backend is running"}
|
| 50 |
+
# ================== CHATBOT – GPT-5 + RAG + ACTION ==================
|
| 51 |
+
import os, re, datetime, httpx
|
| 52 |
+
from typing import List, Optional, Tuple, Dict
|
| 53 |
+
from pydantic import BaseModel
|
| 54 |
+
from fastapi import APIRouter, Body
|
| 55 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 56 |
+
from openai import OpenAI
|
| 57 |
+
from rag_indexer import build_index, search as rag_search
|
| 58 |
+
|
| 59 |
+
# Cho phép frontend gọi từ domain khác (nếu cần)
|
| 60 |
+
app.add_middleware(
|
| 61 |
+
CORSMiddleware,
|
| 62 |
+
allow_origins=["*"], allow_credentials=True,
|
| 63 |
+
allow_methods=["*"], allow_headers=["*"],
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
|
| 67 |
+
MODEL_NAME = os.environ.get("OPENAI_MODEL","gpt-5") # ← dùng GPT-5
|
| 68 |
+
client = OpenAI(api_key=OPENAI_API_KEY)
|
| 69 |
+
|
| 70 |
+
# -------- ReIndex (quét dataset & lập chỉ mục) --------
|
| 71 |
+
router_rag = APIRouter()
|
| 72 |
+
|
| 73 |
+
@router_rag.post("/reindex")
|
| 74 |
+
def reindex():
|
| 75 |
+
out = build_index()
|
| 76 |
+
return {"status":"ok", **out}
|
| 77 |
+
|
| 78 |
+
# -------- Chat dựa trên dữ liệu nội bộ (RAG) ----------
|
| 79 |
+
class AskReq(BaseModel):
|
| 80 |
+
question: str
|
| 81 |
+
history: Optional[List[dict]] = []
|
| 82 |
+
|
| 83 |
+
def _llm_complete(prompt: str) -> str:
|
| 84 |
+
rsp = client.chat.completions.create(
|
| 85 |
+
model=MODEL_NAME, temperature=0.2,
|
| 86 |
+
messages=[{"role":"system","content":
|
| 87 |
+
"Bạn là trợ lý nội bộ. Chỉ trả lời dựa trên NGỮ CẢNH nếu có; nếu thiếu thông tin thì nói rõ không đủ trong dữ liệu nội bộ."},
|
| 88 |
+
{"role":"user","content":prompt}]
|
| 89 |
+
)
|
| 90 |
+
return rsp.choices[0].message.content.strip()
|
| 91 |
+
|
| 92 |
+
@router_rag.post("/chat_rag")
|
| 93 |
+
def chat_rag(req: AskReq):
|
| 94 |
+
hits = rag_search(req.question, top_k=6)
|
| 95 |
+
ctx = "\n".join([f"- {h['repo_path']}: {h['preview']}" for h in hits]) or "(không tìm thấy ngữ cảnh phù hợp)"
|
| 96 |
+
hist = "\n".join([f"[{m.get('role','user')}] {m.get('content','')}" for m in (req.history or [])][-6:])
|
| 97 |
+
|
| 98 |
+
prompt = f"""
|
| 99 |
+
NGỮ CẢNH (trích từ dữ liệu nội bộ):
|
| 100 |
+
{ctx}
|
| 101 |
+
|
| 102 |
+
LỊCH SỬ:
|
| 103 |
+
{hist}
|
| 104 |
+
|
| 105 |
+
YÊU CẦU:
|
| 106 |
+
- Trả lời bằng tiếng Việt, dựa trên NGỮ CẢNH ở trên.
|
| 107 |
+
- Nếu NGỮ CẢNH không đủ hoặc không liên quan, nói rõ: "Mình chưa thấy đủ thông tin trong dữ liệu nội bộ."
|
| 108 |
+
- Cuối câu trả lời, liệt kê 'Nguồn' (các repo_path nổi bật).
|
| 109 |
+
|
| 110 |
+
CÂU HỎI: {req.question}
|
| 111 |
+
"""
|
| 112 |
+
ans = _llm_complete(prompt)
|
| 113 |
+
sources = list({h['repo_path'] for h in hits})[:5]
|
| 114 |
+
return {"reply": ans, "sources": sources, "hits": hits}
|
| 115 |
+
|
| 116 |
+
app.include_router(router_rag)
|
| 117 |
+
|
| 118 |
+
# -------- Chat thường (giống đang dùng ChatGPT-5) --------
|
| 119 |
+
router_chat = APIRouter()
|
| 120 |
+
|
| 121 |
+
class ChatReq(BaseModel):
|
| 122 |
+
messages: List[dict]
|
| 123 |
+
|
| 124 |
+
@router_chat.post("/chat")
|
| 125 |
+
def chat(req: ChatReq):
|
| 126 |
+
sys_prompt = {"role":"system","content":"Bạn là chatbot nội bộ, trả lời ngắn gọn, rõ ràng bằng tiếng Việt."}
|
| 127 |
+
msgs = [sys_prompt] + (req.messages[-15:] if req.messages else [])
|
| 128 |
+
rsp = client.chat.completions.create(model=MODEL_NAME, messages=msgs, temperature=0.2)
|
| 129 |
+
return {"reply": rsp.choices[0].message.content}
|
| 130 |
+
|
| 131 |
+
app.include_router(router_chat)
|
| 132 |
+
|
| 133 |
+
# -------- Chat tự phân loại (ACTION / RAG / GENERAL) --------
|
| 134 |
+
router_smart = APIRouter()
|
| 135 |
+
|
| 136 |
+
class SmartReq(BaseModel):
|
| 137 |
+
message: str
|
| 138 |
+
history: Optional[List[dict]] = []
|
| 139 |
+
|
| 140 |
+
class SmartResp(BaseModel):
|
| 141 |
+
intent: str
|
| 142 |
+
reply: str
|
| 143 |
+
sources: Optional[List[str]] = None
|
| 144 |
+
|
| 145 |
+
KEY_RAG = [r"\bPYC\b", r"phiếu\s*yêu\s*cầu", r"báo\s*giá", r"hợp\s*đồng", r"quy\s*trình", r"biên\s*bản", r"tài\s*liệu"]
|
| 146 |
+
KEY_PYC_PENDING = [r"PYC\s*chưa\s*hoàn\s*thành", r"chưa\s*hoàn\s*thành"]
|
| 147 |
+
KEY_REVENUE = [r"doanh\s*thu", r"tháng\s*\d{1,2}", r"\b\d{1,2}/\d{4}\b"]
|
| 148 |
+
|
| 149 |
+
def _has(t, pats): return any(re.search(p, t, flags=re.I) for p in pats)
|
| 150 |
+
|
| 151 |
+
def _mon_year(t:str):
|
| 152 |
+
t=t.lower()
|
| 153 |
+
m=re.search(r"tháng\s*(\d{1,2})(?:[\/\-](\d{4}))?",t)
|
| 154 |
+
if m: return int(m.group(1)), int(m.group(2)) if m.group(2) else datetime.date.today().year
|
| 155 |
+
m2=re.search(r"\b(\d{1,2})\/(\d{4})\b",t)
|
| 156 |
+
if m2: return int(m2.group(1)), int(m2.group(2))
|
| 157 |
+
return None,None
|
| 158 |
+
|
| 159 |
+
async def _GET(path, params):
|
| 160 |
+
for base in ["","http://127.0.0.1:7860","http://127.0.0.1:8000"]:
|
| 161 |
+
url = f"{base}{path}" if base else path
|
| 162 |
+
try:
|
| 163 |
+
async with httpx.AsyncClient(timeout=60) as c:
|
| 164 |
+
r=await c.get(url, params=params)
|
| 165 |
+
if r.status_code==200: return r.json()
|
| 166 |
+
except: pass
|
| 167 |
+
return {"error": f"GET fail {path}"}
|
| 168 |
+
|
| 169 |
+
async def _POST(path, payload):
|
| 170 |
+
for base in ["","http://127.0.0.1:7860","http://127.0.0.1:8000"]:
|
| 171 |
+
url = f"{base}{path}" if base else path
|
| 172 |
+
try:
|
| 173 |
+
async with httpx.AsyncClient(timeout=60) as c:
|
| 174 |
+
r=await c.post(url, json=payload)
|
| 175 |
+
if r.status_code==200: return r.json()
|
| 176 |
+
except: pass
|
| 177 |
+
return {"error": f"POST fail {path}"}
|
| 178 |
+
|
| 179 |
+
@router_smart.post("/chat_smart", response_model=SmartResp)
|
| 180 |
+
async def chat_smart(req: SmartReq = Body(...)):
|
| 181 |
+
text = (req.message or "").strip()
|
| 182 |
+
if not text:
|
| 183 |
+
return SmartResp(intent="general", reply="Bạn hãy nhập câu hỏi hoặc yêu cầu nhé.")
|
| 184 |
+
|
| 185 |
+
# ACTION: PYC chưa hoàn thành (gọi route sẵn có của bạn)
|
| 186 |
+
if _has(text, KEY_PYC_PENDING):
|
| 187 |
+
data = await _GET("/pyc_chua_hoan_thanh", {})
|
| 188 |
+
if "error" in data: return SmartResp(intent="action.list_pyc_pending", reply="Không lấy được danh sách.")
|
| 189 |
+
rows = data if isinstance(data,list) else data.get("rows") or data.get("data") or []
|
| 190 |
+
if not rows: return SmartResp(intent="action.list_pyc_pending", reply="Hiện không có PYC chưa hoàn thành.")
|
| 191 |
+
lines=["PYC chưa hoàn thành (tối đa 10 mục):"]
|
| 192 |
+
for r in rows[:10]:
|
| 193 |
+
if isinstance(r,dict):
|
| 194 |
+
so = r.get("SỐ PYC") or r.get("so_pyc") or r.get("pyc") or ""
|
| 195 |
+
kh = r.get("Tên khách hàng") or r.get("ten_khach_hang") or r.get("khach_hang") or ""
|
| 196 |
+
lines.append(f"- {so} | {kh}")
|
| 197 |
+
else: lines.append(f"- {r}")
|
| 198 |
+
return SmartResp(intent="action.list_pyc_pending", reply="\n".join(lines))
|
| 199 |
+
|
| 200 |
+
# ACTION: Doanh thu tháng (đổi path nếu bạn dùng /doanh_thu_theo_thang)
|
| 201 |
+
if _has(text, KEY_REVENUE):
|
| 202 |
+
mon, yr = _mon_year(text)
|
| 203 |
+
if not mon: return SmartResp(intent="action.revenue_month", reply="Bạn muốn xem doanh thu tháng nào? (vd: tháng 7/2025)")
|
| 204 |
+
data = await _GET("/doanh_thu_theo_thang", {"month": mon, "year": yr})
|
| 205 |
+
if "error" in data: return SmartResp(intent="action.revenue_month", reply="Không lấy được doanh thu.")
|
| 206 |
+
total = data.get("tong_doanh_thu") or data.get("total") or data.get("sum")
|
| 207 |
+
if total is not None:
|
| 208 |
+
return SmartResp(intent="action.revenue_month", reply=f"Doanh thu tháng {str(mon).zfill(2)}/{yr or datetime.date.today().year}: {total:,} VND")
|
| 209 |
+
return SmartResp(intent="action.revenue_month", reply=f"Kết quả: {data}")
|
| 210 |
+
|
| 211 |
+
# RAG: hỏi tài liệu nội bộ
|
| 212 |
+
if _has(text, KEY_RAG):
|
| 213 |
+
data = await _POST("/chat_rag", {"question": text, "history": req.history or []})
|
| 214 |
+
if data.get("reply"): return SmartResp(intent="rag.query", reply=data["reply"], sources=data.get("sources"))
|
| 215 |
+
# fallback về chat thường
|
| 216 |
+
|
| 217 |
+
# GENERAL: hỏi đáp chung (GPT-5)
|
| 218 |
+
msgs = (req.history or []) + [{"role":"user","content":text}]
|
| 219 |
+
out = await _POST("/chat", {"messages": msgs})
|
| 220 |
+
reply = out.get("reply") or "Xin lỗi, mình chưa trả lời được."
|
| 221 |
+
return SmartResp(intent="general", reply=reply)
|
| 222 |
+
|
| 223 |
+
app.include_router(router_smart)
|
| 224 |
+
# ================== HẾT PHẦN CHATBOT ==================
|