data/skills/n8n-workflow-patterns/ai_agent_workflow.md
Use Case: Build AI agents with tool access, memory, and reasoning capabilities.
Trigger → AI Agent (Model + Tools + Memory) → [Process Response] → Output
Key Characteristic: AI-powered decision making with tool use
n8n supports 8 AI connection types for building agent workflows:
Options:
Purpose: Orchestrate LLM with tools and memory
Configuration:
{
agent: "conversationalAgent", // or "openAIFunctionsAgent"
promptType: "define",
text: "You are a helpful assistant that can search docs, query databases, and send emails."
}
Connections:
Available providers:
Example (OpenAI Chat Model):
{
model: "gpt-4",
temperature: 0.7,
maxTokens: 1000
}
Critical insight: Connect ANY n8n node to agent via ai_tool port
Common tool types:
Purpose: Maintain conversation context
Types:
Purpose: Format AI response for delivery
Common patterns:
Flow: Webhook (chat message) → AI Agent → Webhook Response
Example (Customer support bot):
1. Webhook (path: "chat", POST)
- Receives: {user_id, message, session_id}
2. Window Buffer Memory (load context by session_id)
3. AI Agent
├─ OpenAI Chat Model (gpt-4)
├─ HTTP Request Tool (search knowledge base)
├─ Database Tool (query customer orders)
└─ Window Buffer Memory (conversation context)
4. Code (format response)
5. Webhook Response (send reply)
AI Agent prompt:
You are a customer support assistant.
You can:
1. Search the knowledge base for answers
2. Look up customer orders
3. Provide shipping information
Be helpful and professional.
Flow: Upload docs → Embed → Store → Query with AI
Example (Internal documentation assistant):
Setup Phase (run once):
1. Read Files (load documentation)
2. Text Splitter (chunk into paragraphs)
3. Embeddings (OpenAI Embeddings)
4. Vector Store (Pinecone/Qdrant) (store vectors)
Query Phase (recurring):
1. Webhook (receive question)
2. AI Agent
├─ OpenAI Chat Model (gpt-4)
├─ Vector Store Tool (search similar docs)
└─ Buffer Memory (context)
3. Webhook Response (answer with citations)
Flow: Request → AI Agent (with data tools) → Analysis → Visualization
Example (SQL analyst agent):
1. Webhook (data question: "What were sales last month?")
2. AI Agent
├─ OpenAI Chat Model (gpt-4)
├─ Postgres Tool (execute queries)
└─ Code Tool (data analysis)
3. Code (generate visualization data)
4. Webhook Response (answer + chart data)
Postgres Tool Configuration:
{
name: "query_database",
description: "Execute SQL queries to analyze sales data. Use SELECT queries only.",
// Node executes AI-generated SQL
}
Flow: Command → AI Agent → Execute actions → Report
Example (DevOps assistant):
1. Slack (slash command: /deploy production)
2. AI Agent
├─ OpenAI Chat Model (gpt-4)
├─ HTTP Request Tool (GitHub API)
├─ HTTP Request Tool (Deploy API)
└─ Postgres Tool (deployment logs)
3. Agent actions:
- Check if tests passed
- Create deployment
- Log deployment
- Notify team
4. Slack (deployment status)
Flow: Email received → AI Agent → Categorize → Route → Respond
Example (Support ticket router):
1. Email Trigger (new support email)
2. AI Agent
├─ OpenAI Chat Model (gpt-4)
├─ Vector Store Tool (search similar tickets)
└─ HTTP Request Tool (create Jira ticket)
3. Agent actions:
- Categorize urgency (low/medium/high)
- Find similar past tickets
- Create ticket in appropriate project
- Draft response
4. Email (send auto-response)
5. Slack (notify assigned team)
Critical concept: Any n8n node can become an AI tool!
Requirements:
ai_tool port (NOT main port)Example (HTTP Request as tool):
{
// Tool metadata (for AI)
name: "search_github_issues",
description: "Search GitHub issues by keyword. Returns issue titles and URLs.",
// HTTP Request configuration
method: "GET",
url: "https://api.github.com/search/issues",
sendQuery: true,
queryParameters: {
"q": "={{$json.query}} repo:{{$json.repo}}",
"per_page": "5"
}
}
How it works:
search_github_issues(query, repo)search_github_issues("bug", "n8n-io/n8n")Available in @n8n/n8n-nodes-langchain:
Example (Calculator Tool):
AI Agent
├─ OpenAI Chat Model
└─ Calculator Tool (ai_tool connection)
User: "What's 15% of 2,847?"
AI: *uses calculator tool* → "426.05"
Use when: Connecting to MCP servers (filesystem, databases, etc.)
{
name: "Filesystem Tool",
type: "@n8n/n8n-nodes-langchain.mcpClientTool",
parameters: {
description: "Access file system to read files and list directories",
mcpServer: {
transport: "stdio",
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"]
},
tool: "read_file"
}
}
Use when: Need specialized expertise from a sub-agent
{
name: "Research Specialist",
type: "@n8n/n8n-nodes-langchain.agentTool",
parameters: {
name: "research_specialist",
description: "Expert researcher for detailed research tasks",
systemMessage: "You are a research specialist. Search thoroughly and provide analysis."
}
}
Pattern: Postgres/MySQL node connected as ai_tool
Configuration:
{
// Tool metadata
name: "query_customers",
description: "Query customer database. Use SELECT queries to find customer information by email, name, or ID.",
// Postgres config
operation: "executeQuery",
query: "={{$json.sql}}", // AI provides SQL
// Security: Use read-only database user!
}
Safety: Create read-only DB user for AI tools!
CREATE USER ai_readonly WITH PASSWORD 'secure_password';
GRANT SELECT ON customers, orders TO ai_readonly;
-- NO INSERT, UPDATE, DELETE access
Pattern: Custom Python/JavaScript function
Example (Data processor):
// Tool metadata
{
name: "process_csv",
description: "Process CSV data and return statistics. Input: csv_string"
}
// Code node
const csv = $input.first().json.csv_string;
const lines = csv.split('\n');
const data = lines.slice(1).map(line => line.split(','));
return [{
json: {
row_count: data.length,
columns: lines[0].split(','),
summary: {
// Calculate statistics
}
}
}];
Any AI tool that fetches third-party content (HTTP Request, Serper, Wikipedia, GitHub search, MCP Client, web scrapers) can return attacker-controlled text. That text flows back into the agent's context and can attempt indirect prompt injection — steering the agent into destructive tool calls, data exfiltration, or bypassing your system prompt.
Guidelines:
ai_outputParser with a schema so the agent returns structured data, not free-form text that could be acted on downstream.Rule of thumb: if the agent can read the internet AND take an action the user can't undo, you need a guardrail between them.
Stores all messages (until cleared)
{
memoryType: "bufferMemory",
sessionKey: "={{$json.body.user_id}}" // Per-user memory
}
Stores last N messages (recommended)
{
memoryType: "windowBufferMemory",
sessionKey: "={{$json.body.session_id}}",
contextWindowLength: 10 // Last 10 messages
}
Summarizes old messages (for long conversations)
{
memoryType: "summaryMemory",
sessionKey: "={{$json.body.session_id}}",
maxTokenLimit: 2000
}
How it works:
Best for: General chat, customer support
Features:
When to use: Most common use case
Best for: Tool-heavy workflows, structured outputs
Features:
When to use: Multiple tools, need reliable tool calling
Best for: Step-by-step reasoning
Features:
When to use: Complex multi-step tasks
You are a [ROLE].
You can:
- [CAPABILITY 1]
- [CAPABILITY 2]
- [CAPABILITY 3]
Guidelines:
- [GUIDELINE 1]
- [GUIDELINE 2]
Format:
- [OUTPUT FORMAT]
You are a customer support assistant for Acme Corp.
You can:
- Search the knowledge base for answers
- Look up customer orders and shipping status
- Create support tickets for complex issues
Guidelines:
- Be friendly and professional
- If you don't know something, say so and offer to create a ticket
- Always verify customer identity before sharing order details
Format:
- Keep responses concise
- Use bullet points for multiple items
- Include relevant links when available
You are a data analyst assistant with access to the company database.
You can:
- Query sales, customer, and product data
- Perform data analysis and calculations
- Generate summary statistics
Guidelines:
- Write efficient SQL queries (always use LIMIT)
- Explain your analysis methodology
- Highlight important trends or anomalies
- Use read-only queries (SELECT only)
Format:
- Provide numerical answers with context
- Include query used (for transparency)
- Suggest follow-up analyses when relevant
For real-time user experience, set Chat Trigger to streaming mode:
// Chat Trigger parameters
{
options: {
responseMode: "streaming" // or "lastNode" for non-streaming
}
}
Important: When using streaming mode, the AI Agent must NOT have main output connections - responses stream back through Chat Trigger automatically.
For production reliability, connect a fallback model:
// Primary model (targetIndex: 0)
{
type: "addConnection",
source: "OpenAI Chat Model",
target: "AI Agent",
sourceOutput: "ai_languageModel",
targetIndex: 0
}
// Fallback model (targetIndex: 1)
{
type: "addConnection",
source: "Anthropic Chat Model",
target: "AI Agent",
sourceOutput: "ai_languageModel",
targetIndex: 1
}
Enable with: "parameters.needsFallback": true on the AI Agent node.
Complete knowledge base setup chain:
Documents → Text Splitter → Vector Store ← Embeddings
↓
Vector Store Tool → AI Agent
Use ai_embedding, ai_document, ai_vectorStore, and ai_tool connection types.
AI Agent (continueOnFail on tool nodes)
→ IF (tool error occurred)
└─ Code (log error)
└─ Webhook Response (user-friendly error)
Main Workflow:
AI Agent → Process Response
Error Workflow:
Error Trigger
→ IF (rate limit error)
└─ Wait → Retry
→ ELSE
└─ Notify Admin
// Code node - validate tool output
const result = $input.first().json;
if (!result || !result.data) {
throw new Error('Tool returned invalid data');
}
return [{ json: result }];
Fast & cheap: GPT-3.5-turbo, Claude 3 Haiku
Balanced: GPT-4, Claude 3 Sonnet
Powerful: GPT-4-turbo, Claude 3 Opus
{
memoryType: "windowBufferMemory",
contextWindowLength: 5 // Only last 5 messages
}
// ❌ Vague
description: "Search for things"
// ✅ Clear and concise
description: "Search GitHub issues by keyword and repository. Returns top 5 matching issues with titles and URLs."
For document Q&A, embed documents once:
Setup (run once):
Documents → Embed → Store in Vector DB
Query (fast):
Question → Search Vector DB → AI Agent
AI Agent → [Queue slow tool request]
→ Return immediate response
→ [Background: Execute tool + notify when done]
-- Create limited user for AI tools
CREATE USER ai_agent_ro WITH PASSWORD 'secure';
GRANT SELECT ON public.* TO ai_agent_ro;
-- NO write access!
// Code node - validate before execution
const query = $json.query;
if (query.toLowerCase().includes('drop ') ||
query.toLowerCase().includes('delete ') ||
query.toLowerCase().includes('update ')) {
throw new Error('Invalid query - write operations not allowed');
}
Webhook → IF (check user rate limit)
├─ [Within limit] → AI Agent
└─ [Exceeded] → Error (429 Too Many Requests)
// Code node
const userInput = $json.body.message
.trim()
.substring(0, 1000); // Max 1000 chars
return [{ json: { sanitized: userInput } }];
AI Agent → Log Tool Calls
→ IF (suspicious pattern)
└─ Alert Admin + Pause Agent
Replace webhook with manual trigger:
Manual Trigger
→ Set (mock user input)
→ AI Agent
→ Code (log output)
Before connecting to agent:
Manual Trigger → Tool Node → Verify output format
Create test suite:
1. "Hello" - Test basic response
2. "Search for bug reports" - Test tool calling
3. "What did I ask before?" - Test memory
4. Invalid input - Test error handling
// Code node - log token usage
console.log('Input tokens:', $node['AI Agent'].json.usage.input_tokens);
console.log('Output tokens:', $node['AI Agent'].json.usage.output_tokens);
HTTP Request → AI Agent // Won't work as tool!
HTTP Request --[ai_tool]--> AI Agent
description: "Get data" // AI won't know when to use this
description: "Query customer orders by email address. Returns order ID, status, and shipping info."
Every message is standalone - no context!
Window Buffer Memory --[ai_memory]--> AI Agent
Postgres (full access) as tool // AI could DELETE data!
Postgres (read-only user) as tool // Safe
Tool returns 10MB of data → exceeds token limit
{
query: "SELECT * FROM table LIMIT 10" // Only 10 rows
}
From n8n template library (234 AI templates):
Simple Chatbot:
Webhook → AI Agent (GPT-4 + Memory) → Webhook Response
Document Q&A:
Setup: Files → Embed → Vector Store
Query: Webhook → AI Agent (GPT-4 + Vector Store Tool) → Response
SQL Analyst:
Webhook → AI Agent (GPT-4 + Postgres Tool) → Format → Response
Use search_templates({query: "ai agent"}) to find more!
Key Points:
Pattern: Trigger → AI Agent (Model + Tools + Memory) → Output
Related: