🤖 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:
| Tool | Use Case |
|---|---|
| HTTP Request | Call APIs |
| Code | Execute JavaScript |
| Database | Query data |
| Calculator | Math operations |
| Wikipedia | Search knowledge |
| Custom | Your own tools |
Basic Agent Setup
Step 1: Add AI Agent Node
Text
1Manual Trigger → AI Agent → OutputAI 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 configuration2URL: https://api.weatherapi.com/v1/current.json3Method: GET4Query 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 Hanoi52. User wants calculation → Use calculator for 50 * 0.1563. Combine results7 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 configuration2Type: Window Buffer Memory3Window Size: 10 // Last 10 messages4Session ID: {{ $json.sessionId }}2. Summary Memory
Tóm tắt conversation:
JavaScript
1Type: Summary Memory2Model: GPT-3.5 (for summarization)3Max Tokens: 5003. Vector Store Memory
Semantic search trong history:
JavaScript
1Type: Vector Store Memory2Embedding Model: OpenAI Embeddings3Vector Store: Pinecone/Supabase4Top K: 5 // Retrieve 5 most relevantBuilding Custom Tools
Code Tool
JavaScript
1// Custom tool với Code node2// Description: "Search products by name and category"34const input = $input.first().json;5const { productName, category } = input;67// Simulate database search8const 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];1314let results = products;1516if (productName) {17 results = results.filter(p => 18 p.name.toLowerCase().includes(productName.toLowerCase())19 );20}2122if (category) {23 results = results.filter(p => p.category === category);24}2526return [{ json: { products: results } }];Database Tool
JavaScript
1// PostgreSQL query tool2// Input: { query: "user question about data" }34const userQuestion = $input.first().json.query;56// Agent constructs SQL based on question7// Tool executes and returns results89// 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:
- Trigger: User asks research question
- AI Agent: Plans research steps
- Tools:
- Web Search: Find recent articles
- Wikipedia: Get background info
- Summarize: Combine findings
- 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/articles42. Then, check Wikipedia for background information53. Finally, synthesize findings into a clear report6 7Format your report as:8## Topic Overview9[Background from Wikipedia]10 11## Recent Developments12[From web search]13 14## Key Takeaways15[Your synthesis]Error Handling
Tool Failures
JavaScript
1// Trong tool node2try {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
- Clear tool descriptions - Agent needs to know when to use each
- Specific system prompts - Guide agent behavior
- Limit tools - Too many tools = confusion
- Test extensively - Agents can be unpredictable
- Add guardrails - Prevent harmful actions
- Log everything - Debug agent decisions
Practical Example: Customer Support Agent
JavaScript
1// System Prompt2const systemPrompt = `3You are a customer support agent for TechStore.45Available tools:6- order_lookup: Find order by ID or email7- product_info: Get product details8- refund_request: Submit refund request9- escalate: Transfer to human agent1011Guidelines:12- Always greet customers warmly13- Look up order information before answering questions14- For complex issues, offer to escalate15- Never share other customers' information16`;Tools Setup:
order_lookup→ Database queryproduct_info→ API call to product servicerefund_request→ Create ticket in systemescalate→ Send to human queue
Bài tập thực hành
Hands-on Exercise
Build Research Agent:
- Create AI Agent với system prompt
- Add tools:
- Web search (HTTP)
- Wikipedia
- Calculator
- Add Window Memory
- 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.
