DEV Community

Cover image for Building a Multi-Agent System from Scratch
Emma thomas
Emma thomas

Posted on

Building a Multi-Agent System from Scratch

The future of AI isn't a single powerful model — it's teams of specialized agents working together.
Multi-agent systems (MAS) can divide complex problems, debate solutions, critique each other, and deliver better results than a single LLM prompt.
In this tutorial, we'll build a complete multi-agent system from scratch using Python, focusing on core concepts before using any fancy framework.

What We’ll Build

A research and content creation team consisting of 4 agents:

  • Planner Agent — Breaks down the task
  • Researcher Agent — Gathers information
  • Writer Agent — Creates the content
  • Critic Agent — Reviews and improves output

Prerequisites

  • Python 3.10+
  • OpenAI API key (or any LLM provider)
  • Basic understanding of Python classes and APIs

`Step 1: Define the Agent Class
Pythonfrom openai import OpenAI
from typing import List, Dict
import json

client = OpenAI()

class Agent:
def init(self, name: str, role: str, tools=None):
self.name = name
self.role = role
self.tools = tools or []
self.memory = []

def think(self, prompt: str) -> str:
    """Core reasoning method"""
    messages = [
        {"role": "system", "content": f"You are {self.name}, a {self.role}."},
        *self.memory,
        {"role": "user", "content": prompt}
    ]

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages,
        temperature=0.7
    )

    answer = response.choices[0].message.content
    self.memory.append({"role": "assistant", "content": answer})
    return answer
Enter fullscreen mode Exit fullscreen mode


Step 2: Create Specialized Agents
Pythonplanner = Agent("Planner", "expert project planner")
researcher = Agent("Researcher", "senior technical researcher")
writer = Agent("Writer", "technical content writer")
critic = Agent("Critic", "experienced editor and quality assurance expert")`

Step 3: Implement Communication & Collaboration
Pythondef run_multi_agent_task(task: str, max_rounds=3):
print(f"🎯 Starting task: {task}\n")

# Round 1: Planning
plan = planner.think(f"Break down this task into clear steps: {task}")
print(f"📋 Planner:\n{plan}\n")

` # Round 2: Research
research_prompt = f"""
Task: {task}
Plan: {plan}
Gather relevant, up-to-date, and accurate information.
"""
research = researcher.think(research_prompt)
print(f"🔍 Researcher:\n{research[:500]}...\n")

# Round 3: Writing
draft_prompt = f"""
Create high-quality content based on:
Task: {task}
Research: {research}
"""
draft = writer.think(draft_prompt)
print(f"✍️ Writer Draft:\n{draft[:600]}...\n")

` # Round 4: Criticism & Improvement
critique_prompt = f"""
Review and improve this content:
{draft}

Focus on accuracy, clarity, engagement, and technical depth.
Return the final improved version.
"""
final_output = critic.think(critique_prompt)

print("✅ Final Output:\n")
print(final_output)
return final_output``
Enter fullscreen mode Exit fullscreen mode

Step 4: Run the System
Pythonif __name__ == "__main__":
task = "Write a comprehensive guide on building multi-agent systems in 2026"
result = run_multi_agent_task(task)

Key Learnings

  • Role Specialization dramatically improves output quality.
  • Memory (conversation history) allows agents to stay context-aware.
  • Critic agents act as a powerful quality control layer.
  • Sequential + iterative collaboration often outperforms parallel execution for complex tasks.

Advanced Improvements You Can Add

  • Tool Use (search, code execution, file I/O)
  • Dynamic Agent Creation based on task complexity
  • Debate System (agents argue to reach better conclusions)
  • LangGraph / CrewAI integration for production
  • Vector Memory using embeddings for long-term recall

Conclusion

Building multi-agent systems from scratch helps you deeply understand the architecture before adopting frameworks like CrewAI, AutoGen, LangGraph, or MetaGPT.
The real power emerges when agents can plan, critique, use tools, and iterate together.

Next Steps:

  • Add real web search tools
  • Implement supervisor/worker hierarchy
  • Build a UI with Streamlit or Gradio

Would you like to see a CrewAI version of this same system in the next post? Let me know in the comments!

Top comments (0)