/n8n-tutorials

How to stop Claude from ignoring system instructions in an n8n workflow?

Learn how to make Claude follow system instructions in n8n workflows by structuring prompts, setting temperature, using JSON mode, and validating responses effectively.

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 stop Claude from ignoring system instructions in an n8n workflow?

To ensure Claude follows system instructions in n8n workflows, provide clear, structured instructions directly in the prompt, use explicit response formatting requirements, test your prompts extensively, and optimize your HTTP request node settings by controlling temperature and using "JSON mode" where available.

 

Step 1: Understanding the Problem

 

When working with Claude in n8n workflows, you might notice that sometimes the AI doesn't adhere to system instructions properly. This can happen for several reasons:

  • The way instructions are formatted in the HTTP Request node
  • The structure of your prompt
  • Missing parameters that help control Claude's behavior
  • Lack of explicit instruction enforcement

 

Step 2: Setting Up Your n8n Workflow Correctly

 

First, ensure your n8n workflow is set up correctly to communicate with Claude:

  • Add an HTTP Request node
  • Set the Method to POST
  • Use the correct Claude API endpoint (e.g., https://api.anthropic.com/v1/messages)
  • Set appropriate headers including your API key and content type

// Example HTTP Request node configuration
{
  "authentication": "predefinedCredentialType",
  "credentialType": "anthropicApi",
  "node": "HTTP Request",
  "type": "main",
  "parameters": {
    "method": "POST",
    "url": "https://api.anthropic.com/v1/messages",
    "authentication": "headerAuth",
    "headerParameters": {
      "parameters": [
        {
          "name": "x-api-key",
          "value": "={{$credentials.apiKey}}"
        },
        {
          "name": "anthropic-version",
          "value": "2023-06-01"
        },
        {
          "name": "content-type",
          "value": "application/json"
        }
      ]
    }
  }
}

 

Step 3: Structure Your Prompt Effectively

 

The key to making Claude follow instructions is to structure your prompts properly:

  • Use direct, clear language
  • Put critical instructions at the beginning and end of your prompt
  • Break complex instructions into numbered steps
  • Use specific examples of desired output formats

// Example properly structured JSON body
{
  "model": "claude-3-opus-20240229",
  "max\_tokens": 4000,
  "temperature": 0.2,
  "messages": [
    {
      "role": "user",
      "content": "I need you to follow these instructions EXACTLY:\n\n1. Summarize the following text in exactly 3 bullet points\n2. Each bullet point must be less than 15 words\n3. Format the output with HTML bullet points\n\nText to summarize: [your text here]\n\nRemember to follow ALL formatting instructions precisely."
    }
  ]
}

 

Step 4: Use System Messages Appropriately (When Available)

 

For Claude API versions that support system messages, use them to provide clear guardrails:


// Example with system message
{
  "model": "claude-3-opus-20240229",
  "max\_tokens": 4000,
  "temperature": 0.2,
  "messages": [
    {
      "role": "system",
      "content": "You must always follow these rules:\n- Format all responses in HTML\n- Never use markdown\n- Always provide exactly 3 examples\n- Keep explanations under 100 words"
    },
    {
      "role": "user",
      "content": "Explain how photosynthesis works."
    }
  ]
}

 

Step 5: Control Temperature Parameter

 

One key parameter that affects Claude's adherence to instructions is the temperature setting:

  • Lower temperature (0.1-0.3) makes Claude more deterministic and likely to follow structured instructions
  • Higher temperature (0.7-1.0) increases creativity but may reduce instruction adherence

For workflows where strict instruction following is critical, use a low temperature:


// Example with low temperature setting
{
  "model": "claude-3-opus-20240229",
  "max\_tokens": 4000,
  "temperature": 0.1,  // Low temperature for strict instruction following
  "messages": [
    {
      "role": "user",
      "content": "Generate a product description following these rules: exactly 50 words, include 3 benefits, mention the brand name 'TechPro' twice."
    }
  ]
}

 

Step 6: Enable JSON Mode When Appropriate

 

If you need Claude to return structured data, use the JSON mode parameter:


// Example with JSON mode enabled
{
  "model": "claude-3-opus-20240229",
  "max\_tokens": 4000,
  "temperature": 0.2,
  "system": "You are a helpful assistant that always responds in valid JSON format.",
  "messages": [
    {
      "role": "user",
      "content": "Provide information about 3 planets in our solar system. Return as a JSON array with name, diameter, and one interesting fact for each planet."
    }
  ]
}

 

Step 7: Use Explicit Response Templates

 

Providing explicit templates for how you want Claude to respond can significantly improve instruction adherence:


// Example with response template
{
  "model": "claude-3-opus-20240229",
  "max\_tokens": 4000,
  "temperature": 0.2,
  "messages": [
    {
      "role": "user",
      "content": "Analyze this customer review and extract key information.\n\nReview: 'I purchased the XL5000 camera last month. While the image quality is outstanding and battery life is impressive, I found the menu system confusing and the price too high.'\n\nRespond using EXACTLY this format:\n\n\n- [point 1]\n- [point 2]\n\n\n- [point 1]\n- [point 2]\n\npositive/negative/neutral\n"
    }
  ]
}

 

Step 8: Implement Validation and Error Handling

 

Add validation steps in your n8n workflow to check if Claude's response matches expected formats:

  • Use a Function node after the HTTP Request to validate responses
  • Implement retry logic if instructions weren't followed
  • Set up error handling for cases where Claude consistently ignores instructions

// Example Function node for validation
function validateClaudeResponse(items) {
  const response = items[0].json.content[0].text;
  
  // Check if response contains required elements
  const hasRequiredFormat = response.includes('') && 
                          response.includes('') &&
                          response.includes('');
  
  if (!hasRequiredFormat) {
    // If validation fails, set flag to retry
    items[0].needsRetry = true;
    items[0].retryCount = (items[0].retryCount || 0) + 1;
    
    // Limit retries
    if (items[0].retryCount > 3) {
      throw new Error('Claude failed to follow instructions after multiple attempts');
    }
  }
  
  return items;
}

 

Step 9: Use Conditional Routing in n8n

 

Set up conditional paths in your workflow to handle different Claude response scenarios:


// Pseudocode for n8n conditional routing
if (hasRequiredFormat) {
  // Continue with normal processing
  return [0]; // Success path
} else if (needsRetry && retryCount <= 3) {
  // Retry path with modified prompt
  return [1]; // Retry path
} else {
  // Fallback path for persistent failures
  return [2]; // Error handling path
}

 

Step 10: Implement Progressive Prompting Technique

 

For complex instructions, break them down and use multiple API calls in sequence:

  • First call: Get initial content
  • Second call: Format or refine that content
  • Third call: Final validation and adjustment

This approach can be implemented using multiple HTTP Request nodes connected in sequence:


// Example of progressive prompting
// First HTTP Request (Get content)
{
  "messages": [
    {
      "role": "user",
      "content": "Extract the main points from this article: [article text]"
    }
  ]
}

// Second HTTP Request (Format content)
{
  "messages": [
    {
      "role": "user",
      "content": "Format the following points into HTML with proper headings and bullet points:\n\n{{$node['First Request'].json.content[0].text}}"
    }
  ]
}

// Third HTTP Request (Final validation)
{
  "messages": [
    {
      "role": "user",
      "content": "Check if this content follows proper HTML formatting and fix any issues:\n\n{{$node['Second Request'].json.content[0].text}}"
    }
  ]
}

 

Step 11: Test and Refine Your Prompts

 

Develop a testing process to ensure Claude follows instructions consistently:

  • Create test cases with different instruction types
  • Log success/failure rates for each instruction pattern
  • Refine prompts based on test results

// Example test tracking function
function trackInstructionAdherence(items) {
  const testCases = [
    { name: "HTML formatting", success: items[0].json.content[0].text.includes("
    ") }, { name: "Exact word count", success: countWords(items[0].json.content[0].text) === 100 }, { name: "Example count", success: countExamples(items[0].json.content[0].text) === 3 } ]; // Log results items[0].testResults = testCases; items[0].overallSuccess = testCases.every(test => test.success); return items; }

 

Step 12: Use Claude-Specific Optimization Techniques

 

Each Claude model has specific characteristics. Tailor your approach to the model you're using:

  • Claude 3 Opus: Most capable of following complex instructions, use detailed formatting
  • Claude 3 Sonnet: Good balance, but be explicit with formatting requirements
  • Claude 3 Haiku: Keep instructions simpler and more direct

// Example model-specific settings
// For Claude 3 Opus
{
  "model": "claude-3-opus-20240229",
  "temperature": 0.2,
  "max\_tokens": 4000,
  // Complex instructions work well here
}

// For Claude 3 Haiku
{
  "model": "claude-3-haiku-20240307",
  "temperature": 0.1, // Lower temperature for more reliability
  "max\_tokens": 2000,
  // Simpler, more direct instructions
}

 

Step 13: Implement Automatic Instruction Reinforcement

 

Create a function node that automatically enhances your prompts with instruction reinforcement:


// Function to reinforce instructions
function reinforceInstructions(items) {
  let originalPrompt = items[0].json.prompt;
  
  // Add reinforcement wrapper
  items[0].json.prompt = `I need you to follow these instructions EXACTLY. It's critical that you adhere to ALL formatting requirements:\n\n${originalPrompt}\n\nBefore submitting your response, verify that you've followed ALL instructions correctly.`;
  
  return items;
}

 

Step 14: Use Contextual Examples

 

Include examples of correctly formatted responses directly in your prompts:


// Example with contextual examples
{
  "model": "claude-3-opus-20240229",
  "max\_tokens": 4000,
  "temperature": 0.2,
  "messages": [
    {
      "role": "user",
      "content": "Create a product feature comparison table. Format it in HTML.\n\nHere's an example of the format I need:\n\n  \n    \n    \n    \n  \n  \n    \n    \n    \n  \n
FeatureProduct AProduct B
Price$199$249
\n\nCompare smartphones: iPhone 13 and Samsung Galaxy S21." } ] }

 

Step 15: Monitor and Adapt

 

Finally, set up ongoing monitoring of your Claude interactions to identify patterns of instruction non-adherence:

  • Log all prompts and responses
  • Track which instruction types cause issues most frequently
  • Regularly update your prompt templates based on performance data

// Example logging function
function logClaudeInteraction(items) {
  // Get current timestamp
  const timestamp = new Date().toISOString();
  
  // Create log entry
  const logEntry = {
    timestamp: timestamp,
    prompt: items[0].json.messages[0].content,
    response: items[0].json.content[0].text,
    instructionsFollowed: detectInstructionAdherence(items[0].json.messages[0].content, items[0].json.content[0].text),
    model: items[0].json.model
  };
  
  // Store log entry (could write to file, database, or other storage)
  // This example adds to an array in the workflow data
  if (!items[0].logs) items[0].logs = [];
  items[0].logs.push(logEntry);
  
  return items;
}

By implementing these steps, you'll significantly improve Claude's adherence to system instructions in your n8n workflows. Remember that this is an iterative process - continue refining your approach based on the results you observe.

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