Implement message bus for agent communication:
subscribe(agent_id, topic): Add agent to topic subscribersunsubscribe(agent_id, topic): Remove from topicpublish(topic, message, sender): Send to all subscribers- Message gets unique ID and timestamp
- Add to queue for each subscriber
send_direct(recipient, message, sender): Point-to-pointget_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:
1Explanation: 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
passPython3
ReadyLines: 1Characters: 0
Ready