n8n Anthropic Claude API: Integration Prompt Chain Workflow

I integrate Anthropic’s Claude API with n8n because building reliable AI-powered workflows requires more than a single API call. Claude’s long context window, structured output, and reasoning capabilities make it ideal for complex automation. n8n orchestrates the prompts, chains the responses, and handles the data flow between API calls.

Claude 3.5 Sonnet and Claude 3 Opus offer different tradeoffs between speed and intelligence. I use Sonnet for high-volume tasks like content summarization and Opus for complex reasoning like code generation and data analysis. n8n routes requests to the right model based on task complexity.

Basic Claude API Integration

The Anthropic API accepts messages through a simple JSON structure. I use n8n’s HTTP Request node for maximum flexibility, though the dedicated Anthropic node works for standard use cases:

`javascript
// HTTP Request node: call Claude API
Method: POST
URL: https://api.anthropic.com/v1/messages
Headers: {
x-api-key: {{anthropic_api_key}},
anthropic-version: 2023-06-01,
content-type: application/json
}
Body: {
“model”: “claude-sonnet-4-20250514”,
“max_tokens”: 1024,
“messages”: [
{
“role”: “user”,
“content”: “{{user_prompt}}”
}
]
}
`

The response contains Claude’s reply in content[0].text. I extract it and pass it to downstream nodes for further processing:

`javascript
// Code node: extract Claude response
const response = item.json.content || [];
const text = response.find(c => c.type === ‘text’)?.text || ‘No response’;
return [{ json: { claude_response: text, full_response: item.json } }];
`

System prompts define Claude’s behavior. I store them in n8n’s parameter mapping or as workflow constants:

`javascript
Body: {
“model”: “claude-sonnet-4-20250514”,
“max_tokens”: 1024,
“system”: “You are a technical writer specializing in automation documentation. Write clear, concise explanations with code examples.”,
“messages”: [
{ “role”: “user”, “content”: “{{topic_description}}” }
]
}
`

Prompt Chaining for Complex Tasks

Single API calls work for simple questions. But complex tasks — like generating a full report from raw data — benefit from prompt chaining. I break the task into stages, passing each Claude response as input to the next:

`javascript
// Stage 1: Extract key points from source text
// Claude receives: raw_document_text
// Claude outputs: bullet_point_summary

// Stage 2: Generate structured report from summary
// Claude receives: bullet_point_summary + report_template
// Claude outputs: markdown_report

// Stage 3: Review and refine the report
// Claude receives: markdown_report + style_guidelines
// Claude outputs: final_report
`

Each stage runs as a separate HTTP Request node in the workflow. The Output of one node feeds the Input of the next through n8n’s item linking:

`javascript
// Code node: build chained prompt
const stage1Output = item.json.stage1_result;
const template = item.json.report_template;

const prompt = `Based on the following extracted points, write a structured report:

SUMMARY:
${stage1Output}

TEMPLATE:
${template}

Write the report in markdown format. Include an executive summary, detailed findings, and recommendations.`;

return [{ json: { chained_prompt: prompt } }];
`

Prompt chaining with Claude works best when each stage has a clear responsibility. Stage 1 extracts and summarizes. Stage 2 structures and formats. Stage 3 reviews and refines. This modular approach produces higher quality output than a single monolithic prompt.

Structured Outputs and JSON Mode

Claude supports structured output through the response_format parameter. I use this when I need machine-readable results for downstream processing:

`javascript
// HTTP Request node: Claude with structured output
Method: POST
URL: https://api.anthropic.com/v1/messages
Body: {
“model”: “claude-sonnet-4-20250514”,
“max_tokens”: 1024,
“response_format”: { “type”: “json_object” },
“messages”: [
{
“role”: “user”,
“content”: “Analyze this customer feedback and return JSON with sentiment, topics, and urgency scores.”
}
]
}
`

The response contains valid JSON that I parse and route through n8n’s If node:

`javascript
// Code node: parse and validate Claude JSON
try {
const parsed = JSON.parse(item.json.content[0].text);
if (!parsed.sentiment || !parsed.topics) {
throw new Error(‘Missing required fields’);
}
return [{ json: { …parsed, validated: true } }];
} catch (e) {
return [{
json: { error: e.message, raw_response: item.json.content[0].text },
pairedItem: { item: 0 }
}];
}
`

Structured outputs eliminate regex parsing and make the data immediately usable in spreadsheets, databases, or API calls.

Multi-Turn Conversations and Context Management

Claude supports conversation threads through message history. I maintain context across multiple exchanges by passing the full conversation:

`javascript
// HTTP Request node: continue conversation
Method: POST
URL: https://api.anthropic.com/v1/messages
Body: {
“model”: “claude-sonnet-4-20250514”,
“max_tokens”: 1024,
“messages”: [
{ “role”: “user”, “content”: “What are the main themes?” },
{ “role”: “assistant”, “content”: “The main themes are cost reduction, automation opportunities, and customer satisfaction improvements.” },
{ “role”: “user”, “content”: “For each theme, list 3 specific actions.” }
]
}
`

For long conversations, I use a sliding window approach. The Code node keeps only the most recent exchanges and a summary of earlier context:

`javascript
// Code node: manage conversation context window
const maxMessages = 10;
const allMessages = item.json.conversation_history || [];

if (allMessages.length > maxMessages) {
const recent = allMessages.slice(-maxMessages);
const summary = allMessages[0].summary || ‘Conversation summarized’;
recent.unshift({ role: ‘system’, content: Earlier conversation summary: ${summary} });
return [{ json: { messages: recent } }];
}

return [{ json: { messages: allMessages } }];
`

Context management prevents token overflow while preserving conversation coherence. Claude’s 200K token context window makes this less critical than with smaller models, but it still matters for cost optimization.

Connecting to Your Existing Setup

The n8n Docker Deployment guide covers hosting n8n with API key management. Store your Anthropic API key in n8n’s credential store — never expose it in workflow definitions.

For rate limiting and retry logic, the n8n Docker Environment Variables reference explains timeout and concurrency settings that prevent API quota exhaustion.

The n8n AI Agents guide extends Claude integration into autonomous agent workflows where Claude makes decisions and triggers actions.

Action Card: Basic Claude Integration

Test your Anthropic API connection:

`javascript
// 1. HTTP Request node:
// Method: POST
// URL: https://api.anthropic.com/v1/messages
// Headers: x-api-key={{anthropic_key}}, anthropic-version=2023-06-01
// Body: {“model”:”claude-sonnet-4-20250514″,”max_tokens”:512,”messages”:[{“role”:”user”,”content”:”Explain n8n in one sentence.”}]}

// 2. Response node: check claude_response field

// 3. If node: if response contains “workflow”, route to success branch
`

Replace {{anthropic_key}} with your actual API key. Claude should respond with a concise explanation of n8n.

References

  • Anthropic Claude API Documentation
  • Claude API Messages Endpoint
  • Claude Structured Outputs
  • n8n HTTP Request Node
  • Anthropic API Pricing
  • Leave a Reply

    Your email address will not be published. Required fields are marked *