# AI Lead Qualification & Sales Routing Agent

> An end-to-end system for automated inbound lead scoring, enrichment, and real-time sales routing, powered by GPT-4.1 and n8n.

Section: Custom SaaS Platforms

Page: https://showcase.growlyze.cloud/case/ai-lead-qualification-sales-routing-agent

Image: The lead form with a sample lead and the AI results card: score, HOT category, intent, budget, urgency, ICP match, summary and recommended action. (https://showcase.growlyze.cloud/case-content/ai-lead-qualification/image1.png)

- Type: Systems Case Study
- Platforms: Node.js · Express · OpenAI GPT-4.1 · n8n · Slack · Airtable
- Data Sources: Website Lead Forms · n8n Webhooks · Direct API Submissions
- Integrations: Clearbit (enrichment) · Airtable (CRM) · Slack (alerts) · Email (SMTP)

## Why we built this

Most sales teams receive inbound leads from multiple sources (website contact forms, paid ad landing pages, partner referrals, and API integrations) and have no consistent, fast way to decide which ones deserve immediate attention.

The core problems the team was facing:

- No consistent scoring methodology: qualification decisions depended on whoever happened to read the form first, leading to missed opportunities and wasted rep time
- Hot leads were going cold: without instant routing, a prospect who said “ASAP, budget approved” could wait hours before a rep saw the submission
- Company intelligence had to be looked up manually: reps spent time researching the company behind an email address before they could even decide whether to respond
- No tiered escalation: there was no system to distinguish between a lead that needed a call in the next hour versus one that could go into a drip sequence
- No unified lead record: repeat contacts from the same email were logged as separate entries, losing the interaction history

The goal was to build a fully automated intake-to-routing pipeline: AI scoring that runs in under two seconds, automatic company enrichment from the email domain, tiered alerts that reach the right person at the right time, and a central record of every lead with full analysis history.

### What this system does

The system is composed of three interconnected layers: a lead intake API, a backend processing pipeline, and a real-time alerting engine, all orchestrated through n8n and a Node.js Express server.

### Lead intake

- Accepts inbound leads via a hosted landing page form, a direct REST API call, an embedded form webhook, or an n8n-triggered workflow
- Validates required fields (name, email) and normalises all input before processing begins
- Detects repeat submissions from the same email address: existing records are updated with the new interaction rather than duplicated
- Supports a source field to track which channel each lead arrived from (website, paid ad, referral, n8n, etc.)

### AI scoring engine

- Each lead is analysed by GPT-4.1 across five dimensions: budget signals, urgency language, purchase intent, ICP (Ideal Customer Profile) match, and email quality
- Returns a structured score from 0–100 and classifies the lead as HOT, WARM, or COLD
- Produces a 12-field analysis object: score, category, intent, budget, urgency, ICP match, AI summary, recommended action, key signals, risk factors, estimated deal size, and sales rep assignment
- Falls back to a rule-based keyword scoring engine if the OpenAI API is unavailable, guaranteeing zero-downtime operation

### Enrichment layer

- Extracts the company domain from the lead’s email address and enriches it with external company intelligence
- With Clearbit: pulls company name, industry, employee count, estimated revenue, tech stack, LinkedIn URL, and headquarters location
- Without Clearbit: performs basic domain analysis, infers company name, identifies TLD-based region, and confirms it is a business (not free) email
- Free email providers (Gmail, Yahoo, Hotmail, etc.) are skipped for enrichment and flagged accordingly

### Alerting and routing

- Fires Slack alerts for every HOT lead: rich Block Kit messages, including all 12 analysis fields, AI summary, estimated deal size, and assigned sales team
- Routes WARM leads to a nurture queue for email sequence follow-up
- Archives COLD leads automatically with no sales action triggered
- All notification steps run asynchronously, so they never delay the API response back to the form or caller

## CRM integration

- Pushes every processed lead to Airtable with 18 mapped fields, including all analysis outputs
- Designed to be swapped for HubSpot or any other CRM with a single service file change
- Skips gracefully if CRM credentials are not configured: the pipeline continues without interruption

### Benefits

- Hot leads reach a rep in seconds, not hours, the moment a high-intent submission arrives, a Slack alert lands in the right channel with everything the rep needs to act
- Consistent, bias-free scoring: every lead is evaluated against the same GPT-4.1 criteria, removing the inconsistency of human triage
- Company intelligence without manual research: reps open a Slack alert and already know the company’s industry, size, and tech stack
- Zero-downtime resilience: if the AI API goes down, rule-based fallback scoring keeps the pipeline running
- Unified lead history: repeat contacts are detected, and interactions are appended to the original record, preserving full context
- Clean data from day one: lead sources are tracked, free email submissions are flagged, and all records share a consistent schema
- Scalable without config changes: new lead sources plug in via the webhook endpoint; the pipeline handles volume automatically

### How it works (simplified)

- A lead arrives via the landing page form, a direct API call, an embedded form, or an n8n webhook, all routes converge on the same processing pipeline
- The system checks for a repeat submission by looking up the email address in the lead store; if found, the new interaction is logged against the existing record
- The lead is enriched: the email domain is used to pull company data from Clearbit, or a basic domain analysis runs as a fallback
- GPT-4.1 analyses the lead: the full enriched record is submitted to the AI with a structured scoring prompt; a 12-field JSON response is returned in under two seconds
- The lead is stored in the in-memory data layer (replaceable with PostgreSQL or Supabase) and a full analysis record is written
- HOT lead → Slack alert is sent to the relevant sales channel, tagging the assigned rep team with the full AI summary and deal estimate
- WARM lead → nurture queue: logged for drip email sequence follow-up
- COLD lead → archived: stored for reference with no immediate sales action
- The CRM is updated asynchronously: Airtable receives the full 18-field record without blocking the API response
- The caller receives an instant response: the full analysis JSON is returned to the form or API caller within the same two-second window

## System architecture (simplified)

Image: Architecture: four lead sources feed an Express backend with a five-step pipeline (validate, repeat detection, Clearbit enrichment, GPT-4.1 scoring, store), which routes to Slack alerts, an Airtable CRM and a nurture queue. (https://showcase.growlyze.cloud/case-content/ai-lead-qualification/image2.png)

Ops-controlled settings (thresholds, routing rules, and CRM field mappings) are managed through environment configuration:

| Setting | Where Configured | What It Controls |
| --- | --- | --- |
| OPENAI_API_KEY | .env file | Enables AI scoring via GPT-4.1 |
| SLACK_WEBHOOK_URL | .env file | Destination channel for HOT lead alerts |
| AIRTABLE_API_KEY + BASE_ID | .env file | CRM destination for all processed leads |
| CLEARBIT_API_KEY | .env file | Enables full company enrichment (optional) |
| Alert Toggle (per lead) | Google Sheets control layer | Enable or disable alerts per lead source |
| Score thresholds | Prompt config in aiService.js | Adjustable scoring bands per business context |

## Dashboard overview

## Lead analysis results panel

The lead form renders a live results card immediately after submission, displaying the AI score, category, intent rating, budget signal, urgency level, ICP match, and a plain-English summary of why the lead scored the way it did, along with a specific recommended next action.

Renders in the browser within ~2 seconds of form submission

### Slack alert panel

When a lead is classified as HOT, a Block Kit alert fires to the configured Slack channel. The message includes: lead name and company, email, phone, all five scoring dimensions, the AI-generated summary, recommended action, estimated deal size, and assigned sales team, formatted as a structured card with section dividers.

Delivered to the #sales-alerts channel within seconds of submission

### Analytics dashboard

The /dashboard page provides a live operations view of all processed leads: total volume, HOT / WARM / COLD breakdown, average score, conversion rate, leads today, leads this week, top sources by volume, and a filterable lead feed. Data is drawn directly from the in-memory store and refreshes on page load.

Accessible at /dashboard: no login required in base configuration

### Project evolution & key milestones

The system scope grew significantly from the initial lead scoring proof-of-concept. Key additions and refinements delivered across the project lifecycle:

### Core scoring engine

- Initial GPT-4 integration replaced with GPT-4.1 for faster, more consistent structured output
- AI temperature set to 0.3 after testing: balances consistency with contextual sensitivity
- Strict JSON output schema enforced via system prompt to eliminate parsing failures
- Rule-based fallback engine added to ensure zero downtime when the OpenAI API is unavailable
- Score validation and sanitisation layer added (score clamped 0–100; category constrained to enum)

### Enrichment layer

- Clearbit integration added as the primary enrichment source for business email domains
- Domain-only fallback implemented: company name inference, TLD region mapping, business email detection
- Free email provider list maintained to skip enrichment for Gmail, Yahoo, Hotmail, iCloud, ProtonMail, and similar

### Alerting system

- Slack alerts upgraded from plain text to full Block Kit format with eight labelled fields and section dividers
- Tiered routing logic added: HOT → Slack, WARM → nurture queue, COLD → archive
- All notification steps moved to asynchronous execution to keep main API response time under two seconds
- CRM push also made non-blocking: Airtable delays no longer affect the caller experience

### Data and integration

- n8n webhook route added (/api/webhook/n8n) to support visual workflow orchestration
- Embedded form endpoint added (/api/webhook/form) for third-party form providers
- Importable n8n workflow JSON file shipped with the project for instant setup
- Airtable CRM integration added with 18 mapped fields; designed as a swappable service module

### Memory layer and analytics

- Repeat lead detection added: duplicate email submissions update the existing record rather than creating a new one
- Interaction history log added to each lead record for full contact context
- Analytics aggregation engine built into the storage service: computes category counts, average score, conversion rate, score distribution, top sources, and temporal metrics on demand
- Dashboard feed endpoint added with configurable pagination and category/source filters

### Security and production hardening

- Helmet HTTP security headers added across all routes
- Rate limiter set to 100 requests per 15 minutes per IP on all /api/* routes
- Request body size capped at 1 MB to prevent oversized payload attacks
- Explicit timeouts set on all external API calls (OpenAI: 30s · Clearbit: 5s · Airtable: 10s · Slack: 5s)
- Global error handler middleware added to prevent stack traces leaking to API callers

### Data flow architecture

How data moves through each stage and at what cadence, a key reference for ops teams integrating this system into existing stacks:

| Stage | Source | Destination | Trigger |
| --- | --- | --- | --- |
| Intake | Form / API / n8n webhook | Express backend | On submission (real-time) |
| Enrichment | Clearbit API / domain analysis | Lead record (in memory) | Per lead, synchronous |
| AI Scoring | OpenAI GPT-4.1 | Lead record (in memory) | Per lead, synchronous |
| CRM Push | In-memory lead record | Airtable (18 fields) | Per lead, async (non-blocking) |
| Slack Alert | In-memory lead record | Slack channel (HOT only) | Per lead, async (non-blocking) |
| Dashboard | In-memory lead store | Browser via /dashboard | On page load / manual refresh |

### Note

The current storage layer uses an in-memory Map for speed and simplicity. For production deployments requiring persistence across restarts or horizontal scaling, this is designed to be swapped for PostgreSQL, Supabase, or MongoDB, the storage service exposes a clean interface with no direct database calls in the route layer.

### Lead scoring & classification

The AI scoring engine evaluates every lead across five weighted dimensions and assigns a 0–100 score. Classification thresholds are:

| Category | Score Range | Routing Action | Criteria |
| --- | --- | --- | --- |
| HOT | 80 – 100 | Immediate Slack alert + rep assignment | Clear budget, urgency signal, decision-maker identified, strong ICP match |
| WARM | 50 – 79 | Added to nurture email sequence | Some buying signals, partial ICP match, needs further qualification |
| COLD | 0 – 49 | Archived, no immediate action | No clear intent, no budget signals, poor ICP fit or generic enquiry |

The five scoring dimensions GPT-4.1 evaluates are:

- Budget: explicit dollar amounts, investment language, company size inference
- Urgency: timeline pressure, ASAP / deadline keywords, quarter-based mentions
- Intent: active buying vs. passive browsing language (“want to buy” vs. “just exploring”)
- ICP Match: B2B vs. B2C, company size (50–500 employees = Excellent), industry alignment
- Email Quality: business domain vs. free provider (Gmail, Yahoo, Hotmail, etc.)
