> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentflow.live/llms.txt
> Use this file to discover all available pages before exploring further.

# n8n Workflow Integration

> Execute n8n workflows via webhook triggers for automated task processing

## Overview

Connect your n8n workflows to AgentFlow to automate complex business processes. Trigger workflows from chat conversations, process data automatically, and receive structured responses.

***

## Prerequisites

<CardGroup cols={2}>
  <Card title="n8n Account" icon="cloud">
    Self-hosted or n8n Cloud account
  </Card>

  <Card title="Webhook Access" icon="link">
    Ability to create webhook nodes
  </Card>

  <Card title="API Key" icon="key">
    n8n API key (optional, for authentication)
  </Card>

  <Card title="AgentFlow Admin" icon="user-shield">
    Admin access to AgentFlow
  </Card>
</CardGroup>

***

## Step 1: Setup n8n Workflow

### Create a New Workflow

1. Log in to your n8n instance
2. Click **New Workflow**
3. Name it: `AgentFlow Chat Automation`

### Add Webhook Trigger

1. Click **+** to add a node

2. Search for **Webhook**

3. Configure the webhook:
   * **Method**: POST
   * **Path**: `/agentflow-trigger`
   * **Authentication**: None (or API Key)
   * **Response Mode**: Wait for Response

4. Copy the webhook URL (e.g., `https://your-n8n-instance.com/webhook/abc123`)

<Info>
  The webhook URL is your endpoint for AgentFlow integration.
</Info>

### Build Your Automation

Add nodes to process the incoming message:

<Steps>
  <Step title="Parse Input">
    Add a **Set** node to extract message data:

    ```json theme={null}
    {
      "user_message": "{{ $json.trigger_data.message_content }}",
      "user_id": "{{ $json.trigger_data.user_id }}",
      "timestamp": "{{ $json.trigger_data.timestamp }}"
    }
    ```
  </Step>

  <Step title="Process Data">
    Add business logic nodes:

    * **HTTP Request** - Call external APIs
    * **Code** - Custom JavaScript/Python
    * **Database** - Query/update data
    * **AI** - OpenAI, Anthropic nodes
  </Step>

  <Step title="Format Response">
    Add a **Set** node for the response:

    ```json theme={null}
    {
      "data": {
        "execution_result": "{{ $json.processedData }}",
        "status": "success",
        "metadata": {
          "workflow_id": "{{ $workflow.id }}",
          "execution_id": "{{ $execution.id }}"
        }
      }
    }
    ```
  </Step>

  <Step title="Return Response">
    Connect to **Respond to Webhook** node

    * Set response body to your formatted data
    * HTTP Status: 200
  </Step>
</Steps>

### Example Workflow: Customer Support

```mermaid theme={null}
graph LR
    A[Webhook Trigger] --> B[Parse Message]
    B --> C[Check Database]
    C --> D{Issue Type?}
    D -->|Technical| E[OpenAI Analysis]
    D -->|Billing| F[Stripe Lookup]
    E --> G[Format Response]
    F --> G
    G --> H[Respond to Webhook]
```

### Save and Activate

1. Click **Save** (Ctrl+S)
2. Toggle **Active** to enable the workflow
3. Note your webhook URL

***

## Step 2: Create AI Connection in AgentFlow

### Manual Setup

1. Go to **Admin Dashboard** → **AI Models**

2. Click **Add Model**

3. Fill in details:
   * **Name**: `n8n Customer Support Workflow`
   * **Model ID**: `n8n-workflow-executor`
   * **Description**: `Automated customer support via n8n`

4. Configure API:
   * **Endpoint**: `https://your-n8n-instance.com/webhook/abc123`
   * **Method**: POST

5. Add headers (if using authentication):
   ```json theme={null}
   {
     "n8n-api-key": "{{n8n_api_key}}",
     "Content-Type": "application/json",
     "User-Agent": "ChatPlatform/1.0"
   }
   ```

6. Request schema:
   ```json theme={null}
   {
     "workflow_id": "{{workflow_id}}",
     "trigger_data": {
       "message": "{{message}}",
       "user_id": "{{user_id}}",
       "timestamp": "{{timestamp}}"
     },
     "execution_mode": "trigger",
     "wait_for_completion": true,
     "timeout": 300
   }
   ```

7. Response path: `data.execution_result`

8. Click **Save**

***

## Step 3: Import via YAML Configuration

### YAML Template

Create `n8n-workflow-config.yaml`:

```yaml theme={null}
name: "n8n Workflow Automation"
model_id: "n8n-workflow-executor"
description: "Execute n8n workflows via webhook triggers for automated task processing"
endpoint: "https://your-n8n-instance.com/webhook/{{workflow_id}}"
method: "POST"

headers:
  n8n-api-key: "{{n8n_api_key}}"
  Content-Type: "application/json"
  User-Agent: "ChatPlatform/1.0"

request_schema:
  workflow_id: "{{workflow_id}}"
  trigger_data:
    message: "{{message}}"
    user_id: "{{user_id}}"
    timestamp: "{{timestamp}}"
  execution_mode: "trigger"
  wait_for_completion: true
  timeout: 300

response_path: "data.execution_result"

message_format:
  preset: "custom"
  mapping:
    role:
      source: "role"
      target: "trigger_data.user_role"
      transform: "lowercase"
    content:
      source: "content"
      target: "trigger_data.message_content"
      transform: "none"
    timestamp:
      source: "timestamp"
      target: "trigger_data.timestamp"
      transform: "iso8601"
  customFields:
    - name: "workflow_metadata"
      value:
        platform: "n8n"
        version: "1.0"
        execution_type: "webhook"
      type: "object"
    - name: "retry_config"
      value:
        max_retries: 3
        retry_delay: 1000
        exponential_backoff: true
      type: "object"

suggestion_prompts:
  - "Create a workflow to process customer support tickets"
  - "Set up automated data synchronization between systems"
  - "Build a workflow for invoice processing and approval"
  - "Create an automated lead scoring workflow"
  - "Set up a workflow for social media content scheduling"
```

### Import Process

1. Replace `{{workflow_id}}` with your actual webhook path
2. Go to **Admin Dashboard** → **AI Models**
3. Click **Import Model**
4. Upload `n8n-workflow-config.yaml`
5. Enter your n8n credentials
6. Click **Import**

***

## Step 4: Assign to Group

1. Navigate to **Admin Dashboard** → **Groups**
2. Select target group (e.g., "Support Team")
3. Click **Manage Models**
4. Enable **n8n Workflow Automation**
5. Set usage permissions:
   * **Can Execute**: Yes
   * **Can View Logs**: Yes
   * **Rate Limit**: 100 requests/hour
6. Click **Save**

***

## Step 5: Use in Chat

### Trigger Workflow from Chat

1. Open **Chat Interface**
2. Start a **New Conversation**
3. Select **n8n Workflow** model
4. Send a message to trigger the workflow

### Example Interactions

<CodeGroup>
  ```text Support Ticket theme={null}
  I need help with my billing issue. My last invoice shows duplicate charges for the Pro plan.
  ```

  ```text Data Processing theme={null}
  Process the customer data from yesterday's signups and add them to the CRM with 'trial' status.
  ```

  ```text Lead Scoring theme={null}
  Analyze this lead: Company size 500+, Industry: SaaS, Location: USA, Budget: $50k/year
  ```
</CodeGroup>

### Response Handling

The workflow response appears as a chat message:

```json theme={null}
{
  "status": "success",
  "result": {
    "ticket_id": "SUP-12345",
    "assigned_to": "billing_team",
    "priority": "high",
    "eta": "2 hours"
  }
}
```

***

## Advanced Workflows

### Multi-Step Processing

<Steps>
  <Step title="Data Validation">
    ```javascript theme={null}
    // n8n Code node
    const input = $input.item.json;

    if (!input.message || !input.user_id) {
      throw new Error('Missing required fields');
    }

    return {
      validated: true,
      data: input
    };
    ```
  </Step>

  <Step title="AI Analysis">
    Add OpenAI node:

    * Model: GPT-4
    * Prompt: `Analyze: {{ $json.message }}`
    * Extract: insights, sentiment, intent
  </Step>

  <Step title="Database Operations">
    ```sql theme={null}
    INSERT INTO support_tickets (user_id, message, analysis, created_at)
    VALUES (
      '{{ $json.user_id }}',
      '{{ $json.message }}',
      '{{ $json.ai_analysis }}',
      NOW()
    )
    RETURNING id;
    ```
  </Step>

  <Step title="External Integration">
    Call Slack, email, or other services with results
  </Step>
</Steps>

### Conditional Logic

```javascript theme={null}
// Switch node condition
const sentiment = $json.sentiment;

if (sentiment === 'negative') {
  return [{ json: { route: 'urgent' } }];
} else if (sentiment === 'neutral') {
  return [{ json: { route: 'standard' } }];
} else {
  return [{ json: { route: 'low_priority' } }];
}
```

### Error Handling

```javascript theme={null}
// Error trigger node
if ($json.error) {
  return {
    status: 'error',
    message: $json.error.message,
    retry_available: true
  };
}
```

***

## Workflow Templates

### 1. Customer Support Automation

```yaml theme={null}
Nodes:
  1. Webhook Trigger
  2. Extract Message Data
  3. Sentiment Analysis (OpenAI)
  4. Check Knowledge Base (Database)
  5. If No Match → Escalate to Human
  6. If Match → Send Auto-Response
  7. Create Ticket (if needed)
  8. Respond to Webhook
```

### 2. Lead Qualification

```yaml theme={null}
Nodes:
  1. Webhook Trigger
  2. Parse Lead Data
  3. Enrich with Clearbit
  4. Score Lead (Custom Logic)
  5. Update CRM (Salesforce)
  6. If Score > 80 → Alert Sales
  7. Respond with Score
```

### 3. Invoice Processing

```yaml theme={null}
Nodes:
  1. Webhook Trigger
  2. Extract Invoice Details
  3. Validate Against Orders (Database)
  4. Calculate Amounts
  5. Generate PDF (n8n)
  6. Send Email (SendGrid)
  7. Update Billing System
  8. Respond with Status
```

***

## n8n Cloud vs Self-Hosted

### n8n Cloud Setup

1. Sign up at [n8n.cloud](https://n8n.cloud)
2. Create workflow
3. Webhook URL: `https://yourname.app.n8n.cloud/webhook/...`
4. Built-in authentication
5. Automatic scaling

### Self-Hosted Setup

<Steps>
  <Step title="Deploy n8n">
    ```bash theme={null}
    # Docker
    docker run -it --rm \
      --name n8n \
      -p 5678:5678 \
      -v ~/.n8n:/home/node/.n8n \
      n8nio/n8n
    ```
  </Step>

  <Step title="Configure Reverse Proxy">
    ```nginx theme={null}
    server {
      listen 443 ssl;
      server_name n8n.yourdomain.com;

      location / {
        proxy_pass http://localhost:5678;
        proxy_set_header Host $host;
      }
    }
    ```
  </Step>

  <Step title="Setup Authentication">
    Environment variables:

    ```bash theme={null}
    N8N_BASIC_AUTH_ACTIVE=true
    N8N_BASIC_AUTH_USER=admin
    N8N_BASIC_AUTH_PASSWORD=secure_password
    ```
  </Step>

  <Step title="Get Webhook URL">
    Use: `https://n8n.yourdomain.com/webhook/...`
  </Step>
</Steps>

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="Webhook Timeout">
    **Symptoms**: Requests timeout after 30 seconds

    **Solutions**:

    * Increase timeout in AgentFlow config: `timeout: 300`
    * Use async execution in n8n
    * Optimize workflow performance
  </Accordion>

  <Accordion title="Authentication Errors">
    **Symptoms**: 401 Unauthorized responses

    **Solutions**:

    * Verify API key is correct
    * Check header format: `n8n-api-key`
    * Ensure webhook authentication matches
  </Accordion>

  <Accordion title="Response Not Received">
    **Symptoms**: Empty or malformed responses

    **Solutions**:

    * Check response path: `data.execution_result`
    * Verify "Respond to Webhook" node
    * Test workflow manually in n8n
  </Accordion>

  <Accordion title="Workflow Not Triggering">
    **Symptoms**: Webhook receives request but workflow doesn't execute

    **Solutions**:

    * Ensure workflow is **Active**
    * Check webhook node configuration
    * Review n8n execution logs
  </Accordion>
</AccordionGroup>

***

## Monitoring & Debugging

### n8n Execution Logs

1. Go to **Executions** in n8n
2. Filter by workflow
3. View detailed execution data
4. Check error messages

### AgentFlow Analytics

1. Navigate to **Analytics Dashboard**
2. Select **n8n Workflow** model
3. Monitor:
   * Success rate
   * Response times
   * Error patterns

### Webhook Testing

```bash theme={null}
# Test webhook directly
curl -X POST https://your-n8n-instance.com/webhook/abc123 \
  -H "Content-Type: application/json" \
  -d '{
    "trigger_data": {
      "message": "test message",
      "user_id": "test-user",
      "timestamp": "2024-01-15T10:30:00Z"
    }
  }'
```

***

## Best Practices

<CardGroup cols={2}>
  <Card title="Error Handling" icon="shield-check">
    Always include error handling nodes and fallback responses
  </Card>

  <Card title="Timeout Management" icon="clock">
    Set appropriate timeouts for long-running processes
  </Card>

  <Card title="Data Validation" icon="check-circle">
    Validate all incoming data before processing
  </Card>

  <Card title="Security" icon="lock">
    Use API keys and HTTPS for all webhooks
  </Card>

  <Card title="Logging" icon="file-text">
    Log executions for debugging and compliance
  </Card>

  <Card title="Testing" icon="vial">
    Test workflows thoroughly before production
  </Card>
</CardGroup>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Make.com Integration" icon="puzzle-piece" href="/examples/make-workflow">
    Alternative automation platform
  </Card>

  <Card title="Cloud Functions" icon="cloud" href="/examples/cloud-run-function">
    Serverless processing
  </Card>

  <Card title="Relay Workflows" icon="rotate" href="/examples/relay-workflow">
    Business process automation
  </Card>

  <Card title="Analytics" icon="chart-line" href="/analytics/usage-metrics">
    Monitor workflow performance
  </Card>
</CardGroup>
