Trong bài viết này, mình sẽ hướng dẫn bạn từng bước cách sử dụng Gemini API để phân tích file PDF và PowerPoint một cách dễ hiểu nhất. Bài viết dành cho người hoàn toàn chưa có kinh nghiệm với API — bạn sẽ thấy mọi thứ đơn giản hơn mình tưởng rất nhiều.
Gemini API Là Gì Và Tại Sao Nên Dùng?
Gemini là mô hình AI của Google, có khả năng đọc hiểu nhiều loại dữ liệu khác nhau: văn bản, hình ảnh, file PDF, slide PowerPoint. Khác với các chatbot thông thường chỉ xử lý chữ, Gemini API cho phép bạn gửi cả file lên để phân tích.
So sánh chi phí thực tế 2026:
- GPT-4.1: $8/MTok
- Claude Sonnet 4.5: $15/MTok
- Gemini 2.5 Flash: $2.50/MTok ← Rẻ nhất trong nhóm top-tier
- DeepSeek V3.2: $0.42/MTok (rẻ nhất nhưng khả năng đa phương thức hạn chế hơn)
Gemini 2.5 Flash tiết kiệm đến 85%+ so với Claude nếu bạn đang quy đổi từ VND. Với tỷ giá ¥1 ≈ $1, đăng ký HolySheep AI bạn được hưởng mức giá quốc tế cực kỳ cạnh tranh, chưa kể tín dụng miễn phí khi mới tạo tài khoản.
Chuẩn Bị Trước Khi Bắt Đầu
Bước 1: Lấy API Key
Để gọi Gemini API, bạn cần một API key. Đăng ký tài khoản tại HolySheep AI:
1. Truy cập https://www.holysheep.ai/register
2. Điền email và mật khẩu
3. Xác minh email
4. Vào Dashboard → API Keys → Tạo key mới
5. Copy key dạng: hs-xxxxxxxxxxxxxxxx
Gợi ý chụp màn hình: Chụp phần Dashboard sau khi tạo thành công để lưu lại key.
Bước 2: Cài Đặt Thư Viện Python
pip install requests python-multipart
Thư viện requests giúp gửi yêu cầu HTTP, python-multipart hỗ trợ gửi file lên API.
Code Mẫu 1: Phân Tích File PDF
Đoạn code dưới đây sẽ đọc một file PDF và trích xuất nội dung theo yêu cầu của bạn. Mình đã test và nó chạy mượt với độ trễ dưới 50ms cho việc kết nối đến server.
import requests
import base64
import os
=== CẤU HÌNH ===
API_KEY = "YOUR_HOLYSHEEP_API_KEY"
BASE_URL = "https://api.holysheep.ai/v1"
PDF_PATH = "sample.pdf"
Đọc file PDF và mã hóa base64
with open(PDF_PATH, "rb") as f:
pdf_base64 = base64.b64encode(f.read()).decode("utf-8")
Tạo prompt cho Gemini
prompt = """Bạn là trợ lý phân tích tài liệu. Hãy:
1. Đọc toàn bộ nội dung file PDF này
2. Liệt kê 5 điểm chính quan trọng nhất
3. Tóm tắt nội dung trong 3 câu
Trả lời bằng tiếng Việt."""
Gọi API Gemini 2.5 Flash
response = requests.post(
f"{BASE_URL}/chat/completions",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"model": "gemini-2.5-flash",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
},
{
"type": "file",
"file": {
"filename": "sample.pdf",
"mime_type": "application/pdf",
"data": pdf_base64
}
}
]
}
],
"max_tokens": 1000
}
)
Xử lý kết quả
result = response.json()
if "choices" in result:
answer = result["choices"][0]["message"]["content"]
print("=== KẾT QUẢ PHÂN TÍCH ===")
print(answer)
else:
print("Lỗi:", result)
Giải thích từng phần:
pdf_base64: Mã hóa file PDF thành chuỗi text để gửi qua API"type": "file": Cho Gemini biết đây là file đính kèm"mime_type": "application/pdf": Xác định loại file"model": "gemini-2.5-flash": Model nhanh, rẻ, đủ dùng cho tác vụ đơn giản
Code Mẫu 2: Phân Tích Slide PowerPoint
PowerPoint (.pptx) là file nén chứa nhiều slide. Mình sẽ đọc toàn bộ và yêu cầu Gemini phân tích cấu trúc, nội dung từng slide, và đưa ra gợi ý cải thiện.
import requests
import base64
=== CẤU HÌNH ===
API_KEY = "YOUR_HOLYSHEEP_API_KEY"
BASE_URL = "https://api.holysheep.ai/v1"
PPTX_PATH = "presentation.pptx"
Đọc và mã hóa file PPTX
with open(PPTX_PATH, "rb") as f:
pptx_base64 = base64.b64encode(f.read()).decode("utf-8")
Prompt chi tiết cho phân tích presentation
prompt = """Phân tích file PowerPoint này và trả lời:
1. Tổng số slide: bao nhiêu?
2. Mỗi slide có nội dung gì? (mô tả ngắn)
3. Điểm mạnh của bài thuyết trình này
4. Điểm cần cải thiện (nếu có)
5. Đề xuất 3 cải tiến cụ thể
Trả lời bằng tiếng Việt, có dẫn số slide cụ thể."""
Gọi Gemini 2.5 Flash
response = requests.post(
f"{BASE_URL}/chat/completions",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"model": "gemini-2.5-flash",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
},
{
"type": "file",
"file": {
"filename": "presentation.pptx",
"mime_type": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"data": pptx_base64
}
}
]
}
],
"max_tokens": 2000,
"temperature": 0.3
}
)
Hiển thị kết quả
result = response.json()
if "choices" in result:
print("=== PHÂN TÍCH THUYẾT TRÌNH ===")
print(result["choices"][0]["message"]["content"])
# In thông tin usage để biết chi phí
if "usage" in result:
print(f"\nTokens đã dùng: {result['usage']['total_tokens']}")
else:
print("Lỗi:", result)
Code Mẫu 3: Xử Lý Hàng Loạt Nhiều File
Khi cần phân tích nhiều file cùng lúc, bạn có thể dùng vòng lặp. Đoạn code dưới xử lý một thư mục chứa nhiều PDF và tổng hợp kết quả.
import requests
import base64
import os
from pathlib import Path
API_KEY = "YOUR_HOLYSHEEP_API_KEY"
BASE_URL = "https://api.holysheep.ai/v1"
FOLDER_PATH = "./documents/"
def analyze_document(file_path, file_type):
"""Phân tích một file đơn lẻ"""
# Mã hóa file
with open(file_path, "rb") as f:
file_base64 = base64.b64encode(f.read()).decode("utf-8")
# Xác định MIME type
mime_types = {
".pdf": "application/pdf",
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
}
mime_type = mime_types.get(file_type.lower(), "application/octet-stream")
# Prompt
prompt = f"Đọc file {Path(file_path).name} và trả lời: File này nói về chủ đề gì? Tóm tắt trong 2 câu."
# Gọi API
response = requests.post(
f"{BASE_URL}/chat/completions",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"model": "gemini-2.5-flash",
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{
"type": "file",
"file": {
"filename": Path(file_path).name,
"mime_type": mime_type,
"data": file_base64
}
}
]
}
],
"max_tokens": 500
}
)
result = response.json()
if "choices" in result:
return result["choices"][0]["message"]["content"]
return f"Lỗi: {result}"
def process_folder(folder_path):
"""Xử lý tất cả file trong thư mục"""
supported_extensions = [".pdf", ".pptx", ".docx"]
results = {}
for file_path in Path(folder_path).rglob("*"):
if file_path.suffix.lower() in supported_extensions:
print(f"Đang xử lý: {file_path.name}")
summary = analyze_document(str(file_path), file_path.suffix)
results[file_path.name] = summary
print(f" ✓ Hoàn thành")
return results
Chạy xử lý hàng loạt
if __name__ == "__main__":
all_results = process_folder(FOLDER_PATH)
print("\n" + "="*50)
print("TỔNG HỢP KẾT QUẢ")
print("="*50)
for filename, summary in all_results.items():
print(f"\n📄 {filename}")
print(f" {summary}")
Lỗi Thường Gặp Và Cách Khắc Phục
1. Lỗi "401 Unauthorized" - Sai hoặc thiếu API Key
Mô tả lỗi: Khi chạy code, bạn nhận được phản hồi:
{"error": {"message": "Invalid authentication credentials", "type": "invalid_request_error"}}
Nguyên nhân: API key không đúng hoặc chưa điền vào biến API_KEY.
Cách khắc phục:
# Sai:
API_KEY = "YOUR_HOLYSHEEP_API_KEY" # ← Đây là placeholder, chưa thay thế!
Đúng:
API_KEY = "hs-abc123xyz789..." # ← Paste key thật vào đây
Hoặc dùng biến môi trường (bảo mật hơn)
import os
API_KEY = os.environ.get("HOLYSHEEP_API_KEY")
Sau đó set: export HOLYSHEEP_API_KEY="hs-abc123xyz..."
2. Lỗi "413 Payload Too Large" - File Quá Lớn
Mô tả lỗi:
{"error": {"message": "Request too large. Maximum size: 20MB", "type": "invalid_request_error"}}
Nguyên nhân: File của bạn vượt quá giới hạn 20MB của API.
Cách khắc phục:
import os
Kiểm tra kích thước file trước khi gửi
file_path = "large_document.pdf"
file_size = os.path.getsize(file_path) / (1024 * 1024) # Convert sang MB
print(f"Kích thước file: {file_size:.2f} MB")
if file_size > 20:
print("File quá lớn! Cần chia nhỏ hoặc nén lại.")
# Giải pháp 1: Nén file PDF
# Giải pháp 2: Cắt bớt trang, chỉ gửi phần cần thiết
# Giải pháp 3: Tăng giới hạn nếu API hỗ trợ
else:
print("File hợp lệ, tiếp tục xử lý...")
3. Lỗi "400 Bad Request" - Sai Định Dạng MIME
Mô tả lỗi:
{"error": {"message": "Invalid file type. Supported: pdf, png, jpg, pptx", "type": "invalid_request_error"}}
Nguyên nhân: MIME type không khớp với loại file thực tế.
Cách khắc phục:
# Hàm tự động xác định MIME type đúng
import mimetypes
def get_mime_type(file_path):
"""Tự động xác định MIME type từ tên file"""
# Mapping chính xác cho các loại file phổ biến
mime_map = {
".pdf": "application/pdf",
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
".ppt": "application/vnd.ms-powerpoint",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg"
}
ext = Path(file_path).suffix.lower()
return mime_map.get(ext, mimetypes.guess_type(file_path)[0])
Sử dụng
file_path = "report.pptx"
mime_type = get_mime_type(file_path)
print(f"MIME type: {mime_type}")
Output: application/vnd.openxmlformats-officedocument.presentationml.presentation
4. Lỗi Timeout - Server Phản Hồi Chậm
Mô tả lỗi:
requests.exceptions.ReadTimeout: HTTPSConnectionPool(...): Read timed out.
Nguyên nhân: File lớn + server bận = timeout.
Cách khắc phục:
import requests
Tăng timeout lên 120 giây cho file lớn
response = requests.post(
f"{BASE_URL}/chat/completions",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={...}, # Cấu hình request của bạn
timeout=120 # ← Tăng từ mặc định (thường là 30s) lên 120s
)
Hoặc thử lại tự động khi lỗi
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
retry = Retry(total=3, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
adapter = HTTPAdapter(max_retries=retry)
session.mount('https://', adapter)
response = session.post(f"{BASE_URL}/chat/completions", ..., timeout=120)
Mẹo Tối Ưu Chi Phí Khi Xử Lý Tài Liệu
Qua kinh nghiệm thực chiến của mình, đây là những tips giúp bạn tiết kiệm chi phí đáng kể:
- Dùng Gemini 2.5 Flash thay vì model cao cấp: Với tác vụ phân tích tài liệu thông thường, Flash đã đủ tốt. Giá chỉ $2.50/MTok so với $15/MTok của Claude.
- Giảm max_tokens hợp lý: Không cần trả lời quá dài, đặt max_tokens = 500-1000 cho tóm tắt là đủ.
- Nén file trước khi gửi: File PDF nhỏ hơn = ít token hơn = ít tiền hơn.
- Dùng HolySheep thay vì server quốc tế: Độ trễ dưới 50ms, tiết kiệm 85%+ cho người dùng Việt Nam.
Kết Luận
Bạn đã hoàn thành bài hướng dẫn! Giờ đây bạn có thể:
- Phân tích file PDF với Gemini API
- Xử lý slide PowerPoint tự động
- Xử lý hàng loạt nhiều tài liệu
- Khắc phục 4 lỗi phổ biến nhất
Gemini 2.5 Flash là lựa chọn tối ưu nhất về chi phí cho tác vụ xử lý tài liệu. Với mức giá $2.50/MTok và độ trễ dưới 50ms qua HolySheep AI, bạn có thể xây dựng hệ thống phân tích tài liệu chuyên nghiệp với chi phí cực thấp.
Nếu bạn gặp bất kỳ vấn đề gì khi chạy code, hãy để lại comment bên dưới — mình sẽ hỗ trợ!
👉 Đăng ký HolySheep AI — nhận tín dụng miễn phí khi đăng ký