n8n LangChain Integration: How AI Agent Workflows Work Under the Hood

n8n integrates with LangChain through a dedicated node that orchestrates agent execution via the invokeAgent function, wraps models using LangchainChatModelAdapter, and dynamically injects tools and memory to enable stateful AI automation.

The n8n-io/n8n repository provides native LangChain support through the @n8n/nodes-langchain package, allowing users to embed sophisticated AI agents directly into visual workflows. This n8n LangChain integration bridges n8n's workflow orchestration with LangChain's agent framework through a three-layer architecture that handles model adaptation, tool discovery, and conversation memory.

Architecture of the n8n LangChain Integration

The integration relies on three distinct layers that work together to execute AI agents within n8n's workflow engine.

Agent Orchestration via invokeAgent

The core entry point for all agent execution is the invokeAgent function located in packages/@n8n/nodes-langchain/nodes/vendors/Microsoft/langchain-utils.ts. This function coordinates the entire agent lifecycle from prompt preparation to result parsing.

export async function invokeAgent(
    nodeContext: IWebhookFunctions,
    input: string,
    systemMessage?: string,
    invokeOptions: RunnableConfig = {},
    microsoftMcpTools: Array<DynamicStructuredTool<ToolInputSchemaBase, any, any, any>> = [],
): Promise<string> { … }

When invoked, invokeAgent performs the following operations:

  1. Retrieves the chat model via getChatModel and an optional fallback model for resilience.
  2. Loads conversation memory using getOptionalMemory to maintain state across executions.
  3. Collects available tools through getTools, merging built-in n8n utilities with any Microsoft-specific MCP tools.
  4. Constructs the prompt using prepareMessages and preparePrompt to build a ChatPromptTemplate containing system instructions, chat history placeholders, and agent scratchpad formatting.
  5. Creates the executor via createAgentExecutor, instantiating a ToolsAgent with the model, tools, prompt, memory, and fallback configuration.
  6. Enforces structured output by invoking the executor with a payload that requires the format_final_json_response tool, ensuring consistent JSON returns.
  7. Handles results by parsing JSON output, updating memory buffers, and returning the final string to the workflow.

Chat Model Adaptation

Since n8n's workflow engine requires specific tracing and retry mechanisms, the LangchainChatModelAdapter in packages/@n8n/ai-utilities/src/adapters/langchain-chat-model.ts wraps any LangChain-compatible chat model.

This adapter provides three critical capabilities:

  • Execution Tracing: Registers N8nLlmTracing callbacks to capture token usage, model metadata, and latency metrics within the workflow execution context.
  • Retry Logic: Applies makeN8nLlmFailedAttemptHandler to automatically retry transient LLM errors with exponential backoff.
  • Streaming Support: Converts LangChain's streaming chunks into n8n's ChatGenerationChunk objects while preserving tool-call deltas and usage statistics.

Tools and Memory Management

The integration dynamically discovers and binds tools through two key utilities in the packages/@n8n/nodes-langchain/nodes/vendors/Microsoft/ directory:

  • getTools: Scans node configurations to create LangChain DynamicStructuredTool instances for built-in n8n actions such as HTTP requests, database queries, and webhook triggers.
  • getOptionalMemory: Instantiates a ConversationBufferMemory linked to the workflow's execution context, enabling agents to recall previous interactions within the same workflow instance.

End-to-End Agent Execution Flow

When a workflow containing a LangChain node executes, the following sequence occurs:

  1. Node Initialization: The user-configured LangChain node receives the input prompt and parameters.
  2. Context Injection: n8n calls invokeAgent with the node context (IWebhookFunctions) and user input.
  3. Model Preparation: The LangchainChatModelAdapter wraps the selected LLM (e.g., OpenAI GPT-4) with n8n-specific tracing and retry handlers.
  4. Tool Assembly: getTools dynamically constructs tool instances from the node's configuration, including any custom JavaScript-defined utilities.
  5. Agent Execution: The ToolsAgent executor processes the prompt, potentially calling multiple tools through the LangchainChatModelAdapter.
  6. Result Delivery: The final JSON-structured response returns to the workflow, where downstream nodes access it via $node["LangChain Agent"].json.

Practical Configuration Examples

Configuring a Basic AI Agent

The following JSON represents a standard LangChain node configuration within an n8n workflow:

{
  "nodes": [
    {
      "name": "LangChain Agent",
      "type": "n8n-nodes-langchain.langchain",
      "typeVersion": 1,
      "position": [200, 300],
      "parameters": {
        "chatModel": "openai-gpt4",
        "input": "Summarize the last 5 messages in the chat history.",
        "systemMessage": "You are a helpful summarizer.",
        "needsFallback": true,
        "fallbackModel": "openai-gpt3.5"
      }
    }
  ]
}

When executed, this configuration triggers invokeAgent with the specified system message and fallback resilience.

Adding Custom Tools

You can extend agent capabilities by defining custom tools in the node parameters. The getTools function processes these definitions into DynamicStructuredTool instances:

{
  "parameters": {
    "customTools": [
      {
        "name": "fetchJson",
        "description": "GET a JSON payload from a public API",
        "inputSchema": {
          "type": "object",
          "properties": {
            "url": { "type": "string", "format": "uri" }
          },
          "required": ["url"]
        },
        "code": "const response = await fetch($input.url); return await response.json();"
      }
    ]
  }
}

The agent can invoke fetchJson during execution to retrieve external data.

Implementing Conversation Memory

Memory persistence works automatically across multiple LangChain nodes sharing the same workflow execution context:

// First node establishes context
{
  "name": "Agent 1",
  "type": "n8n-nodes-langchain.langchain",
  "parameters": {
    "input": "Hello, who are you?"
  }
}

// Second node recalls previous interaction
{
  "name": "Agent 2",
  "type": "n8n-nodes-langchain.langchain",
  "parameters": {
    "input": "What did I just ask you?"
  }
}

Because both nodes share the execution context, getOptionalMemory maintains a single ConversationBufferMemory instance that persists between calls.

Summary

  • The n8n LangChain integration centers on the invokeAgent function in packages/@n8n/nodes-langchain/nodes/vendors/Microsoft/langchain-utils.ts, which orchestrates model selection, prompt construction, and executor initialization.
  • Model compatibility is achieved through LangchainChatModelAdapter in packages/@n8n/ai-utilities/src/adapters/langchain-chat-model.ts, adding n8n-native tracing, retries, and streaming support to any LangChain chat model.
  • Dynamic tool discovery via getTools converts n8n node capabilities into LangChain DynamicStructuredTool objects that agents can invoke during reasoning.
  • Stateful conversations are enabled by getOptionalMemory, which creates persistent ConversationBufferMemory instances tied to workflow execution contexts.
  • The architecture enforces structured JSON output through mandatory tool calling, ensuring downstream nodes can reliably parse agent responses.

Frequently Asked Questions

What is the primary function of the invokeAgent method in n8n?

The invokeAgent method serves as the central orchestrator for AI agent execution within n8n. Located in packages/@n8n/nodes-langchain/nodes/vendors/Microsoft/langchain-utils.ts, this function coordinates model retrieval, memory initialization, tool collection, prompt construction, and the creation of the ToolsAgent executor. It handles the entire lifecycle from receiving the user's input string to returning the final structured response, including fallback model management and error handling.

How does n8n handle tracing and error retries for LangChain models?

n8n handles observability and resilience through the LangchainChatModelAdapter class in packages/@n8n/ai-utilities/src/adapters/langchain-chat-model.ts. This wrapper registers N8nLlmTracing callbacks to capture token usage and metadata, implements makeN8nLlmFailedAttemptHandler for automatic retry logic on transient failures, and manages streaming conversion to ensure compatibility with n8n's execution context. These mechanisms operate transparently without requiring manual configuration in the workflow editor.

Can n8n LangChain agents use custom tools built from existing n8n nodes?

Yes, the getTools function dynamically discovers available capabilities from the node configuration and creates LangChain DynamicStructuredTool instances. This allows agents to invoke built-in n8n functionality such as HTTP requests, database queries, and webhook triggers. Additionally, users can define custom tools using JavaScript code blocks within the LangChain node parameters, which getTools processes and binds to the agent's toolkit during the invokeAgent initialization phase.

How does memory persistence work across multiple LangChain node executions?

Memory persistence is managed by getOptionalMemory in the packages/@n8n/nodes-langchain/nodes/vendors/Microsoft/ directory, which creates a ConversationBufferMemory instance linked to the workflow's execution context. When multiple LangChain nodes run within the same workflow instance, they share this memory buffer automatically, allowing the agent to recall previous interactions. This stateful behavior enables complex multi-turn conversations and context-aware automation without manual session management.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →