Lesson 3: Multi-Agent Collaboration
Code multi-agent networks where dedicated agent personas collaborate, review, and solve tasks together.
By Bishwambhar Sen • Last updated • 90 min
A single agent, no matter how powerful the underlying LLM, suffers from cognitive overload when forced to act as researcher, coder, quality assurance tester, and writer simultaneously. **Multi-Agent Collaboration** solves this by dividing complex tasks among a team of specialized agents, each with a distinct system prompt, toolset, and communication protocol.
The Power of Specialization
Just as software organizations thrive on the division of labor (PMs, engineers, testers), AI architectures produce vastly superior results when models are siloed into narrow personas. Specialization reduces the size of system prompts, narrows the selection of tools (minimizing tool-selection errors), and structures the execution path through clear checkpoints.
Standard Multi-Agent Topologies
Depending on the complexity of your task, agent interactions can be configured in several distinct network structures:
1. Sequential Hand-Off (Pipeline)
A linear workflow where Agent A performs task A, formats the result, and passes it as context to Agent B. Example: Researcher Agent (gathers facts) → Copywriter Agent (writes draft) → Editor Agent (fixes grammar).
2. Hierarchical (Orchestrator-Workers)
A centralized Supervisor Agent receives the user's prompt, breaks it down into subtasks, delegates them to specialized Worker Agents, evaluates their returns, and synthesizes the final result.
3. Collaborative Dialogues (Critique Loop)
Two or more agents engage in a multi-turn conversation to iteratively polish a deliverable. Example: Developer Agent writes code → Reviewer Agent critiques bug flaws → Developer Agent patches code.
Managing Conversation State
How do agents share information? There are two primary paradigms:
- Centralized Shared State: All agents read and write to a single global history thread or a shared blackboard. This is simple to code, but as conversations grow, it consumes large quantities of context tokens.
- Explicit Message Passing: Agents operate in isolated context sandboxes and communicate strictly by sending structured payloads (such as JSON messages) to each other. This keeps context clean and allows for parallel computations.
Coding a Collaborative Critique Loop in Python
Below is a complete, working script that implements a multi-turn Writer & Editor Critique Loop. The Writer drafts a short technical article, the Editor audits it for improvements, and the Writer synthesizes a revised draft.
import google.generativeai as genai
# Setup system prompts for distinct personalities
WRITER_PROMPT = """You are a brilliant tech writer. Write a clear, engaging paragraph on the topic requested.
At the end of the text, append '[DRAFT_FINISHED]'.
If you are revising a draft based on feedback, incorporate the feedback carefully and append '[REVISED_FINISHED]'.
"""
EDITOR_PROMPT = """You are a critical copyeditor. Review the provided draft.
List exactly 3 highly actionable bullet-point improvements regarding clarity, tone, and depth.
If the draft is already exceptionally polished, say 'Looks perfect!'
"""
def run_critique_loop(topic: str):
# Initialize the client models
writer_model = genai.GenerativeModel("gemini-1.5-flash", system_instruction=WRITER_PROMPT)
editor_model = genai.GenerativeModel("gemini-1.5-flash", system_instruction=EDITOR_PROMPT)
# 1. First Turn: Writer drafts the content
print("🤖 Writer: Generating initial draft...")
writer_response = writer_model.generate_content(f"Write about: {topic}")
draft = writer_response.text
print(f"\n--- INITIAL DRAFT ---\n{draft}\n")
# 2. Second Turn: Editor reviews the draft
print("🔍 Editor: Auditing the draft...")
editor_response = editor_model.generate_content(f"Review this draft:\n\n{draft}")
feedback = editor_response.text
print(f"\n--- EDITOR FEEDBACK ---\n{feedback}\n")
# 3. Third Turn: Writer revises based on feedback
print("🤖 Writer: Refining text according to critique...")
revision_prompt = f"""Your initial draft was:
{draft}
The editor gave this feedback:
{feedback}
Please revise your draft accordingly.
"""
revision_response = writer_model.generate_content(revision_prompt)
final_output = revision_response.text
print(f"\n--- FINAL POLISHED DRAFT ---\n{final_output}\n")
run_critique_loop("The invention of Transistors in 1947")
Interactive Playroom: Collaboration Challenges
Let's expand the collaboration pipeline in your workspace. You will build a three-agent consensus structure:
- [ ]Task 1: Define a
ResearcherAgentsystem prompt that specializes in producing raw, bulleted factual summaries on technical topics. - [ ]Task 2: Define a
MarketingWriterAgentthat turns factual bullet lists into highly persuasive, benefits-focused copy. - [ ]Task 3: Implement a sequential hand-off chain. Feed a user query to the Researcher, gather their fact list, and forward it directly to the Marketing Writer.
- [ ]Task 4: Add a third agent, the
FactAuditorAgent. The Auditor takes the Marketing Writer's copy AND the Researcher's original facts, identifies any marketing exaggerations (hallucinations) that deviate from the research list, and prints a compliance report.
With the knowledge of tool use, planning loops, and multi-agent coordination under your belt, it's time to build! In the final lesson of this course, you will build an autonomous, file-writing software engineering agent from scratch as your **capstone project**!