Pharmeasy Predictive Churn Prevention Workflow
Pharmeasy Predictive Churn Prevention Workflow - Proactive retention through behavioral analysis
Workflow Information
ID: pharmeasy_churn_prevention
Namespace: pharmeasy
Version: 1.0
Created: 2025-07-28
Updated: 2025-07-28
Tasks: 5
Quick Actions
Inputs
| Name | Type | Required | Default |
|---|---|---|---|
clevertap_account_id |
string | Required | None |
clevertap_passcode |
string | Required | None |
analysis_window_days |
integer | Optional |
30
|
target_segment |
string | Optional |
chronic_patients
|
churn_threshold |
float | Optional |
0.7
|
batch_size |
integer | Optional |
1000
|
Outputs
| Name | Type | Source |
|---|---|---|
at_risk_users |
object | Identified users at risk of churning |
retention_results |
object | Results of retention campaign execution |
behavioral_analysis |
object | User behavioral pattern analysis |
ai_retention_strategy |
object | AI-generated retention strategies |
personalized_campaigns |
object | Personalized retention campaigns created |
Tasks
identify_at_risk_users
scriptIdentify users showing early churn signals
analyze_behavioral_signals
scriptDeep dive into behavioral patterns of at-risk users
ai_retention_strategist
ai_agentAI-powered retention strategy generation
ai_personalized_campaigns
ai_agentCreate personalized retention campaigns for different user segments
execute_retention_campaigns
scriptExecute the personalized retention campaigns
YAML Source
id: pharmeasy_churn_prevention
name: Pharmeasy Predictive Churn Prevention Workflow
tasks:
- id: identify_at_risk_users
name: Identify At-Risk Users
type: script
script: "import json\nimport random\nfrom datetime import datetime, timedelta\n\
import math\n\nprint(\"\U0001F3AF PREDICTIVE CHURN PREVENTION WORKFLOW\")\nprint(\"\
=\" * 60)\nprint(\"\")\n\n# Input parameters\nsegment = \"${target_segment}\"\n\
window_days = int(\"${analysis_window_days}\")\nchurn_threshold = float(\"${churn_threshold}\"\
)\nbatch_size = int(\"${batch_size}\")\n\nprint(\"\U0001F4CA Analysis Parameters:\"\
)\nprint(f\" Target Segment: {segment}\")\nprint(f\" Analysis Window: {window_days}\
\ days\")\nprint(f\" Churn Threshold: {churn_threshold:.0%}\")\nprint(f\" \
\ Batch Size: {batch_size:,} users\")\nprint(\"\")\n\n# Simulate user cohort analysis\n\
print(\"\U0001F50D Analyzing user cohorts for churn signals...\")\n\n# Generate\
\ synthetic user data with churn indicators\nusers_analyzed = 0\nat_risk_users\
\ = []\n\n# Define churn signal patterns\nchurn_patterns = {\n \"declining_frequency\"\
: {\n \"weight\": 0.3,\n \"description\": \"Decreasing order frequency\"\
\n },\n \"reduced_aov\": {\n \"weight\": 0.2,\n \"description\"\
: \"Declining average order value\"\n },\n \"increased_cancellations\":\
\ {\n \"weight\": 0.25,\n \"description\": \"Rising cancellation\
\ rate\"\n },\n \"no_recent_activity\": {\n \"weight\": 0.15,\n \
\ \"description\": \"No activity in recent period\"\n },\n \"negative_feedback\"\
: {\n \"weight\": 0.1,\n \"description\": \"Poor ratings or complaints\"\
\n }\n}\n\n# Analyze users\nfor i in range(batch_size):\n user_id = f\"\
USER_{random.randint(100000, 999999)}\"\n \n # Calculate churn signals for\
\ this user\n signals = {}\n churn_score = 0.0\n \n # Declining frequency\n\
\ if random.random() < 0.3: # 30% show this pattern\n signals[\"declining_frequency\"\
] = {\n \"detected\": True,\n \"severity\": random.uniform(0.5,\
\ 1.0),\n \"detail\": \"Orders decreased from 4/month to 1/month\"\n\
\ }\n churn_score += churn_patterns[\"declining_frequency\"][\"\
weight\"] * signals[\"declining_frequency\"][\"severity\"]\n \n # Reduced\
\ AOV\n if random.random() < 0.25:\n signals[\"reduced_aov\"] = {\n\
\ \"detected\": True,\n \"severity\": random.uniform(0.4,\
\ 0.9),\n \"detail\": \"AOV dropped by 40% in last 30 days\"\n \
\ }\n churn_score += churn_patterns[\"reduced_aov\"][\"weight\"] * signals[\"\
reduced_aov\"][\"severity\"]\n \n # Increased cancellations\n if random.random()\
\ < 0.2:\n signals[\"increased_cancellations\"] = {\n \"detected\"\
: True,\n \"severity\": random.uniform(0.6, 1.0),\n \"detail\"\
: \"2 out of last 3 orders cancelled\"\n }\n churn_score += churn_patterns[\"\
increased_cancellations\"][\"weight\"] * signals[\"increased_cancellations\"][\"\
severity\"]\n \n # No recent activity\n days_since_last_order = random.randint(0,\
\ 60)\n if days_since_last_order > 30:\n signals[\"no_recent_activity\"\
] = {\n \"detected\": True,\n \"severity\": min(days_since_last_order\
\ / 60, 1.0),\n \"detail\": f\"No orders in {days_since_last_order}\
\ days\"\n }\n churn_score += churn_patterns[\"no_recent_activity\"\
][\"weight\"] * signals[\"no_recent_activity\"][\"severity\"]\n \n # Check\
\ if user is at risk\n if churn_score >= churn_threshold:\n # Additional\
\ user attributes for chronic patients\n user_profile = {\n \
\ \"user_id\": user_id,\n \"segment\": segment,\n \"churn_probability\"\
: round(churn_score, 2),\n \"risk_level\": \"HIGH\" if churn_score\
\ > 0.85 else \"MEDIUM\",\n \"signals_detected\": signals,\n \
\ \"days_since_last_order\": days_since_last_order,\n \"lifetime_value\"\
: random.randint(5000, 50000),\n \"total_orders\": random.randint(5,\
\ 100),\n \"member_since_days\": random.randint(90, 1000)\n \
\ }\n \n # For chronic patients, add specific attributes\n \
\ if segment == \"chronic_patients\":\n user_profile[\"chronic_conditions\"\
] = random.choice([\n [\"diabetes\", \"hypertension\"],\n \
\ [\"arthritis\", \"thyroid\"],\n [\"diabetes\"],\n \
\ [\"cardiac\", \"diabetes\"]\n ])\n user_profile[\"\
prescription_refill_due\"] = random.randint(0, 15)\n user_profile[\"\
preferred_brands\"] = random.sample(\n [\"Sun Pharma\", \"Cipla\"\
, \"Mankind\", \"Abbott\", \"Zydus\"], \n random.randint(2, 4)\n\
\ )\n \n at_risk_users.append(user_profile)\n \n \
\ users_analyzed += 1\n\n# Sort by churn probability\nat_risk_users.sort(key=lambda\
\ x: x[\"churn_probability\"], reverse=True)\n\nprint(f\"\u2713 Analyzed {users_analyzed:,}\
\ users\")\nprint(f\"\u26A0\uFE0F Found {len(at_risk_users)} at-risk users ({len(at_risk_users)/users_analyzed*100:.1f}%)\"\
)\nprint(\"\")\n\n# Risk distribution\nhigh_risk = sum(1 for u in at_risk_users\
\ if u[\"risk_level\"] == \"HIGH\")\nmedium_risk = len(at_risk_users) - high_risk\n\
\nprint(\"\U0001F4CA Risk Distribution:\")\nprint(f\" High Risk: {high_risk}\
\ users\")\nprint(f\" Medium Risk: {medium_risk} users\")\n\nif segment == \"\
chronic_patients\":\n refill_due_soon = sum(1 for u in at_risk_users if u.get(\"\
prescription_refill_due\", 30) < 7)\n print(f\" Prescription Refills Due\
\ (7 days): {refill_due_soon} users\")\n\nresult = {\n \"timestamp\": datetime.now().isoformat(),\n\
\ \"analysis_summary\": {\n \"users_analyzed\": users_analyzed,\n \
\ \"at_risk_count\": len(at_risk_users),\n \"at_risk_percentage\"\
: round(len(at_risk_users)/users_analyzed*100, 1),\n \"high_risk_count\"\
: high_risk,\n \"medium_risk_count\": medium_risk,\n \"segment\"\
: segment\n },\n \"at_risk_users\": at_risk_users[:100], # Limit output\
\ size\n \"churn_patterns_detected\": churn_patterns,\n \"next_step\": \"\
behavioral_analysis\"\n}\n\nprint(\"\")\nprint(\"\u2705 At-risk user identification\
\ complete.\")\nprint(f\"__OUTPUTS__ {json.dumps(result)}\")\n"
description: Identify users showing early churn signals
timeout_seconds: 60
- id: analyze_behavioral_signals
name: Analyze Behavioral Signals
type: script
script: "import json\nimport random\nfrom datetime import datetime, timedelta\n\n\
print(\"\")\nprint(\"\U0001F9E0 BEHAVIORAL SIGNAL ANALYSIS\")\nprint(\"=\" * 50)\n\
print(\"\")\n\n# Parse at-risk users data\nrisk_data = json.loads('${identify_at_risk_users}')\n\
at_risk_users = risk_data['at_risk_users']\nsegment = risk_data['analysis_summary']['segment']\n\
\nprint(f\"\U0001F4CA Analyzing behavioral patterns for {len(at_risk_users)} at-risk\
\ users\")\nprint(\"\")\n\n# Aggregate behavioral patterns\nbehavioral_insights\
\ = {\n \"segment\": segment,\n \"total_users_analyzed\": len(at_risk_users),\n\
\ \"common_patterns\": {},\n \"segment_specific_insights\": {},\n \"\
intervention_opportunities\": []\n}\n\n# Analyze common churn patterns\npattern_counts\
\ = {\n \"declining_frequency\": 0,\n \"reduced_aov\": 0,\n \"increased_cancellations\"\
: 0,\n \"no_recent_activity\": 0,\n \"negative_feedback\": 0\n}\n\ntotal_ltv_at_risk\
\ = 0\nrefill_opportunities = 0\n\nfor user in at_risk_users:\n total_ltv_at_risk\
\ += user['lifetime_value']\n \n # Count patterns\n for signal, data\
\ in user['signals_detected'].items():\n if data['detected']:\n \
\ pattern_counts[signal] += 1\n \n # Check for refill opportunities\
\ (chronic patients)\n if segment == \"chronic_patients\" and user.get('prescription_refill_due',\
\ 30) < 7:\n refill_opportunities += 1\n\n# Calculate pattern percentages\n\
for pattern, count in pattern_counts.items():\n behavioral_insights[\"common_patterns\"\
][pattern] = {\n \"count\": count,\n \"percentage\": round(count\
\ / len(at_risk_users) * 100, 1),\n \"severity\": \"HIGH\" if count / len(at_risk_users)\
\ > 0.5 else \"MEDIUM\"\n }\n\nprint(\"\U0001F50D Common Churn Patterns Detected:\"\
)\nsorted_patterns = sorted(\n behavioral_insights[\"common_patterns\"].items(),\
\ \n key=lambda x: x[1][\"count\"], \n reverse=True\n)\n\nfor pattern, data\
\ in sorted_patterns[:3]:\n print(f\" - {pattern.replace('_', ' ').title()}:\
\ {data['percentage']}% of users\")\n\n# Segment-specific insights\nif segment\
\ == \"chronic_patients\":\n behavioral_insights[\"segment_specific_insights\"\
] = {\n \"prescription_refill_opportunities\": refill_opportunities,\n\
\ \"avg_days_to_refill\": 10,\n \"common_chronic_conditions\": [\"\
diabetes\", \"hypertension\", \"arthritis\"],\n \"medication_adherence_risk\"\
: \"HIGH\",\n \"preferred_communication\": \"WhatsApp + SMS\"\n }\n\
\ \n print(\"\")\n print(\"\U0001F48A Chronic Patient Specific Insights:\"\
)\n print(f\" - Refill reminders needed: {refill_opportunities} users\")\n\
\ print(f\" - Medication adherence at risk\")\n\n# Identify intervention\
\ opportunities\ninterventions = []\n\n# Based on top pattern\ntop_pattern = sorted_patterns[0][0]\n\
if top_pattern == \"declining_frequency\":\n interventions.append({\n \
\ \"type\": \"re_engagement_campaign\",\n \"priority\": \"HIGH\",\n \
\ \"tactics\": [\"personalized_offers\", \"loyalty_rewards\", \"health_reminders\"\
],\n \"expected_impact\": \"25-30% reactivation\"\n })\nelif top_pattern\
\ == \"no_recent_activity\":\n interventions.append({\n \"type\": \"\
win_back_campaign\",\n \"priority\": \"HIGH\",\n \"tactics\": [\"\
return_incentive\", \"new_feature_announcement\", \"personalized_health_tips\"\
],\n \"expected_impact\": \"15-20% reactivation\"\n })\n\n# Chronic\
\ patient specific interventions\nif segment == \"chronic_patients\" and refill_opportunities\
\ > 0:\n interventions.append({\n \"type\": \"prescription_refill_reminder\"\
,\n \"priority\": \"CRITICAL\",\n \"tactics\": [\"automated_refill_alerts\"\
, \"doctor_consultation_offer\", \"home_delivery_guarantee\"],\n \"expected_impact\"\
: \"40-50% refill conversion\"\n })\n\nbehavioral_insights[\"intervention_opportunities\"\
] = interventions\nbehavioral_insights[\"total_ltv_at_risk\"] = total_ltv_at_risk\n\
behavioral_insights[\"avg_ltv_per_user\"] = round(total_ltv_at_risk / len(at_risk_users))\n\
\nprint(\"\")\nprint(f\"\U0001F4B0 Total LTV at Risk: \u20B9{total_ltv_at_risk:,}\"\
)\nprint(f\" Average LTV per User: \u20B9{behavioral_insights['avg_ltv_per_user']:,}\"\
)\n\nprint(\"\")\nprint(\"\U0001F3AF Recommended Interventions:\")\nfor intervention\
\ in interventions:\n print(f\" - {intervention['type'].replace('_', ' ').title()}\
\ ({intervention['priority']})\")\n print(f\" Expected Impact: {intervention['expected_impact']}\"\
)\n\nresult = {\n \"timestamp\": datetime.now().isoformat(),\n \"behavioral_insights\"\
: behavioral_insights,\n \"pattern_analysis\": pattern_counts,\n \"intervention_recommendations\"\
: interventions,\n \"financial_impact\": {\n \"total_ltv_at_risk\":\
\ total_ltv_at_risk,\n \"potential_revenue_loss_30d\": int(total_ltv_at_risk\
\ * 0.15),\n \"potential_revenue_recovery\": int(total_ltv_at_risk * 0.35)\n\
\ }\n}\n\nprint(\"\")\nprint(\"\u2705 Behavioral analysis complete.\")\nprint(f\"\
__OUTPUTS__ {json.dumps(result)}\")\n"
depends_on:
- identify_at_risk_users
description: Deep dive into behavioral patterns of at-risk users
timeout_seconds: 90
- id: ai_retention_strategist
name: AI Retention Strategy Generator
type: ai_agent
config:
model_client_id: retention_strategist
depends_on:
- analyze_behavioral_signals
description: AI-powered retention strategy generation
user_message: "Create retention strategies based on this analysis:\n\nAt-Risk Users:\
\ ${identify_at_risk_users.analysis_summary.at_risk_count} (${identify_at_risk_users.analysis_summary.at_risk_percentage}%)\n\
Segment: ${identify_at_risk_users.analysis_summary.segment}\n\nTop Behavioral\
\ Patterns:\n${JSON.stringify(analyze_behavioral_signals.behavioral_insights.common_patterns)}\n\
\nSegment Insights:\n${JSON.stringify(analyze_behavioral_signals.behavioral_insights.segment_specific_insights)}\n\
\nFinancial Impact:\n- LTV at Risk: \u20B9${analyze_behavioral_signals.financial_impact.total_ltv_at_risk}\n\
- Potential Loss (30d): \u20B9${analyze_behavioral_signals.financial_impact.potential_revenue_loss_30d}\n\
\nCreate targeted retention strategies focusing on chronic patient needs and medication\
\ adherence.\n"
system_message: "You are an expert retention strategist specializing in healthcare\
\ e-commerce and chronic patient management.\n\nBased on the behavioral analysis,\
\ create comprehensive retention strategies in JSON format:\n{\n \"retention_strategy\"\
: {\n \"name\": \"Strategy name\",\n \"objective\": \"Clear objective statement\"\
,\n \"target_segment\": \"segment description\",\n \"key_tactics\": [\n\
\ {\n \"tactic\": \"tactic name\",\n \"description\": \"detailed\
\ description\",\n \"implementation\": \"how to implement\",\n \"\
success_metrics\": [\"metric1\", \"metric2\"]\n }\n ],\n \"timeline\"\
: {\n \"immediate\": [\"action1\", \"action2\"],\n \"week_1\": [\"action3\"\
, \"action4\"],\n \"ongoing\": [\"action5\", \"action6\"]\n },\n \"\
personalization_approach\": \"description of personalization strategy\",\n \
\ \"expected_outcomes\": {\n \"churn_reduction\": \"percentage\",\n \
\ \"ltv_improvement\": \"percentage\",\n \"engagement_increase\": \"percentage\"\
\n }\n },\n \"segment_specific_strategies\": {\n \"chronic_patients\"\
: {\n \"medication_adherence_program\": \"description\",\n \"doctor_connect_initiative\"\
: \"description\",\n \"care_companion_features\": [\"feature1\", \"feature2\"\
]\n }\n },\n \"communication_plan\": {\n \"channels\": [\"channel1\",\
\ \"channel2\"],\n \"frequency\": \"description\",\n \"tone\": \"empathetic\
\ and supportive\"\n }\n}\n"
- id: ai_personalized_campaigns
name: AI Personalized Campaign Creator
type: ai_agent
config:
model_client_id: campaign_personalizer
depends_on:
- ai_retention_strategist
description: Create personalized retention campaigns for different user segments
user_message: 'Create personalized retention campaigns based on:
Retention Strategy: ${ai_retention_strategist.retention_strategy}
At-Risk User Profile:
- Segment: ${identify_at_risk_users.analysis_summary.segment}
- High Risk Users: ${identify_at_risk_users.analysis_summary.high_risk_count}
- Common Signals: ${JSON.stringify(analyze_behavioral_signals.pattern_analysis)}
Focus on:
1. Prescription refill reminders for chronic patients
2. Medication adherence support
3. Personalized health tips
4. Loyalty rewards for consistent users
5. Doctor consultation offers
Create 3-4 highly targeted campaigns with specific messaging for each risk level.
'
system_message: "You are an expert in creating highly personalized retention campaigns\
\ for healthcare e-commerce.\n\nCreate detailed campaign specifications in JSON\
\ format:\n{\n \"campaigns\": [\n {\n \"campaign_name\": \"descriptive\
\ name\",\n \"target_audience\": \"specific user segment\",\n \"campaign_type\"\
: \"email|sms|push|in_app|whatsapp\",\n \"personalization_variables\": [\"\
var1\", \"var2\"],\n \"message_templates\": {\n \"subject\": \"personalized\
\ subject line\",\n \"preview\": \"preview text\",\n \"body\": \"\
complete message with {personalization_variables}\",\n \"cta\": \"call\
\ to action text\"\n },\n \"offers\": [\n {\n \"type\"\
: \"discount|freebie|service\",\n \"value\": \"specific value\",\n \
\ \"conditions\": \"any conditions\"\n }\n ],\n \"timing\"\
: {\n \"send_time\": \"optimal time\",\n \"frequency\": \"how often\"\
,\n \"duration\": \"campaign duration\"\n },\n \"success_metrics\"\
: {\n \"primary_kpi\": \"metric name\",\n \"target_value\": \"specific\
\ target\"\n }\n }\n ],\n \"a_b_testing\": {\n \"test_elements\"\
: [\"element1\", \"element2\"],\n \"hypothesis\": \"what we're testing\",\n\
\ \"success_criteria\": \"how to measure success\"\n },\n \"creative_guidelines\"\
: {\n \"tone\": \"caring, supportive, medical\",\n \"imagery\": \"health-focused,\
\ trust-building\",\n \"compliance\": \"Include medical disclaimers\"\n }\n\
}\n"
- id: execute_retention_campaigns
name: Execute Retention Campaigns
type: script
script: "import json\nimport time\nimport random\nfrom datetime import datetime,\
\ timedelta\n\nprint(\"\")\nprint(\"\U0001F680 EXECUTING RETENTION CAMPAIGNS\"\
)\nprint(\"=\" * 60)\nprint(\"\")\n\n# Parse campaign data\ncampaign_data = json.loads('${ai_personalized_campaigns}')\n\
at_risk_data = json.loads('${identify_at_risk_users}')\n\ncampaigns = campaign_data.get('campaigns',\
\ [])\ntotal_at_risk = at_risk_data['analysis_summary']['at_risk_count']\n\nprint(f\"\
\U0001F4E2 Launching {len(campaigns)} personalized retention campaigns\")\nprint(f\"\
\U0001F3AF Targeting {total_at_risk} at-risk users\")\nprint(\"\")\n\nexecution_results\
\ = []\n\n# Execute each campaign\nfor idx, campaign in enumerate(campaigns[:4]):\
\ # Limit to 4 campaigns\n print(f\"Campaign {idx + 1}: {campaign.get('campaign_name',\
\ 'Retention Campaign')}\")\n print(f\" Type: {campaign.get('campaign_type',\
\ 'multi-channel')}\")\n print(f\" Audience: {campaign.get('target_audience',\
\ 'at-risk users')}\")\n \n # Simulate campaign execution\n time.sleep(0.5)\n\
\ \n # Generate realistic campaign metrics\n target_size = int(total_at_risk\
\ * random.uniform(0.3, 0.6))\n \n execution_result = {\n \"campaign_id\"\
: f\"RET_{datetime.now().strftime('%Y%m%d')}_{idx+1}\",\n \"campaign_name\"\
: campaign.get('campaign_name', f'Campaign {idx+1}'),\n \"status\": \"\
ACTIVE\",\n \"launch_time\": datetime.now().isoformat(),\n \"targeting\"\
: {\n \"audience_size\": target_size,\n \"audience_type\"\
: campaign.get('target_audience', 'at-risk segment')\n },\n \"channels_activated\"\
: campaign.get('campaign_type', 'multi-channel').split('|'),\n \"execution_metrics\"\
: {\n \"messages_queued\": target_size,\n \"messages_sent\"\
: int(target_size * 0.95),\n \"delivery_rate\": random.uniform(0.92,\
\ 0.98)\n }\n }\n \n # Add channel-specific metrics\n if 'whatsapp'\
\ in execution_result['channels_activated']:\n execution_result['whatsapp_metrics']\
\ = {\n \"opted_in_users\": int(target_size * 0.7),\n \"\
messages_sent\": int(target_size * 0.7 * 0.95),\n \"read_rate\": random.uniform(0.85,\
\ 0.95)\n }\n \n if 'push' in execution_result['channels_activated']:\n\
\ execution_result['push_metrics'] = {\n \"notifications_sent\"\
: int(target_size * 0.8),\n \"delivered\": int(target_size * 0.8 *\
\ 0.9),\n \"opened\": int(target_size * 0.8 * 0.9 * random.uniform(0.25,\
\ 0.35))\n }\n \n # Special handling for prescription refill campaigns\n\
\ if 'prescription' in campaign.get('campaign_name', '').lower() or 'refill'\
\ in campaign.get('campaign_name', '').lower():\n execution_result['refill_metrics']\
\ = {\n \"users_with_due_refills\": int(target_size * 0.4),\n \
\ \"reminders_sent\": int(target_size * 0.4),\n \"expected_refill_rate\"\
: random.uniform(0.35, 0.45)\n }\n \n execution_results.append(execution_result)\n\
\ print(f\" \u2713 Campaign launched successfully\")\n print(f\" Messages\
\ sent: {execution_result['execution_metrics']['messages_sent']:,}\")\n print(\"\
\")\n\n# Calculate projected impact\ntotal_messages_sent = sum(r['execution_metrics']['messages_sent']\
\ for r in execution_results)\nprojected_reactivations = int(total_messages_sent\
\ * random.uniform(0.08, 0.12))\nprojected_revenue_recovery = projected_reactivations\
\ * random.randint(800, 1200)\n\nprint(\"\U0001F4CA Campaign Execution Summary:\"\
)\nprint(f\" Total Campaigns: {len(execution_results)}\")\nprint(f\" Total\
\ Messages Sent: {total_messages_sent:,}\")\nprint(f\" Projected Reactivations:\
\ {projected_reactivations:,}\")\nprint(f\" Projected Revenue Recovery: \u20B9\
{projected_revenue_recovery:,}\")\n\n# Set up monitoring\nprint(\"\")\nprint(\"\
\U0001F4C8 Campaign Monitoring:\")\nprint(\" Real-time tracking: ENABLED\")\n\
print(\" A/B tests: ACTIVE\")\nprint(\" Next optimization: +2 hours\")\nprint(\"\
\ Full results expected: +24-48 hours\")\n\nfinal_result = {\n \"timestamp\"\
: datetime.now().isoformat(),\n \"execution_summary\": {\n \"campaigns_launched\"\
: len(execution_results),\n \"total_users_targeted\": total_at_risk,\n\
\ \"total_messages_sent\": total_messages_sent,\n \"channels_used\"\
: list(set(\n channel for r in execution_results \n for\
\ channel in r['channels_activated']\n ))\n },\n \"campaign_details\"\
: execution_results,\n \"projected_impact\": {\n \"reactivations_expected\"\
: projected_reactivations,\n \"revenue_recovery_expected\": projected_revenue_recovery,\n\
\ \"churn_reduction_target\": \"15-20%\",\n \"confidence_interval\"\
: \"\xB110%\"\n },\n \"monitoring_status\": {\n \"real_time_tracking\"\
: True,\n \"ab_tests_active\": True,\n \"next_checkpoint\": (datetime.now()\
\ + timedelta(hours=2)).isoformat(),\n \"full_results_eta\": (datetime.now()\
\ + timedelta(hours=48)).isoformat()\n },\n \"next_actions\": [\n \
\ \"Monitor early engagement metrics\",\n \"Optimize underperforming campaigns\"\
,\n \"Scale successful tactics\",\n \"Prepare follow-up campaigns\
\ for non-responders\"\n ]\n}\n\nprint(\"\")\nprint(\"\u2705 Retention campaigns\
\ executed successfully!\")\nprint(\"\U0001F504 Continuous optimization loop activated.\"\
)\n\nprint(f\"__OUTPUTS__ {json.dumps(final_result)}\")\n"
depends_on:
- ai_personalized_campaigns
description: Execute the personalized retention campaigns
timeout_seconds: 120
inputs:
- name: clevertap_account_id
type: string
required: true
description: CleverTap Account ID
- name: clevertap_passcode
type: string
required: true
description: CleverTap API Passcode
- name: analysis_window_days
type: integer
default: 30
description: Days to analyze for churn signals
- name: target_segment
type: string
default: chronic_patients
description: User segment to analyze (chronic_patients, regular_buyers, all)
- name: churn_threshold
type: float
default: 0.7
description: Minimum churn probability to trigger intervention (0.0-1.0)
- name: batch_size
type: integer
default: 1000
description: Maximum users to process in this batch
outputs:
at_risk_users:
type: object
source: identify_at_risk_users
description: Identified users at risk of churning
retention_results:
type: object
source: execute_retention_campaigns
description: Results of retention campaign execution
behavioral_analysis:
type: object
source: analyze_behavioral_signals
description: User behavioral pattern analysis
ai_retention_strategy:
type: object
source: ai_retention_strategist
description: AI-generated retention strategies
personalized_campaigns:
type: object
source: ai_personalized_campaigns
description: Personalized retention campaigns created
version: 1.0
namespace: pharmeasy
description: Pharmeasy Predictive Churn Prevention Workflow - Proactive retention
through behavioral analysis
model_clients:
- id: churn_analyst
config:
model: gpt-4o-mini
api_key: ${OPENAI_API_KEY}
max_tokens: 3000
temperature: 0.2
provider: openai
- id: retention_strategist
config:
model: gpt-4o-mini
api_key: ${OPENAI_API_KEY}
max_tokens: 2500
temperature: 0.3
provider: openai
- id: campaign_personalizer
config:
model: gpt-4o-mini
api_key: ${OPENAI_API_KEY}
max_tokens: 2000
temperature: 0.4
provider: openai
timeout_seconds: 3600
No executions yet. Execute this workflow to see results here.