DEV Community

Cover image for How to Build an AI Lead Qualification Workflow in n8n
Hashim khan
Hashim khan

Posted on

How to Build an AI Lead Qualification Workflow in n8n

Lead qualification is one of those business processes that looks simple until the number of enquiries starts increasing.

A business may receive leads from website forms, landing pages, advertising platforms, WhatsApp or other sources. Someone then needs to read each enquiry, understand what the customer wants, decide whether the lead is qualified and enter the information into a CRM.

This is a good use case for n8n + AI.

In this tutorial, we'll build a workflow with this architecture:

New Lead

Webhook

Validate Input

OpenAI

Parse Structured Output

Validate AI Response

Calculate Lead Score

Route Lead

CRM / Sales Notification

The important part is that we don't send an AI response directly into a business action. We validate the data first.

Aiotagen's current n8n implementations use n8n as an automation layer connecting CRM systems, WhatsApp, AI calling agents and other business tools.

  1. What We Are Building

Our example lead will contain:

{
"name": "John Smith",
"email": "john@example.com",
"service": "Website development",
"budget": 5000,
"urgency": "high",
"message": "We need a new website within the next month."
}

The AI will analyse the lead and return structured information such as:

{
"summary": "Business needs a new website within one month.",
"service": "Website development",
"budget": 5000,
"urgency": "high",
"score": 85,
"qualification": "high"
}

We can then use the score to decide what happens next.

For example:

Score >= 70
→ Sales notification

Score 40–69
→ Nurture sequence

Score < 40
→ Low-priority follow-up

  1. Create the Webhook

In n8n, create a new workflow and add a Webhook node.

Configure:

HTTP Method: POST
Path: /ai-lead
Response: Immediately

Your application can then send a request to the webhook.

Example JavaScript:

const response = await fetch(
"https://your-n8n-domain.com/webhook/ai-lead",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "John Smith",
email: "john@example.com",
service: "Website development",
budget: 5000,
urgency: "high",
message: "We need a new website within the next month."
})
}
);

console.log(await response.json());

The webhook becomes the entry point for the automation.

  1. Validate the Incoming Lead

Don't send incomplete data to the AI model.

Add a Code node after the Webhook.

Use:

const lead = $json;

const required = [
"name",
"email",
"service",
"message"
];

for (const field of required) {
if (
lead[field] === undefined ||
lead[field] === null ||
String(lead[field]).trim() === ""
) {
throw new Error(Missing required field: ${field});
}
}

return [
{
json: {
...lead,
budget: Number(lead.budget || 0)
}
}
];

This prevents obviously incomplete enquiries from entering the AI stage.

  1. Send the Lead to OpenAI

Next, add your OpenAI node.

The AI needs clear instructions about the output format.

A useful prompt is:

You are a lead qualification assistant.

Analyse the customer enquiry below.

Determine:

  1. What service the customer needs
  2. Their budget
  3. Their urgency
  4. A short summary
  5. A lead score from 0 to 100
  6. Qualification level

Scoring guidance:

70-100 = high-quality lead
40-69 = medium-quality lead
0-39 = low-quality lead

Return ONLY valid JSON.

Required format:

{
"summary": "string",
"service": "string",
"budget": 0,
"urgency": "low|medium|high",
"score": 0,
"qualification": "high|medium|low"
}

Customer data:

Name: {{$json.name}}
Email: {{$json.email}}
Service: {{$json.service}}
Budget: {{$json.budget}}
Urgency: {{$json.urgency}}
Message: {{$json.message}}

Structured output is important because the next nodes need predictable data.

  1. Parse the AI Response

If your AI node returns the JSON as a string, add another Code node.

const raw = $json.output;

let result;

try {
result = JSON.parse(raw);
} catch (error) {
throw new Error("AI returned invalid JSON");
}

return [
{
json: result
}
];

Now the workflow has structured data instead of an unstructured AI response.

  1. Validate the AI Output

This is one of the most important steps.

AI output should not automatically trigger CRM updates, messages or other business actions.

Use this Code node:

const required = [
"summary",
"service",
"budget",
"urgency",
"score",
"qualification"
];

const lead = $json;

for (const field of required) {
if (
lead[field] === undefined ||
lead[field] === null
) {
throw new Error(
Missing AI field: ${field}
);
}
}

const score = Number(lead.score);

if (!Number.isFinite(score)) {
throw new Error("score must be a number");
}

if (score < 0 || score > 100) {
throw new Error(
"score must be between 0 and 100"
);
}

const validLevels = [
"high",
"medium",
"low"
];

if (!validLevels.includes(lead.qualification)) {
throw new Error(
"Invalid qualification level"
);
}

return [
{
json: {
...lead,
score
}
}
];

This gives us a safety layer between the AI model and the business logic.

  1. Calculate Business Routing

Now we can decide what should happen to the lead.

For example:

const score = Number($json.score);

let route;

if (score >= 70) {
route = "sales";
} else if (score >= 40) {
route = "nurture";
} else {
route = "low_priority";
}

return [
{
json: {
...$json,
route
}
}
];

The result could look like:

{
"summary": "Customer needs website development.",
"service": "Website development",
"budget": 5000,
"urgency": "high",
"score": 85,
"qualification": "high",
"route": "sales"
}

  1. Route the Lead in n8n

Now use an IF or Switch node.

Example:

                ┌── High → Sales Team
                │
Enter fullscreen mode Exit fullscreen mode

AI Lead → Score ────┼── Medium → Nurture

└── Low → Low Priority

For a high-quality lead, you could:

Create CRM Record

Notify Sales Team

Send WhatsApp Message

Create Follow-Up Task

For a medium-quality lead:

Create CRM Record

Start Nurture Sequence

Follow Up Later

For a low-quality lead:

Store Lead

Educational Follow-Up

  1. Send the Lead to a CRM

At this stage, connect your CRM.

The exact node depends on the CRM you're using.

The data sent to the CRM could be:

{
"name": "John Smith",
"email": "john@example.com",
"service": "Website development",
"budget": 5000,
"score": 85,
"qualification": "high",
"source": "website",
"status": "new"
}

You can use n8n's CRM integrations or an HTTP Request node when the CRM provides an API.

  1. Notify the Sales Team

For high-quality leads, send an immediate notification.

Example Slack message:

🚨 New High-Quality Lead

Name: {{$json.name}}
Service: {{$json.service}}
Budget: {{$json.budget}}
Urgency: {{$json.urgency}}
AI Score: {{$json.score}}

Summary:
{{$json.summary}}

Action: Contact the lead.

You could use the same approach with email, Microsoft Teams, WhatsApp or another internal notification system.

  1. Add Human Handoff

Automation shouldn't necessarily handle every lead from beginning to end.

For example:

AI Qualification

High Score

Sales Team

Human Conversation

The AI handles the repetitive qualification work while the sales representative handles the actual sales conversation.

This is especially useful when the enquiry involves complex requirements or needs professional judgement.

  1. Final Workflow

The complete workflow now looks like this:

┌─────────────┐
│ Webhook │
└──────┬──────┘

┌─────────────┐
│ Validate │
│ Lead │
└──────┬──────┘

┌─────────────┐
│ OpenAI │
│ Qualification│
└──────┬──────┘

┌─────────────┐
│ Parse JSON │
└──────┬──────┘

┌─────────────┐
│ Validate AI │
│ Output │
└──────┬──────┘

┌─────────────┐
│ Lead Score │
└──────┬──────┘

┌──┴───┐
↓ ↓
High Medium/Low
↓ ↓
CRM Nurture

Sales Notification

This pattern is useful because the AI is only responsible for understanding and classifying the enquiry. n8n remains responsible for the actual business logic.

  1. Error Handling

Production workflows should also consider failures.

For example:

OpenAI Error

Retry

Still Failed?
↙ ↘
Yes No
↓ ↓
Human Continue
Review

You should also log:

Lead ID
Workflow execution ID
AI response
Validation result
Lead score
Final route
Error message
Timestamp

This makes the workflow much easier to debug.

  1. Security Considerations

Never put API keys directly inside Code nodes.

Use n8n's credential system for:

OpenAI
CRM
WhatsApp
Email
Slack
Other APIs

Also avoid sending unnecessary personal information to an AI model.

Only send the data required for the qualification task.

  1. Why This Pattern Works

The important architecture is:

AI = Understand
n8n = Orchestrate
Business Rules = Decide
CRM = Store
Human = Handle Complex Cases

This separation makes the automation easier to maintain.

If you change the AI model later, your CRM and business logic don't necessarily need to change.

If you change your CRM, the qualification logic can remain the same.

If the AI produces an unexpected response, validation can stop the workflow before an incorrect action is performed.

Conclusion

n8n becomes much more useful when it is treated as an orchestration layer rather than simply a collection of connected nodes.

A lead qualification workflow can combine:

Webhooks + OpenAI + JavaScript + validation + business rules + CRM + notifications

The same architecture can later be extended to WhatsApp, AI calling agents, email follow-ups and appointment booking.

The key principle is simple:

Let AI understand the data. Let deterministic automation decide what happens next.

More n8n workflow automation examples from Aiotagen:
https://aiotagen.com/n8n-workflow-automation/

Top comments (0)