LangChain & AI Nodes
Relevant source files
The following files were used as context for generating this wiki page:- packages/@n8n/ai-workflow-builder.ee/src/tools/prompts/main-agent.prompt.ts
- packages/@n8n/nodes-langchain/package.json
- packages/@n8n/ai-workflow-builder.ee/evaluations/chains/evaluators/connections-evaluator.ts
- packages/@n8n/ai-workflow-builder.ee/src/tools/best-practices/knowledge-base.ts
- packages/@n8n/ai-workflow-builder.ee/src/tools/best-practices/data-analysis.ts
- packages/@n8n/ai-workflow-builder.ee/src/chains/prompts/parameter-types/system-message.ts
- packages/nodes-base/AGENTS.md
The @n8n/n8n-nodes-langchain package provides a comprehensive suite of nodes for building sophisticated AI-powered workflows within n8n. These nodes serve as building blocks for creating applications like chatbots, data analysis pipelines, content generators, and Retrieval-Augmented Generation (RAG) systems. The architecture emphasizes a modular, component-based approach where specialized nodes are connected to provide capabilities to primary nodes like the AI Agent.
This system is governed by a strict set of connection rules and best practices designed to ensure robustness and maintainability. A key principle is the distinction between standard data flow connections and special "AI capability" connections. Understanding these concepts is crucial for building functional and efficient AI workflows.
Sources: packages/nodes-base/AGENTS.md, packages/@n8n/nodes-langchain/package.json, packages/@n8n/ai-workflow-builder.ee/src/tools/prompts/main-agent.prompt.ts:13-15
Core Architecture & Connection Model
AI workflows in n8n utilize two distinct types of connections, which are fundamental to the architecture.
Sources: packages/@n8n/ai-workflow-builder.ee/evaluations/chains/evaluators/connections-evaluator.ts:5-20
Connection Types
-
Main Workflow Connections (
main): These are the standard n8n connections that carry runtime data between nodes. They represent the primary execution path, flowing from a node that produces data to a node that consumes it (e.g.,HTTP Request->Set). -
AI Capability Connections (
ai_*): These connections are specific to the LangChain framework within n8n. They do not carry the main workflow data. Instead, they "provide" a capability from a sub-node to a parent node. The sub-node is always the source of the connection, and the parent node is the target. For example, a Language Model node connects to an AI Agent node to provide it with language processing capabilities.
The diagram below illustrates the two connection types.
This diagram shows a Vector Store node receiving main data from an HTTP Request while simultaneously being augmented with capabilities from Embeddings and Document Loader nodes via `ai_
` connections.*
Sources: packages/@n8n/ai-workflow-builder.ee/evaluations/chains/evaluators/connections-evaluator.ts:8-20, packages/@n8n/ai-workflow-builder.ee/src/tools/prompts/main-agent.prompt.ts:210-222
Hybrid and Capability-Only Nodes
- Hybrid Nodes: Nodes like
AI AgentandVector Storecan have bothmainandai_*connections. They participate in the main data flow while also being enhanced by capability sub-nodes. - Capability-Only Sub-nodes: Nodes such as
Document Loader,Token Splitter,Embeddings, LLM nodes (e.g.,OpenAI Chat Model), andToolnodes exist purely to provideai_*capabilities. They are not expected to havemaininputs or outputs.
Sources: packages/@n8n/ai-workflow-builder.ee/evaluations/chains/evaluators/connections-evaluator.ts:22-31
AI Workflow Creation Sequence
The AI Workflow Builder follows a structured, multi-phase sequence to construct workflows. This ensures all necessary components are discovered, analyzed, and configured correctly.
| Phase | Name | Description |
|---|---|---|
| 1 | Categorization | Categorize the user's prompt and search for best practices documentation. |
| 2 | Discovery | Search for all required node types. |
| 3 | Analysis | Get details for all discovered nodes to understand their inputs and outputs. |
| 4 | Creation | Add all required nodes to the canvas, often in parallel. |
| 5 | Connection | Connect the nodes based on the analyzed input/output structure. |
| 6 | Configuration | Configure parameters for every node. This is a mandatory step. |
| 7 | Validation | Run validate_workflow to check for structural issues and resolve violations. |
Sources: packages/@n8n/ai-workflow-builder.ee/src/tools/prompts/main-agent.prompt.ts:24-124
This sequence can be visualized as a flowchart:
This flowchart shows the mandatory phases for building an AI workflow, from initial categorization to final validation.
Sources: packages/@n8n/ai-workflow-builder.ee/src/tools/prompts/main-agent.prompt.ts:24-124
Key Node Categories and Patterns
The @n8n/n8n-nodes-langchain package contains a wide variety of nodes, which can be grouped into several categories.
| Category | Description | Example Nodes |
|---|---|---|
| Agents | Orchestrate AI tasks and tool usage. | Agent, AgentTool, OpenAiAssistant |
| Chains | Pre-built sequences for specific tasks. | ChainSummarization, ChainRetrievalQa, InformationExtractor |
| Document Loaders | Load documents from various sources. | DocumentDefaultDataLoader, DocumentGithubLoader |
| Embeddings | Generate vector embeddings for text. | EmbeddingsOpenAi, EmbeddingsCohere, EmbeddingsOllama |
| LLMs | Interface with Large Language Models. | LmChatOpenAi, LmChatAnthropic, LmChatGoogleGemini |
| Memory | Provide conversational history to agents. | MemoryBufferWindow, MemoryPostgresChat, MemoryRedisChat |
| Output Parsers | Structure the output from LLMs. | OutputParserStructured, OutputParserItemList |
| Retrievers | Fetch relevant documents for context. | RetrieverVectorStore, RetrieverMultiQuery |
| Text Splitters | Split large documents into smaller chunks. | TextSplitterRecursiveCharacterTextSplitter, TextSplitterTokenSplitter |
| Tools | Provide specific capabilities to agents. | ToolCalculator, ToolHttpRequest, ToolVectorStore |
| Vector Stores | Store and query vector embeddings. | VectorStoreQdrant, VectorStorePinecone, VectorStoreInMemory |
Sources: packages/@n8n/nodes-langchain/package.json:44-121
The AI Agent Node
The AI Agent node (n8n-nodes-langchain.agent) is a central component for building autonomous workflows. It acts as an orchestrator that can use LLMs, memory, and tools to accomplish complex tasks. It's critical to distinguish it from the AI Agent Tool node (n8n-nodes-langchain.agentTool), which is a sub-node that allows one agent to be used as a tool by another.
The diagram below shows the relationship between an AI Agent and its capability sub-nodes.
This class diagram illustrates how an AI Agent is composed of a language model, memory, and one or more tools, connected via `ai_
` links.*
Sources: packages/@n8n/ai-workflow-builder.ee/src/tools/prompts/main-agent.prompt.ts:244-266
Retrieval-Augmented Generation (RAG) Pattern
RAG is a common and powerful pattern for building knowledge bases. It involves two main workflows: ingestion and querying. The connection pattern is very specific and must be followed to work correctly.
- Data Ingestion: Data is fed into the
Vector Storevia its main connection. - AI Capabilities: The
Vector Storeis augmented with threeai_*connections:Document Loader->Vector Store[ai_document]Embeddings->Vector Store[ai_embedding]Text Splitter->Document Loader[ai_textSplitter]
The Document Loader is a capability provider for the Vector Store and should never be connected to the main data flow.
This flowchart depicts the standard RAG pattern, separating the ingestion flow (populating the Vector Store) from the query flow (using the Vector Store as a tool for an AI Agent).
Sources: packages/@n8n/ai-workflow-builder.ee/src/tools/prompts/main-agent.prompt.ts:225-242, packages/@n8n/ai-workflow-builder.ee/src/tools/best-practices/knowledge-base.ts:6-9, 21-31
Configuration Best Practices
Proper configuration is mandatory for AI nodes to function correctly. Relying on default values is a common source of runtime failures.
Sources: packages/@n8n/ai-workflow-builder.ee/src/tools/prompts/main-agent.prompt.ts:269-271
System Message vs. User Prompt
A critical best practice is the separation of the AI's role/instructions from the user's dynamic input.
- System Message: Defines the AI's role, capabilities, task description, and behavioral instructions. This is static content. It is configured in fields like
options.systemMessage(AI Agent) or a message with asystemrole (OpenAI). - User Message/Text: Contains the dynamic user input, context variables, and data references from the workflow (e.g.,
{{ $json.field }}). This is configured in thetextparameter or a message with auserrole.
Incorrect Example (mixing concerns):
{
"text": "=You are an orchestrator agent. Your task is to call the Research Tool. The research topic is: {{ $json.researchTopic }}"
}
Correct Example (separated concerns):
{
"text": "=The research topic is: {{ $json.researchTopic }}",
"options": {
"systemMessage": "You are an orchestrator agent. Your task is to call the Research Agent Tool to gather information and return a report."
}
}
This separation makes workflows more maintainable and aligns with standard prompt engineering practices.
Sources: packages/@n8n/ai-workflow-builder.ee/src/tools/prompts/main-agent.prompt.ts:333-413, packages/@n8n/ai-workflow-builder.ee/src/chains/prompts/parameter-types/system-message.ts
$fromAI Expressions for Tool Nodes
Tool nodes (e.g., Gmail Tool, Google Calendar Tool) support a special $fromAI expression. This allows the AI Agent to dynamically fill in parameters at runtime based on the conversational context.
| Parameter | Description | Type | Example |
|---|---|---|---|
key | A unique identifier for the parameter. | string | to, subject |
description | (Optional) A description for the AI. | string | 'Customer name' |
type | (Optional) The data type. | `'string' | 'number' |
defaultValue | (Optional) A fallback value. | any | 'Customer' |
Example Usage in a Gmail Tool node:
{
"sendTo": "={{ $fromAI('to') }}",
"subject": "={{ $fromAI('subject') }}",
"message": "={{ $fromAI('message_html') }}"
}
This syntax should only be used in nodes whose type ends with "Tool".
Sources: packages/@n8n/ai-workflow-builder.ee/src/tools/prompts/main-agent.prompt.ts:430-488
Summary
The LangChain & AI nodes in n8n provide a powerful, modular framework for building complex AI applications. Success with these nodes depends on a solid understanding of the core architectural principles, particularly the distinction between main and ai_* connections. By following the recommended workflow creation sequence, adhering to connection patterns like RAG, and applying configuration best practices such as separating system and user prompts, developers can create robust, maintainable, and effective AI-driven automations.