🧲 Lesson 4.4: Lead Generation & CRM Integration Agent


🎯 Lesson Objective

By the end of this lesson, you will be able to:

  • Build an AI agent that automatically captures, qualifies, and stores leads

  • Integrate your agent with a CRM platform like HubSpot, Zoho, or Google Sheets

  • Generate custom follow-up emails, messages, or outreach scripts

  • Support both web-based forms and chat-based lead interactions


🧠 Why Automate Lead Generation?

Lead generation is the lifeline of sales, but it’s often:

  • 📉 Time-consuming to qualify

  • 🗂️ Disorganized without a CRM

  • 🧍‍♂️ Dependent on manual entry

An AI-powered lead agent can:

  • 🧠 Analyze visitor input (via chat or forms)

  • ✅ Score or qualify leads based on custom rules

  • 📤 Send personalized follow-ups

  • 🗃️ Store data directly in a CRM or spreadsheet


🧰 Tools You’ll Use

Tool Purpose
LangChain + LLM Understand user intent, qualify leads, write follow-ups
Streamlit or Webhooks Capture user input via a form/chat
CRM API or Google Sheets Store leads
SMTP or email-sender Send follow-up emails

🔧 Step-by-Step: Build the Lead Generation Agent


✅ 1. Create a Prompt Template to Qualify the Lead

from langchain.prompts import PromptTemplate
from langchain.llms import Ollama

llm = Ollama(model="mistral")

template = """
You are a smart sales assistant. Based on the following inquiry, determine:

1. The user's name
2. Their interest
3. Whether they are a qualified lead (yes/no)
4. A short, professional follow-up message

Inquiry: {inquiry}

Reply in JSON format with keys: name, interest, qualified, follow_up
"""

prompt = PromptTemplate(
    input_variables=["inquiry"],
    template=template
)

✅ 2. Process a New Inquiry

inquiry = "Hi, I'm Sarah from GreenTech. I'm interested in a demo of your solar tracking system."

formatted_prompt = prompt.format(inquiry=inquiry)
response = llm(formatted_prompt)

import json
lead_data = json.loads(response)

print(lead_data)

✅ 3. Save the Lead to Google Sheets or CRM

Option 1: Save to Google Sheets (Using gspread)

pip install gspread oauth2client
import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("credentials.json", scope)
client = gspread.authorize(creds)

sheet = client.open("Leads").sheet1
sheet.append_row([lead_data['name'], lead_data['interest'], lead_data['qualified'], lead_data['follow_up']])

Option 2: Save to CRM (e.g., HubSpot)

import requests

api_key = "YOUR_HUBSPOT_API_KEY"
url = "https://api.hubapi.com/crm/v3/objects/contacts"

data = {
    "properties": {
        "email": "[email protected]",
        "firstname": lead_data["name"],
        "lifecyclestage": "lead",
        "message": lead_data["interest"]
    }
}

headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
response = requests.post(url, json=data, headers=headers)
print(response.json())

✅ 4. Send Follow-Up Email Automatically

import smtplib
from email.mime.text import MIMEText

msg = MIMEText(lead_data['follow_up'])
msg['Subject'] = "Thanks for your interest!"
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"

with smtplib.SMTP('smtp.gmail.com', 587) as server:
    server.starttls()
    server.login("your_email", "your_password")
    server.sendmail(msg['From'], msg['To'], msg.as_string())

🧪 Example Use Cases

Business Type Example Inquiry Agent Output
SaaS Company “Can I get a demo of your CRM tool?” ✅ Qualified, follow-up scheduled
Coaching Service “Tell me more about your programs.” 🚫 Unqualified until more info
E-commerce B2B “Interested in buying 100+ units” ✅ High-potential lead

🧠 Advanced Features

Feature Benefit
🧠 Scoring rules Use AI or custom logic to score leads (e.g. industry, company size)
📨 Email campaigns Auto-subscribe to sequences (Mailchimp, Brevo, etc.)
📊 Analytics Track how many leads convert from each channel
🔗 Webhooks Receive leads from chatbots, Facebook Lead Ads, or Typeform
🤖 Integration with chatbot Use AI in real-time to collect lead info in a conversation

🧱 Streamlit Interface (Optional)

import streamlit as st

st.title("🔍 AI Lead Qualification Assistant")

user_input = st.text_area("Paste a new lead inquiry:")

if st.button("Analyze"):
    ai_output = llm(prompt.format(inquiry=user_input))
    st.markdown("### AI Output")
    st.json(json.loads(ai_output))

✅ Summary

Step What You Did
🧠 Used an LLM to parse inquiries Extracted lead details and decision
🧾 Saved to CRM or Google Sheets Stored leads automatically
📤 Sent personalized replies Instant follow-up
🧠 Added logic for qualification Auto-judged lead quality

🔜 Next Steps

Would you like to:

  1. 🔁 Create a lead follow-up sequence bot (with memory)?

  2. 📲 Integrate the agent into a live website chat (e.g., with Gradio or Botpress)?

  3. 💼 Train your agent on company-specific leads, services, and responses?

 

53