On this tutorial, we construct a totally practical Pre-Emptive Churn Agent that proactively identifies at-risk customers and drafts customized re-engagement emails earlier than they cancel. Quite than ready for churn to happen, we design an agentic loop by which we observe person inactivity, analyze behavioral patterns, strategize incentives, and generate human-ready electronic mail drafts utilizing Gemini. We orchestrate your entire course of step-by-step, guaranteeing every part, from information simulation to supervisor approval, works seamlessly collectively. Try the FULL CODES right here.
import os
import time
import json
import random
from datetime import datetime, timedelta
from typing import Checklist, Dict, Any
import textwrap
strive:
import google.generativeai as genai
besides ImportError:
!pip set up -q -U google-generativeai
import google.generativeai as genai
from google.colab import userdata
import getpassWe arrange the environment, import all required libraries, and guarantee Gemini is out there to be used. We hold the initialization minimal so the remainder of the system hundreds cleanly. As we run it, we put together the muse for the agent-driven workflow that follows. Try the FULL CODES right here.
def setup_gemini():
print("--- 🔐 Safety Verify ---")
strive:
api_key = userdata.get('GEMINI_API_KEY')
besides:
print("Please enter your Google Gemini API Key:")
api_key = getpass.getpass("API Key: ")
if not api_key:
elevate ValueError("API Secret's required to run the agent.")
genai.configure(api_key=api_key)
return genai.GenerativeModel('gemini-2.5-flash')
class MockCustomerDB:
def __init__(self):
self.right now = datetime.now()
self.customers = self._generate_mock_users()
def _generate_mock_users(self) -> Checklist[Dict]:
profiles = [
{"id": "U001", "name": "Sarah Connor", "plan": "Enterprise",
"last_login_days_ago": 2, "top_features": ["Reports", "Admin Panel"], "total_spend": 5000},
{"id": "U002", "title": "John Smith", "plan": "Fundamental",
"last_login_days_ago": 25, "top_features": ["Image Editor"], "total_spend": 50},
{"id": "U003", "title": "Emily Chen", "plan": "Professional",
"last_login_days_ago": 16, "top_features": ["API Access", "Data Export"], "total_spend": 1200},
{"id": "U004", "title": "Marcus Aurelius", "plan": "Enterprise",
"last_login_days_ago": 45, "top_features": ["Team Management"], "total_spend": 8000}
]
return profiles
def fetch_at_risk_users(self, threshold_days=14) -> Checklist[Dict]:
return [u for u in self.users if u['last_login_days_ago'] >= threshold_days]We configure authentication for Gemini and assemble a mock buyer database that behaves like an actual system. We simulate customers with various ranges of inactivity to generate reasonable churn situations. Try the FULL CODES right here.
class ChurnPreventionAgent:
def __init__(self, mannequin):
self.mannequin = mannequin
def analyze_and_strategize(self, person: Dict) -> Dict:
print(f" ... 🧠 Analyzing technique for {person['name']}...")
immediate = f"""
You're a Buyer Success AI Specialist.
Analyze this person profile and decide one of the best 'Win-Again Technique'.
USER PROFILE:
- Identify: {person['name']}
- Plan: {person['plan']}
- Days Inactive: {person['last_login_days_ago']}
- Favourite Options: {', '.be part of(person['top_features'])}
- Whole Spend: ${person['total_spend']}
TASK:
1. Decide the 'Churn Chance' (Medium/Excessive/Important).
2. Choose a selected INCENTIVE.
3. Clarify your reasoning briefly.
OUTPUT FORMAT:
{{
"risk_level": "Excessive",
"incentive_type": "Particular Incentive",
"reasoning": "One sentence rationalization."
}}
"""
strive:
response = self.mannequin.generate_content(immediate)
clean_json = response.textual content.substitute("```json", "").substitute("```", "").strip()
return json.hundreds(clean_json)
besides Exception as e:
return {
"risk_level": "Unknown",
"incentive_type": "Common Verify-in",
"reasoning": f"Evaluation failed: {str(e)}"
}We construct the analytical core of our churn agent to guage person habits and choose win-back methods. We let Gemini interpret indicators, comparable to inactivity and utilization patterns, to find out threat and incentives. Try the FULL CODES right here.
def draft_engagement_email(self, person: Dict, technique: Dict) -> str:
print(f" ... ✍️ Drafting electronic mail for {person['name']} utilizing '{technique['incentive_type']}'...")
immediate = f"""
Write a brief, empathetic, skilled re-engagement electronic mail.
TO: {person['name']}
CONTEXT: They have not logged in for {person['last_login_days_ago']} days.
STRATEGY: {technique['incentive_type']}
REASONING: {technique['reasoning']}
USER HISTORY: They love {', '.be part of(person['top_features'])}.
TONE: Useful and concise.
"""
response = self.mannequin.generate_content(immediate)
return response.textual contentWe generate customized re-engagement emails based mostly on the technique output from the earlier step. We use Gemini to craft concise, empathetic messaging that aligns with every person’s historical past. Try the FULL CODES right here.
class ManagerDashboard:
def review_draft(self, user_name, technique, draft_text):
print("n" + "="*60)
print(f"🚨 REVIEW REQUIRED: Re-engagement for {user_name}")
print(f"🎯 Technique: {technique['incentive_type']}")
print(f"📝 Threat Stage: {technique['risk_level']}")
print("-" * 60)
print("📨 DRAFT EMAIL:n")
print(textwrap.indent(draft_text, ' '))
print("-" * 60)
print("n[Auto-Simulation] Supervisor reviewing...")
time.sleep(1.5)
if technique['risk_level'] == "Important":
print("✅ MANAGER DECISION: Authorised (Precedence Ship)")
return True
else:
print("✅ MANAGER DECISION: Authorised")
return TrueWe simulate a supervisor dashboard the place human oversight approves or rejects the drafted electronic mail. We hold the stream easy however reasonable, guaranteeing the agent’s actions stay aligned with human judgment. Try the FULL CODES right here.
def predominant():
print("Initializing Agentic System...")
strive:
mannequin = setup_gemini()
db = MockCustomerDB()
agent = ChurnPreventionAgent(mannequin)
supervisor = ManagerDashboard()
besides Exception as e:
print(f"Setup failed: {e}")
return
print("n🔍 AGENT STATUS: Scanning Database for inactive customers (>14 days)...")
at_risk_users = db.fetch_at_risk_users(threshold_days=14)
print(f"Discovered {len(at_risk_users)} at-risk customers.n")
for person in at_risk_users:
print(f"--- Processing Case: {person['id']} ({person['name']}) ---")
technique = agent.analyze_and_strategize(person)
email_draft = agent.draft_engagement_email(person, technique)
accredited = supervisor.review_draft(person['name'], technique, email_draft)
if accredited:
print(f"🚀 ACTION: E-mail queued for sending to {person['name']}.")
else:
print(f"🛑 ACTION: E-mail rejected.")
print("n")
time.sleep(1)
if __name__ == "__main__":
predominant()We orchestrate the complete system: scanning for at-risk customers, analyzing them, drafting messages, and routing the whole lot for approval. We convey all elements collectively into one steady loop.
In conclusion, we have now accomplished a churn-prevention pipeline that observes, causes, drafts, and entails a human reviewer earlier than motion. We watch the agent detect threat patterns, craft tailor-made methods, and generate skilled emails, all whereas sustaining human oversight for closing choices. This implementation demonstrates how agentic workflows can remodel buyer success operations by enabling well timed, customized, and scalable interventions. We now have a modular basis we will develop additional, connecting it to actual databases, CRMs, internet dashboards, or automation methods, to construct a really production-ready churn prevention engine.
Try the FULL CODES right here. Additionally, be at liberty to comply with us on Twitter and don’t neglect to hitch our 100k+ ML SubReddit and Subscribe to our Publication. Wait! are you on telegram? now you’ll be able to be part of us on telegram as properly.
Asif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is dedicated to harnessing the potential of Synthetic Intelligence for social good. His most up-to-date endeavor is the launch of an Synthetic Intelligence Media Platform, Marktechpost, which stands out for its in-depth protection of machine studying and deep studying information that’s each technically sound and simply comprehensible by a large viewers. The platform boasts of over 2 million month-to-month views, illustrating its recognition amongst audiences.