Introduction
In our last session, you mastered architectural patterns for handling high-volume data, preparing you to build systems that are not just functional but also scalable and resilient. Now, we begin Phase 4: High-Value Portfolio Systems. This is where you transition from learning foundational patterns to architecting and building your first client-ready asset: the AI Lead Intelligence Engine.
Today's objective is to design the brain of this system: a multi-factor lead scoring algorithm with weighted criteria. Your previous lead qualification system used simple conditional logic (Hot/Warm/Cold). We are now engineering a quantitative, dynamic, and far more intelligent system. A robust scoring algorithm is what turns a simple automation into a high-value "intelligence engine" that clients will pay for, as it directly impacts their sales prioritization and efficiency.
This lesson requires you to think like an architect first and an implementer second. You will define the business logic before writing any code, a critical discipline in professional engineering.
Deconstructing the Scoring Algorithm
A multi-factor scoring algorithm translates disparate data points about a lead into a single, actionable numerical score. This is analogous to a credit score, but for sales qualification. The more data points you synthesize, and the more intelligently you weigh them, the more accurate the prediction.
These data points fall into three categories:
- Explicit Data: Information the lead provides directly (e.g., from a form: job title, company name).
- Implicit Data: Information inferred from the lead's behavior (e.g., visited the pricing page, downloaded a case study).
- Enriched Data: Information appended from third-party sources (e.g., company size, revenue, tech stack retrieved via an API).
A professional-grade algorithm combines these data types using weighted criteria.
The Hybrid Scoring Model: AI Nuance + Rule-Based Control
A simple rule-based system (IF company_size > 50, score +10) is transparent but rigid. An AI-only system can understand nuance (e.g., a "Coordinator" at a startup might be a decision-maker) but can be a "black box."
We will implement a hybrid model, which is the industry best practice:
- AI Base Score: Use an AI model to perform a qualitative analysis and provide a baseline score (0-100).
- Rule-Based Adjustments: Use a Code node to make deterministic adjustments to the AI's score based on your most critical, non-negotiable business rules.
This approach gives you the best of both worlds: the contextual understanding of AI and the predictable control of code.
Step 1: Design the Scoring Blueprint
Before you build, you must design. This is your first architectural task for the project.
Scenario: Your client is a B2B SaaS company that sells project management software. Their Ideal Customer Profile (ICP) is:
- Companies: Mid-sized (50-500 employees).
- Industries: Technology, Marketing Agencies, Professional Services.
- Decision-Makers: Project Managers, Heads of Operations, C-level executives.
- Pain Points: They are likely using spreadsheets or a competitor's legacy software (e.g., MS Project).
System Design Task 1: Define Scoring Criteria
Based on the client's ICP, define the factors, values, and weights for your scoring algorithm. Create a simple table in a text editor or spreadsheet to document your logic. This table is your blueprint.
| Factor | Condition | Weight (Points) |
|---|---|---|
| Company Size | 50-500 employees (Ideal) | +20 |
| > 500 employees (Enterprise, longer sale) | +5 | |
| < 50 employees (Too small) | -15 | |
| Industry | In ['Technology', 'Marketing', 'Services'] | +15 |
| Not in target list | -5 | |
| Job Title | Contains 'Manager', 'Head', 'Director', 'VP', 'C-level' | +25 |
| Contains 'Coordinator', 'Assistant', 'Intern' | -10 | |
| Lead Source | 'Demo Request' or 'Pricing Page' | +20 |
| 'Webinar' or 'Whitepaper' | +10 | |
| 'Contact Us' (Generic) | +5 |
Deliverable: A completed table with your chosen factors and weights. You can use the one above as a starting point, but feel free to add or modify criteria (e.g., a penalty for freemail domains like @gmail.com).
Step 2: Implement the Hybrid Algorithm
Now, translate your design into an n8n workflow. The following resources provide the exact patterns you need to implement this.
How to Build an AI-Powered Lead Qualification Agent with n8n
The article 'How to Build an AI-Powered Lead Qualification Agent with n8n' by Atherial.ai provides a perfect template for the hybrid scoring model. Focus on how it separates AI analysis from rule-based adjustments.
Read the sections 'Step 3: AI-Powered Qualification Analysis' and 'Step 4: Calculate Final Lead Score'. Pay close attention to: The AI Prompt: Notice how the system prompt defines the ICP for the AI model. The Hybrid Logic: See how 'Step 4' takes the AI's base score ($json.score) and then programmatically adds or subtracts points using a Function node. This is the exact pattern we are implementing.
The article uses a Function node. Since you are comfortable with JavaScript, we will use the more modern and powerful Code node.
Practical Task: Build the Scoring Workflow
Objective: Create an n8n workflow that takes raw lead data and outputs a final, weighted score using the hybrid model.
-
Workflow Setup:
-
Create a new workflow named
[P1] Lead Scoring Algorithm. -
Node 1: Code (Input Data): To start, use a Code node to provide mock input data. This allows you to test your logic without needing a live webhook. Set it to 'Run Once'.
// Mock data representing different lead profiles const leads = [ // Ideal Lead { "name": "Jane Doe", "jobTitle": "VP of Operations", "company": "TechSolutions Inc.", "employeeCount": 250, "industry": "Technology", "leadSource": "Demo Request" }, // Mediocre Lead { "name": "John Smith", "jobTitle": "Marketing Coordinator", "company": "Creative Co.", "employeeCount": 75, "industry": "Marketing", "leadSource": "Webinar" }, // Poor Lead { "name": "Sam Jones", "jobTitle": "Student", "company": "University", "employeeCount": 1000, "industry": "Education", "leadSource": "Contact Us" } ]; return leads.map(lead => ({ json: lead }));
-
-
Node 2: Split In Batches: Add a
Split In Batchesnode with the default batch size of 1 to process each lead individually. -
Node 3: AI Agent (Base Score):
- Add an
AI AgentorOpenAInode. - Model: Use a capable model (e.g., GPT-4o, Claude 3 Sonnet).
- Prompting:
- Set the System Prompt to define the AI's role and the ICP from your design document.
You are a B2B lead qualification expert for a SaaS company selling project management software. Your task is to analyze a lead and provide a baseline qualification score from 0 to 100 based on their fit with our Ideal Customer Profile: mid-sized tech/marketing companies (50-500 employees) and decision-making roles. - Set the User Prompt to pass the lead data from the previous node.
Analyze this lead and provide a score. Lead Data: {{ JSON.stringify($json) }}
- Set the System Prompt to define the AI's role and the ICP from your design document.
- Output Formatting: To ensure a predictable numeric output, use the Add Output Formatting > Use JSON Format option. Provide an example to guide the model:
{ "ai_score": 85, "reasoning": "The lead is a VP at a mid-sized tech company, which is a strong fit." } - Constraint Note: If you lack access to a paid AI service, you can simulate this step. Replace the AI node with a Code node that returns a mock AI score, allowing you to focus on the rule-based logic:
// Mock AI Output Node $item.json.ai_score = Math.floor(Math.random() * 40) + 40; // Random score between 40-80 $item.json.reasoning = "This is a simulated AI analysis."; return $item;
- Add an
-
Node 4: Code (Weighted Scoring Logic):
-
This is the core of the task. Add a Code node that will execute your custom scoring blueprint.
-
Use the JavaScript from the Atherial.ai article as a reference, but adapt it to the criteria you designed.
// Start with the AI's base score // Use a default of 50 if the AI fails to provide a score let finalScore = $json.ai_score || 50; const scoreBreakdown = { aiBase: finalScore, sizeAdj: 0, industryAdj: 0, titleAdj: 0 }; // --- COMPANY SIZE ADJUSTMENT --- const employees = $json.employeeCount; if (employees >= 50 && employees <= 500) { finalScore += 20; scoreBreakdown.sizeAdj = 20; } else if (employees > 500) { finalScore += 5; scoreBreakdown.sizeAdj = 5; } else { finalScore -= 15; scoreBreakdown.sizeAdj = -15; } // --- INDUSTRY ADJUSTMENT --- const targetIndustries = ['technology', 'marketing', 'services']; if (targetIndustries.some(ind => $json.industry.toLowerCase().includes(ind))) { finalScore += 15; scoreBreakdown.industryAdj = 15; } else { finalScore -=5; scoreBreakdown.industryAdj = -5; } // --- JOB TITLE ADJUSTMENT --- // Implement your job title logic here... // ... // Cap the score at 100 and floor at 0 finalScore = Math.max(0, Math.min(100, finalScore)); // Determine final tier let finalTier; if (finalScore >= 80) { finalTier = 'Hot'; } else if (finalScore >= 60) { finalTier = 'Warm'; } else { finalTier = 'Cold'; } // Return a structured output object $item.json.finalScore = finalScore; $item.json.finalTier = finalTier; $item.json.scoreBreakdown = scoreBreakdown; return $item;
-
Execution & Verification:
Execute the workflow. Inspect the output of the final Code node for each of the three test leads.
- Does the "Ideal Lead" have a high score and a "Hot" tier?
- Does the "Poor Lead" have a low score and a "Cold" tier?
- Does the
scoreBreakdownobject accurately reflect the adjustments made?
Deliverable:
Export the JSON of your completed workflow.
Conclusion
You have now designed and implemented the intellectual core of your first portfolio project. You have moved beyond simple branching logic to a quantitative, weighted, and hybrid scoring system that mirrors professional-grade automation.
Key Takeaways:
- Design Before Building: Defining the ICP and scoring criteria in a blueprint is a critical architectural step that ensures clarity and purpose.
- Hybrid is Superior: Combining AI's contextual nuance with rule-based deterministic control creates a robust and intelligent scoring model.
- Structured Output is Key: Returning a detailed JSON object with the final score, tier, and breakdown makes the data immediately usable for downstream actions like routing, reporting, and CRM updates.
The scoring algorithm is only as good as the data it receives. In our next lesson, we will focus on implementing a data enrichment process using free APIs to automatically gather the crucial data points (like company size and industry) that fuel this engine.