Python course ยท Module 11: RAG and Multi-Agent Systems
Multi-Agent Systems
In this lesson6
Ask one model to gather information, analyze it, write an article and then criticise it too. You will get a text where everything is a little bit there and nothing is done properly, because a single prompt pulls the model in four directions at once. On the savanna nobody does everything alone either.
Multi-agent systems are an architecture where multiple specialized AI agents collaborate to solve complex tasks. It is like a herd of animals where each individual has its role - hunters, lookouts, defenders. Each agent gets its own system prompt and does one thing well.
Multi-Agent Basics
First let's agree on a vocabulary. We store roles as an Enum, a closed set of named constants, and a message between agents as a @dataclass:
from dataclasses import dataclass
from enum import Enum
from abc import ABC, abstractmethod
from openai import OpenAI
class AgentRole(Enum):
"""Agent roles in the system."""
RESEARCHER = "researcher" # Gathers information
ANALYZER = "analyzer" # Analyzes data
WRITER = "writer" # Writes content
CRITIC = "critic" # Reviews and improves
COORDINATOR = "coordinator" # Coordinates work
@dataclass
class AgentMessage:
"""Message between agents."""
sender: str
receiver: str
content: str
message_type: str = "task"AgentMessage remembers the sender, receiver, content and message type. The default type is "task", so for an ordinary assignment you do not have to pass it.
Now the base agent class. It inherits from ABC, and the system_prompt property is marked with @abstractmethod, so every subclass has to define it:
class BaseAgent(ABC):
"""Base agent class."""
def __init__(self, name: str, role: AgentRole, model: str = "gpt-4o-mini"):
self.name = name
self.role = role
self.model = model
self.client = OpenAI()
self.memory: list[AgentMessage] = []
@property
@abstractmethod
def system_prompt(self) -> str:
"""Agent's system prompt."""
pass
def process(self, message: AgentMessage) -> str:
"""Processes a message and returns a response."""
self.memory.append(message)
response = self.client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": self.system_prompt},
{"role": "user", "content": message.content}
]
)
return response.choices[0].message.contentThe process method stores the message in the agent's memory and sends two messages to the model: the system prompt with the role and the task content. You cannot create an object of BaseAgent itself, Python raises a TypeError because the system_prompt implementation is missing.
Implementing Specialized Agents
Specialized agents differ only in their prompt. The first pair is the researcher and the analyzer:
class ResearcherAgent(BaseAgent):
"""Research agent - gathers information."""
@property
def system_prompt(self) -> str:
return """You are a research agent. Your role is to:
1. Gather information on the given topic
2. Identify key facts
3. Verify sources
4. Structure knowledge
Always provide sources and categorize information."""
class AnalyzerAgent(BaseAgent):
"""Analytical agent - analyzes data."""
@property
def system_prompt(self) -> str:
return """You are an analytical agent. Your role is to:
1. Analyze provided data
2. Identify patterns and trends
3. Formulate conclusions
4. Assess risks and opportunities
Be precise and provide specific numbers."""Each class overrides only system_prompt, and the whole model-calling logic stays in BaseAgent. That is inheritance in practice: shared code once, differences in subclasses.
The second pair is the writer and the critic:
class WriterAgent(BaseAgent):
"""Writer agent - creates content."""
@property
def system_prompt(self) -> str:
return """You are a writer agent. Your role is to:
1. Create engaging content
2. Adapt style to the audience
3. Structure the text
4. Ensure clarity of message
Write concisely and stay on topic."""
class CriticAgent(BaseAgent):
"""Critic agent - reviews and improves."""
@property
def system_prompt(self) -> str:
return """You are a critic agent. Your role is to:
1. Evaluate content quality
2. Identify errors and shortcomings
3. Suggest improvements
4. Verify facts
Be constructive but honest."""The Researcher gathers information, the Analyzer analyzes it, the Writer creates content, and the Critic reviews and improves. These are typical roles in a multi-agent system. Notice that a "Destroyer that deletes files" role never appears here: an agent is there to help, not to destroy.
Agent Orchestration
Someone has to pass messages between members of the herd. That is the orchestrator's job: it registers agents and mediates every conversation:
from typing import Optional
class AgentOrchestrator:
"""Coordinator of agent work."""
def __init__(self):
self.agents: dict[str, BaseAgent] = {}
self.conversation_history: list[AgentMessage] = []
def register_agent(self, agent: BaseAgent) -> None:
"""Registers an agent in the system."""
self.agents[agent.name] = agent
print(f"Registered agent: {agent.name} ({agent.role.value})")
def send_message(
self,
sender: str,
receiver: str,
content: str
) -> str:
"""Sends a message between agents."""
if receiver not in self.agents:
raise ValueError(f"Agent {receiver} does not exist!")
message = AgentMessage(
sender=sender,
receiver=receiver,
content=content
)
self.conversation_history.append(message)
response = self.agents[receiver].process(message)
# Save response
response_message = AgentMessage(
sender=receiver,
receiver=sender,
content=response,
message_type="response"
)
self.conversation_history.append(response_message)
return responsesend_message checks that the receiver exists, stores the message in the history, calls process and stores the response as well. This keeps the whole conversation in one place.
The run_pipeline method arranges the agents in a chain where the output of one becomes the input of the next:
def run_pipeline(self, task: str) -> dict[str, str]:
"""Runs the processing pipeline."""
results = {}
# 1. Researcher gathers information
research = self.send_message("user", "researcher",
f"Gather information on: {task}")
results["research"] = research
# 2. Analyzer analyzes
analysis = self.send_message("researcher", "analyzer",
f"Analyze this information:\n{research}")
results["analysis"] = analysis
# 3. Writer creates content
draft = self.send_message("analyzer", "writer",
f"Based on the analysis, write an article:\n{analysis}")
results["draft"] = draft
# 4. Critic reviews
review = self.send_message("writer", "critic",
f"Review this article:\n{draft}")
results["review"] = review
return resultsThe order is fixed: the Researcher gathers information, the Analyzer analyzes the data, the Writer creates content, the Critic reviews. The results dictionary keeps the output of every stage, not only the last one.
All that is left is to register the four agents and run the pipeline:
# Usage
orchestrator = AgentOrchestrator()
orchestrator.register_agent(ResearcherAgent("researcher", AgentRole.RESEARCHER))
orchestrator.register_agent(AnalyzerAgent("analyzer", AgentRole.ANALYZER))
orchestrator.register_agent(WriterAgent("writer", AgentRole.WRITER))
orchestrator.register_agent(CriticAgent("critic", AgentRole.CRITIC))
results = orchestrator.run_pipeline("The future of artificial intelligence in 2025")Each agent is stored under its name, so send_message("user", "researcher", ...) lands exactly where it should.
Asynchronous Communication
Agents do not have to talk strictly in turn. You can leave them messages in an asyncio.Queue, like notes at the watering hole:
import asyncio
from typing import Callable
class AsyncAgentSystem:
"""Asynchronous agent system."""
def __init__(self):
self.agents: dict[str, BaseAgent] = {}
self.message_queue: asyncio.Queue = asyncio.Queue()
self.results: dict[str, str] = {}
async def process_messages(self) -> None:
"""Processes messages from the queue."""
while True:
message = await self.message_queue.get()
if message.content == "STOP":
break
agent = self.agents.get(message.receiver)
if agent:
response = agent.process(message)
self.results[message.receiver] = response
self.message_queue.task_done()The process_messages loop waits for a message with await, handles it, and stops when it receives the "STOP" signal.
The run_parallel_tasks method puts tasks into the queue and starts processing:
async def run_parallel_tasks(self, tasks: list[tuple[str, str]]) -> dict:
"""Runs tasks in parallel."""
# Add tasks to the queue
for agent_name, task in tasks:
await self.message_queue.put(
AgentMessage("system", agent_name, task)
)
# Add end signal
await self.message_queue.put(
AgentMessage("system", "STOP", "STOP")
)
# Start processing
await self.process_messages()
return self.results
# Parallel processing example
async def main():
system = AsyncAgentSystem()
# ... register agents ...
tasks = [
("researcher", "Research topic X"),
("analyzer", "Analyze data Y"),
]
results = await system.run_parallel_tasks(tasks)
print(results)
asyncio.run(main())To be honest: despite the name, these tasks do not run in parallel. There is a single queue consumer, and agent.process is an ordinary blocking call. Real parallelism would come from the asynchronous AsyncOpenAI client with asyncio.gather, or from asyncio.to_thread. The queue is still useful for decoupling senders from receivers.
Agent Tools
An agent that can only write is like a tracker without binoculars. Tools let it act: search a database, fetch the weather, calculate a cost. In LangChain you turn a function into a tool with the @tool decorator:
from langchain_core.tools import tool
@tool
def search_db(query: str) -> list:
"""Searches the animal observation database."""
return [f"Observation matching: {query}"]
print(search_db.name) # search_db
print(search_db.invoke("lions")) # ['Observation matching: lions']The docstring is not decoration here: the model reads it as the tool description, and without it the decorator raises an error. Parameter types tell the model which arguments to pass. An agent with tools works in a loop: it plans an action, acts, observes the result and reflects on whether to correct its course.
Agent Collaboration Patterns
Finally, three classic patterns. Chain is a sequence in which every agent passes its output to the next one:
class CollaborationPatterns:
"""Agent collaboration patterns."""
@staticmethod
def chain(agents: list[BaseAgent], initial_input: str) -> str:
"""Chain - each agent passes output to the next."""
current_output = initial_input
for agent in agents:
message = AgentMessage("system", agent.name, current_output)
current_output = agent.process(message)
return current_outputIt generalizes our run_pipeline: the list of agents can have any length.
Debate is a discussion between two agents over several rounds:
@staticmethod
def debate(agent1: BaseAgent, agent2: BaseAgent, topic: str, rounds: int = 3) -> list[str]:
"""Debate - agents discuss a topic."""
conversation = []
current = f"Discussion on: {topic}. Present your position."
for i in range(rounds):
# Agent 1
response1 = agent1.process(
AgentMessage(agent2.name, agent1.name, current)
)
conversation.append(f"{agent1.name}: {response1}")
# Agent 2 responds
response2 = agent2.process(
AgentMessage(agent1.name, agent2.name, response1)
)
conversation.append(f"{agent2.name}: {response2}")
current = response2
return conversationEach answer from one agent becomes the input of the other, and the conversation list records the whole exchange.
Consensus gathers everyone's opinions and asks one agent for a synthesis:
@staticmethod
def consensus(agents: list[BaseAgent], question: str) -> str:
"""Consensus - agents reach a common conclusion."""
opinions = []
# Collect opinions
for agent in agents:
opinion = agent.process(
AgentMessage("system", agent.name, question)
)
opinions.append(f"{agent.name}: {opinion}")
# Synthesis (use one of the agents)
synthesis_prompt = f"""Question: {question}
Agent opinions:
{chr(10).join(opinions)}
Formulate a common consensus based on these opinions."""
return agents[0].process(
AgentMessage("system", agents[0].name, synthesis_prompt)
)chr(10) is the newline character, used instead of "\n" inside the f-string. I recommend starting with a simple chain and adding debate and consensus only where one perspective really is not enough, because every round means more paid model calls.
Multi-agent systems open the door to complex AI applications. In the next lesson you will learn CrewAI - a framework for building agent teams that gives you these patterns ready-made!
Remember: a good agent system works like a herd in which everyone knows their role and the guide keeps the direction.
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is a multi-agent system?
2. Which agent role is NOT typical in a multi-agent system?
Hands-on tasks in the game
- Code editor
Implement an AgentOrchestrator
- Vertical ordering
Arrange the steps in order:
- Click in order
Arrange the agent tool definition:
- Vertical ordering
Arrange the typical processing workflow in a multi-agent system: