/n8n-tutorials

How to pass conversation history to Anthropic Claude reliably in n8n?

Learn how to reliably pass conversation history to Anthropic Claude in n8n by structuring API requests, managing message arrays, and maintaining context for seamless multi-turn interactions.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free consultation

How to pass conversation history to Anthropic Claude reliably in n8n?

To pass conversation history to Anthropic Claude reliably in n8n, you need to structure your requests properly by maintaining and including previous messages in each new API call. This ensures context continuity as your workflow progresses, enabling Claude to reference earlier parts of the conversation.

 

Understanding the Anthropic Claude API Message Structure

 

Before diving into the n8n implementation, it's important to understand how Claude's API handles conversations. Claude uses a structured message format where each message has a "role" (either "user" or "assistant") and "content". To maintain conversation history, you need to append new messages to the existing array of messages with each request.

 

Step 1: Setting Up Your n8n Workflow

 

First, create a new workflow in n8n:

  1. Log in to your n8n instance
  2. Click on "Workflows" in the left sidebar
  3. Click "Create new workflow"
  4. Name your workflow (e.g., "Claude Conversation")
  5. Click "Save" to create the workflow

 

Step 2: Add a Trigger Node

 

Add a node that will trigger your conversation:

  1. Click on the "+" button to add a node
  2. Select a trigger node based on your requirements (e.g., "Webhook", "Manual", or "Schedule")
  3. Configure the trigger node according to your needs
  4. If using a Webhook, note the webhook URL for later use

 

Step 3: Set Up the Initial Claude Request

 

Add the HTTP Request node to make your first call to Claude:

  1. Click the "+" button after your trigger node
  2. Search for and select "HTTP Request"
  3. Configure the node with the following settings:
  • Method: POST
  • URL: https://api.anthropic.com/v1/messages
  • Authentication: Header Auth
  • Header Parameters:
    • Name: "anthropic-version"
    • Value: "2023-06-01" (or the latest version)
    • Name: "x-api-key"
    • Value: "Your-Claude-API-Key"
    • Name: "content-type"
    • Value: "application/json"
  • Request Body: JSON

{
  "model": "claude-3-opus-20240229",
  "max\_tokens": 1000,
  "messages": [
    {
      "role": "user",
      "content": "Hello, Claude. This is our first interaction."
    }
  ]
}
  1. Rename this node to "Initial Claude Request"

 

Step 4: Store the Conversation History

 

After the initial request, add a Set node to store the conversation:

  1. Add a new node after "Initial Claude Request"
  2. Search for and select "Set"
  3. Configure it as follows:
  • Name: "Store Conversation"
  • Keep Only Set: Checked (optional)
  • Add Value:
    • Name: "conversationHistory"
    • Type: Array
    • Value:

[
  {
    "role": "user",
    "content": "Hello, Claude. This is our first interaction."
  },
  {
    "role": "assistant",
    "content": "={{ $node["Initial Claude Request"].json.content }}"
  }
]

This stores both the initial user message and Claude's response in an array.

 

Step 5: Create a Function to Handle Follow-up Messages

 

Now, create a path for handling follow-up messages:

  1. Add a Function node after "Store Conversation"
  2. Name it "Prepare Follow-up Request"
  3. Enter the following code:

// Get the existing conversation history
const conversationHistory = $input.item.json.conversationHistory || [];

// Get the new user message (this would come from your input mechanism)
// For this example, we'll hardcode it, but in a real scenario, this would come from user input
const newUserMessage = {
  "role": "user",
  "content": "Tell me more about this conversation feature."
};

// Add the new message to conversation history
const updatedHistory = [...conversationHistory, newUserMessage];

// Prepare the request body for Claude
const requestBody = {
  "model": "claude-3-opus-20240229",
  "max\_tokens": 1000,
  "messages": updatedHistory
};

// Return the updated history and request body
return {
  conversationHistory: updatedHistory,
  requestBody: requestBody
};

 

Step 6: Make the Follow-up Request to Claude

 

Add another HTTP Request node to send the follow-up message:

  1. Add a node after "Prepare Follow-up Request"
  2. Search for and select "HTTP Request"
  3. Configure it as follows:
  • Name: "Follow-up Claude Request"
  • Method: POST
  • URL: https://api.anthropic.com/v1/messages
  • Authentication: Header Auth
  • Header Parameters:
    • Name: "anthropic-version"
    • Value: "2023-06-01" (or the latest version)
    • Name: "x-api-key"
    • Value: "Your-Claude-API-Key"
    • Name: "content-type"
    • Value: "application/json"
  • Request Body: JSON
  • JSON Body: ={{ $node["Prepare Follow-up Request"].json.requestBody }}

 

Step 7: Update the Conversation History

 

After receiving Claude's follow-up response, update the conversation history:

  1. Add a new Set node after "Follow-up Claude Request"
  2. Name it "Update Conversation History"
  3. Configure it as follows:
  • Keep Only Set: Checked (optional)
  • Add Value:
    • Name: "conversationHistory"
    • Type: Array
    • Value:

={{
  // Get the previous conversation history and add Claude's latest response
  [
    ...$node["Prepare Follow-up Request"].json.conversationHistory,
    {
      "role": "assistant",
      "content": $node["Follow-up Claude Request"].json.content
    }
  ]
}}

 

Step 8: Creating a Loop for Continuous Conversation

 

To create a loop that allows for multiple back-and-forth exchanges:

  1. Add a "Split In Batches" node after "Update Conversation History"
  2. Configure it to create a loop or use a specific condition to control the flow
  3. Connect it back to the "Prepare Follow-up Request" node to create a loop

Alternatively, you can use webhook responses to create an interactive chatbot:

  1. After "Update Conversation History", add a "Respond to Webhook" node if your trigger was a webhook
  2. Configure it to send back Claude's response
  3. Create a new webhook entry point for receiving the next user message

 

Step 9: Implement Dynamic User Input

 

For a real conversation, you'll want to accept dynamic user input rather than hardcoded messages:

  1. Modify the "Prepare Follow-up Request" function to get user input from a webhook payload or other input source:

// Get the existing conversation history
const conversationHistory = $input.item.json.conversationHistory || [];

// Get the new user message from the webhook payload or other input
const newUserMessage = {
  "role": "user",
  "content": $input.item.json.userMessage || "Default fallback message"
};

// Add the new message to conversation history
const updatedHistory = [...conversationHistory, newUserMessage];

// Prepare the request body for Claude
const requestBody = {
  "model": "claude-3-opus-20240229",
  "max\_tokens": 1000,
  "messages": updatedHistory
};

// Return the updated history and request body
return {
  conversationHistory: updatedHistory,
  requestBody: requestBody
};
  1. Ensure your input mechanism (webhook, form, etc.) provides the "userMessage" field

 

Step 10: Handling Conversation Storage and State Management

 

For maintaining conversations across multiple sessions or workflow runs:

  1. Add a node to store the conversation history in a database or file:
  • Use the "Write Binary File" node to save the conversation history to a JSON file
  • Or use a database node (MongoDB, PostgreSQL, etc.) to store the conversation
  1. Add a corresponding node at the beginning of your workflow to retrieve the stored conversation history

This approach lets you maintain conversations even if the workflow is restarted or across different sessions.

 

Step 11: Optimizing for Token Usage

 

As conversations grow longer, you may need to manage token usage:

  1. Add a Function node to trim the conversation history when it gets too long:

// Get the current conversation history
const conversationHistory = $input.item.json.conversationHistory || [];

// If the history is longer than a certain number of messages, trim it
// Keep the most recent N messages (e.g., 10)
const maxMessages = 10;
const trimmedHistory = conversationHistory.length > maxMessages
  ? conversationHistory.slice(conversationHistory.length - maxMessages)
  : conversationHistory;

// Return the trimmed history
return {
  conversationHistory: trimmedHistory
};
  1. Insert this node at appropriate points in your workflow, such as before preparing a new request

 

Step 12: Error Handling and Retries

 

Add error handling to make your conversation flow more robust:

  1. Add an "IF" node after your HTTP Request nodes to check for successful responses
  2. Configure branches for handling successful and failed requests
  3. For failed requests, you can:
  • Add a "Wait" node followed by a retry attempt
  • Send an error notification
  • Provide a fallback response to the user

 

Complete Workflow Example

 

Here's a streamlined example of the complete workflow for a webhook-based conversation:

  1. Webhook node (trigger)
  2. IF node to check if it's a new conversation
  • If new: Initial Claude Request → Store Conversation
  • If existing: Read Existing Conversation → Prepare Follow-up Request
  1. HTTP Request to Claude API
  2. Update Conversation History
  3. Store Updated Conversation (to database/file)
  4. Respond to Webhook (with Claude's response)

This structure creates a reliable way to maintain conversation history with Claude through n8n workflows.

 

Final Tips for Reliable Claude Conversations in n8n

 

  • Always validate that your message structure follows Claude's API requirements
  • Include proper error handling for API rate limits and other potential issues
  • Consider implementing a message ID system to track individual messages in the conversation
  • Test your workflow thoroughly with various conversation paths
  • Monitor token usage to avoid hitting limits in long conversations
  • Implement proper security measures if your conversation system is user-facing

By following these steps, you'll create a robust system for maintaining conversation history with Claude in your n8n workflows, enabling contextual and coherent exchanges across multiple interactions.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022