PubSub
Publish-subscribe messaging
Agents can use publish-subscribe messaging to communicate with each other and external systems.
Quick Start
- Simple Usage
typescript import { createPubSub } from 'praisonai'; const pubsub = createPubSub(); // Subscribe to topic pubsub.subscribe('orders', (event) => { console.log('New order:', event.data); }); // Publish message pubsub.publish('orders', { id: '123', total: 99.99 }); - With Configuration
typescript const agent1 = new Agent({ pubsub, onComplete: (result) => { pubsub.publish('task.done', result); } }); pubsub.subscribe('task.done', (event) => { agent2.chat(`Process: ${event.data}`); });
User Interaction Flow
Configuration Levels
// Level 1: Function - Simple create
const pubsub = createPubSub();
// Level 2: Dict - With options
const pubsub = createPubSub({
maxListeners: 100,
wildcard: true
});
// Level 3: Instance - Full control
import { EventEmitterPubSub } from 'praisonai';
const pubsub = new EventEmitterPubSub({
maxListeners: 100,
wildcard: true,
delimiter: '.',
onError: (err) => console.error(err)
});Use Cases
| Pattern | Description |
|---|---|
| Events | Notify when things happen |
| Decoupling | Components don’t know each other |
| Broadcasting | Send to multiple listeners |
| Queuing | Process messages asynchronously |
API Reference
EventEmitterPubSubPubSub implementation
Best Practices
Use descriptive topics
user.created is clearer than event1.
Handle errors
Subscribers should handle their own errors.
Unsubscribe when done
Prevent memory leaks by cleaning up.