🔨 Custom Tools
🎯 Mục tiêu bài học
Sau bài học này, bạn sẽ:
✅ Hiểu Tool Design Principles cho AI Agents
✅ Biết các loại Tool Types trong n8n
✅ Tạo được HTTP Tools, Code Tools, Workflow Tools
✅ Xây dựng Web Scraper và Google Sheets tools
✅ Implement Email Sender tool với confirmation
✅ Áp dụng Tool Design Rules và best practices
Custom tools mở rộng khả năng của agents. Bài này cover cách design và implement tools cho n8n agents.
🔍 Tool Design Principles
| Tool Type | Implementation | Use Case |
|---|---|---|
| HTTP Tool | HTTP Request node | API calls |
| Code Tool | Code node as tool | Custom logic |
| Workflow Tool | Sub-workflow | Complex operations |
| Built-in | Calculator, Wikipedia | Common tasks |
Checkpoint
Good Tool Design cần đáp ứng những tiêu chí nào? So sánh các Tool Types trong n8n.
🌐 Creating HTTP Tools
1// Tool: Weather API2// Agent Tool node configuration:3// Name: get_weather4// Description: "Get current weather for a city. Input: city name."56// Connected to HTTP Request node:7// URL: https://api.weatherapi.com/v1/current.json8// Query: q={{ $json.query }}9// API Key: configured in credential1011// Return format for agent:12// Code node after HTTP:13const data = $json;14return {15 json: {16 result: `Weather in ${data.location.name}: ${data.current.condition.text}, Temperature: ${data.current.temp_c} celsius`17 }18};Checkpoint
Các bước tạo HTTP Tool trong n8n là gì? Output format nào tốt nhất cho Agent?
💻 Creating Code Tools
1// Tool: Calculator2// n8n Calculator Tool node (built-in)3// Or custom code tool:45// Name: advanced_calculator6// Description: "Perform calculations. Supports: +, -, *, /, sqrt, power, percentage"78// Code node implementation:9function calculate(expression) {10 // Safe math evaluation11 const cleanExpr = expression.replace(/[^0-9+\-*/().%sqrt pow]/g, '');12 13 // Handle special functions14 let result;15 if (cleanExpr.includes('sqrt')) {16 const num = parseFloat(cleanExpr.match(/\d+/)[0]);17 result = Math.sqrt(num);18 } else if (cleanExpr.includes('pow')) {19 const nums = cleanExpr.match(/\d+/g);20 result = Math.pow(parseFloat(nums[0]), parseFloat(nums[1]));21 } else {22 result = Function('"use strict"; return (' + cleanExpr + ')')();23 }24 25 return { result: result.toString() };26}2728return { json: calculate($json.query) };Checkpoint
Khi tạo Code Tool, cần chú ý những gì về input validation và safe execution?
🏗️ Creating Workflow Tools
1// Sub-workflow as tool2// 1. Create separate workflow3// 2. Start with "Execute Workflow Trigger" node4// 3. Add your complex logic5// 4. End with return data67// In Agent workflow:8// Add "Call n8n Workflow" tool9// Select the sub-workflow10// Agent will call it when neededCheckpoint
Workflow Tool khác gì so với Code Tool? Khi nào nên tách logic thành sub-workflow?
🕷️ Tool: Web Scraper
1// Name: web_scraper2// Description: "Fetch and extract text content from a web URL"34// HTTP Request node:5// URL: {{ $json.url }}6// Response Format: Text78// Code node: Extract clean text9const html = $json.data;1011// Simple text extraction12const text = html13 .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')14 .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')15 .replace(/<[^>]+>/g, ' ')16 .replace(/\s+/g, ' ')17 .trim()18 .substring(0, 3000); // Limit length1920return { json: { content: text, url: $json.url } };Checkpoint
Web Scraper tool cần xử lý HTML như thế nào? Tại sao cần limit output length?
📊 Tool: Google Sheets & Email
Google Sheets CRUD
1// Name: spreadsheet_manager2// Description: "Read, write, or search data in Google Sheets"34// Google Sheets node configuration:5// Operation: {{ $json.operation }}6// Sheet: {{ $json.sheetName }}78// Agent can specify:9// - operation: "read", "append", "search"10// - sheetName: target sheet11// - data: rows to write12// - searchKey: what to search forEmail Sender
1// Name: send_email2// Description: "Send an email. Requires: to, subject, body"34// Gmail node:5// To: {{ $json.to }}6// Subject: {{ $json.subject }} 7// Body: {{ $json.body }}89// Important: Always require AI to confirm before sending10// Add confirmation step in workflowCheckpoint
Google Sheets tool hỗ trợ những operations nào? Tại sao Email tool cần confirmation step?
💡 Best Practices
1// Good tool description - Agent knows when to use it2const goodDescription = "Search company knowledge base for HR policies, benefits, and employee guidelines. Input: search query about HR topics.";34// Bad tool description - Too vague5const badDescription = "Search stuff.";67// Tool input validation8function validateInput(input, schema) {9 const errors = [];10 for (const [key, config] of Object.entries(schema)) {11 if (config.required && !input[key]) {12 errors.push(`Missing required field: ${key}`);13 }14 if (config.type && typeof input[key] !== config.type) {15 errors.push(`${key} should be ${config.type}`);16 }17 }18 return errors;19}- One purpose per tool — Mỗi tool làm 1 việc cụ thể
- Clear description — Agent dựa vào description để chọn tool
- Validate inputs — Check inputs trước khi execute
- Handle errors — Return clear error messages
- Limit scope — Đừng cho tool quá nhiều quyền
Checkpoint
Những Tool Design Rules nào quan trọng nhất? Cho ví dụ về good vs bad tool description.
📚 Bài tập thực hành
- Create weather API tool và test với agent
- Build web scraper tool cho content extraction
- Create Google Sheets CRUD tool
- Build agent sử dụng 3+ custom tools cùng lúc
Checkpoint
Bạn đã tạo được bao nhiêu custom tools? Agent có thể sử dụng chúng đúng cách không?
🚀 Bài tiếp theo
Bài tiếp theo: Database Tools →
