AI-based proactive customer notification system
Reactive support is expensive: one call to the contact center = $5-15. Proactive notification prevents problems before the customer even notices them = $0.02-0.05. AI determines who, when, and what to notify to reduce incoming calls and improve NPS.
Potential Problem Detection System
import pandas as pd
import numpy as np
from anthropic import Anthropic
import json
class ProactiveNotificationEngine:
"""Детекция событий, требующих проактивного уведомления"""
NOTIFICATION_TRIGGERS = {
'delivery_delay': {
'threshold': 'expected_delivery exceeded by 1 day',
'channel': 'sms+push',
'priority': 'high'
},
'payment_failure_risk': {
'threshold': 'card expires within 30 days',
'channel': 'email',
'priority': 'medium'
},
'service_disruption': {
'threshold': 'user in affected region',
'channel': 'push+sms',
'priority': 'critical'
},
'subscription_limit_approaching': {
'threshold': 'usage > 80% of plan limit',
'channel': 'in_app+email',
'priority': 'medium'
},
'anomalous_account_activity': {
'threshold': 'login from new location',
'channel': 'email+sms',
'priority': 'high'
}
}
def detect_delivery_issues(self, orders: pd.DataFrame,
logistics_data: pd.DataFrame) -> pd.DataFrame:
"""Детекция заказов с риском задержки"""
merged = orders.merge(logistics_data, on='tracking_id', how='left')
today = pd.Timestamp.now()
# Заказы, где прогноз доставки > ожидаемая дата
merged['days_delayed'] = (
merged['estimated_delivery_updated'] - merged['expected_delivery']
).dt.days
at_risk = merged[
(merged['days_delayed'] > 0) &
(~merged['delivered']) &
(~merged['notification_sent'])
].copy()
at_risk['urgency'] = pd.cut(
at_risk['days_delayed'],
bins=[-np.inf, 1, 3, np.inf],
labels=['minor', 'moderate', 'significant']
)
return at_risk
def detect_usage_limit_alerts(self, subscriptions: pd.DataFrame) -> pd.DataFrame:
"""Клиенты, приближающиеся к лимитам подписки"""
subscriptions = subscriptions.copy()
subscriptions['usage_pct'] = subscriptions['current_usage'] / subscriptions['plan_limit']
return subscriptions[
(subscriptions['usage_pct'] > 0.80) &
(subscriptions['usage_pct'] < 1.0) &
(~subscriptions['upsell_shown'])
].sort_values('usage_pct', ascending=False)
def generate_notification(self, trigger_type: str,
customer: dict,
event_data: dict) -> dict:
"""Персонализированный текст уведомления"""
llm = Anthropic()
trigger_config = self.NOTIFICATION_TRIGGERS.get(trigger_type, {})
response = llm.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=150,
messages=[{
"role": "user",
"content": f"""Write a proactive customer notification in Russian.
Trigger: {trigger_type}
Customer: {customer.get('first_name', 'Клиент')}
Event details: {json.dumps(event_data, ensure_ascii=False)[:200]}
Write:
1. Short subject/title (push notification style, max 50 chars)
2. Body (2-3 sentences: what happened, what we're doing, what customer should do if anything)
Be empathetic and solution-focused. No corporate speak.
Return JSON: {{"title": "...", "body": "..."}}"""
}]
)
try:
content = json.loads(response.content[0].text)
except Exception:
content = {'title': 'Важная информация о вашем заказе', 'body': ''}
return {
'customer_id': customer.get('id'),
'channel': trigger_config.get('channel', 'email'),
'priority': trigger_config.get('priority', 'normal'),
'title': content.get('title'),
'body': content.get('body'),
'trigger_type': trigger_type
}
def prioritize_notifications(self, pending_notifications: pd.DataFrame) -> pd.DataFrame:
"""Приоритизация с учётом усталости от уведомлений"""
# Не спамим: не более 2 уведомлений в день на клиента
priority_order = {'critical': 0, 'high': 1, 'medium': 2, 'low': 3}
pending_notifications['priority_num'] = pending_notifications['priority'].map(priority_order)
# Сортируем и лимитируем
sorted_notifs = pending_notifications.sort_values(
['customer_id', 'priority_num']
)
# Первые 2 на клиента
result = sorted_notifs.groupby('customer_id').head(2)
return result
Proactive notifications reduce inbound support contacts by 20-35% when implemented correctly. ROI is calculated simply: (notifications sent × cost of sending) vs. (calls prevented × call cost). With a call cost of $8 and a notification cost of $0.03, preventing 0.4% of calls is enough to break even.







