Lý thuyết
35 phút
Bài 1/3

AI Agents trong n8n

Tìm hiểu cách xây dựng AI Agents với n8n AI nodes

🤖 AI Agents trong n8n

n8n cung cấp powerful AI Agent nodes để build autonomous workflows. Bài này giới thiệu concepts và implementation.

AI Agent là gì?

Agent Definition

AI Agent là LLM có khả năng:

  • Reasoning: Suy nghĩ về task
  • Tool Use: Sử dụng tools để thực hiện actions
  • Memory: Nhớ context từ conversations
  • Planning: Lập kế hoạch multi-step
Diagram
graph TD
    U[User Query] --> A[AI Agent]
    A --> R{Reasoning}
    R --> T1[Use Tool 1]
    R --> T2[Use Tool 2]
    R --> T3[Search Memory]
    T1 & T2 & T3 --> A
    A --> O[Final Response]

AI Agent Nodes trong n8n

1. AI Agent Node

Node chính để create agents:

Configuration:

  • Model: OpenAI, Claude, local LLMs
  • System Prompt: Instructions cho agent
  • Tools: Connected tool nodes
  • Memory: Conversation history

2. Tool Nodes

Các tools agent có thể sử dụng:

ToolUse Case
HTTP RequestCall APIs
CodeExecute JavaScript
DatabaseQuery data
CalculatorMath operations
WikipediaSearch knowledge
CustomYour own tools

Basic Agent Setup

Step 1: Add AI Agent Node

Text
1Manual Trigger → AI Agent → Output

AI Agent Configuration:

  • Model: GPT-4o-mini
  • System Prompt:
Text
1You are a helpful assistant that can answer questions and perform tasks.
2When asked about weather, use the weather tool.
3When asked to calculate, use the calculator tool.
4Always explain your reasoning.

Step 2: Add Tools

Calculator Tool:

  • Add "Calculator" node
  • Connect to AI Agent's "Tools" input

HTTP Tool (Weather API):

JavaScript
1// Tool node configuration
2URL: https://api.weatherapi.com/v1/current.json
3Method: GET
4Query Parameters:
5 - key: {{ $env.WEATHER_API_KEY }}
6 - q: {{ $json.location }}

Step 3: Test Agent

Text
1Input: "What's the weather in Hanoi and calculate 15% tip on $50"
2
3Agent reasoning:
41. User wants weather → Use weather tool for Hanoi
52. User wants calculation → Use calculator for 50 * 0.15
63. Combine results
7
8Output: "The weather in Hanoi is 28°C with partly cloudy skies.
9 A 15% tip on $50 would be $7.50."

Memory Systems

1. Window Memory

Nhớ N messages gần nhất:

JavaScript
1// Memory node configuration
2Type: Window Buffer Memory
3Window Size: 10 // Last 10 messages
4Session ID: {{ $json.sessionId }}

2. Summary Memory

Tóm tắt conversation:

JavaScript
1Type: Summary Memory
2Model: GPT-3.5 (for summarization)
3Max Tokens: 500

3. Vector Store Memory

Semantic search trong history:

JavaScript
1Type: Vector Store Memory
2Embedding Model: OpenAI Embeddings
3Vector Store: Pinecone/Supabase
4Top K: 5 // Retrieve 5 most relevant

Building Custom Tools

Code Tool

JavaScript
1// Custom tool với Code node
2// Description: "Search products by name and category"
3
4const input = $input.first().json;
5const { productName, category } = input;
6
7// Simulate database search
8const products = [
9 { id: 1, name: "iPhone 15", category: "phones", price: 999 },
10 { id: 2, name: "MacBook Pro", category: "laptops", price: 1999 },
11 { id: 3, name: "AirPods Pro", category: "audio", price: 249 }
12];
13
14let results = products;
15
16if (productName) {
17 results = results.filter(p =>
18 p.name.toLowerCase().includes(productName.toLowerCase())
19 );
20}
21
22if (category) {
23 results = results.filter(p => p.category === category);
24}
25
26return [{ json: { products: results } }];

Database Tool

JavaScript
1// PostgreSQL query tool
2// Input: { query: "user question about data" }
3
4const userQuestion = $input.first().json.query;
5
6// Agent constructs SQL based on question
7// Tool executes and returns results
8
9// Example: "How many orders last month?"
10// → SELECT COUNT(*) FROM orders WHERE created_at > NOW() - INTERVAL '1 month'

Multi-Step Agent Workflow

Research Agent Example

Diagram
graph TD
    T[User Query] --> A[AI Agent]
    A --> S[Web Search Tool]
    S --> A
    A --> W[Wikipedia Tool]
    W --> A
    A --> Sum[Summarize Tool]
    Sum --> A
    A --> R[Final Report]

Workflow:

  1. Trigger: User asks research question
  2. AI Agent: Plans research steps
  3. Tools:
    • Web Search: Find recent articles
    • Wikipedia: Get background info
    • Summarize: Combine findings
  4. Output: Structured research report

System Prompt:

Text
1You are a research assistant. When given a topic:
2
31. First, search the web for recent news/articles
42. Then, check Wikipedia for background information
53. Finally, synthesize findings into a clear report
6
7Format your report as:
8## Topic Overview
9[Background from Wikipedia]
10
11## Recent Developments
12[From web search]
13
14## Key Takeaways
15[Your synthesis]

Error Handling

Tool Failures

JavaScript
1// Trong tool node
2try {
3 const result = await callExternalAPI();
4 return [{ json: { success: true, data: result } }];
5} catch (error) {
6 return [{ json: {
7 success: false,
8 error: error.message,
9 suggestion: "Try with different parameters"
10 }}];
11}

Agent Fallbacks

Text
1System Prompt addition:
2
3If a tool fails, explain the issue to the user and suggest alternatives.
4Never make up information - if you can't find data, say so.

Best Practices

Agent Best Practices
  1. Clear tool descriptions - Agent needs to know when to use each
  2. Specific system prompts - Guide agent behavior
  3. Limit tools - Too many tools = confusion
  4. Test extensively - Agents can be unpredictable
  5. Add guardrails - Prevent harmful actions
  6. Log everything - Debug agent decisions

Practical Example: Customer Support Agent

JavaScript
1// System Prompt
2const systemPrompt = `
3You are a customer support agent for TechStore.
4
5Available tools:
6- order_lookup: Find order by ID or email
7- product_info: Get product details
8- refund_request: Submit refund request
9- escalate: Transfer to human agent
10
11Guidelines:
12- Always greet customers warmly
13- Look up order information before answering questions
14- For complex issues, offer to escalate
15- Never share other customers' information
16`;

Tools Setup:

  1. order_lookup → Database query
  2. product_info → API call to product service
  3. refund_request → Create ticket in system
  4. escalate → Send to human queue

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

Hands-on Exercise

Build Research Agent:

  1. Create AI Agent với system prompt
  2. Add tools:
    • Web search (HTTP)
    • Wikipedia
    • Calculator
  3. Add Window Memory
  4. Test với multi-step queries

Target: Agent có thể research topics và provide structured answers


Tiếp theo

Bài tiếp theo: Tool Calling - Deep dive vào defining và using tools.