A newer version of the Gradio SDK is available:
5.49.1
Quick Start: PDF-Based ChatbotRAG
Tóm Tắt Nhanh
Bây giờ bạn có thể:
- Upload PDF hướng dẫn sử dụng vào hệ thống
- Chatbot tự động trả lời các câu hỏi dựa trên nội dung trong PDF
- Không cần train model, chỉ cần upload PDF!
Quy Trình Hoàn Chỉnh
Bước 1: Tạo PDF Hướng Dẫn
Bạn có 2 cách:
Cách 1: Sử dụng Template Có Sẵn
File chatbot_guide_template.md đã sẵn sàng. Customize nội dung cho hệ thống của bạn, sau đó convert sang PDF:
# Cài pandoc (nếu chưa có)
# Windows: choco install pandoc
# Mac: brew install pandoc
# Linux: sudo apt-get install pandoc
# Convert markdown to PDF
pandoc chatbot_guide_template.md -o chatbot_user_guide.pdf --pdf-engine=xelatex
Cách 2: Tự Viết Content
Tạo file Word/Google Docs với nội dung hướng dẫn, sau đó:
- File → Export → PDF
Nội dung nên bao gồm:
- Giới thiệu hệ thống
- Các chức năng chính
- Hướng dẫn sử dụng từng tính năng
- FAQ (Câu hỏi thường gặp)
- Examples
Bước 2: Upload PDF Vào Hệ Thống
# Khởi động server
cd ChatbotRAG
python main.py
Trong terminal khác:
# Upload PDF
curl -X POST "http://localhost:8000/upload-pdf" \
-F "file=@chatbot_user_guide.pdf" \
-F "title=Hướng dẫn sử dụng ChatbotRAG" \
-F "description=Tài liệu hướng dẫn đầy đủ" \
-F "category=user_guide"
Hoặc dùng Python:
import requests
with open('chatbot_user_guide.pdf', 'rb') as f:
response = requests.post(
'http://localhost:8000/upload-pdf',
files={'file': f},
data={
'title': 'Hướng dẫn sử dụng ChatbotRAG',
'category': 'user_guide'
}
)
print(response.json())
# Output: {"success": true, "document_id": "pdf_...", "chunks_indexed": 45}
Bước 3: Verify Upload
# Xem danh sách PDFs
curl http://localhost:8000/documents/pdf
Bước 4: Chat!
import requests
response = requests.post('http://localhost:8000/chat', json={
'message': 'Làm sao để upload PDF vào ChatbotRAG?',
'use_rag': True,
'use_advanced_rag': True,
'top_k': 5,
'hf_token': 'your_huggingface_token' # Get from https://huggingface.co/settings/tokens
})
result = response.json()
print("Answer:", result['response'])
print("\nSources:")
for ctx in result['context_used']:
print(f"- Page {ctx['metadata']['page']}: Confidence {ctx['confidence']:.2%}")
Test Script Mẫu
File test_pdf_chatbot.py:
"""
Test PDF-based chatbot
"""
import requests
import time
BASE_URL = "http://localhost:8000"
HF_TOKEN = "your_huggingface_token" # Replace with your token
def upload_pdf():
"""Upload PDF guide"""
print("=== Uploading PDF ===")
with open('chatbot_user_guide.pdf', 'rb') as f:
response = requests.post(
f'{BASE_URL}/upload-pdf',
files={'file': f},
data={
'title': 'ChatbotRAG User Guide',
'category': 'user_guide'
}
)
result = response.json()
print(f"✓ Uploaded: {result['chunks_indexed']} chunks")
return result['document_id']
def chat(question):
"""Ask chatbot"""
print(f"\n=== Question: {question} ===")
response = requests.post(f'{BASE_URL}/chat', json={
'message': question,
'use_rag': True,
'use_advanced_rag': True,
'top_k': 5,
'hf_token': HF_TOKEN
})
result = response.json()
print(f"Answer: {result['response']}\n")
print(f"Retrieved {len(result['context_used'])} documents:")
for i, ctx in enumerate(result['context_used'], 1):
print(f"{i}. Page {ctx['metadata'].get('page')}, Confidence: {ctx['confidence']:.2%}")
def main():
# 1. Upload PDF
doc_id = upload_pdf()
# Wait for indexing to complete
time.sleep(2)
# 2. Test questions
questions = [
"Làm sao để upload PDF vào hệ thống?",
"Chatbot có support tiếng Việt không?",
"Tối đa bao nhiêu texts có thể index cùng lúc?",
"Advanced RAG có những tính năng gì?"
]
for q in questions:
chat(q)
time.sleep(1)
if __name__ == "__main__":
main()
Chạy:
python test_pdf_chatbot.py
Upload Nhiều PDFs Cùng Lúc
Nếu bạn có nhiều PDFs (FAQ, User Guide, Policies, etc.):
# Đặt tất cả PDFs vào thư mục
mkdir docs
# Copy PDFs vào docs/
# Batch index
python batch_index_pdfs.py ./docs --category=user_guide
Script sẽ tự động index tất cả PDFs và skip những file đã có.
Câu Hỏi Test Mẫu
Sau khi upload PDF hướng dẫn, test với các câu hỏi:
Về tính năng:
- "ChatbotRAG có những tính năng gì?"
- "Làm sao để index dữ liệu?"
- "Advanced RAG là gì?"
Hướng dẫn sử dụng:
- "Làm sao để upload PDF?"
- "Cách chat với chatbot như thế nào?"
- "Làm sao để xem lịch sử chat?"
FAQ:
- "Chatbot không tìm thấy thông tin phải làm sao?"
- "Tối đa bao nhiêu images có thể upload?"
- "Token limit là bao nhiêu?"
Technical:
- "Score threshold là gì?"
- "Top_k trong chat request có ý nghĩa gì?"
- "Làm sao để cải thiện độ chính xác?"
Tips Để Chatbot Trả Lời Tốt
1. PDF Content Quality
- Viết rõ ràng, có cấu trúc
- Mỗi section tập trung 1 topic
- Có examples cụ thể
- FAQ với câu hỏi thực tế
2. Chat Settings
{
'use_advanced_rag': True, # Luôn bật
'use_reranking': True, # Rerank cho accuracy
'use_compression': True, # Nén context
'score_threshold': 0.5, # 0.4-0.6 là tốt
'top_k': 5, # 3-7 tùy use case
'temperature': 0.3 # Thấp cho factual answers
}
3. Query Tips
- Hỏi câu rõ ràng, cụ thể
- Tránh câu hỏi quá chung chung
- Nếu không tìm thấy, rephrase câu hỏi
Monitoring
Check Index Status
curl http://localhost:8000/stats
View PDFs
curl http://localhost:8000/documents/pdf
Check Chat History
curl "http://localhost:8000/history?limit=10"
Kết Luận
Bây giờ bạn có thể:
✓ Tạo PDF hướng dẫn với nội dung của bạn ✓ Upload PDF vào hệ thống trong vài giây ✓ Chatbot tự động trả lời dựa trên PDF content ✓ Không cần train, không cần code phức tạp ✓ Update content? Chỉ cần upload PDF mới!
Next Steps:
- Tạo PDF hướng dẫn của bạn (hoặc customize template)
- Upload vào hệ thống
- Test với câu hỏi thực tế
- Fine-tune settings nếu cần
- Add thêm PDFs (FAQ, policies, etc.)
Files Quan Trọng
pdf_parser.py- PDF parsing enginebatch_index_pdfs.py- Batch indexing scriptchatbot_guide_template.md- Template PDF contentPDF_RAG_GUIDE.md- Chi tiết về PDF RAGADVANCED_RAG_GUIDE.md- Advanced RAG features
Chúc bạn thành công! 🚀