How to Build a Proactive Pre-Emptive Churn Prevention Agent with Intelligent Observation and Strategy Formation
AI

How to Build a Proactive Pre-Emptive Churn Prevention Agent with Intelligent Observation and Strategy Formation

MarkTechPost
MarkTechPostDec 23, 2025

Why It Matters

Proactive churn detection reduces revenue loss and boosts retention, giving SaaS firms a competitive edge. Embedding AI with human approval ensures personalized, compliant outreach at scale.

How to Build a Proactive Pre-Emptive Churn Prevention Agent with Intelligent Observation and Strategy Formation

In this tutorial, we build a fully functional Pre‑Emptive Churn Agent that proactively identifies at‑risk users and drafts personalized re‑engagement emails before they cancel. Rather than waiting for churn to occur, we design an agentic loop in which we observe user inactivity, analyze behavioral patterns, strategize incentives, and generate human‑ready email drafts using Gemini. We orchestrate the entire process step by step, ensuring each component, from data simulation to manager approval, works seamlessly together.

Full code: https://github.com/Marktechpost/AI-Tutorial-Codes-Included/blob/main/Agentic%20AI%20Codes/preemptive_churn_agent_Marktechpost.ipynb


import os

import time

import json

import random

from datetime import datetime, timedelta

from typing import List, Dict, Any

import textwrap



try:

   import google.generativeai as genai

except ImportError:

   !pip install -q -U google-generativeai

   import google.generativeai as genai



from google.colab import userdata

import getpass

We set up our environment, import all required libraries, and ensure Gemini is available for use. The initialization is kept minimal so the rest of the system loads cleanly.


def setup_gemini():

   print("---  Security Check ---")

   try:

       api_key = userdata.get('GEMINI_API_KEY')

   except:

       print("Please enter your Google Gemini API Key:")

       api_key = getpass.getpass("API Key: ")

   if not api_key:

       raise ValueError("API Key is required to run the agent.")

   genai.configure(api_key=api_key)

   return genai.GenerativeModel('gemini-2.5-flash')



class MockCustomerDB:

   def __init__(self):

       self.today = datetime.now()

       self.users = self._generate_mock_users()



   def _generate_mock_users(self) -> List[Dict]:

       profiles = [

           {"id": "U001", "name": "Sarah Connor", "plan": "Enterprise",

            "last_login_days_ago": 2, "top_features": ["Reports", "Admin Panel"], "total_spend": 5000},

           {"id": "U002", "name": "John Smith", "plan": "Basic",

            "last_login_days_ago": 25, "top_features": ["Image Editor"], "total_spend": 50},

           {"id": "U003", "name": "Emily Chen", "plan": "Pro",

            "last_login_days_ago": 16, "top_features": ["API Access", "Data Export"], "total_spend": 1200},

           {"id": "U004", "name": "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) -> List[Dict]:

       return [u for u in self.users if u['last_login_days_ago'] >= threshold_days]

We configure authentication for Gemini and construct a mock customer database that behaves like a real system. The simulated users have varying levels of inactivity to generate realistic churn scenarios.


class ChurnPreventionAgent:

   def __init__(self, model):

       self.model = model



   def analyze_and_strategize(self, user: Dict) -> Dict:

       print(f"   ...  Analyzing strategy for {user['name']}...")

       prompt = f"""

       You are a Customer Success AI Specialist.

       Analyze this user profile and determine the best 'Win-Back Strategy'.

       USER PROFILE:

       - Name: {user['name']}

       - Plan: {user['plan']}

       - Days Inactive: {user['last_login_days_ago']}

       - Favorite Features: {', '.join(user['top_features'])}

       - Total Spend: ${user['total_spend']}

       TASK:

       1. Determine the 'Churn Probability' (Medium/High/Critical).

       2. Select a specific INCENTIVE.

       3. Explain your reasoning briefly.

       OUTPUT FORMAT:

       {{

           "risk_level": "High",

           "incentive_type": "Specific Incentive",

           "reasoning": "One sentence explanation."

       }}

       """

       try:

           response = self.model.generate_content(prompt)

           clean_json = response.text.replace("```json", "").replace("```", "").strip()

           return json.loads(clean_json)

       except Exception as e:

           return {

               "risk_level": "Unknown",

               "incentive_type": "General Check-in",

               "reasoning": f"Analysis failed: {str(e)}"

           }



   def draft_engagement_email(self, user: Dict, strategy: Dict) -> str:

       print(f"   ...   Drafting email for {user['name']} using '{strategy['incentive_type']}'...")

       prompt = f"""

       Write a short, empathetic, professional re-engagement email.

       TO: {user['name']}

       CONTEXT: They haven't logged in for {user['last_login_days_ago']} days.

       STRATEGY: {strategy['incentive_type']}

       REASONING: {strategy['reasoning']}

       USER HISTORY: They love {', '.join(user['top_features'])}.

       TONE: Helpful and concise.

       """

       response = self.model.generate_content(prompt)

       return response.text

The analytical core evaluates user behavior and selects win‑back strategies. Gemini interprets signals such as inactivity and usage patterns to determine risk and appropriate incentives. The next step drafts personalized re‑engagement emails that are empathetic, concise, and aligned with each user’s history.

We then simulate a manager dashboard where a human reviewer can approve or reject the drafted email, keeping the workflow realistic and ensuring the agent’s actions remain aligned with human judgment.

Finally, we orchestrate the full system: scanning for at‑risk users, analyzing them, drafting messages, and routing everything for approval. The result is a complete churn‑prevention pipeline that observes, reasons, drafts, and involves a human reviewer before any action is taken. This demonstrates how agentic workflows can transform customer‑success operations by enabling timely, personalized, and scalable interventions.


Author: Asif Razzaq

CEO, Marktechpost Media Inc.

Asif Razzaq is the CEO of Marktechpost Media Inc. As a visionary entrepreneur and engineer, he is committed to harnessing the potential of artificial intelligence for social good. His most recent endeavor is the launch of an AI media platform, Marktechpost, which provides in‑depth coverage of machine‑learning and deep‑learning news that is both technically sound and accessible to a wide audience. The platform receives over 2 million monthly views.

Comments

Want to join the conversation?

Loading comments...