Skip to content

Repository files navigation

v2 Runtime Notes

The current production baseline receives leads at POST /webhook/leadiq. Production requests must include X-Webhook-Secret matching N8N_WEBHOOK_SECRET. The existing routing behavior is HOT -> Slack, WARM -> Gmail, and COLD -> no active notification; HOT Gmail is intentionally not enabled in the exported v2 workflow. GET /webhook/leadiq-health reports configuration readiness and returns HTTP 503 when required settings are missing.

LeadIQ-AI

Enterprise AI Lead Qualification & Multi-Channel Routing Pipeline

License: MIT Python 3.11+ n8n Stars Issues Last Commit PRs Welcome

πŸ“– Architecture Β· πŸ”Œ API Spec Β· πŸ”„ Workflow Guide Β· πŸ› οΈ Setup Guide Β· 🎬 Live Demo


The Problem

Sales teams lose 23% of qualified leads due to slow response times and inconsistent follow-up. Manual triage creates bottlenecks β€” reps waste hours reviewing low-quality leads while high-value prospects go cold.

LeadIQ-AI solves this by automating the entire lead qualification pipeline. When a prospect submits an inquiry, the system instantly scores their intent using AI, prevents duplicate processing, routes hot leads to Slack for immediate attention, sends personalized follow-up emails, and logs everything to an audit trail β€” all within seconds, with zero manual intervention.


πŸŽ₯ Project Demo

Watch the full pipeline in action β€” from lead submission to AI qualification, duplicate prevention, Slack notification, Gmail generation, and Google Sheets reporting.

LeadIQ-AI Demo Preview β€” Click to watch full video

▢️ Click the preview above to watch the full demo video

What the demo covers
Step What Happens
1. Lead Submission A prospect submits an inquiry via the webhook endpoint
2. Data Normalization Email is normalized, correlation IDs are generated
3. Duplicate Check Supabase RPC checks the 10-minute deduplication window
4. AI Qualification Gemini 2.5 Flash scores intent (0–100) and assigns a tier
5. Audit Logging Full lead record is appended to Google Sheets
6. Slack Alert HOT leads trigger an immediate alert in #sales-hot
7. Gmail Follow-up Personalized acknowledgment email is sent to the lead

πŸ’‘ Why LeadIQ-AI?

Without LeadIQ-AI

  • ❌ Manual lead review takes hours
  • ❌ Hot leads go cold waiting for response
  • ❌ Duplicate submissions waste AI tokens
  • ❌ No audit trail for qualification decisions
  • ❌ Inconsistent scoring across reps

With LeadIQ-AI

  • βœ… Leads qualified in under 3 seconds
  • βœ… Hot leads routed to Slack instantly
  • βœ… 10-minute deduplication saves API costs
  • βœ… Every decision logged to Google Sheets
  • βœ… Consistent AI-powered scoring

⚑ Key Highlights

Highlight Detail
πŸ€– AI-Powered Scoring Google Gemini 2.5 Flash evaluates buyer intent, budget signals, and urgency
⚑ Sub-3s Qualification End-to-end pipeline from webhook to notification in under 3 seconds
πŸ”’ Atomic Deduplication PostgreSQL RPCs prevent race conditions and duplicate processing
πŸ“Š Full Audit Trail Every lead decision logged to Google Sheets with AI reasoning
🐳 One-Command Deploy Docker Compose brings up the entire stack with docker compose up -d
πŸ”Œ Extensible Architecture Modular n8n pipeline β€” add new channels or scoring models without code changes

πŸ—οΈ System Architecture

Business Flow

A prospect submits an inquiry β†’ the system normalizes their data β†’ checks for duplicate submissions β†’ scores their intent using AI β†’ logs the result β†’ routes alerts based on priority tier. Hot leads get instant Slack alerts and email follow-ups. Warm leads get email nurturing. Cold leads are logged for reference.

Technical Architecture

flowchart TD
    subgraph Client ["Client / Ingress"]
        Form[Inbound Lead Payload]
    end

    subgraph n8n ["n8n Pipeline Engine"]
        Norm[Data Normaliser Node]
        Switch{Priority Switch}
    end

    subgraph Supabase ["Supabase PostgreSQL Engine"]
        RPC1[reserve_lead_v1 RPC]
        RPC2[complete_lead_v1 RPC]
        DB[(leads & lead_reservations)]
    end

    subgraph AI ["Google Gemini AI"]
        Gemini[Gemini 2.5 Flash API]
    end

    subgraph Dispatch ["Multi-Channel Dispatch"]
        Sheets[Google Sheets Audit Log]
        Slack[Slack #sales-hot Alert]
        Gmail[Gmail Nurture Response]
    end

    Form --> Norm
    Norm --> RPC1
    RPC1 --> DB
    RPC1 -->|Status: OWNER| Gemini
    RPC1 -->|Status: DUPLICATE_COMPLETED| Sheets
    Gemini --> RPC2
    RPC2 --> DB
    RPC2 --> Sheets
    Sheets --> Switch
    Switch -->|HOT Tier| Slack
    Slack --> Gmail
    Switch -->|WARM Tier| Gmail
    Switch -->|COLD Tier| EndProcess[End Pipeline]
Loading

Channel Dispatch Matrix

Tier Score Range Slack Alert Gmail Follow-up Google Sheets
πŸ”΄ HOT 80–100 βœ… Immediate βœ… Personalized βœ… Logged
🟑 WARM 50–79 β€” βœ… Nurture email βœ… Logged
πŸ”΅ COLD 0–49 β€” β€” βœ… Logged

✨ Features

Feature Description
πŸ€– AI Lead Qualification Gemini 2.5 Flash evaluates buyer intent, company fit, urgency, and budget against ICP criteria β€” producing a score (0–100), tier, and structured reasoning
⚑ Transactional Duplicate Prevention Supabase PostgreSQL RPCs (reserve_lead_v1, complete_lead_v1) enforce a 10-minute deduplication window with atomic state management
πŸ“Š Immutable Audit Trail Every lead payload, AI score, tier, and reasoning is appended to Google Sheets for non-technical stakeholder access
πŸ’¬ Real-time Slack Alerts HOT enterprise leads trigger formatted Markdown alerts in #sales-hot for immediate representative triage
πŸ“§ Automated Email Follow-up Personalized Gmail acknowledgments are sent based on qualification tier
🐳 One-Command Deployment Containerized n8n execution via Docker Compose with isolated secret management

πŸ”„ Workflow Overview

Click to expand the full pipeline sequence diagram
sequenceDiagram
    autonumber
    actor Form as Lead / Client
    participant n8n as n8n Pipeline
    participant Supa as Supabase PostgreSQL
    participant AI as Gemini 2.5 Flash
    participant Out as Sheets / Slack / Gmail

    Form->>n8n: POST /webhook/lead-qualification
    n8n->>n8n: Normalize payload & email
    n8n->>Supa: Call reserve_lead_v1(email_normalized)
    
    alt Status == OWNER (New Lead)
        Supa-->>n8n: Return status: OWNER
        n8n->>AI: Score lead (Prompt + JSON)
        AI-->>n8n: Return {score, tier, reasoning}
        n8n->>Supa: Call complete_lead_v1(lead_id, score, tier)
        Supa-->>n8n: State updated to completed
        n8n->>Out: Log to Sheets β†’ Route by tier
        n8n->>Form: 200 OK (Qualification Output)
    else Status == DUPLICATE_COMPLETED (Within 10 min)
        Supa-->>n8n: Return cached AI result
        n8n->>Out: Log duplicate to Sheets
        n8n-->>Form: 200 OK (Cached Result)
    end
Loading

Pipeline stages: Webhook Ingestion β†’ Data Normalization β†’ Duplicate Check β†’ AI Scoring β†’ State Persistence β†’ Audit Logging β†’ Tier Routing β†’ Slack/Gmail Dispatch


πŸ› οΈ Tech Stack

Technology Role Why This Choice
n8n Workflow Orchestration Visual debugging, self-hostable, native integrations, no per-execution fees
Supabase State Engine & PostgreSQL ACID transactions, PL/pgSQL RPCs for atomic operations, built-in Studio UI
Google Gemini AI Lead Scoring gemini-2.5-flash β€” fast, structured JSON output, contextual reasoning
Google Sheets Audit Trail Zero-infrastructure log for non-technical stakeholders
Slack API Real-time Alerts Channel-based routing, rich Markdown formatting
Gmail API Email Automation OAuth2 personalized follow-ups with dynamic content
Docker Containerization One-command deployment, isolated environments

πŸ“Έ Screenshots

Screenshots of the live pipeline β€” n8n workflow, Slack alerts, Gmail emails, Google Sheets audit log, and Supabase Studio.

Screenshot Description
n8n Workflow Canvas Full pipeline with duplicate detection branch visible
Gemini AI Response n8n execution log showing AI scoring JSON output
Slack #sales-hot Formatted Markdown alert for a HOT enterprise lead
Gmail Follow-up Personalized acknowledgment email sent to the lead
Google Sheets Log Audit spreadsheet with multiple lead records and tiers
Supabase Studio leads and lead_reservations tables showing state transitions

Tip

To add screenshots: capture each system's output during a demo run, then place the images in demo/screenshots/. See the screenshot guide for naming conventions.


πŸš€ Installation

Prerequisites

Tool Version Install
Docker Desktop Latest docker.com
Git 2.40+ git-scm.com
Python 3.11+ python.org
Supabase CLI Latest supabase.com/docs/guides/cli

Quick Start

# 1. Clone & configure
git clone https://github.com/sourabh-jangid-dev/LeadIQ-AI.git
cd LeadIQ-AI
cp .env.example .env
# Edit .env with your API keys (see Configuration below)

# 2. Start Supabase & apply migrations
supabase start
supabase db reset

# 3. Launch n8n via Docker Compose
docker volume create n8n_data
docker compose up -d

# 4. Access n8n dashboard
# Open http://localhost:5678 in your browser

Note

For detailed setup instructions including OAuth configuration, see the full Setup Guide.


βš™οΈ Configuration

Variable Required Description
LLM_API_KEY βœ… Google Gemini API key
LLM_MODEL βœ… Model identifier (default: gemini-2.5-flash)
SUPABASE_URL βœ… Supabase REST URL
SUPABASE_SERVICE_ROLE_KEY βœ… Supabase service role secret
GOOGLE_SHEETS_SPREADSHEET_ID βœ… Target Google Sheets document ID
SLACK_CHANNEL_HOT βœ… Slack channel for HOT alerts (default: #sales-hot)
GMAIL_SENDER_NAME βœ… Display name for outbound emails

See .env.example for a complete template with inline documentation.


▢️ Running the Workflow

Import the Workflow into n8n

  1. Open n8n at http://localhost:5678
  2. Go to Workflows β†’ Import from File
  3. Select n8n/v2/workflows/leadiq-ai-v2.1-fixed.json
  4. Configure credentials (Google Sheets OAuth2, Slack, Gmail) in n8n's credential manager
  5. Toggle the workflow to Active

Test with a Sample Lead

# Send a HOT lead
python scripts/generate_test_leads.py --count 1 --tier hot

# Or use cURL directly
curl -X POST "http://localhost:5678/webhook/lead-qualification" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Sarah Jenkins",
    "email": "s.jenkins@enterprise-tech.com",
    "company": "Enterprise Tech Solutions",
    "message": "We have an urgent budget of $50,000 to deploy AI lead automation across 40 reps.",
    "phone": "+1-555-019-2834",
    "country": "United States",
    "source": "Web Form"
  }'

Verify Output

Check Where to Look
Pipeline execution n8n β†’ Executions tab
Database state Supabase Studio (http://localhost:54323) β†’ leads table
Audit log Google Sheets β†’ Leads tab
Slack alert Slack β†’ #sales-hot channel
Email sent Gmail β†’ Sent folder

πŸ“ Project Structure

LeadIQ-AI/
β”œβ”€β”€ assets/                        # Hero banner & visual assets
β”œβ”€β”€ business/                      # Business model & client presentation guides
β”‚   β”œβ”€β”€ ClientDemo.md
β”‚   β”œβ”€β”€ Pricing.md
β”‚   β”œβ”€β”€ Problem.md
β”‚   └── UseCases.md
β”œβ”€β”€ data/                          # Sample payloads & schema references
β”‚   β”œβ”€β”€ sample_leads.json
β”‚   └── schema.md
β”œβ”€β”€ demo/                          # Demo assets & walkthrough
β”‚   β”œβ”€β”€ demo_walkthrough.md
β”‚   β”œβ”€β”€ screenshots/               # Pipeline screenshots
β”‚   β”œβ”€β”€ scripts/                   # Live webhook test sender
β”‚   β”‚   └── send_demo_lead.py
β”‚   └── videos/                    # Demo recordings & GIF previews
β”œβ”€β”€ diagrams/                      # Mermaid diagrams & .drawio files
β”œβ”€β”€ docs/                          # Technical documentation suite
β”‚   β”œβ”€β”€ API.md                     # Webhook REST API specification
β”‚   β”œβ”€β”€ Architecture.md            # System architecture reference
β”‚   β”œβ”€β”€ DATABASE.md                # Supabase schema & RPC guide
β”‚   β”œβ”€β”€ DECISIONS.md               # Engineering decision records
β”‚   β”œβ”€β”€ DEMO.md                    # Live demo walkthrough guide
β”‚   β”œβ”€β”€ LIMITATIONS.md             # Known tradeoffs & limitations
β”‚   β”œβ”€β”€ PRD.md                     # Product Requirements Document
β”‚   β”œβ”€β”€ SETUP.md                   # Installation & setup guide
β”‚   └── Workflow.md                # n8n pipeline node-by-node guide
β”œβ”€β”€ examples/                      # cURL commands & sample payloads
β”œβ”€β”€ n8n/                           # n8n workflow definitions
β”‚   └── v2/workflows/              # ← Production workflow JSON
β”œβ”€β”€ portfolio/                     # Case studies & portfolio collateral
β”œβ”€β”€ prompts/                       # Google Gemini AI prompt templates
β”‚   β”œβ”€β”€ lead_scoring.md
β”‚   └── email_reply.md
β”œβ”€β”€ scripts/                       # Developer utility tools
β”‚   β”œβ”€β”€ generate_test_leads.py
β”‚   └── validate_schema.py
β”œβ”€β”€ supabase/                      # PostgreSQL migrations & RPC definitions
β”‚   └── migrations/
β”œβ”€β”€ tests/                         # Workflow test scenarios
β”œβ”€β”€ .env.example                   # Environment configuration template
β”œβ”€β”€ CHANGELOG.md                   # Release notes (Keep a Changelog)
β”œβ”€β”€ CONTRIBUTING.md                # Contribution guidelines
β”œβ”€β”€ docker-compose.yml             # Docker stack configuration
β”œβ”€β”€ LICENSE                        # MIT License
β”œβ”€β”€ README.md                      # ← You are here
└── SECURITY.md                    # Security policy

🧠 Engineering Decisions

Note

Full decision records with rationale are documented in docs/DECISIONS.md.

Why n8n for Orchestration?

Visual flow execution enables node-by-node debugging. Self-hostable via Docker with no per-execution cloud fees. Native connectors for Google Sheets, Slack, and Gmail eliminate custom integration code.

Why Supabase PostgreSQL for State Management?

Full ACID transaction guarantees for concurrency control. PL/pgSQL stored procedures (reserve_lead_v1, complete_lead_v1) encapsulate atomic duplicate detection and state transitions, eliminating race conditions at the database level.

Why Gemini 2.5 Flash for AI Scoring?

Reliable structured JSON output matching strict qualification schemas. Fast turnaround (~1-2s) suitable for synchronous webhook processing. Superior contextual reasoning compared to keyword-based rules engines for evaluating buyer intent, budget, and urgency.

Why a 10-Minute Duplicate Window?

Web forms frequently receive accidental double-clicks or script loop resubmissions. The 10-minute window prevents redundant Gemini API calls (saving token costs) while being short enough that a genuine re-inquiry after the window expires gets fresh scoring.

Why Google Sheets as an Audit Log?

Gives sales leadership and non-technical stakeholders instant, real-time access to incoming leads without needing database query access or custom admin UI development. Zero additional infrastructure to maintain.


⚠️ Limitations & Tradeoffs

Limitation Current State Why This Tradeoff
Fixed duplicate window Hardcoded at 10 minutes Simplifies configuration; covers 95% of accidental resubmissions
Synchronous processing Webhook caller waits for full pipeline Provides instant feedback; async queueing planned for v2
Single-tenant deployment One Supabase + n8n instance Reduces operational complexity for initial deployment
Fixed lease timeout 15-minute worker lease Balances crash recovery with processing window
Third-party rate limits Bound by Gemini, Sheets, Slack, Gmail APIs Mitigated by deduplication; queueing planned for high-throughput

Tip

See docs/LIMITATIONS.md for detailed analysis of each tradeoff and planned mitigations.


πŸ›£οΈ Roadmap

βœ… Completed

  • Core webhook ingestion pipeline
  • Supabase PostgreSQL state engine with atomic RPCs
  • Google Gemini AI lead scoring and tiering
  • 10-minute duplicate detection and suppression
  • Google Sheets immutable audit logging
  • Slack real-time alerts for HOT leads
  • Gmail personalized follow-up emails
  • Tier-based conditional routing (HOT / WARM / COLD)
  • Docker Compose one-command deployment
  • Comprehensive documentation suite
  • Portfolio and case study materials

πŸ”œ Planned

  • Asynchronous message queueing (Redis / BullMQ) for high-throughput
  • Multi-tenant routing with territory-based rules
  • Lead enrichment integrations (Clearbit / Apollo)
  • CRM integrations (Salesforce, HubSpot)
  • Authentication and API key management
  • CI/CD pipeline with automated testing
  • Monitoring and alerting dashboard
  • Automated replay CLI for RECOVERY_REQUIRED leads

πŸ“Έ Project Journey

A timeline of how LeadIQ-AI evolved from concept to production.

timeline
    title LeadIQ-AI Development Timeline
    July 2026 Week 1 : Problem research & market analysis
                     : Architecture design & technology selection
    July 2026 Week 2 : v1.0 β€” Core pipeline with Supabase & Gemini AI
                     : Webhook ingestion, duplicate detection, AI scoring
    July 2026 Week 3 : v1.3 β€” Multi-channel routing & notifications
                     : Slack alerts, Gmail follow-ups, Google Sheets audit
                     : Full documentation suite & portfolio materials
    July 2026 Week 4 : Repository polish & open-source preparation
                     : Demo video, architecture diagrams, contributor guides
Loading

πŸ’­ Lessons Learned

Database-Level Deduplication > Application-Level

Moving duplicate detection from the n8n workflow into Supabase PostgreSQL RPCs eliminated race conditions entirely. Application-level checks couldn't handle concurrent webhook submissions for the same email. The database's serializable transaction isolation guarantees correctness that application logic cannot.

Structured AI Output Requires Prompt Engineering

Getting Gemini to consistently return valid JSON with exact field names (score, tier, reasoning) required iterative prompt refinement. Including explicit output schema examples and negative constraints ("do NOT include any text outside the JSON") in the prompt template achieved ~99% structured output reliability.

Google Sheets as a Stakeholder Interface

Initially considered building a custom dashboard, but Google Sheets turned out to be the highest-impact, lowest-effort solution. Sales leadership could filter, sort, and create charts without any engineering support. The tradeoff is scale β€” Sheets works perfectly for hundreds of leads per day but would need replacement at enterprise volumes.

Visual Workflow Engines Accelerate Debugging

n8n's visual execution traces made debugging production issues significantly faster than reading application logs. Being able to click on a node and see its exact input/output JSON β€” including the Gemini AI response β€” reduced mean time to diagnosis from hours to minutes.


❓ FAQ

How does duplicate detection work?

When a lead is submitted, n8n calls Supabase's reserve_lead_v1 RPC. If the normalized email was qualified within the last 10 minutes, Supabase returns status DUPLICATE_COMPLETED and the cached AI qualification output, bypassing Gemini AI completely.

Can I customize the scoring criteria?

Yes! The AI scoring logic is driven by the prompt in prompts/lead_scoring.md. You can adjust ICP definitions, company size weightings, budget thresholds, and urgency signals.

What happens if a downstream service fails?

Downstream integration statuses (Slack, Sheets, Gmail) are recorded independently. A failed notification can be retried without re-running Gemini AI scoring. If the worker crashes mid-execution, the processing lease expires after 15 minutes, marking the record RECOVERY_REQUIRED.


πŸ”§ Troubleshooting

Common issues and solutions
Symptom Root Cause Resolution
500 Internal Error on webhook Supabase key or URL missing Ensure SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY are set in .env and passed to n8n via docker-compose.yml
Gemini API timeout Invalid API key or network block Verify LLM_API_KEY in .env and test connectivity to generativelanguage.googleapis.com
Duplicate not cached Email normalization issue Ensure input email is lowercased; check lead_reservations table in Supabase Studio
Slack alert not received Bot token permissions Verify the Slack bot has chat:write scope for the target channel

🀝 Contributing

Contributions are welcome! See the Contributing Guide for:

  • πŸ“‹ Prerequisites and development environment setup
  • πŸš€ Step-by-step onboarding (clone β†’ install β†’ configure β†’ run β†’ test)
  • πŸ“ Commit message conventions
  • πŸ’‘ Contribution ideas

Important

The core n8n workflow and Supabase schema are in a production freeze. Community contributions are welcome for documentation, tests, diagrams, and examples.


πŸ“š Documentation

Document Description
Architecture System architecture, component breakdown, data flow
API Specification Webhook endpoints, request/response schemas
Workflow Guide n8n node-by-node pipeline execution guide
Setup Guide Installation, configuration, and deployment
Database Guide Supabase schema, RPCs, and state model
Engineering Decisions Architecture decision records with rationale
Limitations Known tradeoffs and future improvements
Demo Guide Step-by-step demonstration walkthrough
Docker Setup Docker Compose deployment guide
Environment Config Complete environment variable reference
Production Checklist Pre-deployment verification checklist
Test Results System validation and test outcomes

πŸ“œ License

Distributed under the MIT License. See LICENSE for details.


πŸ™ Acknowledgements

  • n8n β€” Open-source workflow automation platform
  • Supabase β€” Open-source Firebase alternative with PostgreSQL
  • Google Gemini AI β€” Multimodal AI model for lead scoring
  • Google Sheets API β€” Audit trail and stakeholder reporting
  • Slack API β€” Real-time team notifications
  • Gmail API β€” Automated email dispatch
  • Docker β€” Containerization and deployment

Built with ❀️ for modern sales teams

⭐ Star this repo if you found it useful!