Quivr通知系统:邮件、短信、推送通知集成
引言:智能助手的沟通桥梁
在当今信息爆炸的时代,一个优秀的AI助手不仅需要强大的知识处理能力,更需要及时有效的通知机制。Quivr作为你的第二大脑,其通知系统扮演着至关重要的角色——它是用户与AI助手之间的沟通桥梁,确保重要信息能够及时传达,任务状态能够实时反馈。
你是否曾经遇到过:
- 文件上传完成后不知道处理状态?
- 重要任务执行失败时无法及时获知?
- 需要实时了解AI助手的操作进展?
Quivr的通知系统正是为了解决这些痛点而生,通过邮件、短信和推送通知的集成,为用户提供全方位的通知体验。
通知系统架构设计
Quivr的通知系统采用模块化设计,基于Supabase实时数据库构建,支持多种通知类型和状态管理。
核心组件架构
通知状态管理
Quivr定义了完善的通知状态枚举,确保通知的生命周期管理:
class NotificationsStatusEnum(str, Enum):
INFO = "info" # 信息通知
SUCCESS = "success" # 成功通知
WARNING = "warning" # 警告通知
ERROR = "error" # 错误通知
邮件通知集成
Resend邮件服务配置
Quivr使用Resend作为主要的邮件服务提供商,配置在CMS系统中:
// cms/quivr/config/plugins.js
module.exports = ({ env }) => ({
email: {
config: {
provider: 'strapi-provider-email-resend',
providerOptions: {
apiKey: env('RESEND_API_KEY'),
},
settings: {
defaultFrom: 'notifications@quivr.app',
defaultReplyTo: 'support@quivr.app',
},
},
},
});
邮件通知类型
| 通知类型 | 触发场景 | 邮件模板 | 优先级 |
|---|---|---|---|
| 文件处理完成 | 文件上传成功处理 | 成功状态模板 | 中 |
| 同步任务状态 | 数据同步完成 | 同步报告模板 | 中 |
| 系统警告 | 资源不足或配置问题 | 警告模板 | 高 |
| 错误报告 | 任务执行失败 | 错误详情模板 | 紧急 |
邮件发送实现
# 邮件发送工具类示例
class EmailNotifier:
def __init__(self, resend_client):
self.client = resend_client
async def send_upload_success(self, user_email, file_name, brain_name):
"""发送文件上传成功通知"""
subject = f"✅ 文件处理完成: {file_name}"
html_content = f"""
<h2>文件处理成功</h2>
<p>您的文件 <strong>{file_name}</strong> 已成功处理并添加到知识库 <strong>{brain_name}</strong>。</p>
<p>现在您可以向AI助手提问关于这个文件的内容了。</p>
"""
await self.client.emails.send({
"from": "Quivr Notifications <notifications@quivr.app>",
"to": [user_email],
"subject": subject,
"html": html_content
})
实时推送通知系统
Web推送集成
Quivr的前端实现了完整的实时通知系统,基于Supabase的实时订阅功能:
// frontend/lib/api/notification/useNotificationApi.ts
export const useNotificationApi = () => {
const supabase = useSupabaseClient();
// 实时订阅通知
const subscribeToNotifications = (userId: string, callback: (payload: any) => void) => {
return supabase
.channel('notifications')
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'notifications',
filter: `user_id=eq.${userId}`
},
callback
)
.subscribe();
};
// 获取用户通知
const getNotifications = async (userId: string) => {
const { data, error } = await supabase
.from('notifications')
.select('*')
.eq('user_id', userId)
.order('datetime', { ascending: false });
return { data, error };
};
};
通知状态管理
// 前端通知状态管理
interface NotificationState {
notifications: Notification[];
unreadCount: number;
isLoading: boolean;
}
const useNotificationStore = create<NotificationState>((set, get) => ({
notifications: [],
unreadCount: 0,
isLoading: false,
// 标记通知为已读
markAsRead: async (notificationId: string) => {
const { error } = await supabase
.from('notifications')
.update({ read: true })
.eq('id', notificationId);
if (!error) {
set(state => ({
notifications: state.notifications.map(n =>
n.id === notificationId ? { ...n, read: true } : n
),
unreadCount: Math.max(0, state.unreadCount - 1)
}));
}
},
}));
短信通知集成
短信服务配置
虽然Quivr主要专注于邮件和推送通知,但系统架构支持短信通知的扩展:
# 短信通知抽象层
class SMSNotifier:
def __init__(self, provider_config):
self.provider = self._get_provider(provider_config)
def _get_provider(self, config):
# 支持多个短信服务商:Twilio、阿里云、腾讯云等
if config['provider'] == 'twilio':
return TwilioProvider(config)
elif config['provider'] == 'aliyun':
return AliyunSMSProvider(config)
# 其他提供商...
async def send_urgent_notification(self, phone_number, message):
"""发送紧急短信通知"""
return await self.provider.send_sms(phone_number, message, priority='high')
短信通知场景
| 场景类型 | 内容模板 | 触发条件 | 优先级 |
|---|---|---|---|
| 安全警报 | 【Quivr】检测到异常登录尝试 | 异地登录检测 | 紧急 |
| 服务中断 | 【Quivr】系统维护通知,预计耗时X分钟 | 计划维护 | 高 |
| 额度提醒 | 【Quivr】您的API额度即将用完 | 额度使用率>90% | 中 |
通知分类与优先级系统
通知分类体系
Quivr的通知系统支持多种分类,便于用户过滤和管理:
-- 通知表结构
CREATE TABLE notifications (
id UUID PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id),
bulk_id UUID,
status status NOT NULL DEFAULT 'info',
title TEXT NOT NULL,
description TEXT,
archived BOOLEAN NOT NULL DEFAULT false,
read BOOLEAN NOT NULL DEFAULT false,
datetime TIMESTAMP,
category TEXT,
brain_id UUID,
-- 索引优化
CONSTRAINT notifications_user_id_idx ON (user_id),
CONSTRAINT notifications_status_idx ON (status),
CONSTRAINT notifications_datetime_idx ON (datetime DESC)
);
优先级处理逻辑
class NotificationPriority:
@staticmethod
def determine_priority(status, category):
priority_map = {
'error': {
'security': 'urgent',
'sync': 'high',
'upload': 'high',
'*': 'high'
},
'warning': {
'quota': 'high',
'performance': 'medium',
'*': 'medium'
},
'success': {
'upload': 'low',
'sync': 'low',
'*': 'low'
},
'info': {
'system': 'low',
'*': 'lowest'
}
}
return priority_map.get(status, {}).get(category,
priority_map.get(status, {}).get('*', 'lowest'))
实战:文件上传通知流程
完整通知流程
代码实现示例
# 文件上传通知处理
async def handle_file_upload_notification(file_upload: FileUpload, user: User):
# 创建初始通知
notification = CreateNotification(
user_id=user.id,
status=NotificationsStatusEnum.INFO,
title=f"处理文件: {file_upload.filename}",
description="文件正在处理中,请稍候...",
category="upload"
)
notification_record = notification_service.add_notification(notification)
try:
# 异步处理文件
process_file_task = process_file_and_notify.delay(
file_upload.id,
notification_id=notification_record.id
)
# 实时推送到前端
await notify_frontend(notification_record)
except Exception as e:
# 错误处理
error_notification = NotificationUpdatableProperties(
status=NotificationsStatusEnum.ERROR,
description=f"文件处理失败: {str(e)}"
)
notification_service.update_notification_by_id(
notification_record.id, error_notification
)
# 发送错误邮件
email_notifier.send_upload_error(
user.email, file_upload.filename, str(e)
)
性能优化与最佳实践
批量通知处理
# 批量通知优化
class BulkNotificationHandler:
def __init__(self):
self.bulk_id = uuid.uuid4()
self.notifications = []
def add_notification(self, user_id, title, description, status):
self.notifications.append({
'user_id': user_id,
'bulk_id': self.bulk_id,
'title': title,
'description': description,
'status': status
})
async def send_bulk(self):
"""批量发送通知,减少数据库操作"""
if not self.notifications:
return
# 批量插入数据库
await self._bulk_insert()
# 批量发送邮件
await self._send_bulk_emails()
async def _bulk_insert(self):
# 使用Supabase批量插入
response = supabase.table('notifications').insert(self.notifications).execute()
return response
实时性能优化
| 优化策略 | 实施方法 | 效果提升 |
|---|---|---|
| 批量操作 | 减少数据库往返次数 | 50-70% |
| 连接池 | 使用数据库连接池 | 30-40% |
| 缓存 | 高频数据缓存 | 60-80% |
| 索引优化 | 合理设计数据库索引 | 40-60% |
安全与隐私考虑
数据保护措施
- 端到端加密:所有敏感通知内容在传输过程中加密
- 权限控制:基于RLS(Row Level Security)的行级安全策略
- 审计日志:所有通知操作记录审计日志
- 数据最小化:只收集必要的通知元数据
RLS安全策略
-- 行级安全策略
CREATE POLICY "allow_user_all_notifications"
ON "public"."notifications"
AS PERMISSIVE
FOR ALL
TO public
USING (user_id = auth.uid());
总结与展望
Quivr的通知系统通过邮件、短信和推送通知的有机集成,为用户提供了全方位、实时、可靠的通知体验。系统设计注重性能、安全和可扩展性,支持多种通知场景和优先级处理。
未来发展方向:
- 增加更多通知渠道(如Slack、Teams集成)
- 实现智能通知路由和去重
- 开发移动端推送通知
- 增强通知模板自定义能力
通过不断完善通知系统,Quivr致力于成为最懂用户需求的AI助手,让每一次交互都更加顺畅、每一次通知都更加精准。
立即体验Quivr通知系统:开始上传文件或配置数据同步,亲身体验智能通知带来的便捷!
下一篇预告:我们将深入探讨Quivr的实时数据处理管道,揭秘如何实现毫秒级的知识检索和响应。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



