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

API Tools

Tạo API integration tools cho agents - REST APIs, webhooks, third-party services

🔌 API Tools

0

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

TB5 min

Sau bài học này, bạn sẽ:

✅ Hiểu API Tool Architecture cho AI Agents

✅ Xây dựng Generic API Tool với domain whitelist

✅ Tạo CRM Tool (HubSpot integration)

✅ Build Project Management Tool (Trello)

✅ Implement Multi-Channel Notification Tool

✅ Áp dụng Error Handling và API Security

Cho phép agents gọi external APIs, integrate third-party services, và thực hiện real-world actions.

1

🔍 API Tool Architecture

TB5 min
Diagram
Đang vẽ diagram...

Checkpoint

API Tool Architecture gồm những layers nào? Tại sao cần API Tool Manager?

2

🌐 Generic API Tool

TB5 min
JavaScript
1// Tool: api_request
2// Description: "Make HTTP requests to APIs. Specify URL, method, headers, body"
3
4// Code node: API call wrapper
5const config = {
6 url: $json.url,
7 method: $json.method || "GET",
8 headers: $json.headers || {},
9 body: $json.body || null
10};
11
12// Safety checks
13const allowedDomains = [
14 "api.hubspot.com",
15 "api.trello.com",
16 "api.notion.com",
17 "slack.com"
18];
19
20const domain = new URL(config.url).hostname;
21if (!allowedDomains.some(d => domain.includes(d))) {
22 return { json: { error: `Domain ${domain} not in allowed list` } };
23}
24
25// Execute via HTTP Request node
26return { json: config };

Checkpoint

Tại sao Generic API Tool cần domain whitelist? Cách implement safety checks cho API calls?

3

🛠️ CRM Tool: HubSpot

TB5 min
JavaScript
1// Tool: crm_manager
2// Description: "Manage contacts, deals, and companies in HubSpot CRM"
3
4// Sub-tools:
5const crmOperations = {
6 searchContacts: {
7 method: "POST",
8 url: "https://api.hubapi.com/crm/v3/objects/contacts/search",
9 body: {
10 filterGroups: [{
11 filters: [{
12 propertyName: "email",
13 operator: "EQ",
14 value: $json.email
15 }]
16 }]
17 }
18 },
19
20 createContact: {
21 method: "POST",
22 url: "https://api.hubapi.com/crm/v3/objects/contacts",
23 body: {
24 properties: {
25 email: $json.email,
26 firstname: $json.firstName,
27 lastname: $json.lastName,
28 company: $json.company
29 }
30 }
31 },
32
33 createDeal: {
34 method: "POST",
35 url: "https://api.hubapi.com/crm/v3/objects/deals",
36 body: {
37 properties: {
38 dealname: $json.dealName,
39 amount: $json.amount,
40 pipeline: "default",
41 dealstage: "appointmentscheduled"
42 }
43 }
44 }
45};
46
47return { json: crmOperations[$json.operation] };

Checkpoint

CRM Tool hỗ trợ những operations nào? Làm sao để Agent biết khi nào dùng searchContacts vs createContact?

4

📋 Project Management Tool: Trello

TB5 min
JavaScript
1// Tool: project_manager
2// Description: "Create and manage Trello cards and boards"
3
4const trelloOps = {
5 createCard: {
6 url: `https://api.trello.com/1/cards`,
7 method: "POST",
8 params: {
9 key: process.env.TRELLO_KEY,
10 token: process.env.TRELLO_TOKEN,
11 idList: $json.listId,
12 name: $json.title,
13 desc: $json.description,
14 due: $json.dueDate
15 }
16 },
17
18 listCards: {
19 url: `https://api.trello.com/1/lists/${$json.listId}/cards`,
20 method: "GET",
21 params: {
22 key: process.env.TRELLO_KEY,
23 token: process.env.TRELLO_TOKEN
24 }
25 },
26
27 moveCard: {
28 url: `https://api.trello.com/1/cards/${$json.cardId}`,
29 method: "PUT",
30 params: {
31 key: process.env.TRELLO_KEY,
32 token: process.env.TRELLO_TOKEN,
33 idList: $json.targetListId
34 }
35 }
36};

Checkpoint

Trello Tool hỗ trợ những operations nào? API credentials được quản lý như thế nào?

5

📢 Notification Tool

TB5 min
JavaScript
1// Tool: notify
2// Description: "Send notifications via Slack, email, or SMS"
3
4// Route based on channel
5const channel = $json.channel;
6
7switch (channel) {
8 case "slack":
9 // Slack node: Post Message
10 return {
11 json: {
12 channel: $json.slackChannel,
13 text: $json.message,
14 blocks: [{
15 type: "section",
16 text: { type: "mrkdwn", text: $json.message }
17 }]
18 }
19 };
20
21 case "email":
22 // Gmail node: Send
23 return {
24 json: {
25 to: $json.to,
26 subject: $json.subject,
27 body: $json.message
28 }
29 };
30
31 case "telegram":
32 // Telegram node: Send Message
33 return {
34 json: {
35 chatId: $json.chatId,
36 text: $json.message
37 }
38 };
39}

Checkpoint

Multi-channel Notification Tool routing dựa trên gì? Mỗi channel cần những parameters khác nhau nào?

6

⚡ Multi-API Agent Example

TB5 min
Diagram
Đang vẽ diagram...
JavaScript
1// Agent with multiple API tools
2const agentPrompt = `
3You are an operations assistant with access to multiple tools:
41. crm_manager - Search/create contacts and deals in HubSpot
52. project_manager - Create/manage tasks in Trello
63. notify - Send Slack/email notifications
7
8When given a task:
91. Break it into steps
102. Use appropriate tools
113. Confirm each action result
124. Report summary when done
13
14Always ask for confirmation before sending emails.
15`;

Checkpoint

Multi-API Agent orchestrate nhiều APIs như thế nào? Agent quyết định thứ tự gọi API dựa trên gì?

7

🛡️ Error Handling & Security

TB5 min
JavaScript
1// Code node: API error handler
2const response = $json;
3
4if (response.statusCode >= 400) {
5 const errorMsg = {
6 400: "Bad request - check input parameters",
7 401: "Authentication failed - check API credentials",
8 403: "Access denied - insufficient permissions",
9 404: "Resource not found",
10 429: "Rate limited - wait and retry",
11 500: "Server error - try again later"
12 };
13
14 return {
15 json: {
16 success: false,
17 error: errorMsg[response.statusCode] || `Error: ${response.statusCode}`,
18 details: response.body
19 }
20 };
21}
22
23return { json: { success: true, data: response.body } };
API Security
  1. Domain whitelist: Chỉ cho phép approved domains
  2. Credential isolation: API keys trong n8n credentials, không trong prompts
  3. Rate limiting: Respect API rate limits
  4. Confirmation: Ask before destructive actions (delete, send email)
  5. Audit trail: Log mọi API calls agent thực hiện

Checkpoint

Cách xử lý HTTP error codes trong API Tool? Những biện pháp bảo mật nào cần áp dụng?

8

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

TB5 min
Exercises
  1. Create CRM tool (search contacts, create deals)
  2. Build project management tool (Trello/Notion tasks)
  3. Create multi-channel notification tool
  4. Build agent kết hợp 3+ API tools cho complex task

Checkpoint

Bạn đã build được multi-API agent chưa? Agent có thể orchestrate nhiều API calls hiệu quả không?

🚀 Bài tiếp theo

Bài tiếp theo: Speech-to-Text →