使用Rasa实现定时提醒后,如何向客户端(如APP)推送通知?
Great question! When building a reminder feature with Rasa that needs to alert a client app when the reminder time hits, you’ve got a few practical, production-ready approaches to choose from. Let’s break them down with actionable steps and code examples:
1. Custom Action + Background Scheduler (APScheduler)
This is the most straightforward approach for small to medium-scale deployments. You’ll use a custom Rasa action to parse the user’s reminder request, schedule a timed task, and trigger a client notification when the time comes.
Step-by-Step Implementation:
- Parse Reminder Details: Use Rasa NLU to extract the reminder message and time interval (e.g., "after one minutes" → 60 seconds delay).
- Initialize a Persistent Scheduler: Use
APSchedulerwith a persistent job store (like SQLite or Redis) to avoid losing tasks if Rasa restarts. - Schedule Notification Task: Add a job to the scheduler that calls your client’s push API when the reminder time arrives.
- Send Confirmation: Reply to the user to confirm the reminder is set.
Example Code:
from rasa_sdk import Action, Tracker from rasa_sdk.executor import CollectingDispatcher from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore import datetime import requests # Initialize scheduler with persistent storage jobstores = { 'default': SQLAlchemyJobStore(url='sqlite:///rasa_reminders.sqlite') } scheduler = BackgroundScheduler(jobstores=jobstores) scheduler.start() def trigger_client_notification(user_id: str, reminder_msg: str): # Replace this with your client's push notification API logic # Example: Call FCM/APNs for mobile apps, or WebSocket for web clients push_endpoint = "https://your-client-app.com/api/send-notification" payload = { "user_id": user_id, "title": "Reminder", "message": reminder_msg } try: requests.post(push_endpoint, json=payload) except Exception as e: # Add error logging here for debugging print(f"Failed to send notification: {str(e)}") class ActionSetReminder(Action): def name(self) -> str: return "action_set_reminder" def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: dict) -> list: # Extract parsed data from NLU (adjust based on your intent/entities) reminder_text = tracker.get_slot("reminder_message") or "Go to the meeting" delay_seconds = int(tracker.get_slot("delay_seconds")) or 60 # Schedule the notification task scheduler.add_job( trigger_client_notification, 'date', run_date=datetime.datetime.now() + datetime.timedelta(seconds=delay_seconds), args=[tracker.sender_id, reminder_text] ) dispatcher.utter_message(text=f"Got it! I'll remind you to {reminder_text} in {delay_seconds//60} minute(s).") return []
2. Rasa + External Message Queue (Redis Queue/RabbitMQ)
For distributed or high-availability setups, offload the timing logic to an external message queue. This ensures reminders survive Rasa restarts and scales better across multiple Rasa instances.
How It Works:
- Custom Action: Parse the reminder request, then send a delayed task to the message queue (e.g., Redis Queue with
rq-scheduler). - Worker Service: Run a separate worker that listens for delayed tasks. When a task is due, the worker calls the client’s push API.
- Benefits: Persistent task storage, no dependency on Rasa’s runtime, easy to scale workers.
3. Rasa X Event Scheduling (If Using Rasa X)
If you’re using Rasa X (the enterprise tooling for Rasa), you can leverage its built-in event scheduler to create timed events that trigger custom actions. This is ideal if you’re already using Rasa X for deployment and monitoring.
Key Notes for Client Notifications:
- Choose the Right Push Mechanism: For mobile apps, use FCM (Android) or APNs (iOS). For web apps, use WebSockets for real-time alerts or browser push notifications.
- User Identification: Ensure
tracker.sender_idmaps to a unique ID in your client app (e.g., user UUID) so notifications reach the correct user. - Error Handling: Add retries and logging for failed notification attempts to avoid missing reminders.
内容的提问来源于stack exchange,提问作者shaojie

