Trích xuất JSON có cấu trúc với Tool Use — Không cần regex
Điểm nổi bật
Nhấn để đến mục tương ứng
- 1 Công cụ AI sẽ thay đổi cách bạn làm việc: Giả sử bạn cần trích xuất thông tin từ bài báo: tác giả, chủ đề chính, điểm chất lượng và keywords. Điểm mấu chốt là biết cách đặt prompt đúng để nhận kết quả có thể sử dụng ngay.
- 2 Một điều ít người đề cập: NER là bài toán trích xuất các thực thể có tên người, tổ chức, địa điểm từ văn bản. Hiểu rõ bối cảnh áp dụng sẽ quyết định 80% thành công khi triển khai.
- 3 Nội dung cốt lõi: Thay vì chỉ Positive/Negative, bạn có thể yêu cầu phân tích cảm xúc chi tiết với điểm số và lý do: sentimenttool = {. Nắm vững phần này sẽ giúp bạn áp dụng hiệu quả hơn 70% so với đọc lướt toàn bài.
- 4 Để đạt hiệu quả tối đa: Đây là trường hợp thú vị nhất: khi bạn không biết trước các keys. Nhiều người bỏ qua bước này và mất thời gian gấp đôi để đạt cùng kết quả.
- 5 Một điều ít người đề cập: Tiêu chí Prompt thông thường Tool Use Structured Output format Có thể thay đổi Luôn đúng schema Parse complexity Cần. Hiểu rõ bối cảnh áp dụng sẽ quyết định 80% thành công khi triển khai.
Một trong những thách thức lớn nhất khi làm việc với LLM trong production là output không nhất quán. Claude có thể trả lời "Sentiment: Positive" hoặc "Tích cực" hoặc "Đây là review tích cực vì..." — tùy hứng. Đây là cơn ác mộng khi build pipeline tự động.
Tool Use giải quyết vấn đề này một cách thanh lịch: thay vì nhờ Claude trả lời bằng text, bạn định nghĩa một tool giả với input schema chính xác là JSON structure bạn cần. Claude sẽ "gọi tool" bằng cách điền vào schema đó — và bạn đọc phần tool.input thay vì parse text.
Trick này đặc biệt mạnh vì: không cần thực thi tool, không cần gửi tool_result, không cần vòng lặp phức tạp. Chỉ cần một lần gọi API và đọc structured data từ response.
Ví dụ 1: Tóm tắt bài viết có cấu trúc
Giả sử bạn cần trích xuất thông tin từ bài báo: tác giả, chủ đề chính, điểm chất lượng và keywords.
import anthropic
import json
client = anthropic.Anthropic()
# Dinh nghia "tool" - thuc ra la schema output ban muon
article_summarizer = {
"name": "print_article_summary",
"description": "Tom tat bai viet theo format co cau truc",
"input_schema": {
"type": "object",
"properties": {
"author": {
"type": "string",
"description": "Ten tac gia bai viet"
},
"topics": {
"type": "array",
"items": {"type": "string"},
"description": "Danh sach chu de chinh (toi da 5)"
},
"summary": {
"type": "string",
"description": "Tom tat ngan gon trong 2-3 cau"
},
"quality_score": {
"type": "number",
"description": "Diem chat luong 0-10"
}
},
"required": ["author", "topics", "summary", "quality_score"]
}
}
article_text = """
Tac gia: Nguyen Van A
Tieu de: Trien vong AI trong y te Viet Nam 2026
...noi dung bai viet...
"""
response = client.messages.create(
model="claude-opus-4-5",
max_tokens=1024,
tools=[article_summarizer],
tool_choice={"type": "tool", "name": "print_article_summary"},
messages=[{
"role": "user",
"content": f"Hay tom tat bai viet nay: {article_text}"
}]
)
# Doc ket qua - khong can parse text!
tool_use = response.content[0]
summary_data = tool_use.input
print(f"Tac gia: {summary_data['author']}")
print(f"Chu de: {', '.join(summary_data['topics'])}")
print(f"Diem: {summary_data['quality_score']}/10")
Chú ý tool_choice={"type": "tool", "name": "print_article_summary"} — đây là cách ép buộc Claude phải gọi đúng tool đó. Không có tùy chọn, không có ngoại lệ.
Ví dụ 2: Named Entity Recognition (NER)
NER là bài toán trích xuất các thực thể có tên (người, tổ chức, địa điểm) từ văn bản. Trước đây cần model NLP chuyên biệt, giờ Claude làm được với vài dòng code:
ner_tool = {
"name": "extract_entities",
"description": "Trich xuat cac thuc the co ten tu van ban",
"input_schema": {
"type": "object",
"properties": {
"people": {
"type": "array",
"items": {"type": "string"},
"description": "Ten nguoi duoc de cap"
},
"organizations": {
"type": "array",
"items": {"type": "string"},
"description": "Ten to chuc, cong ty, co quan"
},
"locations": {
"type": "array",
"items": {"type": "string"},
"description": "Ten dia diem, quoc gia, thanh pho"
},
"dates": {
"type": "array",
"items": {"type": "string"},
"description": "Cac moc thoi gian duoc de cap"
}
},
"required": ["people", "organizations", "locations", "dates"]
}
}
text = """
Nguyen Van Binh, CEO cua VinAI, vua ky ket hop tac
voi Google DeepMind tai Ha Noi ngay 15/3/2026.
Thoa thuan tri gia 50 trieu USD nham phat trien
he thong AI cho thi truong Dong Nam A.
"""
response = client.messages.create(
model="claude-opus-4-5",
max_tokens=512,
tools=[ner_tool],
tool_choice={"type": "tool", "name": "extract_entities"},
messages=[{"role": "user", "content": f"Trich xuat entities: {text}"}]
)
entities = response.content[0].input
# entities = {
# "people": ["Nguyen Van Binh"],
# "organizations": ["VinAI", "Google DeepMind"],
# "locations": ["Ha Noi", "Dong Nam A"],
# "dates": ["15/3/2026"]
# }
Ví dụ 3: Sentiment Analysis đa chiều
Thay vì chỉ Positive/Negative, bạn có thể yêu cầu phân tích cảm xúc chi tiết với điểm số và lý do:
sentiment_tool = {
"name": "analyze_sentiment",
"description": "Phan tich cam xuc van ban theo nhieu chieu",
"input_schema": {
"type": "object",
"properties": {
"overall_sentiment": {
"type": "string",
"enum": ["very_positive", "positive", "neutral", "negative", "very_negative"]
},
"score": {
"type": "number",
"description": "Diem cam xuc tu -1.0 (rat tieu cuc) den 1.0 (rat tich cuc)"
},
"emotions": {
"type": "array",
"items": {
"type": "object",
"properties": {
"emotion": {"type": "string"},
"intensity": {"type": "number", "description": "0.0 den 1.0"}
}
},
"description": "Cac cam xuc cu the duoc phat hien"
},
"key_phrases": {
"type": "array",
"items": {"type": "string"},
"description": "Cac cum tu quyet dinh den sentiment"
},
"reasoning": {
"type": "string",
"description": "Ly giai ngan gon ve ket qua phan tich"
}
},
"required": ["overall_sentiment", "score", "emotions", "key_phrases", "reasoning"]
}
}
review = """
San pham nay that su vuot ngoai mong doi! Chat lieu tot, giao hang
nhanh hon du kien. Tuy nhien, huong dan su dung kha kho hieu,
phai doc nhieu lan moi hieu. Nhin chung, toi rat hai long va
se mua lai lan sau.
"""
response = client.messages.create(
model="claude-opus-4-5",
max_tokens=512,
tools=[sentiment_tool],
tool_choice={"type": "tool", "name": "analyze_sentiment"},
messages=[{"role": "user", "content": review}]
)
result = response.content[0].input
print(f"Sentiment: {result['overall_sentiment']} (score: {result['score']})")
print(f"Emotions: {result['emotions']}")
print(f"Reasoning: {result['reasoning']}")
Ví dụ 4: Text Classification đa nhãn
Phân loại nội dung vào nhiều categories cùng lúc — phổ biến trong content moderation và tagging:
classifier_tool = {
"name": "classify_content",
"description": "Phan loai noi dung vao cac danh muc",
"input_schema": {
"type": "object",
"properties": {
"primary_category": {
"type": "string",
"enum": ["technology", "business", "health", "entertainment", "sports", "politics", "other"]
},
"secondary_categories": {
"type": "array",
"items": {
"type": "string",
"enum": ["AI", "finance", "startup", "mobile", "cloud", "education", "sustainability"]
},
"description": "Danh muc phu (co the nhieu)"
},
"target_audience": {
"type": "string",
"enum": ["general", "professional", "student", "developer", "executive"]
},
"content_maturity": {
"type": "string",
"enum": ["all_ages", "teen", "adult"]
},
"confidence": {
"type": "number",
"description": "Do tin cay phan loai tu 0.0 den 1.0"
}
},
"required": ["primary_category", "secondary_categories", "target_audience", "content_maturity", "confidence"]
}
}
# Su dung tuong tu nhu tren
Ví dụ 5: Trích xuất với Unknown Keys
Đây là trường hợp thú vị nhất: khi bạn không biết trước các keys. Ví dụ, trích xuất thông số kỹ thuật từ mô tả sản phẩm:
flexible_extractor = {
"name": "extract_specifications",
"description": "Trich xuat cac thong so ky thuat tu mo ta san pham",
"input_schema": {
"type": "object",
"properties": {
"product_name": {"type": "string"},
"specifications": {
"type": "object",
"description": "Cap key-value cac thong so ky thuat. Key la ten thong so, value la gia tri.",
"additionalProperties": {
"type": "string"
}
},
"price_vnd": {
"type": "number",
"description": "Gia san pham theo VND, null neu khong co"
}
},
"required": ["product_name", "specifications"]
}
}
product_description = """
Laptop Dell XPS 15 9530 - Bao hanh 12 thang
Processor: Intel Core i9-13900H, 24 cores
RAM: 32GB DDR5 4800MHz
Storage: 1TB NVMe SSD PCIe Gen 4
Display: 15.6 inch OLED, 3.5K 120Hz
GPU: NVIDIA RTX 4060 8GB
Gia: 45.990.000d
"""
response = client.messages.create(
model="claude-opus-4-5",
max_tokens=512,
tools=[flexible_extractor],
tool_choice={"type": "tool", "name": "extract_specifications"},
messages=[{"role": "user", "content": product_description}]
)
specs = response.content[0].input
print(f"San pham: {specs['product_name']}")
for key, value in specs['specifications'].items():
print(f" {key}: {value}")
# Output:
# San pham: Dell XPS 15 9530
# Processor: Intel Core i9-13900H, 24 cores
# RAM: 32GB DDR5 4800MHz
# Storage: 1TB NVMe SSD...
# ...
Claude sẽ tự động tạo ra các keys phù hợp dựa trên nội dung — không cần biết trước schema!
So sánh: Tool Use vs Prompt thông thường
| Tiêu chí | Prompt thông thường | Tool Use (Structured) |
|---|---|---|
| Output format | Có thể thay đổi | Luôn đúng schema |
| Parse complexity | Cần regex/text parsing | JSON trực tiếp |
| Missing fields | Không được đảm bảo | Required fields luôn có |
| Type safety | Không có | Validated theo schema |
| Nested data | Khó parse | Dễ dàng |
| Token cost | Thấp hơn | Cao hơn nhẹ (schema tokens) |
Khi nào dùng kỹ thuật này?
- Data extraction pipeline — Xử lý hàng nghìn documents cần consistent output
- API response — Trả JSON cho frontend mà không cần transform
- Database population — Tự động điền vào fields cụ thể
- Multi-language NLP — NER, sentiment cho tiếng Việt không cần model riêng
Kỹ thuật này đặc biệt valuable khi bạn cần độ tin cậy cao trong production. Thay vì chạy 1000 requests và hy vọng Claude luôn output đúng format, bạn có guarantee về schema từ đầu.
Bài tiếp theo: xây dựng Customer Service Agent thực sự — nơi Tool Use không chỉ là trick mà là cơ chế cốt lõi để chatbot truy vấn database và xử lý đơn hàng.
Bai viet co huu ich khong?
Bản quyền thuộc về tác giả. Vui lòng dẫn nguồn khi chia sẻ.



