Hoàn thành bài "Chương 7 – Bài 2: Agent Marketing, SEO và viết Content tự động" trước để mở khoá bài này.Đến bài trước

Giới thiệu

Trong thực tế, phần lớn công việc văn phòng xoay quanh bốn loại tác vụ: xử lý email, đọc báo cáo bảng tính, trích xuất thông tin từ PDF, và tìm kiếm câu trả lời trong kho tài liệu nội bộ. Bài này sẽ xây dựng một AI Agent có khả năng tự động hóa cả bốn tác vụ đó bằng cách kết hợp các tool chuyên biệt với LLM làm bộ não điều phối.

Chúng ta sẽ dùng Python với thư viện LangChain, mô hình GPT-4o-mini qua OpenAI API, và các thư viện hỗ trợ như imaplib (email), openpyxl (bảng tính), PyMuPDF (PDF), cùng FAISS cho vector search.

sơ đồ kiến trúc agent với 4 nhánh tool: Email Tool, Spreadsheet Tool, PDF Tool, QA Tool — tất cả kết nối vào LLM Agent ở trung tâm

Tool 1 — Đọc và phân tích email

Agent cần một tool để lấy email từ hộp thư và tóm tắt nội dung. Dưới đây là tool kết nối IMAP, lấy 5 email mới nhất và trả về danh sách subject + body rút gọn.

python
import imaplib
import email
from email.header import decode_header
from langchain.tools import tool
@tool
def read_recent_emails(query: str) -> str:
"""Lấy 5 email mới nhất từ hộp thư INBOX và trả về nội dung tóm tắt."""
IMAP_HOST = "imap.gmail.com"
USERNAME = "your_email@gmail.com"
PASSWORD = "your_app_password" # dùng App Password, không phải mật khẩu thật
mail = imaplib.IMAP4_SSL(IMAP_HOST)
mail.login(USERNAME, PASSWORD)
mail.select("INBOX")
_, msg_ids = mail.search(None, "ALL")
latest_ids = msg_ids[0].split()[-5:]
results = []
for mid in reversed(latest_ids):
_, data = mail.fetch(mid, "(RFC822)")
msg = email.message_from_bytes(data[0][1])
subject, enc = decode_header(msg["Subject"])[0]
if isinstance(subject, bytes):
subject = subject.decode(enc or "utf-8")
body = ""
if msg.is_multipart():
for part in msg.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True).decode("utf-8", errors="ignore")
break
else:
body = msg.get_payload(decode=True).decode("utf-8", errors="ignore")
results.append(f"Subject: {subject}\nBody (200 ký tự đầu): {body[:200]}")
mail.logout()
return "\n\n---\n\n".join(results)

Lưu ý quan trọng: Gmail yêu cầu bật IMAP và tạo App Password riêng trong phần bảo mật tài khoản. Không dùng mật khẩu đăng nhập thông thường.

Tool 2 — Phân tích bảng tính Excel

Tool này nhận đường dẫn file Excel và câu hỏi, dùng pandas để tính toán rồi trả lời.

python
import pandas as pd
from langchain.tools import tool
@tool
def analyze_spreadsheet(input: str) -> str:
"""
Phân tích file Excel. Input theo định dạng: 'đường_dẫn_file | câu hỏi'
Ví dụ: 'data/doanh_thu.xlsx | Tổng doanh thu tháng 3 là bao nhiêu?'
"""
parts = input.split(" | ", 1)
if len(parts) != 2:
return "Input không đúng định dạng. Dùng: 'file_path | câu hỏi'"
file_path, question = parts
df = pd.read_excel(file_path)
summary = f"Bảng có {len(df)} dòng, {len(df.columns)} cột.\n"
summary += f"Các cột: {list(df.columns)}\n"
summary += f"Thống kê mô tả:\n{df.describe().to_string()}\n"
summary += f"5 dòng đầu:\n{df.head().to_string()}"
return f"Dữ liệu file:\n{summary}\n\nCâu hỏi cần trả lời: {question}"

Tool này trả về dữ liệu thô cho LLM. Agent sẽ tự diễn giải và trả lời câu hỏi dựa trên thống kê mô tả đó.

Tool 3 — Trích xuất nội dung PDF

PyMuPDF (fitz) là thư viện nhanh và ổn định để đọc PDF có văn bản. Cài bằng lệnh pip install pymupdf.

python
import fitz # PyMuPDF
from langchain.tools import tool
@tool
def extract_pdf_text(file_path: str) -> str:
"""Trích xuất toàn bộ văn bản từ file PDF và trả về nội dung."""
doc = fitz.open(file_path)
full_text = ""
for page_num, page in enumerate(doc, start=1):
text = page.get_text()
full_text += f"\n--- Trang {page_num} ---\n{text}"
doc.close()
# Giới hạn 4000 ký tự để tránh vượt context window
if len(full_text) > 4000:
return full_text[:4000] + "\n...[nội dung bị cắt ngắn]"
return full_text

Với PDF dài nhiều trang, cần chiến lược chunking thay vì đọc toàn bộ — đó chính là lúc cần đến tool hỏi đáp tài liệu ở bước tiếp theo.

Tool 4 — Hỏi đáp kho tài liệu (RAG)

Khi tài liệu quá dài để nhét vào một lần, kỹ thuật RAG (Retrieval-Augmented Generation) chia nhỏ tài liệu, lưu vector embedding, và chỉ lấy đoạn liên quan khi cần trả lời.

python
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.chains import RetrievalQA
from langchain.tools import tool
import fitz
def build_qa_chain(pdf_path: str) -> RetrievalQA:
"""Xây dựng QA chain từ một file PDF."""
doc = fitz.open(pdf_path)
raw_text = "".join(page.get_text() for page in doc)
doc.close()
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
chunks = splitter.create_documents([raw_text])
embeddings = OpenAIEmbeddings()
vectorstore = FAISS.from_documents(chunks, embeddings)
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
return RetrievalQA.from_chain_type(
llm=llm,
retriever=vectorstore.as_retriever(search_kwargs={"k": 3})
)
@tool
def ask_document(input: str) -> str:
"""
Hỏi đáp nội dung tài liệu PDF. Input: 'đường_dẫn_file | câu hỏi'
Ví dụ: 'docs/hop_dong.pdf | Điều khoản thanh toán là gì?'
"""
parts = input.split(" | ", 1)
if len(parts) != 2:
return "Input không đúng định dạng."
file_path, question = parts
qa_chain = build_qa_chain(file_path)
result = qa_chain.invoke({"query": question})
return result["result"]
sơ đồ quy trình RAG gồm 4 bước: PDF → Chunking → Vector Embedding → Retrieval → LLM trả lời

Lắp ghép Agent hoàn chỉnh

Sau khi có đủ bốn tool, khai báo agent với ReAct framework để LLM tự quyết định dùng tool nào.

python
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_react_agent
from langchain import hub
tools = [read_recent_emails, analyze_spreadsheet, extract_pdf_text, ask_document]
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
prompt = hub.pull("hwchase17/react")
agent = create_react_agent(llm=llm, tools=tools, prompt=prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True, max_iterations=5)
# Thử nghiệm
response = executor.invoke({
"input": "Đọc email mới nhất và tóm tắt xem có email nào liên quan đến hợp đồng không?"
})
print(response["output"])

Bật verbose=True giúp bạn thấy rõ từng bước agent suy luận: nó chọn tool nào, truyền tham số gì, nhận kết quả ra sao trước khi đưa ra câu trả lời cuối.

Tổng kết

Bài này xây dựng một agent đa năng với bốn tool thực chiến: đọc email qua IMAP, phân tích Excel bằng pandas, trích xuất PDF với PyMuPDF, và hỏi đáp tài liệu dài qua RAG với FAISS. Điểm mấu chốt là mỗi tool chỉ làm một việc rõ ràng, trả về text mô tả để LLM xử lý tiếp — không cần tool phải thông minh, chỉ cần trả đúng dữ liệu. Với kiến trúc này, bạn có thể mở rộng thêm tool mới mà không cần thay đổi logic agent.

Luyện tập sau buổi học

Bài kiểm tra cuối bài

Ôn lại kiến thức, thử sức và nhận góp ý cho bài làm.

0/1
Đã trả lời · 0/1