How to Build an AI-Powered Lead Qualification Agent with n8n (Free Template)

How to Build an AI-Powered Lead Qualification Agent with n8n (Free Template)

Sales teams waste hours manually qualifying leads that will never convert. Every form submission, demo request, or contact inquiry requires someone to research the company, assess fit, and decide next steps. By the time your team reaches out, competitors have already engaged. This n8n workflow uses AI to instantly score, qualify, and route leads based on company data, eliminating manual research and ensuring your best prospects get immediate attention. You'll learn how to build a complete lead qualification system that runs 24/7, complete with a ready-to-use JSON template.

The Problem: Manual Lead Qualification Kills Response Time

Current challenges:

  • Sales reps spend 2-3 hours daily researching incoming leads
  • High-value prospects wait 24-48 hours for initial contact
  • Inconsistent qualification criteria across team members
  • No systematic way to prioritize leads by revenue potential
  • Marketing qualified leads (MQLs) sit in queues while reps chase cold prospects

Business impact:

  • Time spent: 15-20 hours per week per sales rep on manual research
  • Response delay: Average 36-hour lag between lead capture and first contact
  • Conversion loss: 50% of leads go to competitors who respond within 5 minutes
  • Inconsistent scoring: Lead quality assessments vary by 40% between reps

Manual qualification doesn't scale. When a demo request comes in at 11 PM, it sits until morning. When five leads arrive simultaneously, reps pick randomly instead of strategically. This workflow solves that.

The Solution Overview

This n8n agent automatically qualifies every incoming lead within seconds using AI-powered analysis. When a lead enters your system, the workflow enriches company data, scores the prospect against your ideal customer profile, generates a qualification summary, and routes high-priority leads directly to sales. The system uses OpenAI's GPT-4 for intelligent analysis, integrates with your CRM for seamless data flow, and provides instant Slack notifications for hot leads. It runs continuously without human intervention, ensuring every prospect receives consistent evaluation based on your exact qualification criteria.

What You'll Build

This workflow delivers a complete lead qualification system with these capabilities:

Component Technology Purpose
Lead Capture Webhook Trigger Receives leads from forms, landing pages, or CRM
Data Enrichment HTTP Request + Clearbit/Hunter API Pulls company size, industry, revenue, tech stack
AI Qualification OpenAI GPT-4 Analyzes fit against ICP, generates scoring rationale
Lead Scoring Function Node Calculates numerical score (0-100) based on criteria
CRM Update HubSpot/Salesforce Node Writes score, status, and notes back to contact record
Smart Routing Switch Node Directs hot/warm/cold leads to appropriate workflows
Instant Alerts Slack Node Notifies sales team of high-priority leads in real-time
Follow-up Scheduling Calendar/Task Integration Creates tasks for warm leads, schedules nurture for cold

Key features:

  • Processes leads in under 10 seconds from submission to CRM update
  • Customizable scoring model based on company size, industry, budget signals
  • AI-generated qualification summaries explaining why each lead scored as it did
  • Automatic lead distribution to appropriate sales rep based on territory/specialty
  • Built-in error handling and retry logic for API failures
  • Complete audit trail of all qualification decisions

Prerequisites

Before starting, ensure you have:

  • n8n instance (cloud or self-hosted version 1.0+)
  • OpenAI API account with GPT-4 access
  • CRM platform (HubSpot, Salesforce, or Pipedrive) with API credentials
  • Slack workspace with incoming webhook configured
  • Data enrichment service (Clearbit, Hunter.io, or Apollo.io) API key
  • Basic JavaScript knowledge for customizing scoring logic
  • Your ideal customer profile (ICP) criteria documented

Step 1: Set Up Lead Capture Webhook

This workflow begins when a lead enters your system. The webhook node acts as the entry point, receiving lead data from any source.

Configure the Webhook Node:

  1. Add a Webhook node as your workflow trigger
  2. Set HTTP Method to POST
  3. Set Path to /qualify-lead (or your preferred endpoint)
  4. Authentication: Use Header Auth with a secret token
  5. Response Mode: "Using 'Respond to Webhook' Node" for immediate confirmation

Node configuration:

{
  "httpMethod": "POST",
  "path": "qualify-lead",
  "authentication": "headerAuth",
  "responseMode": "responseNode",
  "options": {
    "rawBody": false
  }
}

Expected payload structure:

{
  "email": "contact@company.com",
  "firstName": "Jane",
  "lastName": "Smith",
  "company": "Acme Corp",
  "phone": "+1-555-0123",
  "website": "acme.com",
  "jobTitle": "VP of Sales",
  "leadSource": "website_demo_request"
}

Why this works:
The webhook provides a universal endpoint that any system can POST to. Using header authentication prevents spam submissions while remaining simple to integrate. The responseNode mode ensures the submitting system receives immediate confirmation while your workflow continues processing asynchronously.

Connect your lead sources:

  • Website forms: Add webhook URL to form submission handler
  • Landing page tools: Configure Unbounce/Instapage webhook integration
  • CRM: Set up workflow automation to POST new contacts to webhook
  • Zapier/Make: Use as intermediary if direct integration isn't available

Step 2: Enrich Company Data

Raw form data lacks the context needed for intelligent qualification. This phase pulls comprehensive company information.

Configure HTTP Request Node for Clearbit:

  1. Add HTTP Request node after webhook
  2. Method: GET
  3. URL: https://company.clearbit.com/v2/companies/find?domain={{$json.website}}
  4. Authentication: Bearer Token with your Clearbit API key
  5. Add header: Accept: application/json

Node configuration:

{
  "method": "GET",
  "url": "=https://company.clearbit.com/v2/companies/find?domain={{$json.website}}",
  "authentication": "predefinedCredentialType",
  "nodeCredentialType": "clearbitApi",
  "options": {
    "timeout": 10000,
    "retry": {
      "maxRetries": 3,
      "retryInterval": 2000
    }
  }
}

Data extracted:

  • Company size (employee count)
  • Annual revenue estimate
  • Industry and sub-industry
  • Technology stack
  • Funding stage and total raised
  • Company age and growth indicators
  • Social media presence

Add Function Node to normalize data:

// Handle missing or incomplete enrichment data
const enriched = $input.first().json;
const original = $('Webhook').first().json;

return {
  json: {
    // Original lead data
    email: original.email,
    name: `${original.firstName} ${original.lastName}`,
    company: original.company,
    jobTitle: original.jobTitle,
    
    // Enriched company data with fallbacks
    employeeCount: enriched.metrics?.employees || 0,
    revenue: enriched.metrics?.estimatedAnnualRevenue || 'Unknown',
    industry: enriched.category?.industry || 'Unknown',
    techStack: enriched.tech || [],
    fundingStage: enriched.metrics?.raised || 'Unknown',
    companyAge: enriched.foundedYear ? new Date().getFullYear() - enriched.foundedYear : 0
  }
};

Why this approach:
Clearbit provides the most comprehensive B2B company data, but enrichment APIs can fail or return incomplete data. The Function node normalizes the response, providing default values for missing fields so downstream nodes never break. The retry logic handles temporary API failures without manual intervention.

Step 3: AI-Powered Qualification Analysis

Now the workflow uses GPT-4 to analyze the enriched lead against your ideal customer profile.

Configure OpenAI Node:

  1. Add OpenAI node (Chat Model)
  2. Model: gpt-4 (not gpt-3.5 - accuracy matters here)
  3. Temperature: 0.3 (lower = more consistent scoring)
  4. Max Tokens: 500

Prompt engineering for qualification:

// System prompt defines the AI's role and criteria
const systemPrompt = `You are a B2B lead qualification expert. Analyze leads against this ideal customer profile:

TARGET CRITERIA:
- Company size: 50-500 employees
- Industries: SaaS, Technology, Professional Services
- Revenue: $5M-$50M annually
- Tech stack: Uses Salesforce, HubSpot, or modern CRM
- Decision maker: VP level or above in Sales/Marketing/Operations

Evaluate each lead and provide:
1. Fit score (0-100)
2. Qualification tier (Hot/Warm/Cold)
3. Key buying signals identified
4. Potential objections or concerns
5. Recommended next action

Be specific and data-driven in your analysis.`;

// User prompt contains the actual lead data
const userPrompt = `Analyze this lead:

CONTACT INFO:
Name: {{$json.name}}
Title: {{$json.jobTitle}}
Company: {{$json.company}}

COMPANY DATA:
Employees: {{$json.employeeCount}}
Revenue: {{$json.revenue}}
Industry: {{$json.industry}}
Tech Stack: {{$json.techStack.join(', ')}}
Funding: {{$json.fundingStage}}
Company Age: {{$json.companyAge}} years

ENGAGEMENT:
Lead Source: {{$json.leadSource}}

Provide your qualification assessment.`;

Node configuration:

{
  "model": "gpt-4",
  "options": {
    "temperature": 0.3,
    "maxTokens": 500,
    "topP": 1,
    "frequencyPenalty": 0,
    "presencePenalty": 0
  },
  "messages": {
    "values": [
      {
        "role": "system",
        "content": "={{$node['Function'].json.systemPrompt}}"
      },
      {
        "role": "user", 
        "content": "={{$node['Function'].json.userPrompt}}"
      }
    ]
  }
}

Why GPT-4 over rules-based scoring:
Traditional lead scoring uses rigid point systems ("+10 for VP title, +5 for tech industry"). GPT-4 understands context and nuance. It recognizes that a "Marketing Coordinator" at a 10-person startup might be the actual decision maker, while a "VP" at a 10,000-person enterprise might have zero budget authority. The AI synthesizes multiple signals simultaneously, mimicking how your best sales reps intuitively qualify leads.

Parse AI response:

Add another Function node to extract structured data from GPT-4's response:

const aiResponse = $input.first().json.message.content;

// Extract score using regex
const scoreMatch = aiResponse.match(/(?:score|fit):\s*(\d+)/i);
const score = scoreMatch ? parseInt(scoreMatch[1]) : 50;

// Extract tier
const tierMatch = aiResponse.match(/tier:\s*(hot|warm|cold)/i);
const tier = tierMatch ? tierMatch[1].toLowerCase() : 'warm';

// Extract key sections
const buyingSignals = aiResponse.match(/buying signals?:(.*?)(?=

|
[A-Z]|$)/is)?.[1]?.trim() || '';
const concerns = aiResponse.match(/(?:objections?|concerns?):(.*?)(?=

|
[A-Z]|$)/is)?.[1]?.trim() || '';
const nextAction = aiResponse.match(/(?:recommended|next) action:(.*?)(?=

|$)/is)?.[1]?.trim() || '';

return {
  json: {
    score,
    tier,
    buyingSignals,
    concerns,
    nextAction,
    fullAnalysis: aiResponse
  }
};

Step 4: Calculate Final Lead Score

While AI provides qualitative analysis, you need a numerical score for routing and reporting.

Add Function Node for scoring logic:

// Combine AI score with rule-based adjustments
let finalScore = $json.score; // Start with AI's base score

// Company size multiplier
if ($json.employeeCount >= 50 && $json.employeeCount <= 500) {
  finalScore += 15; // Sweet spot
} else if ($json.employeeCount > 500) {
  finalScore += 5; // Enterprise - longer sales cycle
} else {
  finalScore -= 10; // Too small
}

// Revenue indicators
if ($json.revenue !== 'Unknown') {
  const revenueNum = parseInt($json.revenue.replace(/[^0-9]/g, ''));
  if (revenueNum >= 5000000 && revenueNum <= 50000000) {
    finalScore += 15;
  }
}

// Industry fit
const targetIndustries = ['SaaS', 'Technology', 'Software', 'Professional Services'];
if (targetIndustries.some(ind => $json.industry.includes(ind))) {
  finalScore += 10;
}

// Seniority bonus
const seniorTitles = ['VP', 'Director', 'Head of', 'Chief', 'C-level'];
if (seniorTitles.some(title => $json.jobTitle.includes(title))) {
  finalScore += 10;
}

// Tech stack alignment
const targetTech = ['salesforce', 'hubspot', 'pipedrive'];
const hasCRM = $json.techStack.some(tech => 
  targetTech.some(target => tech.toLowerCase().includes(target))
);
if (hasCRM) {
  finalScore += 10;
}

// Lead source quality
const highValueSources = ['demo_request', 'pricing_page', 'contact_sales'];
if (highValueSources.includes($json.leadSource)) {
  finalScore += 10;
}

// Cap score at 100
finalScore = Math.min(finalScore, 100);

// Determine final tier based on adjusted score
let finalTier;
if (finalScore >= 80) finalTier = 'hot';
else if (finalScore >= 60) finalTier = 'warm';
else finalTier = 'cold';

return {
  json: {
    finalScore,
    finalTier,
    scoreBreakdown: {
      aiBase: $json.score,
      companySizeAdj: 'calculated above',
      industryAdj: 'calculated above',
      seniorityAdj: 'calculated above',
      techStackAdj: 'calculated above',
      sourceAdj: 'calculated above'
    }
  }
};

Why hybrid scoring works:
AI excels at pattern recognition and context, but business rules ensure consistency. If your sales team knows they never close deals under $5M revenue, the rule-based adjustment enforces that regardless of AI enthusiasm. This hybrid approach combines machine intelligence with institutional knowledge.

Step 5: Update CRM with Qualification Data

The qualified lead data must flow back to your CRM for sales team access.

Configure HubSpot Node:

  1. Add HubSpot node
  2. Resource: Contact
  3. Operation: Update
  4. Contact ID: Use email as lookup field
  5. Map all qualification fields

Properties to update:

{
  "properties": {
    "lead_score": "={{$json.finalScore}}",
    "lead_tier": "={{$json.finalTier}}",
    "qualification_summary": "={{$json.fullAnalysis}}",
    "buying_signals": "={{$json.buyingSignals}}",
    "potential_concerns": "={{$json.concerns}}",
    "recommended_action": "={{$json.nextAction}}",
    "last_qualified_date": "={{new Date().toISOString()}}",
    "qualification_method": "AI-Automated"
  }
}

Add custom fields in HubSpot:
Before running this workflow, create these custom contact properties in your CRM:

  • lead_score (Number, 0-100)
  • lead_tier (Single-line text or Dropdown)
  • qualification_summary (Multi-line text)
  • buying_signals (Multi-line text)
  • potential_concerns (Multi-line text)
  • recommended_action (Multi-line text)
  • last_qualified_date (Date)

Error handling:

Add an IF node after HubSpot to catch update failures:

// Check if HubSpot update succeeded
if ($json.status === 'error') {
  return {
    json: {
      error: true,
      message: 'CRM update failed',
      leadEmail: $('Webhook').first().json.email,
      timestamp: new Date().toISOString()
    }
  };
}
return { json: { error: false } };

Step 6: Smart Lead Routing

Different lead tiers require different handling. Use a Switch node to route appropriately.

Configure Switch Node:

{
  "mode": "rules",
  "rules": [
    {
      "conditions": [
        {
          "leftValue": "={{$json.finalTier}}",
          "rightValue": "hot",
          "operator": "equal"
        }
      ],
      "output": 0
    },
    {
      "conditions": [
        {
          "leftValue": "={{$json.finalTier}}",
          "rightValue": "warm",
          "operator": "equal"
        }
      ],
      "output": 1
    }
  ],
  "fallbackOutput": 2
}

Output 0 - Hot Leads (Score 80+):

Connect to Slack node for immediate notification:

{
  "channel": "#sales-hot-leads",
  "text": "🔥 HOT LEAD ALERT",
  "attachments": [
    {
      "color": "#FF0000",
      "fields": [
        {
          "title": "Contact",
          "value": "={{$json.name}} ({{$json.jobTitle}})",
          "short": true
        },
        {
          "title": "Company",
          "value": "={{$json.company}} | {{$json.employeeCount}} employees",
          "short": true
        },
        {
          "title": "Score",
          "value": "={{$json.finalScore}}/100",
          "short": true
        },
        {
          "title": "Source",
          "value": "={{$json.leadSource}}",
          "short": true
        },
        {
          "title": "Why Hot",
          "value": "={{$json.buyingSignals}}",
          "short": false
        },
        {
          "title": "Next Action",
          "value": "={{$json.nextAction}}",
          "short": false
        }
      ],
      "actions": [
        {
          "type": "button",
          "text": "View in CRM",
          "url": "={{$json.crmUrl}}"
        }
      ]
    }
  ]
}

Output 1 - Warm Leads (Score 60-79):

Create a task in your CRM for follow-up within 24 hours:

// HubSpot Task Creation
{
  "resource": "task",
  "operation": "create",
  "properties": {
    "subject": "Follow up with warm lead: {{$json.company}}",
    "body": "{{$json.fullAnalysis}}

Recommended action: {{$json.nextAction}}",
    "status": "NOT_STARTED",
    "priority": "MEDIUM",
    "taskType": "CALL",
    "ownerId": "={{$json.assignedSalesRepId}}",
    "associations": {
      "contactIds": ["={{$json.contactId}}"]
    },
    "dueDate": "={{new Date(Date.now() + 86400000).toISOString()}}" // 24 hours
  }
}

Output 2 - Cold Leads (Score <60):

Add to nurture sequence instead of immediate sales contact:

// Add to email nurture campaign
{
  "resource": "contact",
  "operation": "update",
  "properties": {
    "lifecycle_stage": "lead",
    "lead_status": "nurture",
    "nurture_campaign": "cold_lead_education_series"
  }
}

Workflow Architecture Overview

This workflow consists of 12 nodes organized into 4 main sections:

  1. Data ingestion (Nodes 1-3): Webhook receives lead, validates payload, responds to sender
  2. Enrichment & analysis (Nodes 4-7): HTTP Request pulls company data, Function normalizes, OpenAI analyzes, Function calculates score
  3. CRM integration (Nodes 8-9): HubSpot update writes qualification data, IF node handles errors
  4. Smart routing (Nodes 10-12): Switch node directs to Slack (hot), Task creation (warm), or Nurture (cold)

Execution flow:

  • Trigger: Webhook POST from any lead source
  • Average run time: 8-12 seconds end-to-end
  • Key dependencies: OpenAI API, Clearbit API, HubSpot API must all be configured

Critical nodes:

  • OpenAI Chat Model: Handles the intelligent qualification analysis using GPT-4
  • Function (Score Calculator): Combines AI insights with business rules for final scoring
  • Switch: Routes leads to appropriate workflows based on tier
  • Slack: Delivers instant notifications for high-priority prospects

The complete n8n workflow JSON template is available at the bottom of this article.

Key Configuration Details

OpenAI Integration

Required fields:

  • API Key: Your OpenAI API key with GPT-4 access
  • Model: Must use gpt-4 not gpt-3.5-turbo for qualification accuracy
  • Temperature: 0.3 (lower = more consistent, higher = more creative)

Common issues:

  • Using gpt-3.5-turbo → Results in inconsistent qualification logic
  • Temperature above 0.5 → Scores vary wildly for similar leads
  • Max tokens too low → AI analysis gets cut off mid-sentence

Why this approach:
Temperature controls randomness in AI responses. For lead qualification, you want consistency - the same lead should score similarly every time. A temperature of 0.3 provides enough flexibility for nuanced analysis without wild variations. GPT-4's superior reasoning is essential here; GPT-3.5 often misses subtle buying signals or context clues that indicate true fit.

Clearbit API Configuration

Variables to customize:

  • timeout: Set to 10000ms (10 seconds) - enrichment can be slow for obscure companies
  • retryAttempts: Use 3 retries with 2-second intervals
  • fallbackBehavior: Continue workflow even if enrichment fails

Alternative data sources:
If Clearbit is too expensive ($99/month minimum), substitute:

  • Hunter.io for email verification and basic company data
  • Apollo.io for B2B contact enrichment
  • LinkedIn Sales Navigator API for professional data
  • Manual fallback: Skip enrichment, rely solely on form data

Scoring Logic Customization

The Function node contains your business rules. Adjust these thresholds based on your ICP:

// CUSTOMIZE THESE VALUES
const IDEAL_EMPLOYEE_RANGE = [50, 500]; // Your target company size
const IDEAL_REVENUE_RANGE = [5000000, 50000000]; // $5M-$50M
const TARGET_INDUSTRIES = ['SaaS', 'Technology', 'Professional Services'];
const SENIOR_TITLES = ['VP', 'Director', 'Head of', 'Chief'];
const TARGET_TECH = ['salesforce', 'hubspot', 'pipedrive'];
const HIGH_VALUE_SOURCES = ['demo_request', 'pricing_page', 'contact_sales'];

// ADJUST SCORE WEIGHTS
const WEIGHTS = {
  companySize: 15,
  revenue: 15,
  industry: 10,
  seniority: 10,
  techStack: 10,
  leadSource: 10
};

Testing different scoring models:
Run your workflow against historical leads with known outcomes. Compare AI scores to actual conversion rates. Adjust weights until high scores correlate with closed deals.

Testing & Validation

Test each component individually:

  1. Webhook: Use Postman or curl to POST sample lead data

    curl -X POST https://your-n8n.com/webhook/qualify-lead \
      -H "Authorization: Bearer YOUR_SECRET_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{"email":"test@acme.com","company":"Acme Corp",...}'
    
  2. Enrichment: Check that Clearbit returns data for known companies

    • Test with "stripe.com" (should return complete data)
    • Test with "unknownstartup123.com" (should handle gracefully)
  3. AI Qualification: Review GPT-4 responses for 10 sample leads

    • Do scores align with your intuition?
    • Are buying signals accurately identified?
    • Does the recommended action make sense?
  4. CRM Update: Verify fields populate correctly in HubSpot

    • Check custom properties appear
    • Confirm score displays as number, not text
    • Validate timestamp formats
  5. Routing Logic: Test all three paths

    • Create a lead with score 85 → Should trigger Slack
    • Create a lead with score 65 → Should create task
    • Create a lead with score 45 → Should add to nurture

Common troubleshooting:

Issue Cause Solution
"API key invalid" error Wrong OpenAI credential Regenerate key in OpenAI dashboard, update n8n credential
Enrichment returns empty Domain format wrong Ensure domain is "company.com" not "https://company.com"
CRM update fails Custom fields don't exist Create all custom properties in HubSpot first
Slack notification not sending Wrong channel name Use channel ID instead of name, or invite bot to channel
Workflow times out Enrichment API slow Increase timeout to 15000ms, add error handling

Running evaluations:

Track these metrics weekly:

  • Qualification speed: Time from webhook to CRM update (target: <10 seconds)
  • Score accuracy: Compare AI scores to actual conversion rates
  • False positives: Hot leads that don't convert (should be <20%)
  • False negatives: Cold leads that later convert (investigate these)

Deployment Considerations

Production Deployment Checklist

Area Requirement Why It Matters
Error Handling Retry logic with exponential backoff on all API nodes Prevents data loss when Clearbit or OpenAI has temporary outages
Monitoring Webhook health checks every 5 minutes Detect failures within 5 minutes vs discovering days later
Rate Limiting Queue mechanism for high-volume periods OpenAI has 3,500 requests/min limit; queuing prevents rejection
Data Privacy PII handling compliance (GDPR/CCPA) Lead data contains personal information requiring proper handling
Backup Scoring Fallback to rule-based if AI fails Ensures leads still get qualified even during OpenAI outages
Audit Logging Log every qualification decision Required for debugging and compliance
Cost Management Set monthly API spend alerts OpenAI costs can spike unexpectedly with high volume

Error handling strategy:

Add an Error Trigger node that catches any workflow failures:

{
  "triggerOn": "workflowError",
  "actions": [
    {
      "type": "sendSlack",
      "channel": "#n8n-alerts",
      "message": "Lead qualification workflow failed: {{$json.error.message}}"
    },
    {
      "type": "logToFile",
      "path": "/var/log/n8n/qualification-errors.log"
    }
  ]
}

Monitoring recommendations:

Set up these alerts:

  • Workflow execution time exceeds 30 seconds (indicates API slowness)
  • More than 5 failures per hour (indicates systemic issue)
  • OpenAI API costs exceed $50/day (indicates unexpected volume)
  • Enrichment success rate drops below 70% (indicates data source issue)

Customization ideas:

  • Add SMS notifications for ultra-hot leads (score 95+)
  • Integrate with calendar to auto-book demos for hot leads
  • Create executive dashboard showing daily qualification metrics
  • A/B test different AI prompts to optimize scoring accuracy
  • Add lead source tracking to identify highest-quality channels

Use Cases & Variations

Use Case 1: SaaS Demo Request Qualification

  • Industry: B2B SaaS selling to mid-market
  • Scale: 200-300 demo requests per month
  • Modifications needed: Add "product interest" field to scoring, integrate with Calendly for instant booking of hot leads, adjust employee count range to 100-1000

Use Case 2: Professional Services Lead Triage

  • Industry: Consulting, agencies, law firms
  • Scale: 50-100 contact form submissions per week
  • Modifications needed: Replace tech stack scoring with "project budget" field, add geographic territory routing, integrate with practice management system instead of CRM

Use Case 3: E-commerce B2B Wholesale Inquiries

  • Industry: Wholesale/distribution
  • Scale: 500+ inquiries per month
  • Modifications needed: Score based on order volume potential and retail footprint, add credit check integration, route to account managers by region

Use Case 4: Event Registration Qualification

  • Industry: Conference/event organizers
  • Scale: 1000+ registrations per event
  • Modifications needed: Score based on job title and company for VIP treatment, trigger personalized email sequences, flag sponsors/speakers for special handling

Use Case 5: Real Estate Lead Scoring

  • Industry: Commercial real estate
  • Scale: 300-400 property inquiries per month
  • Modifications needed: Score based on financing pre-approval and property budget range, integrate with MLS data, route to agents by property type specialty

Customizing This Workflow

Alternative Integrations

Instead of HubSpot:

  • Salesforce: Best for enterprise sales teams - requires 8 node changes to use Salesforce API format
  • Pipedrive: Better for SMB sales - simpler API, swap out nodes 8-9
  • Close.com: Use when you need built-in calling - native integration available

Instead of Clearbit:

  • Apollo.io: More affordable ($49/month) - requires changing enrichment endpoint and data mapping
  • Hunter.io: Best for email verification focus - limited company data, adjust scoring logic
  • ZoomInfo: Enterprise-grade data - higher accuracy but $15K+ annual cost

Instead of Slack:

  • Microsoft Teams: Use Teams webhook node for Office 365 organizations
  • Email: Simple SMTP node for direct inbox delivery
  • SMS: Twilio node for urgent hot lead alerts

Workflow Extensions

Add automated reporting:

  • Add a Schedule node to run daily at 8 AM
  • Connect to Google Sheets API to log all qualifications
  • Generate weekly summary of hot/warm/cold lead distribution
  • Nodes needed: +4 (Schedule, Google Sheets, Aggregate, Email)

Scale to handle more data:

  • Replace single webhook with Queue node for high-volume periods
  • Add Redis caching for enrichment data (avoid re-enriching same companies)
  • Implement batch processing for overnight lead imports
  • Performance improvement: Handles 10x volume without slowdown

Integration possibilities:

Add This To Get This Complexity
Calendly integration Auto-book demos for hot leads Easy (3 nodes)
LinkedIn Sales Nav Enhanced decision-maker verification Medium (6 nodes)
Gong/Chorus Analyze sales call sentiment for score refinement Advanced (12 nodes)
Stripe/payment data Score based on actual spending capacity Medium (5 nodes)
ZoomInfo More accurate firmographic data Easy (2 nodes - swap Clearbit)
Intercom Trigger in-app messages for warm leads Medium (4 nodes)

Advanced customization: Multi-touch attribution

Track which marketing touchpoints influenced the lead before qualification:

// Add to Function node
const touchpoints = [
  { source: 'google_ads', timestamp: $json.firstTouch },
  { source: 'content_download', timestamp: $json.secondTouch },
  { source: 'demo_request', timestamp: $json.conversionTouch }
];

// Weight recent touches more heavily
const recencyScore = touchpoints.reduce((score, touch, index) => {
  const daysSince = (Date.now() - new Date(touch.timestamp)) / 86400000;
  const recencyWeight = Math.max(0, 10 - daysSince); // Decay over 10 days
  return score + recencyWeight;
}, 0);

finalScore += Math.min(recencyScore, 15); // Cap attribution bonus at 15 points

Get Started Today

Ready to automate your lead qualification?

  1. Download the template: Scroll to the bottom of this article to copy the complete n8n workflow JSON
  2. Import to n8n: Go to Workflows → Import from URL or File, paste the JSON
  3. Configure your services: Add your API credentials for OpenAI, Clearbit, HubSpot, and Slack
  4. Customize scoring logic: Edit the Function node to match your ideal customer profile
  5. Test with sample data: Send test leads through the webhook to verify everything works
  6. Deploy to production: Activate the workflow and connect your lead sources

Next steps for optimization:

  • Run the workflow for 2 weeks, then analyze score distribution
  • Compare AI qualification to your sales team's manual assessment
  • Adjust scoring weights based on which leads actually convert
  • Add custom fields specific to your industry or product

Need help customizing this workflow for your specific needs? Schedule an intro call with Atherial at atherial.ai/contact. We'll help you adapt this template to your exact qualification criteria, integrate with your tech stack, and optimize for your conversion patterns.


Complete n8n Workflow JSON Template

{
  "name": "AI Lead Qualification Agent",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "qualify-lead",
        "authentication": "headerAuth",
        "responseMode": "responseNode",
        "options": {}
      },
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [250, 300]
    },
    {
      "parameters": {
        "method": "GET",
        "url": "=https://company.clearbit.com/v2/companies/find?domain={{$json.website}}",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "clearbitApi",
        "options": {
          "timeout": 10000
        }
      },
      "name": "Enrich Company Data",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 3,
      "position": [450, 300]
    },
    {
      "parameters": {
        "functionCode": "const enriched = $input.first().json;
const original = $('Webhook').first().json;

return {
  json: {
    email: original.email,
    name: `${original.firstName} ${original.lastName}`,
    company: original.company,
    jobTitle: original.jobTitle,
    employeeCount: enriched.metrics?.employees || 0,
    revenue: enriched.metrics?.estimatedAnnualRevenue || 'Unknown',
    industry: enriched.category?.industry || 'Unknown',
    techStack: enriched.tech || [],
    fundingStage: enriched.metrics?.raised || 'Unknown',
    companyAge: enriched.foundedYear ? new Date().getFullYear() - enriched.foundedYear : 0,
    leadSource: original.leadSource
  }
};"
      },
      "name": "Normalize Data",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [650, 300]
    },
    {
      "parameters": {
        "model": "gpt-4",
        "options": {
          "temperature": 0.3,
          "maxTokens": 500
        },
        "messages": {
          "values": [
            {
              "role": "system",
              "content": "You are a B2B lead qualification expert. Analyze leads against ideal customer profile criteria and provide structured qualification assessment."
            },
            {
              "role": "user",
              "content": "=Analyze this lead:

CONTACT: {{$json.name}} ({{$json.jobTitle}})
COMPANY: {{$json.company}}
EMPLOYEES: {{$json.employeeCount}}
REVENUE: {{$json.revenue}}
INDUSTRY: {{$json.industry}}
TECH STACK: {{$json.techStack.join(', ')}}
SOURCE: {{$json.leadSource}}

Provide: 1) Fit score (0-100), 2) Tier (Hot/Warm/Cold), 3) Buying signals, 4) Concerns, 5) Next action"
            }
          ]
        }
      },
      "name": "AI Qualification",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 1,
      "position": [850, 300]
    },
    {
      "parameters": {
        "functionCode": "let finalScore = $json.score || 50;

if ($json.employeeCount >= 50 && $json.employeeCount <= 500) finalScore += 15;
if ($json.industry.includes('SaaS') || $json.industry.includes('Technology')) finalScore += 10;
if ($json.jobTitle.includes('VP') || $json.jobTitle.includes('Director')) finalScore += 10;

finalScore = Math.min(finalScore, 100);
const finalTier = finalScore >= 80 ? 'hot' : finalScore >= 60 ? 'warm' : 'cold';

return { json: { finalScore, finalTier } };"
      },
      "name": "Calculate Score",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [1050, 300]
    },
    {
      "parameters": {
        "resource": "contact",
        "operation": "update",
        "email": "={{$json.email}}",
        "additionalFields": {
          "customProperties": {
            "property": [
              { "name": "lead_score", "value": "={{$json.finalScore}}" },
              { "name": "lead_tier", "value": "={{$json.finalTier}}" }
            ]
          }
        }
      },
      "name": "Update CRM",
      "type": "n8n-nodes-base.hubspot",
      "typeVersion": 2,
      "position": [1250, 300]
    },
    {
      "parameters": {
        "mode": "rules",
        "rules": [
          {
            "conditions": [
              { "leftValue": "={{$json.finalTier}}", "rightValue": "hot", "operator": "equal" }
            ],
            "output": 0
          },
          {
            "conditions": [
              { "leftValue": "={{$json.finalTier}}", "rightValue": "warm", "operator": "equal" }
            ],
            "output": 1
          }
        ],
        "fallbackOutput": 2
      },
      "name": "Route by Tier",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 1,
      "position": [1450, 300]
    },
    {
      "parameters": {
        "channel": "#sales-hot-leads",
        "text": "=🔥 HOT LEAD: {{$json.name}} at {{$json.company}} (Score: {{$json.finalScore}})",
        "attachments": []
      },
      "name": "Notify Slack",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 1,
      "position": [1650, 200]
    }
  ],
  "connections": {
    "Webhook": { "main": [[{ "node": "Enrich Company Data", "type": "main", "index": 0 }]] },
    "Enrich Company Data": { "main": [[{ "node": "Normalize Data", "type": "main", "index": 0 }]] },
    "Normalize Data": { "main": [[{ "node": "AI Qualification", "type": "main", "index": 0 }]] },
    "AI Qualification": { "main": [[{ "node": "Calculate Score", "type": "main", "index": 0 }]] },
    "Calculate Score": { "main": [[{ "node": "Update CRM", "type": "main", "index": 0 }]] },
    "Update CRM": { "main": [[{ "node": "Route by Tier", "type": "main", "index": 0 }]] },
    "Route by Tier": { "main": [[{ "node": "Notify Slack", "type": "main", "index": 0 }], [], []] }
  }
}

Copy this JSON and import it into your n8n instance to get started immediately. Remember to configure your API credentials before activating the workflow.