Thứ Bảy, 28 tháng 2, 2026

Xây dựng Chatbot "Chạy bằng cơm" (Local RAG): Chat với tài liệu mật, không cần Internet

Bạn có một file PDF chứa thông tin nhạy cảm (báo cáo tài chính, bí mật công nghệ, hồ sơ nhân sự...) và muốn dùng AI để phân tích nó? Tuy nhiên, bạn sợ rằng nếu upload lên ChatGPT hay Gemini, dữ liệu của bạn có thể bị rò rỉ hoặc bị dùng để train lại model?

Xây dựng Chatbot Chạy bằng cơm (Local RAG) Chat với tài liệu mật, không cần Internet.jpg

Giải pháp dành cho bạn là **Local RAG**: Chạy AI ngay trên máy tính cá nhân.
  • Bảo mật tuyệt đối: Dữ liệu không bao giờ rời khỏi máy tính của bạn (rút dây mạng vẫn chạy tốt).
  • Miễn phí: Không tốn tiền API OpenAI.
  • Mạnh mẽ: Sử dụng Llama 3 (Meta) hoặc Mistral - những model mã nguồn mở mạnh nhất hiện nay.


Chúng ta sẽ sử dụng kiến trúc **RAG (Retrieval-Augmented Generation)**. Thay vì để AI "chém gió" dựa trên trí nhớ, chúng ta sẽ ép nó đọc tài liệu của mình trước khi trả lời.

Các thành phần chính:
  1. Ollama: Phần mềm giúp chạy các model AI (LLM) trên máy tính cá nhân cực nhẹ.
  2. LangChain: Framework giúp kết nối AI với dữ liệu PDF.
  3. ChromaDB: Kho lưu trữ vector (Vector Database) để AI tìm kiếm thông tin nhanh chóng.
  4. Streamlit: Thư viện Python giúp tạo giao diện web chat đẹp mắt chỉ trong nháy mắt.


Bước 1: Cài đặt "Trái tim" Ollama
Truy cập Ollama.com, tải và cài đặt bản cho Windows/Mac/Linux.
Sau khi cài xong, mở Terminal/CMD và chạy lệnh sau để tải model Llama 3 (phiên bản 8 tỷ tham số):
Mã:
ollama pull llama3

Bước 2: Cài đặt thư viện Python
Mã:
pip install langchain langchain-community langchain-core pypdf chromadb ollama streamlit


Dưới đây là đoạn code Python hoàn chỉnh (`app.py`). Nó tích hợp cả giao diện web và logic xử lý AI.

Python:
import streamlit as st
import tempfile
import os

from langchain_community.document_loaders import PyPDFLoader
from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import OllamaEmbeddings
from langchain_community.llms import Ollama
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.chains import RetrievalQA

# --- CẤU HÌNH ---
MODEL_NAME = "llama3" # Đảm bảo bạn đã chạy 'ollama pull llama3'

# Tiêu đề trang
st.set_page_config(page_title="Chat với PDF (Offline)", page_icon="🔒")
st.title("🔒 Chat với tài liệu mật (Local RAG)")

# --- SIDEBAR: Upload File ---
with st.sidebar:
    st.header("1. Nạp dữ liệu")
    uploaded_file = st.file_uploader("Upload file PDF của bạn", type="pdf")
   
    if uploaded_file is not None:
        # Lưu file tạm thời để LangChain đọc
        with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
            tmp_file.write(uploaded_file.getvalue())
            tmp_file_path = tmp_file.name

        st.success("Đã upload file thành công!")
       
        # Nút xử lý
        if st.button("2. Số hóa dữ liệu (Embedding)"):
            with st.spinner("Đang đọc và số hóa tài liệu... (Sẽ mất vài giây)"):
                # 1. Load PDF
                loader = PyPDFLoader(tmp_file_path)
                data = loader.load()
               
                # 2. Cắt nhỏ văn bản
                text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
                splits = text_splitter.split_documents(data)
               
                # 3. Tạo Vector DB với Ollama Embeddings
                embeddings = OllamaEmbeddings(model=MODEL_NAME)
                vectorstore = Chroma.from_documents(documents=splits, embedding=embeddings)
               
                # Lưu vào Session State để dùng lại
                st.session_state.vectorstore = vectorstore
                st.success(f"✅ Đã số hóa xong {len(splits)} đoạn văn bản!")
               
                # Xóa file tạm
                os.remove(tmp_file_path)

# --- GIAO DIỆN CHAT ---
if "messages" not in st.session_state:
    st.session_state.messages = []

# Hiển thị lịch sử chat
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

# Ô nhập liệu
if prompt := st.chat_input("Hỏi gì đó về tài liệu này..."):
    # 1. Hiển thị câu hỏi của người dùng
    st.chat_message("user").markdown(prompt)
    st.session_state.messages.append({"role": "user", "content": prompt})

    # 2. Xử lý câu trả lời
    if "vectorstore" in st.session_state:
        with st.spinner("AI đang đọc tài liệu và suy nghĩ..."):
            llm = Ollama(model=MODEL_NAME)
           
            # Tạo chuỗi RAG
            qa_chain = RetrievalQA.from_chain_type(
                llm=llm,
                retriever=st.session_state.vectorstore.as_retriever(),
            )
           
            response = qa_chain.invoke({"query": prompt})
            answer = response['result']
           
            # Hiển thị câu trả lời
            st.chat_message("assistant").markdown(answer)
            st.session_state.messages.append({"role": "assistant", "content": answer})
    else:
        st.warning("⚠️ Vui lòng upload và số hóa file PDF trước!")


  1. Lưu đoạn code trên thành file app.py.
  2. Mở Terminal tại thư mục đó.
  3. Chạy lệnh:
    Mã:
    streamlit run app.py
  4. Trình duyệt sẽ tự bật lên với giao diện Chatbot.


Tại sao chúng ta dùng **OllamaEmbeddings**?
Bình thường, để máy tính hiểu văn bản, ta phải chuyển chữ thành số (Vector). OpenAI có API làm việc này rất tốt nhưng tốn phí. Ở đây, chúng ta ép chính con Llama 3 trên máy tính làm việc này luôn. Kết quả là hệ thống hoàn toàn offline 100%.

Lưu ý về cấu hình máy:
  • Để chạy mượt Llama 3 (8B), máy bạn nên có RAM từ 8GB trở lên (tốt nhất là 16GB).
  • Nếu có GPU rời (NVIDIA), tốc độ trả lời sẽ cực nhanh (chỉ 1-2 giây). Nếu chạy bằng CPU, có thể mất 10-20 giây cho một câu trả lời.

Chúc các bạn thành công bảo vệ dữ liệu của mình!
=============================
TƯ VẤN: Click Here hoặc Hotline/Zalo 090.29.12.888
=============================
Website không chứa bất kỳ quảng cáo nào, mọi đóng góp để duy trì phát triển cho website (donation) xin vui lòng gửi về STK 90.2142.8888 - Ngân hàng Vietcombank Thăng Long - TRAN VAN BINH
=============================
Nếu bạn không muốn bị AI thay thế và tiết kiệm 3-5 NĂM trên con đường trở thành DBA chuyên nghiệp hay làm chủ Database thì hãy đăng ký ngay KHOÁ HỌC ORACLE DATABASE A-Z ENTERPRISE, được Coaching trực tiếp từ tôi với toàn bộ bí kíp thực chiến, thủ tục, quy trình của gần 20 năm kinh nghiệm (mà bạn sẽ KHÔNG THỂ tìm kiếm trên Internet/Google) từ đó giúp bạn dễ dàng quản trị mọi hệ thống Core tại Việt Nam và trên thế giới, đỗ OCP.
- CÁCH ĐĂNG KÝ: Gõ (.) hoặc để lại số điện thoại hoặc inbox https://m.me/tranvanbinh.vn hoặc Hotline/Zalo 090.29.12.888
- Chi tiết tham khảo:
https://bit.ly/oaz_w
=============================
2 khóa học online qua video giúp bạn nhanh chóng có những kiến thức nền tảng về Linux, Oracle, học mọi nơi, chỉ cần có Internet/4G:
- Oracle cơ bản: https://bit.ly/admin_1200
- Linux: https://bit.ly/linux_1200
=============================
KẾT NỐI VỚI CHUYÊN GIA TRẦN VĂN BÌNH:
📧 Mail: binhoracle@gmail.com
☎️ Mobile/Zalo: 0902912888
👨 Facebook: https://www.facebook.com/BinhOracleMaster
👨 Inbox Messenger: https://m.me/101036604657441 (profile)
👨 Fanpage: https://www.facebook.com/tranvanbinh.vn
👨 Inbox Fanpage: https://m.me/tranvanbinh.vn
👨👩 Group FB: https://www.facebook.com/groups/DBAVietNam
👨 Website: https://www.tranvanbinh.vn
👨 Blogger: https://tranvanbinhmaster.blogspot.com
🎬 Youtube: https://www.youtube.com/@binhguru
👨 Tiktok: https://www.tiktok.com/@binhguru
👨 Linkin: https://www.linkedin.com/in/binhoracle
👨 Twitter: https://twitter.com/binhguru
👨 Podcast: https://www.podbean.com/pu/pbblog-eskre-5f82d6
👨 Địa chỉ: Tòa nhà Sun Square - 21 Lê Đức Thọ - Phường Mỹ Đình 1 - Quận Nam Từ Liêm - TP.Hà Nội

=============================
cơ sở dữ liệu, cơ sở dữ liệu quốc gia, database, AI, trí tuệ nhân tạo, artificial intelligence, machine learning, deep learning, LLM, ChatGPT, DeepSeek, Grok, oracle tutorial, học oracle database, Tự học Oracle, Tài liệu Oracle 12c tiếng Việt, Hướng dẫn sử dụng Oracle Database, Oracle SQL cơ bản, Oracle SQL là gì, Khóa học Oracle Hà Nội, Học chứng chỉ Oracle ở đầu, Khóa học Oracle online,sql tutorial, khóa học pl/sql tutorial, học dba, học dba ở việt nam, khóa học dba, khóa học dba sql, tài liệu học dba oracle, Khóa học Oracle online, học oracle sql, học oracle ở đâu tphcm, học oracle bắt đầu từ đâu, học oracle ở hà nội, oracle database tutorial, oracle database 12c, oracle database là gì, oracle database 11g, oracle download, oracle database 19c/21c/23c/23ai, oracle dba tutorial, oracle tunning, sql tunning , oracle 12c, oracle multitenant, Container Databases (CDB), Pluggable Databases (PDB), oracle cloud, oracle security, oracle fga, audit_trail,oracle RAC, ASM, oracle dataguard, oracle goldengate, mview, oracle exadata, oracle oca, oracle ocp, oracle ocm , oracle weblogic, postgresql tutorial, mysql tutorial, mariadb tutorial, ms sql server tutorial, nosql, mongodb tutorial, oci, cloud, middleware tutorial, docker, k8s, micro service, hoc solaris tutorial, hoc linux tutorial, hoc aix tutorial, unix tutorial, securecrt, xshell, mobaxterm, putty

ĐỌC NHIỀU

Trần Văn Bình - Oracle Database Master