Series 2 - Bài 5: Error Handling khi tool fail
Error handling trong agent system khác fundamentally so với trong service thường. Lỗi không chỉ được throw — nó có thể được đưa về cho LLM để tự recover. Bài này xây dựng taxonomy lỗi và chiến lược xử lý từng loại.
Khi service API fail, bạn throw exception, log, và trả lỗi cho user. Đơn giản.
Khi tool trong agent fail, có nhiều lựa chọn hơn. Error có thể đi về LLM để nó tự quyết định: retry? thử cách khác? Hỏi user? Dừng lại?
Biết cái nào có thể recover là kỹ năng quan trọng trong agent design.
Error Taxonomy
┌───────────────────────────────────────────────────────┐
│ Error Types │
│ │
│ Type 1: Expected — Recoverable by LLM │
│ File not found │
│ Command exit code != 0 │
│ Invalid path format │
│ Search returns no results │
│ │
│ Type 2: Expected — Requires human decision │
│ Permission denied (intentional policy) │
│ User cancelled action │
│ Tool outside allowed scope │
│ │
│ Type 3: Unexpected — System issue │
│ LLM API timeout │
│ Disk full │
│ Out of memory │
│ Network unavailable │
│ │
│ Type 4: Logic error — Agent stuck │
│ Tool gọi cùng lệnh lần thứ 4 │
│ LLM loop giữa 2 tool calls │
│ Contradictory requirements │
└───────────────────────────────────────────────────────┘
Type 1: Expected Errors — Làm giàu cho LLM
Đây là loại error LLM có thể reason trải và tự recover. Xử lý chính: return error như tool_result bình thường, không throw exception.
Scenario: LLM gọi read_file cho file không tồn tại
Xấu (throw exception → agent crash):
throw new Error("File not found: src/nonexistent.ts")
Tốt (return như tool_result, LLM tự xử lý):
{
type: "tool_result",
tool_use_id: "toolu_01ABC",
is_error: true,
content: "File not found: src/nonexistent.ts.\n"
+ "Suggestion: Use list_directory to see "
+ "available files in src/"
}
Khi LLM nhận result này, nó có thể quyết định:
- Gọi
list_directoryđể tìm file đúng - Hỏi user tên file thực sự
- Báo cáo rằng file không tồn tại
Hint trong error message là investment. Mỗi hint tốt có thể giảm 1-2 vòng loop, tiết kiệm token và thời gian.
Type 2: Policy Errors — Escalate rõ ràng
Type 2 không phải lỗi kỹ thuật — là policy decision. LLM cần biết đây là intentional và không nên retry:
Scenario: Agent muốn đọc file ngoài allowed directory
Tool result:
"Permission denied: src/../config/secrets.ts is outside
the allowed working directory /project/my-app/.
This restriction is intentional and cannot be bypassed.
If you need this file, ask the user to provide its
contents explicitly."
LLM biết:
• Đây là intentional policy
• Không nên retry
• Option thay thế là gì
"This restriction is intentional and cannot be bypassed" quan trọng — nó ngăn LLM tốn thêm vòng loop cố tìm cách đi vòng.
Type 3: System Errors — Retry với backoff
System errors thường transient — retry có thể giải quyết:
Retry strategy:
LLM API timeout:
• Retry 3 lần với exponential backoff: 1s, 2s, 4s
• Nếu vẫn fail → stop agent, thông báo user
Network blip:
• Retry ngay 1 lần
• Nếu fail → exponential backoff
Disk full:
• Không retry (không có gì thay đổi giữa các lần)
• Stop agent ngay, message rõ ràng cho user
System errors không nên đưa vào context của LLM — LLM không biết cách fix disk full hay network timeout. Xử lý trong infrastructure layer, không phải trong agent loop.
Type 4: Logic Errors — Break the loop
Type 4 nguy hiểm nhất vì nó đưa đến infinite loop:
Pattern: LLM stuck trong loop
Vòng 1: search_files("*.service.ts") → 10 files
Vòng 2: read_file("a.service.ts") → content
Vòng 3: search_files("*.service.ts") → same 10 files
Vòng 4: read_file("a.service.ts") → same content
…
Detection:
Track tool calls và inputs
Nếu (tool, input) được gọi exact 2 lần liên tiếp
→ Inject meta-message:
"[System] You appear to be stuck in a loop.
You've called search_files with the same query twice.
Please try a different approach or ask the user
for clarification."
Meta-message injection là technique hữu ích: bạn inject một message vào conversation mà không phải từ user, để re-orient LLM.
Error Message Design là UX
Người nhận error message trong agent system là LLM, không phải human. Thiết kế error message cho LLM khác:
For humans:
"Error 404: Resource not found"
For LLM:
"File 'src/user.repository.ts' does not exist.
The src/ directory contains these files:
user.service.ts, user.controller.ts, user.entity.ts
Perhaps you meant one of these?"
Chìa khóa: actionable information. Error message tốt cho LLM biết cụ thể có thể làm gì ngay tiếp theo.
Consecutive Error Threshold
Nếu agent gặp nhiều lỗi liên tiếp, đó là signal có gì đó fundamentally sai:
Consecutive error counter:
Reset về 0 mỗi khi tool thành công
Tăng 1 mỗi khi tool fail
Nếu consecutive_errors >= 3:
• Stop agent loop
• Summary những gì đã thử
• Hỏi user hướng giải quyết
Threshold này ngăn agent tiếp tục consume tokens khi đang rõ ràng là không tiến triển.
Trade-off: Verbose vs Concise Error Messages
Verbose error message:
+ LLM có nhiều context để recover
+ Ít vòng loop hơn
- Tốn nhiều token (mỗi error message vào context)
- Nếu agent gặp nhiều lỗi, context bị ô nhiễm nhanh
Concise error message:
+ Token efficient
- LLM có thể cần thêm vòng loop để tìm ra cách fix
Điều chỉnh theo loại error:
- Type 1 errors: verbose (hữu ích để recover)
- Type 2 errors: concise + rõ ràng là policy (không cần nhiều context)
- Type 3 errors: không đưa vào LLM context
- Type 4 errors: meta-message ngắn gọn
Kết luận
- Error taxonomy: Expected/Recoverable, Policy/Escalate, System/Retry, Logic/Break.
- Type 1 errors đưa vào LLM như tool_result với actionable hints — LLM tự recover.
- Type 2 errors explicit rằng là intentional policy — ngăn LLM tốn vòng loop cố bypass.
- Type 3 errors xử lý trong infrastructure, không đưa vào agent loop.
- Type 4 errors được detect bằng loop pattern recognition và xử lý bằng meta-message injection.
- Error message design là UX cho LLM — actionable information giảm vòng loop.