MinAI - Về trang chủ
Lý thuyết
6/1335 phút
Đang tải...

Custom Tools

Tạo custom tools cho AI Agents - extend agent capabilities

🔨 Custom Tools

0

🎯 Mục tiêu bài học

TB5 min

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.

1

🔍 Tool Design Principles

TB5 min
Diagram
Đang vẽ diagram...
Tool TypeImplementationUse Case
HTTP ToolHTTP Request nodeAPI calls
Code ToolCode node as toolCustom logic
Workflow ToolSub-workflowComplex operations
Built-inCalculator, WikipediaCommon 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.

2

🌐 Creating HTTP Tools

TB5 min
JavaScript
1// Tool: Weather API
2// Agent Tool node configuration:
3// Name: get_weather
4// Description: "Get current weather for a city. Input: city name."
5
6// Connected to HTTP Request node:
7// URL: https://api.weatherapi.com/v1/current.json
8// Query: q={{ $json.query }}
9// API Key: configured in credential
10
11// 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?

3

💻 Creating Code Tools

TB5 min
JavaScript
1// Tool: Calculator
2// n8n Calculator Tool node (built-in)
3// Or custom code tool:
4
5// Name: advanced_calculator
6// Description: "Perform calculations. Supports: +, -, *, /, sqrt, power, percentage"
7
8// Code node implementation:
9function calculate(expression) {
10 // Safe math evaluation
11 const cleanExpr = expression.replace(/[^0-9+\-*/().%sqrt pow]/g, '');
12
13 // Handle special functions
14 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}
27
28return { json: calculate($json.query) };

Checkpoint

Khi tạo Code Tool, cần chú ý những gì về input validation và safe execution?

4

🏗️ Creating Workflow Tools

TB5 min
Diagram
Đang vẽ diagram...
JavaScript
1// Sub-workflow as tool
2// 1. Create separate workflow
3// 2. Start with "Execute Workflow Trigger" node
4// 3. Add your complex logic
5// 4. End with return data
6
7// In Agent workflow:
8// Add "Call n8n Workflow" tool
9// Select the sub-workflow
10// Agent will call it when needed

Checkpoint

Workflow Tool khác gì so với Code Tool? Khi nào nên tách logic thành sub-workflow?

5

🕷️ Tool: Web Scraper

TB5 min
JavaScript
1// Name: web_scraper
2// Description: "Fetch and extract text content from a web URL"
3
4// HTTP Request node:
5// URL: {{ $json.url }}
6// Response Format: Text
7
8// Code node: Extract clean text
9const html = $json.data;
10
11// Simple text extraction
12const text = html
13 .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 length
19
20return { 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?

6

📊 Tool: Google Sheets & Email

TB5 min

Google Sheets CRUD

JavaScript
1// Name: spreadsheet_manager
2// Description: "Read, write, or search data in Google Sheets"
3
4// Google Sheets node configuration:
5// Operation: {{ $json.operation }}
6// Sheet: {{ $json.sheetName }}
7
8// Agent can specify:
9// - operation: "read", "append", "search"
10// - sheetName: target sheet
11// - data: rows to write
12// - searchKey: what to search for

Email Sender

JavaScript
1// Name: send_email
2// Description: "Send an email. Requires: to, subject, body"
3
4// Gmail node:
5// To: {{ $json.to }}
6// Subject: {{ $json.subject }}
7// Body: {{ $json.body }}
8
9// Important: Always require AI to confirm before sending
10// Add confirmation step in workflow

Checkpoint

Google Sheets tool hỗ trợ những operations nào? Tại sao Email tool cần confirmation step?

7

💡 Best Practices

TB5 min
JavaScript
1// Good tool description - Agent knows when to use it
2const goodDescription = "Search company knowledge base for HR policies, benefits, and employee guidelines. Input: search query about HR topics.";
3
4// Bad tool description - Too vague
5const badDescription = "Search stuff.";
6
7// Tool input validation
8function 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}
Tool Design Rules
  1. One purpose per tool — Mỗi tool làm 1 việc cụ thể
  2. Clear description — Agent dựa vào description để chọn tool
  3. Validate inputs — Check inputs trước khi execute
  4. Handle errors — Return clear error messages
  5. 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.

8

📚 Bài tập thực hành

TB5 min
Exercises
  1. Create weather API tool và test với agent
  2. Build web scraper tool cho content extraction
  3. Create Google Sheets CRUD tool
  4. 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 →