Agent Message Bus

Medium
Agents

Implement message bus for agent communication:

  1. subscribe(agent_id, topic): Add agent to topic subscribers
  2. unsubscribe(agent_id, topic): Remove from topic
  3. publish(topic, message, sender): Send to all subscribers
    • Message gets unique ID and timestamp
    • Add to queue for each subscriber
  4. send_direct(recipient, message, sender): Point-to-point
  5. get_messages(agent_id): Retrieve and clear pending messages

Message Format: {'id': unique_id, 'sender': ..., 'content': ..., 'timestamp': ...}

Delivery: Messages stay in queue until retrieved. Retrieved messages move to delivered.

Examples

Example 1:
Input: bus = AgentMessageBus(); bus.subscribe('agent1', 'alerts'); bus.publish('alerts', 'Warning!', 'system'); len(bus.get_messages('agent1'))
Output: 1
Explanation: Subscribed agent receives published message

Starter Code

class AgentMessageBus:
    """
    Message bus for inter-agent communication.
    Supports pub/sub and direct messaging patterns.
    """
    
    def __init__(self):
        self.subscribers = {}  # topic -> [agent_ids]
        self.message_queue = []  # Pending messages
        self.delivered = []  # Delivered messages
    
    def subscribe(self, agent_id, topic):
        """Subscribe agent to topic"""
        # Your implementation here
        pass
    
    def unsubscribe(self, agent_id, topic):
        """Unsubscribe agent from topic"""
        # Your implementation here
        pass
    
    def publish(self, topic, message, sender_id):
        """
        Publish message to topic.
        Message format: {'sender': ..., 'content': ..., 'timestamp': ..., 'id': ...}
        """
        # Your implementation here
        pass
    
    def send_direct(self, recipient_id, message, sender_id):
        """Send direct message to specific agent"""
        # Your implementation here
        pass
    
    def get_messages(self, agent_id):
        """Get all pending messages for agent"""
        # Your implementation here
        pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews