Skip to main content

AI Agent Workflow Example

This example demonstrates how to build a production-ready AI Agent workflow with LangChain integration, including language models, tools, and conversation memory.

Workflow Overview

The AI agent workflow includes:
  1. Chat Trigger - Receives user messages via webhook
  2. AI Agent - Orchestrates conversation and tool usage
  3. Language Model - Powers the AI’s reasoning (OpenAI GPT-4)
  4. HTTP Request Tool - Allows AI to fetch external data
  5. Code Tool - Enables custom logic execution
  6. Memory - Maintains conversation history

Use Cases

  • Customer support chatbots
  • Data analysis assistants
  • Research and information retrieval
  • Multi-step task automation
  • Intelligent API orchestration

Complete Workflow JSON

{
  "name": "AI Agent with Tools",
  "nodes": [
    {
      "id": "chat-trigger-1",
      "name": "Chat Trigger",
      "type": "@n8n/n8n-nodes-langchain.chatTrigger",
      "typeVersion": 1.1,
      "position": [250, 400],
      "parameters": {
        "options": {
          "responseMode": "lastNode",
          "publicChatKey": "ai-assistant"
        }
      },
      "webhookId": "ai-chat"
    },
    {
      "id": "openai-model-1",
      "name": "OpenAI Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1,
      "position": [450, 200],
      "parameters": {
        "model": "gpt-4-turbo-preview",
        "options": {
          "temperature": 0.7,
          "maxTokens": 2000
        }
      },
      "credentials": {
        "openAiApi": {
          "id": "1",
          "name": "OpenAI API"
        }
      }
    },
    {
      "id": "http-tool-1",
      "name": "Weather API Tool",
      "type": "@n8n/n8n-nodes-langchain.toolHttpRequest",
      "typeVersion": 1.1,
      "position": [450, 300],
      "parameters": {
        "method": "GET",
        "url": "https://api.openweathermap.org/data/2.5/weather",
        "toolDescription": "Fetch current weather conditions for any city. Use this when user asks about weather, temperature, or conditions.",
        "placeholderDefinitions": {
          "values": [
            {
              "name": "city",
              "description": "City name (e.g., London, New York, Tokyo)"
            },
            {
              "name": "units",
              "description": "Temperature units: metric (Celsius) or imperial (Fahrenheit)"
            }
          ]
        },
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "q",
              "value": "={{$json.city}}"
            },
            {
              "name": "units",
              "value": "={{$json.units || 'metric'}}"
            },
            {
              "name": "appid",
              "value": "={{$credentials.openWeatherMapApi.apiKey}}"
            }
          ]
        },
        "options": {}
      },
      "credentials": {
        "openWeatherMapApi": {
          "id": "2",
          "name": "OpenWeatherMap API"
        }
      }
    },
    {
      "id": "code-tool-1",
      "name": "Calculate Tool",
      "type": "@n8n/n8n-nodes-langchain.toolCode",
      "typeVersion": 1,
      "position": [450, 400],
      "parameters": {
        "name": "calculate",
        "description": "Perform mathematical calculations, conversions, or data analysis. Use when user asks to compute, calculate, or convert values.",
        "language": "javaScript",
        "code": "// Available inputs: $input object with all tool parameters\n// Must return an object with results\n\nconst { operation, value1, value2 } = $input;\n\nlet result;\n\nswitch(operation) {\n  case 'add':\n    result = value1 + value2;\n    break;\n  case 'subtract':\n    result = value1 - value2;\n    break;\n  case 'multiply':\n    result = value1 * value2;\n    break;\n  case 'divide':\n    result = value2 !== 0 ? value1 / value2 : 'Error: Division by zero';\n    break;\n  case 'power':\n    result = Math.pow(value1, value2);\n    break;\n  case 'percentage':\n    result = (value1 / 100) * value2;\n    break;\n  default:\n    result = 'Error: Unknown operation';\n}\n\nreturn {\n  operation,\n  value1,\n  value2,\n  result,\n  formatted: `${value1} ${operation} ${value2} = ${result}`\n};",
        "specifyInputSchema": true,
        "inputSchema": "{\n  \"type\": \"object\",\n  \"properties\": {\n    \"operation\": {\n      \"type\": \"string\",\n      \"description\": \"Math operation: add, subtract, multiply, divide, power, percentage\"\n    },\n    \"value1\": {\n      \"type\": \"number\",\n      \"description\": \"First number\"\n    },\n    \"value2\": {\n      \"type\": \"number\",\n      \"description\": \"Second number\"\n    }\n  },\n  \"required\": [\"operation\", \"value1\", \"value2\"]\n}"
      }
    },
    {
      "id": "memory-1",
      "name": "Window Buffer Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "typeVersion": 1.2,
      "position": [450, 500],
      "parameters": {
        "contextWindowLength": 10,
        "sessionIdType": "customKey",
        "sessionKey": "={{$json.sessionId}}"
      }
    },
    {
      "id": "agent-1",
      "name": "AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [650, 400],
      "parameters": {
        "promptType": "define",
        "text": "={{$json.chatInput}}",
        "hasOutputParser": false,
        "options": {
          "systemMessage": "You are a helpful AI assistant with access to weather data and calculation tools. \n\nWhen users ask about weather, use the weather tool to fetch current conditions. When they need calculations, use the calculate tool.\n\nAlways:\n- Be concise and accurate\n- Cite the tool you used\n- Format responses clearly\n- Ask clarifying questions if needed\n- Remember conversation context",
          "maxIterations": 10,
          "returnIntermediateSteps": false
        }
      }
    }
  ],
  "connections": {
    "Chat Trigger": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Weather API Tool": {
      "ai_tool": [
        [
          {
            "node": "AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Calculate Tool": {
      "ai_tool": [
        [
          {
            "node": "AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Window Buffer Memory": {
      "ai_memory": [
        [
          {
            "node": "AI Agent",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "active": false
}

Step-by-Step Breakdown

1

Chat Trigger Setup

The Chat Trigger node receives user messages via webhook and initializes the conversation.Key Parameters:
  • responseMode: lastNode - Returns agent’s response
  • publicChatKey - Unique identifier for the chat interface
2

Language Model Configuration

The OpenAI Chat Model provides the AI reasoning capabilities.Settings:
  • Model: GPT-4 Turbo for advanced reasoning
  • Temperature: 0.7 for balanced creativity
  • Max tokens: 2000 for detailed responses
3

Tool Setup - Weather API

HTTP Request Tool enables the AI to fetch real-time weather data.Critical Elements:
  • toolDescription - Tells AI when to use this tool (15+ chars)
  • placeholderDefinitions - Defines tool parameters
  • Query parameters with n8n expressions
4

Tool Setup - Calculator

Code Tool allows the AI to perform mathematical operations.Features:
  • Multiple operations (add, subtract, multiply, etc.)
  • Input schema for type validation
  • Error handling for edge cases
5

Conversation Memory

Window Buffer Memory maintains context across messages.Configuration:
  • 10 message history window
  • Session-based tracking
  • Automatic context management
6

AI Agent Orchestration

The Agent node coordinates everything:
  • Analyzes user input
  • Decides which tools to use
  • Executes tools in sequence
  • Formulates final response
System Prompt: Guides AI behavior and response style

Connection Types Explained

Important: AI connections use special port types that differ from standard n8n connections:
  • ai_languageModel - Connects language model to agent
  • ai_tool - Connects tools to agent
  • ai_memory - Connects memory to agent
  • main - Standard data flow (Chat Trigger → Agent)

Example Conversation

User: “What’s the weather in London and calculate 15% of 200?” AI Agent Process:
  1. Analyzes request (two separate tasks)
  2. Calls Weather API Tool with city=“London”
  3. Calls Calculate Tool with operation=“percentage”, value1=15, value2=200
  4. Synthesizes results into coherent response
Response:
In London, the current weather is partly cloudy with a temperature 
of 12°C (54°F). There's a light breeze from the west.

Regarding your calculation: 15% of 200 equals 30.

Is there anything else you'd like to know?

Advanced Configuration

Add Streaming Responses

For real-time response streaming:
{
  "parameters": {
    "options": {
      "responseMode": "streaming"
    }
  }
}
Critical: When using streaming mode, the AI Agent must NOT have any outgoing main connections. Responses stream automatically through the Chat Trigger.

Add Fallback Language Model

For production reliability:
{
  "name": "Claude Fallback",
  "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
  "parameters": {
    "model": "claude-3-opus"
  }
}
Connect as second language model with targetIndex: 1 and set needsFallback: true on the Agent.

Add Vector Store for RAG

Enable knowledge base retrieval:
{
  "name": "Vector Store Tool",
  "type": "@n8n/n8n-nodes-langchain.toolVectorStore",
  "parameters": {
    "name": "knowledge_base",
    "description": "Search company knowledge base for product information, policies, and documentation"
  }
}

Validation Checklist

1

Before Deployment

Run n8n_validate_workflow({id: "workflow_id"}) to check:
  • Language model is connected
  • All tools have descriptions (15+ characters)
  • Tool parameters are properly configured
  • Memory settings are valid
  • No connection errors
2

Test Scenarios

Test the agent with:
  • Single tool usage (“What’s the weather in Paris?”)
  • Multiple tools (“Weather in Tokyo and calculate 25% of 400”)
  • Conversation memory (“What city did I just ask about?”)
  • Edge cases (invalid cities, division by zero)
3

Monitor Performance

Track:
  • Response times
  • Tool usage patterns
  • Error rates
  • Token consumption

Common Issues and Solutions

”AI Agent has no language model”

Cause: Language model not connected or wrong connection type. Solution: Use sourceOutput: "ai_languageModel" when connecting.

”Tool has no description”

Cause: Missing or too short tool description. Solution: Add clear description (15+ characters) explaining when to use the tool.

”Streaming mode not working”

Cause: AI Agent has outgoing main connections. Solution: Remove all main output connections from the Agent node.

Next Steps

Build docs developers (and LLMs) love