1. Vấn đề xử lý nghiệp vụ
AI (LLM) rất thông minh, nhưng trong tài chính – ngân hàng lại khó áp dụng trực tiếp:
- Dữ liệu nhạy cảm: hợp đồng, giao dịch, quy định → cần kiểm soát quyền.
- Hallucination: LLM có thể “bịa” → rủi ro nghiệp vụ & pháp lý.
- Chính sách thay đổi liên tục → dễ trả lời theo bản cũ.
- Tuân thủ: cần audit rõ “ai đã truy xuất gì”.
👉 Giải pháp: RAG + RuleBook để ép AI tra cứu dữ liệu thật và trả lời có kiểm soát.
2. RuleBook
answer_policy:
must_cite: true # luôn trích dẫn nguồn
if_no_evidence: "INSUFFICIENT" # không bịa, dám nói "Không đủ thông tin"
style: "vi-short-bullets"
redact: ["account_number","id_number","address"]
access_policy:
acl_mode: "row_and_field_level" # quyền theo user/chi nhánh
audit_log: true # log mọi truy vấn
ranking_policy:
weights: {vector: 0.55, bm25: 0.25, recency: 0.15, source_trust: 0.05}
prefer_sources: ["policy","fee_table"] # ưu tiên tài liệu chính sách
mmr: true
3. RAG là gì?
- Retrieval: tìm tài liệu liên quan.
- Augmented Generation: đưa tài liệu vào context để LLM trả lời.
- Ý tưởng: “Tra sổ tay chính sách trước khi mở miệng.”
4. Pipeline triển khai
+-----------+ +------------+ +------------+ +------------+
| User Q | ---> | Rewrite | ---> | Retrieval | ---> | Generation |
+-----------+ +------------+ +------------+ +------------+
^ |
| v
AnswerPolicy RankingPolicy
|
v
AccessPolicy
5. Các bước thực thi
Bước 1 – Chuẩn hóa dữ liệu
(AnswerPolicy: đảm bảo bằng chứng chuẩn)
# ingest.py
import re, uuid
from bs4 import BeautifulSoup
from pathlib import Path
def chunk_by_heading(html, max_tokens=800, overlap=120):
soup = BeautifulSoup(html, "html.parser")
chunks, buf, tok = [], [], 0
for tag in soup.find_all(["h1","h2","h3","p","li"]):
text = re.sub(r"\s+", " ", tag.get_text().strip())
if not text: continue
t = len(text.split())
if tok + t > max_tokens and buf:
chunks.append(" ".join(buf))
buf = buf[-overlap//10:] # giữ mạch nghĩa
tok = sum(len(x.split()) for x in buf)
buf.append(text); tok += t
if buf: chunks.append(" ".join(buf))
return chunks
def build_docs(input_dir):
for p in Path(input_dir).glob("*.html"):
html = p.read_text(encoding="utf-8")
for i, c in enumerate(chunk_by_heading(html)):
yield {
"id": f"{p.stem}-{i}-{uuid.uuid4().hex[:6]}",
"text": c,
"metadata": {
"doc_id": p.stem,
"doc_type": guess_doc_type(p.name), # policy/fee_table/faq/...
"effective_date": extract_effective_date(html),
"version": extract_version(html)
}
}
Giúp trả lời có bằng chứng rõ ràng, tránh “ăn bớt ngữ cảnh”.
Bước 2 – Lập chỉ mục Hybrid
(RankingPolicy: recall tốt hơn)
# index.py
from sentence_transformers import SentenceTransformer
from elasticsearch import Elasticsearch
import qdrant_client, qdrant_client.models as qm
emb = SentenceTransformer("intfloat/multilingual-e5-large")
es = Elasticsearch("http://localhost:9200")
qdr = qdrant_client.QdrantClient("http://localhost:6333")
def index_doc(doc):
es.index(index="bank_docs", id=doc["id"],
document={"text": doc["text"], **doc["metadata"]})
vec = emb.encode(doc["text"], normalize_embeddings=True).tolist()
qdr.upsert("bank_vectors", points=[qm.PointStruct(
id=doc["id"], vector=vec, payload={**doc["metadata"], "text": doc["text"]}
)])
Kết hợp BM25 + Vector → vừa bắt từ khóa, vừa hiểu ngữ nghĩa.
Bước 3 – Truy xuất theo tầng + Re-rank
(RankingPolicy: chọn đúng và mới nhất)
# retrieve.py
from datetime import datetime
from sentence_transformers import CrossEncoder
cross = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
def es_bm25(q, k=60, filters=None):
must = [{"multi_match":{"query":q,"fields":["text^2"]}}]
for kf,vf in (filters or {}).items(): must.append({"term": {kf: vf}})
rs = es.search(index="bank_docs", query={"bool":{"must":must}}, size=k)["hits"]["hits"]
return [{"id":h["_id"],"text":h["_source"]["text"],"meta":h["_source"]} for h in rs]
def qdr_vector(q, k=60, filters=None):
qv = emb.encode(q, normalize_embeddings=True).tolist()
cond = [{"key":k,"match":{"value":v}} for k,v in (filters or {}).items()]
rs = qdr.search("bank_vectors", query_vector=qv,
query_filter={"must":cond} if cond else None, limit=k, with_payload=True)
return [{"id":r.id,"text":r.payload["text"],"meta":r.payload} for r in rs]
def time_decay_score(eff):
if not eff: return 1.0
days = max(1,(datetime.now() - datetime.fromisoformat(eff)).days)
return max(0.6, 1.0 - min(days/365, 0.4)) # không giảm quá 40%
def source_trust(dt):
return {"policy":1.0,"fee_table":0.95,"faq":0.85,"marketing":0.6}.get(dt,0.8)
def staged_retrieve(query, filters=None, topk=5):
pool = {c["id"]:c for c in (es_bm25(query,filters=filters)+qdr_vector(query,filters=filters))}.values()
scores = cross.predict([(query,c["text"]) for c in pool])
for c, s in zip(pool, scores):
c["s_rel"] = float(s)
c["s_tim"] = time_decay_score(c["meta"].get("effective_date"))
c["s_src"] = source_trust(c["meta"].get("doc_type"))
c["score"] = 0.75*c["s_rel"] + 0.15*c["s_tim"] + 0.10*c["s_src"]
return sorted(pool, key=lambda x: x["score"], reverse=True)[:topk]
Tránh kéo văn bản cũ hoặc nguồn kém tin cậy.
Bước 4 – Query handling
(AnswerPolicy + RankingPolicy)
# query.py
import re
INTENTS = {
"transaction_status":[r"thanh toán|kỳ gần nhất|dư nợ"],
"fee_clause":[r"phí|miễn|thường niên|biểu phí"],
"procedure":[r"thủ tục|hồ sơ|quy trình"],
"definition":[r"định nghĩa|khái niệm"]
}
ALIASES = {"tất toán":["trả trước","prepayment"], "thẻ hạng x":["card tier x","x-tier card"]}
def classify(q):
for name, pats in INTENTS.items():
if any(re.search(p, q, re.I) for p in pats): return name
return "general"
def rewrite(q):
outs = {q}
ql = q.lower()
for k, syns in ALIASES.items():
if k in ql:
for s in syns: outs.add(ql.replace(k, s))
if "kỳ gần nhất" in ql: outs.add(q + " tháng này")
return list(outs)
Giúp “dịch” câu hỏi mơ hồ thành truy vấn rõ ràng.
Bước 5 – Generation có kiểm soát
(AnswerPolicy: buộc có citation)
# generate.py
SYSTEM = """Bạn là trợ lý nghiệp vụ ngân hàng.
- Chỉ dùng thông tin trong CONTEXT.
- Nếu thiếu bằng chứng: trả "Không đủ thông tin".
- Trả lời ngắn gọn, ưu tiên bullet + con số.
- Luôn kèm trích dẫn [DocID#Mục/Điều]."""
def build_context(chunks):
ctx, cites = "", []
for i, c in enumerate(chunks, 1):
ctx += f"[{i}] {c['text']}\n"
cites.append(f"{c['meta'].get('doc_id','?')}#{c['id'].split('-')[1]}")
return ctx, " | ".join(cites)
def answer(llm, q, chunks):
ctx, cites = build_context(chunks)
prompt = f"{SYSTEM}\nCONTEXT:\n{ctx}\n\nCÂU HỎI: {q}\n---\nTRẢ LỜI:"
out = llm.generate(prompt) # client của bạn
if not out.strip(): out = "Không đủ thông tin."
return f"{out.strip()}\n\nNguồn: {cites}"
Người dùng tin tưởng vì luôn thấy nguồn.
Bước 6 – Access control
(AccessPolicy: ACL + audit)
# security.py (FastAPI)
from fastapi import FastAPI, Header, HTTPException
import jwt
app = FastAPI()
def require_scope(token, scope):
payload = jwt.decode(token, "pubkey", algorithms=["RS256"], options={"verify_aud": False})
if scope not in payload.get("scope","").split():
raise HTTPException(403, "insufficient_scope")
return payload
@app.get("/rag")
def rag(q: str, authorization: str = Header(...)):
user = require_scope(authorization.replace("Bearer ",""), "rag.read")
filters = {"branch_id": user.get("branch_id")} # ví dụ ràng quyền theo đơn vị
# classify + rewrite
rew = rewrite(q)
cands = []
for rq in rew:
cands += staged_retrieve(rq, filters=filters, topk=5)
# dedup
seen, chunks = set(), []
for c in cands:
if c["id"] in seen: continue
seen.add(c["id"]); chunks.append(c)
if len(chunks) >= 5: break
return {"answer": answer(llm, q, chunks), "intent": classify(q)}
Đảm bảo an toàn & tuân thủ trong ngân hàng.
6. Kết quả tôi đạt được
- Trả lời nghiệp vụ: từ 15 phút tìm tài liệu → <10 giây có trích dẫn.
- Đồng nghiệp tin tưởng hơn vì có nguồn cụ thể.
- AI sẵn sàng nói “Không đủ thông tin”, không bịa.
7. Hạn chế & hướng tối ưu
- Dữ liệu: cần làm sạch, đồng bộ version, gắn ngày hiệu lực.
- Thuật toán: xem xét RAG-Fusion, re-rank mạnh hơn (ColBERT, SPLADE).
- Chi phí/latency: cần cache, giảm top-k.