Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 27

Automated Tagging with Dynamic Rules

Recommended resources

Introduction

In our previous lessons, you architected a multi-factor scoring algorithm and a resilient data enrichment sub-workflow. Your AI Lead Intelligence Engine can now calculate a lead's potential value and automatically fetch critical firmographic data. However, this raw data—a score of 87, an employee count of 250-500—is not yet actionable.

Today's objective is to translate this raw data into business intelligence. You will build a dynamic tagging system that applies labels based on calculated scores and enriched data. Tags like tier-hot, size-mid-market, or industry-tech make data instantly filterable, reportable, and routable. This is the mechanism that allows a sales team to immediately identify their best opportunities or triggers different automated sequences. Mastering this is a non-negotiable skill for building production-grade automation systems for clients.


Architecting a Hybrid Tagging System

A robust tagging system is not a monolithic block of IF statements. A professional architecture uses a hybrid approach, combining deterministic rules with nuanced AI-based judgment.

  1. Deterministic Tagging: This is for clear, unambiguous conditions. It's fast, cheap, and reliable. We use it for rules like:

    • If score >= 80, tag is tier-hot.
    • If employeeCount is between 100-1000, tag is size-mid-market.
    • If industry is SaaS, tag is industry-tech.
  2. AI-driven Tagging: This is for interpreting qualitative data that lacks clear structure, such as a message from a contact form or a description of a company's business model. AI can infer intent, identify needs, or spot "buying signals" that rule-based logic would miss.

You'll implement this hybrid approach sequentially. First, apply the clear rule-based tags. Then, feed the lead profile and those initial tags to an AI model to derive more nuanced, qualitative tags.

n8n Lead Scoring and Routing Workflow
This workflow illustrates the core concept. After a lead is scored, a 'Route by Grade' node directs it to different paths. Our tagging system is a more sophisticated version of this 'grading' process, creating a rich set of labels instead of just one grade.

Core Mechanisms for Tagging in n8n

To implement your tagging system, you'll need to master a few key n8n nodes. Given your background, we'll lean on the Code node for efficiency, but it's important to understand the full toolkit.

Master N8N & AI Workflows: The 80/20 Approach

To see these core nodes in action, watch this excellent overview from Simon Scrapes. It covers the fundamental 80/20 of n8n data manipulation, which is directly applicable to our tagging logic.

Focus on these four concepts: The Set Node (08:34 - 10:04): Understand how this node is used to create new data fields. We will use this principle to add our tags array. The If Node (10:04 - 10:58): This is the basic building block for conditional logic, equivalent to an if/else statement. The Code Node (10:58 - 13:43): This is the power tool. Pay close attention to how it's used for complex data transformations that would be cumbersome with other nodes. We will use this to implement our multi-conditional tagging rules. Structured Output with AI (28:40 - 30:06): This is critical. Observe how the 'structured output parser' forces the AI to return data in a specific JSON format. This is essential for getting reliable, machine-readable tags from the AI model.


Practical Task: Implementing the Dynamic Tagger

You will now add the tagging logic to your main AI Lead Intelligence Engine workflow. This task assumes your workflow has already executed the scoring and enrichment sub-workflows, and the results (finalScore, employeeRange, naicsCode, etc.) are available on the n8n item.

1. Implement Rule-Based Tagging

Instead of chaining multiple IF or Switch nodes, you will use a single Code node. This is cleaner, more scalable, and leverages your existing development skills.

Add a Code node named Generate Rule-Based Tags:

This node will read the score and enriched data, then apply a set of deterministic tags.

// Get the current lead data from the input item
const item = $input.item.json;

// Initialize an empty array to hold our tags
let tags = [];

// 1. Score Tier Tagging
const score = item.finalScore || 0;
if (score >= 80) {
  tags.push('tier-hot');
} else if (score >= 60) {
  tags.push('tier-warm');
} else {
  tags.push('tier-cold');
}

// 2. Company Size Tagging
const employeeRange = item.employeeRange || '';
// Simple example, you can make this more granular
if (employeeRange.includes('1-50') || employeeRange.includes('1-10') || employeeRange.includes('11-50')) {
  tags.push('size-smb');
} else if (employeeRange.includes('51-200') || employeeRange.includes('201-500') || employeeRange.includes('501-1000')) {
  tags.push('size-mid-market');
} else if (employeeRange) { // Catches larger sizes
  tags.push('size-enterprise');
}

// 3. Industry Tagging (using NAICS codes for precision)
const naicsCode = item.naicsCode || '';
// Example: Codes for Software Publishers and Computer Systems Design
if (naicsCode.startsWith('5112') || naicsCode.startsWith('5415')) {
  tags.push('industry-tech');
}

// 4. Add a "Missing Data" tag if enrichment failed
if (!employeeRange && !naicsCode) {
    tags.push('status-enrichment-failed');
}

// Add the new 'tags' array to the item's JSON data
item.tags = tags;

// Return the modified item
return item;

Configuration:

  • Connect this node after the point where scoring and enrichment data have been merged.
  • Paste the code above into the node's JavaScript editor.
  • Execute and verify that the output item now includes a tags array with the correct rule-based tags.

For more advanced examples of scoring logic in JavaScript, you can refer to the scoring_logic.js file in this [GitHub repository (ID LINK)](https://github.com/tparzonka/ai-lead-scoring-qualification) and the detailed Function Node examples in this [Atherial.ai article (ID LINK)](https://www.atherial.ai/how-to-build-an-ai-powered-lead-qualification-agent-with-n8n-free-template-dxpr2e).

2. Implement AI-Driven Tagging

Now, you'll add an AI layer to identify qualitative buying signals.

Add an OpenAI node (or your preferred AI model) named Identify Buying Signals:

  • Connect this node after the Generate Rule-Based Tags node.

  • Mode: Chat Model

  • Model: gpt-4o-mini (or a similar fast, low-cost model).

  • System Prompt: Define the AI's role and constraints.

    You are an expert B2B sales analyst. Your task is to analyze a company profile and identify key buying signals. You must only respond with a JSON array of strings. The strings must be from this predefined list: ['signal-high-growth', 'signal-recent-funding', 'signal-hiring-aggressively', 'signal-competitor-user', 'signal-legacy-tech']. If no signals are found, return an empty array.
    
  • User Prompt: Pass the enriched data to the AI.

    Analyze the following company data and identify relevant buying signals.
    
    Company Name: {{ $json.companyName }}
    Description: {{ $json.description }}
    Industry: {{ $json.industry }}
    Recent News/Activity: {{ $('Enrichment-Node-Name').item.json.news_summary }} // Adjust this expression to your actual enrichment data
    
  • Crucial Step: Enforce Structured Output.

    • Under Options, enable JSON Mode. This forces the model to output valid JSON, which is essential for reliability.

3. Consolidate All Tags

Finally, merge the tags from the rule-based step and the AI-based step into a single, clean array.

Add a Code node named Consolidate Tags:

  • Connect this node after the Identify Buying Signals node.
  • The Code node will receive the item with the initial tags array, and the AI's output will be in the special $self variable (as it's the output of the node right before).
const item = $input.item.json;

// The AI's response is a JSON string. Parse it.
// The AI's full response is in item.content.
// Make sure to adjust the path based on your AI node's output structure.
let aiTags = [];
try {
  if (item.content) {
    aiTags = JSON.parse(item.content);
  }
} catch (error) {
  // If AI output is not valid JSON, log it and continue.
  console.log("AI returned non-JSON output:", item.content);
}


// Get the rule-based tags created earlier.
const ruleTags = item.tags || [];

// Combine both arrays and remove duplicates using a Set.
const finalTags = [...new Set([...ruleTags, ...aiTags])];

// Overwrite the old tags array with the final, consolidated one.
item.tags = finalTags;

// Remove the raw AI content field to keep the data clean.
delete item.content;

// Return the final item with a clean tags array.
return item;

After running this final node, your lead item will have a comprehensive, de-duplicated tags array ready for the final step of the intelligence engine.


Conclusion

You have now engineered a sophisticated, hybrid tagging system that transforms raw lead data into actionable intelligence. This is a significant step up from basic hot/warm/cold routing and demonstrates a true systems-thinking approach.

Key Takeaways:

  • Tags Bridge Data and Action: A well-designed tagging system is the critical link that enables automated routing, personalized communication, and insightful reporting.
  • Hybrid (Rules + AI) is the Professional Standard: This approach combines the reliability and speed of deterministic rules with the nuance and insight of AI analysis.
  • Code Nodes Scale: For complex conditional logic, a single Code node is often more maintainable, readable, and performant than a sprawling canvas of IF/Switch nodes.
  • Structured AI Outputs are Non-Negotiable: Always use features like JSON Mode or structured output parsers to ensure your AI provides reliable, machine-readable data. Never trust an LLM to "just format it correctly" without enforcement.

In our next lesson, you will complete the core functionality of the AI Lead Intelligence Engine. You will learn to generate a structured reporting summary for each processed lead, taking all the scores, enriched data, and dynamic tags to create a concise, human-readable brief—the final deliverable for a sales user.