Learn how to make Claude follow system instructions in n8n workflows by structuring prompts, setting temperature, using JSON mode, and validating responses effectively.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
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:
Step 2: Setting Up Your n8n Workflow Correctly
First, ensure your n8n workflow is set up correctly to communicate with Claude:
// 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:
// 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:
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:
// 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:
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:
// 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:
// 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 Feature \n Product A \n Product B \n \n \n Price \n $199 \n $249 \n \n
\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:
// 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.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.