1+ {
2+ "nbformat" : 4 ,
3+ "nbformat_minor" : 0 ,
4+ "metadata" : {
5+ "colab" : {
6+ "provenance" : []
7+ },
8+ "kernelspec" : {
9+ "name" : " python3" ,
10+ "display_name" : " Python 3"
11+ },
12+ "language_info" : {
13+ "name" : " python"
14+ }
15+ },
16+ "cells" : [
17+ {
18+ "cell_type" : " code" ,
19+ "source" : [
20+ " import os\n " ,
21+ " import time\n " ,
22+ " import json\n " ,
23+ " import random\n " ,
24+ " from datetime import datetime, timedelta\n " ,
25+ " from typing import List, Dict, Any\n " ,
26+ " import textwrap\n " ,
27+ " \n " ,
28+ " try:\n " ,
29+ " import google.generativeai as genai\n " ,
30+ " except ImportError:\n " ,
31+ " !pip install -q -U google-generativeai\n " ,
32+ " import google.generativeai as genai\n " ,
33+ " \n " ,
34+ " from google.colab import userdata\n " ,
35+ " import getpass"
36+ ],
37+ "metadata" : {
38+ "id" : " 2lDQkcQJoIAN"
39+ },
40+ "execution_count" : null ,
41+ "outputs" : []
42+ },
43+ {
44+ "cell_type" : " code" ,
45+ "source" : [
46+ " def setup_gemini():\n " ,
47+ " print(\" --- 🔐 Security Check ---\" )\n " ,
48+ " try:\n " ,
49+ " api_key = userdata.get('GEMINI_API_KEY')\n " ,
50+ " except:\n " ,
51+ " print(\" Please enter your Google Gemini API Key:\" )\n " ,
52+ " api_key = getpass.getpass(\" API Key: \" )\n " ,
53+ " if not api_key:\n " ,
54+ " raise ValueError(\" API Key is required to run the agent.\" )\n " ,
55+ " genai.configure(api_key=api_key)\n " ,
56+ " return genai.GenerativeModel('gemini-2.5-flash')\n " ,
57+ " \n " ,
58+ " class MockCustomerDB:\n " ,
59+ " def __init__(self):\n " ,
60+ " self.today = datetime.now()\n " ,
61+ " self.users = self._generate_mock_users()\n " ,
62+ " \n " ,
63+ " def _generate_mock_users(self) -> List[Dict]:\n " ,
64+ " profiles = [\n " ,
65+ " {\" id\" : \" U001\" , \" name\" : \" Sarah Connor\" , \" plan\" : \" Enterprise\" ,\n " ,
66+ " \" last_login_days_ago\" : 2, \" top_features\" : [\" Reports\" , \" Admin Panel\" ], \" total_spend\" : 5000},\n " ,
67+ " {\" id\" : \" U002\" , \" name\" : \" John Smith\" , \" plan\" : \" Basic\" ,\n " ,
68+ " \" last_login_days_ago\" : 25, \" top_features\" : [\" Image Editor\" ], \" total_spend\" : 50},\n " ,
69+ " {\" id\" : \" U003\" , \" name\" : \" Emily Chen\" , \" plan\" : \" Pro\" ,\n " ,
70+ " \" last_login_days_ago\" : 16, \" top_features\" : [\" API Access\" , \" Data Export\" ], \" total_spend\" : 1200},\n " ,
71+ " {\" id\" : \" U004\" , \" name\" : \" Marcus Aurelius\" , \" plan\" : \" Enterprise\" ,\n " ,
72+ " \" last_login_days_ago\" : 45, \" top_features\" : [\" Team Management\" ], \" total_spend\" : 8000}\n " ,
73+ " ]\n " ,
74+ " return profiles\n " ,
75+ " \n " ,
76+ " def fetch_at_risk_users(self, threshold_days=14) -> List[Dict]:\n " ,
77+ " return [u for u in self.users if u['last_login_days_ago'] >= threshold_days]"
78+ ],
79+ "metadata" : {
80+ "id" : " 5NXlyd9PoH0J"
81+ },
82+ "execution_count" : null ,
83+ "outputs" : []
84+ },
85+ {
86+ "cell_type" : " code" ,
87+ "source" : [
88+ " class ChurnPreventionAgent:\n " ,
89+ " def __init__(self, model):\n " ,
90+ " self.model = model\n " ,
91+ " \n " ,
92+ " def analyze_and_strategize(self, user: Dict) -> Dict:\n " ,
93+ " print(f\" ... 🧠 Analyzing strategy for {user['name']}...\" )\n " ,
94+ " prompt = f\"\"\"\n " ,
95+ " You are a Customer Success AI Specialist.\n " ,
96+ " Analyze this user profile and determine the best 'Win-Back Strategy'.\n " ,
97+ " USER PROFILE:\n " ,
98+ " - Name: {user['name']}\n " ,
99+ " - Plan: {user['plan']}\n " ,
100+ " - Days Inactive: {user['last_login_days_ago']}\n " ,
101+ " - Favorite Features: {', '.join(user['top_features'])}\n " ,
102+ " - Total Spend: ${user['total_spend']}\n " ,
103+ " TASK:\n " ,
104+ " 1. Determine the 'Churn Probability' (Medium/High/Critical).\n " ,
105+ " 2. Select a specific INCENTIVE.\n " ,
106+ " 3. Explain your reasoning briefly.\n " ,
107+ " OUTPUT FORMAT:\n " ,
108+ " {{\n " ,
109+ " \" risk_level\" : \" High\" ,\n " ,
110+ " \" incentive_type\" : \" Specific Incentive\" ,\n " ,
111+ " \" reasoning\" : \" One sentence explanation.\"\n " ,
112+ " }}\n " ,
113+ " \"\"\"\n " ,
114+ " try:\n " ,
115+ " response = self.model.generate_content(prompt)\n " ,
116+ " clean_json = response.text.replace(\" ```json\" , \"\" ).replace(\" ```\" , \"\" ).strip()\n " ,
117+ " return json.loads(clean_json)\n " ,
118+ " except Exception as e:\n " ,
119+ " return {\n " ,
120+ " \" risk_level\" : \" Unknown\" ,\n " ,
121+ " \" incentive_type\" : \" General Check-in\" ,\n " ,
122+ " \" reasoning\" : f\" Analysis failed: {str(e)}\"\n " ,
123+ " }"
124+ ],
125+ "metadata" : {
126+ "id" : " UeKD2-zNoHxS"
127+ },
128+ "execution_count" : null ,
129+ "outputs" : []
130+ },
131+ {
132+ "cell_type" : " code" ,
133+ "source" : [
134+ " def draft_engagement_email(self, user: Dict, strategy: Dict) -> str:\n " ,
135+ " print(f\" ... ✍️ Drafting email for {user['name']} using '{strategy['incentive_type']}'...\" )\n " ,
136+ " prompt = f\"\"\"\n " ,
137+ " Write a short, empathetic, professional re-engagement email.\n " ,
138+ " TO: {user['name']}\n " ,
139+ " CONTEXT: They haven't logged in for {user['last_login_days_ago']} days.\n " ,
140+ " STRATEGY: {strategy['incentive_type']}\n " ,
141+ " REASONING: {strategy['reasoning']}\n " ,
142+ " USER HISTORY: They love {', '.join(user['top_features'])}.\n " ,
143+ " TONE: Helpful and concise.\n " ,
144+ " \"\"\"\n " ,
145+ " response = self.model.generate_content(prompt)\n " ,
146+ " return response.text"
147+ ],
148+ "metadata" : {
149+ "id" : " q49A1ilFoHur"
150+ },
151+ "execution_count" : null ,
152+ "outputs" : []
153+ },
154+ {
155+ "cell_type" : " code" ,
156+ "source" : [
157+ " class ManagerDashboard:\n " ,
158+ " def review_draft(self, user_name, strategy, draft_text):\n " ,
159+ " print(\"\\ n\" + \" =\" *60)\n " ,
160+ " print(f\" 🚨 REVIEW REQUIRED: Re-engagement for {user_name}\" )\n " ,
161+ " print(f\" 🎯 Strategy: {strategy['incentive_type']}\" )\n " ,
162+ " print(f\" 📝 Risk Level: {strategy['risk_level']}\" )\n " ,
163+ " print(\" -\" * 60)\n " ,
164+ " print(\" 📨 DRAFT EMAIL:\\ n\" )\n " ,
165+ " print(textwrap.indent(draft_text, ' '))\n " ,
166+ " print(\" -\" * 60)\n " ,
167+ " print(\"\\ n[Auto-Simulation] Manager reviewing...\" )\n " ,
168+ " time.sleep(1.5)\n " ,
169+ " if strategy['risk_level'] == \" Critical\" :\n " ,
170+ " print(\" ✅ MANAGER DECISION: Approved (Priority Send)\" )\n " ,
171+ " return True\n " ,
172+ " else:\n " ,
173+ " print(\" ✅ MANAGER DECISION: Approved\" )\n " ,
174+ " return True"
175+ ],
176+ "metadata" : {
177+ "id" : " VCpqXQw9oHr0"
178+ },
179+ "execution_count" : null ,
180+ "outputs" : []
181+ },
182+ {
183+ "cell_type" : " code" ,
184+ "execution_count" : 2 ,
185+ "metadata" : {
186+ "colab" : {
187+ "base_uri" : " https://localhost:8080/" ,
188+ "height" : 1000
189+ },
190+ "id" : " dOeZcjTPmUeD" ,
191+ "outputId" : " a877205a-6143-4cd0-ca6f-8e332f32f96c"
192+ },
193+ "outputs" : [
194+ {
195+ "output_type" : " stream" ,
196+ "name" : " stdout" ,
197+ "text" : [
198+ " Initializing Agentic System...\n " ,
199+ " --- 🔐 Security Check ---\n " ,
200+ " Please enter your Google Gemini API Key:\n " ,
201+ " API Key: ··········\n " ,
202+ " \n " ,
203+ " 🔍 AGENT STATUS: Scanning Database for inactive users (>14 days)...\n " ,
204+ " Found 3 at-risk users.\n " ,
205+ " \n " ,
206+ " --- Processing Case: U002 (John Smith) ---\n " ,
207+ " ... 🧠 Analyzing strategy for John Smith...\n " ,
208+ " ... ✍️ Drafting email for John Smith using 'Feature Teaser'...\n " ,
209+ " \n " ,
210+ " ============================================================\n " ,
211+ " 🚨 REVIEW REQUIRED: Re-engagement for John Smith\n " ,
212+ " 🎯 Strategy: Feature Teaser\n " ,
213+ " 📝 Risk Level: High\n " ,
214+ " ------------------------------------------------------------\n " ,
215+ " 📨 DRAFT EMAIL:\n " ,
216+ " \n " ,
217+ " Subject: John, new Image Editor features await!\n " ,
218+ " \n " ,
219+ " Hi John,\n " ,
220+ " \n " ,
221+ " It's been a little while since you last logged in, and we wanted to share something we think you'll really appreciate, especially given how much you enjoy the Image Editor.\n " ,
222+ " \n " ,
223+ " We've been busy rolling out some exciting enhancements, designed to give you even more creative control and efficiency. Think more intuitive AI-powered tools for quicker edits, advanced layering options, and a wider array of filters to truly elevate your visuals.\n " ,
224+ " \n " ,
225+ " We believe these updates will open up new possibilities for your projects. Why not take a quick moment to explore them?\n " ,
226+ " \n " ,
227+ " Log in here to see what's new:\n " ,
228+ " [Link to your app/dashboard]\n " ,
229+ " \n " ,
230+ " Best regards,\n " ,
231+ " \n " ,
232+ " [Your Company Name]\n " ,
233+ " ------------------------------------------------------------\n " ,
234+ " \n " ,
235+ " [Auto-Simulation] Manager reviewing...\n " ,
236+ " ✅ MANAGER DECISION: Approved\n " ,
237+ " 🚀 ACTION: Email queued for sending to John Smith.\n " ,
238+ " \n " ,
239+ " \n " ,
240+ " --- Processing Case: U003 (Emily Chen) ---\n " ,
241+ " ... 🧠 Analyzing strategy for Emily Chen...\n " ,
242+ " ... ✍️ Drafting email for Emily Chen using 'Feature Teaser'...\n " ,
243+ " \n " ,
244+ " ============================================================\n " ,
245+ " 🚨 REVIEW REQUIRED: Re-engagement for Emily Chen\n " ,
246+ " 🎯 Strategy: Feature Teaser\n " ,
247+ " 📝 Risk Level: High\n " ,
248+ " ------------------------------------------------------------\n " ,
249+ " 📨 DRAFT EMAIL:\n " ,
250+ " \n " ,
251+ " Subject: Quick Update: API & Data Export Enhancements You Might Like\n " ,
252+ " \n " ,
253+ " Hi Emily,\n " ,
254+ " \n " ,
255+ " Hope you're having a productive week!\n " ,
256+ " \n " ,
257+ " We noticed it's been a little while since you last logged in, and wanted to gently check in. Given your frequent use of our API Access and Data Export functionalities, we thought you'd be particularly interested in some recent developments.\n " ,
258+ " \n " ,
259+ " We've rolled out some powerful enhancements designed to make your data exports even more robust and your API integrations more flexible. These updates could really streamline your workflow and unlock new possibilities for your data.\n " ,
260+ " \n " ,
261+ " We'd love for you to explore what's new and see how these updates can further benefit your work.\n " ,
262+ " \n " ,
263+ " [Link to Feature Updates / Blog Post / Dashboard with highlights]\n " ,
264+ " \n " ,
265+ " If there's anything we can do to help you get the most out of [Product Name], or if you have any feedback, please don't hesitate to reply.\n " ,
266+ " \n " ,
267+ " Best regards,\n " ,
268+ " \n " ,
269+ " [Your Name/Team Name]\n " ,
270+ " ------------------------------------------------------------\n " ,
271+ " \n " ,
272+ " [Auto-Simulation] Manager reviewing...\n " ,
273+ " ✅ MANAGER DECISION: Approved\n " ,
274+ " 🚀 ACTION: Email queued for sending to Emily Chen.\n " ,
275+ " \n " ,
276+ " \n " ,
277+ " --- Processing Case: U004 (Marcus Aurelius) ---\n " ,
278+ " ... 🧠 Analyzing strategy for Marcus Aurelius...\n " ,
279+ " ... ✍️ Drafting email for Marcus Aurelius using 'Free Training'...\n " ,
280+ " \n " ,
281+ " ============================================================\n " ,
282+ " 🚨 REVIEW REQUIRED: Re-engagement for Marcus Aurelius\n " ,
283+ " 🎯 Strategy: Free Training\n " ,
284+ " 📝 Risk Level: High\n " ,
285+ " ------------------------------------------------------------\n " ,
286+ " 📨 DRAFT EMAIL:\n " ,
287+ " \n " ,
288+ " Subject: Reconnecting: Personalized Team Management Training for Marcus\n " ,
289+ " \n " ,
290+ " Hi Marcus,\n " ,
291+ " \n " ,
292+ " Hope this email finds you well.\n " ,
293+ " \n " ,
294+ " We noticed it's been a little while since your last login to [Product Name]. Given your past engagement, we know how much you value the Team Management features within our platform.\n " ,
295+ " \n " ,
296+ " To ensure you're continually leveraging these tools to their fullest potential – especially with any recent updates – we'd like to offer you a complimentary, personalized training session. This session can be focused specifically on advanced Team Management functionalities or any other areas you'd like to explore, tailored to your team's unique needs.\n " ,
297+ " \n " ,
298+ " If this is something that could benefit you and your team, please reply to this email, and we'll be happy to arrange a convenient time. No obligation, of course.\n " ,
299+ " \n " ,
300+ " Looking forward to hearing from you, or seeing you back in [Product Name] soon!\n " ,
301+ " \n " ,
302+ " Best regards,\n " ,
303+ " \n " ,
304+ " [Your Name]\n " ,
305+ " [Your Title]\n " ,
306+ " [Your Company]\n " ,
307+ " ------------------------------------------------------------\n " ,
308+ " \n " ,
309+ " [Auto-Simulation] Manager reviewing...\n " ,
310+ " ✅ MANAGER DECISION: Approved\n " ,
311+ " 🚀 ACTION: Email queued for sending to Marcus Aurelius.\n " ,
312+ " \n " ,
313+ " \n "
314+ ]
315+ }
316+ ],
317+ "source" : [
318+ " def main():\n " ,
319+ " print(\" Initializing Agentic System...\" )\n " ,
320+ " try:\n " ,
321+ " model = setup_gemini()\n " ,
322+ " db = MockCustomerDB()\n " ,
323+ " agent = ChurnPreventionAgent(model)\n " ,
324+ " manager = ManagerDashboard()\n " ,
325+ " except Exception as e:\n " ,
326+ " print(f\" Setup failed: {e}\" )\n " ,
327+ " return\n " ,
328+ " \n " ,
329+ " print(\"\\ n🔍 AGENT STATUS: Scanning Database for inactive users (>14 days)...\" )\n " ,
330+ " at_risk_users = db.fetch_at_risk_users(threshold_days=14)\n " ,
331+ " print(f\" Found {len(at_risk_users)} at-risk users.\\ n\" )\n " ,
332+ " \n " ,
333+ " for user in at_risk_users:\n " ,
334+ " print(f\" --- Processing Case: {user['id']} ({user['name']}) ---\" )\n " ,
335+ " strategy = agent.analyze_and_strategize(user)\n " ,
336+ " email_draft = agent.draft_engagement_email(user, strategy)\n " ,
337+ " approved = manager.review_draft(user['name'], strategy, email_draft)\n " ,
338+ " if approved:\n " ,
339+ " print(f\" 🚀 ACTION: Email queued for sending to {user['name']}.\" )\n " ,
340+ " else:\n " ,
341+ " print(f\" 🛑 ACTION: Email rejected.\" )\n " ,
342+ " print(\"\\ n\" )\n " ,
343+ " time.sleep(1)\n " ,
344+ " \n " ,
345+ " if __name__ == \" __main__\" :\n " ,
346+ " main()"
347+ ]
348+ }
349+ ]
350+ }
0 commit comments