Inter-agent communication

When agents need to collaborate without a fixed pipeline, they need a way to send messages to each other. The inter-agent communication pattern provides a hub where agents can send, receive, and process messages, enabling dynamic collaboration.

Communication hub architecture

Multi-agent coordination uses a fixed pipeline (A then B then C). Inter-agent communication is dynamic: any agent can message any other agent through a hub, enabling flexible collaboration without a predefined order.

patterns/15_inter_agent_communication.py
python
class Message:
    def __init__(self, sender, recipient, content, msg_type="request"):
        self.sender = sender
        self.recipient = recipient
        self.content = content
        self.msg_type = msg_type

class CommunicationHub:
    def __init__(self):
        self.agents = {}
        self.message_history = []

    def register_agent(self, agent):
        self.agents[agent.name] = agent

    def send_message(self, sender, recipient, content, msg_type="request"):
        message = Message(sender, recipient, content, msg_type)
        self.agents[recipient].receive_message(message)
        self.message_history.append(message)
        return message

    def process_all_messages(self):
        responses = []
        for agent in self.agents.values():
            agent_responses = agent.process_messages()
            responses.extend(agent_responses)
        # Deliver responses back
        for response in responses:
            self.agents[response.recipient].receive_message(response)

A CommunicationHub that routes messages between named agents.

Quiz: Quiz

Loading practice…

Matching exercise: Match communication concepts

Loading practice…

Flashcards: Flashcards

Loading practice…

Your agents can now communicate dynamically through a message hub. Next, we will optimize resource usage by routing tasks to the right model based on complexity.