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.
Enterprise AI Lead Qualification & Multi-Channel Routing Pipeline
π Architecture Β· π API Spec Β· π Workflow Guide Β· π οΈ Setup Guide Β· π¬ Live Demo
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.
Watch the full pipeline in action β from lead submission to AI qualification, duplicate prevention, Slack notification, Gmail generation, and Google Sheets reporting.
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 |
|
Without LeadIQ-AI
|
With LeadIQ-AI
|
| 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 |
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.
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]
| 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 |
| 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 |
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
Pipeline stages: Webhook Ingestion β Data Normalization β Duplicate Check β AI Scoring β State Persistence β Audit Logging β Tier Routing β Slack/Gmail Dispatch
| 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 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.
| 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 |
# 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 browserNote
For detailed setup instructions including OAuth configuration, see the full Setup Guide.
| 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.examplefor a complete template with inline documentation.
- Open n8n at
http://localhost:5678 - Go to Workflows β Import from File
- Select
n8n/v2/workflows/leadiq-ai-v2.1-fixed.json - Configure credentials (Google Sheets OAuth2, Slack, Gmail) in n8n's credential manager
- Toggle the workflow to Active
# 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"
}'| 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 |
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
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.
| 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.
- 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
- 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_REQUIREDleads
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
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.
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.
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 |
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.
| 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 |
Distributed under the MIT License. See LICENSE for details.
- 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!