Introduction
In our last lesson, we established the architectural foundation for multi-agent collaboration by implementing a shared blackboard. This pattern provides a decoupled, asynchronous space for agents to share information. Now, we will build upon that foundation by defining a structured protocol for interaction within that space. This brings us to this lesson's objective: Implement a multi-agent debate pattern where agents critique each other's work to converge on a solution.
The core idea is that adversarial collaboration—constructive critique and iterative refinement—can lead to more robust and accurate outcomes than a single agent working in isolation. This pattern is particularly effective for complex problem-solving, analysis, or generation tasks where initial solutions may contain subtle flaws or biases. We will explore how to orchestrate this debate from first principles, focusing on the state transitions and control flow that make it possible.
1. The Principle of Iterative Refinement
Before diving into the implementation, let's establish the intuition behind the debate pattern. A single LLM, no matter how powerful, can produce plausible but incorrect answers. By introducing multiple agents who analyze and critique each other's reasoning, we can create a system that is more likely to self-correct.
The following video provides a clear, high-level overview of this concept using simple math problems. It demonstrates how two agents, by exchanging their rationales, can converge on a correct answer even when one or both are initially wrong.
Debating AI Agents: How LLMs Work Together to Solve Complex Problems
This video from the Don Woodlock channel, "Debating AI Agents," introduces the core concept of using multiple LLMs to improve accuracy through mutual critique and reconsideration.
Watch the segments that explain the motivation and mechanics of the debate: First, get the core idea from to solve math problems. Next, see the first example where one agent corrects its mistake after seeing another's rationale, from ask a few of them. Finally, observe a multi-round debate where agents go back and forth before converging, from that I ran. Focus on the iterative nature of the process: generate, critique, reconsider, and repeat.
As the video highlights, this process introduces a non-deterministic workflow. We don't know in advance how many rounds it will take for the agents to reach an agreement. This requires us to design a control loop that can manage the debate until a specific condition—such as consensus or a maximum number of rounds—is met.
2. A Structured Debate Workflow
To implement this pattern robustly, we need to formalize the flow of the debate. A typical multi-agent debate follows a sequence of well-defined rounds.
Let's break down these stages:
- Round 1: Initial Answers. Each participating agent independently generates its initial response or solution to the given problem. This ensures a diversity of starting points.
- Round 2: Critique & Discussion. The agents' initial answers are shared. Each agent is then prompted to critique the responses of the others, identifying potential flaws, questioning assumptions, or proposing alternatives.
- Round 3: Revision of Answers. Based on the critiques received, each agent is given a chance to defend its original position or revise its answer. This is where synthesis and self-correction occur.
- Subsequent Rounds (Optional). The cycle of critique and revision can be repeated for multiple rounds. The debate continues until the agents' positions converge, a predefined quality bar is met, or a maximum number of iterations is reached.
- Finalization. Once the debate concludes, a final answer is determined. If the agents reached a consensus, that becomes the output. If not, a separate decision mechanism is needed, such as a final vote, a summary generated by a moderator agent, or selecting the answer from the last round's most highly-rated agent.
3. Implementation from First Principles
In line with your preference for building from scratch, we will now implement a debate system using only basic LLM API calls and software engineering patterns. The following resource provides an excellent, framework-free guide.
Multi-agent debate with state pattern from scratch | Yixin Tian
This blog post by Yixin Tian walks through a complete implementation of a three-agent debate (proponent, opponent, neutral) without relying on any orchestration frameworks like LangGraph or CrewAI. It perfectly aligns with our course's philosophy.
Read through the entire article, from the introduction to the conclusion. The author demonstrates three distinct methods for managing the state transition—i.e., how to decide which agent speaks next. Pay close attention to these three implementation patterns: String Matching: A simple but brittle approach. Tool Calling: A more structured method using function calling schemas. Structured Output: The most robust approach, using the model's ability to generate guaranteed JSON.
This article provides a superb hands-on guide. Let's crystallize the key architectural takeaways and connect them to our previous lessons.
Agent Roles and State Management
The implementation begins by defining distinct agent personas ("proponent," "opponent," "neutral") using system prompts. This directly applies the principles from our first module.
The DebateContext class introduced in the article serves as a simple, in-memory blackboard. It holds the shared state of the debate: the proposition, the list of agents, and the message history. In the previous lesson, we discussed implementing a blackboard with a message queue for production-grade systems. The DebateContext object is the logical equivalent; in a distributed system, you would replace this in-memory object with writes and reads to a shared, persistent store like Redis or Kafka.
Each round of the debate would correspond to a new message or a new version of a state object being published to the blackboard.
Orchestrating Turns: State Transition Mechanisms
The most critical part of the debate is the control flow—the turn-taking. The article's exploration of three methods for state transition is particularly valuable.
- String Matching (Regex): The agent includes a phrase like "Transition to opponent" in its text response, and the orchestrator parses this. This is easy to implement but fragile. It tightly couples the agent's natural language output to the control flow logic.
- Tool Calling: The agent is given a
handoff(next_agent)tool. The LLM's output is a tool call, which the orchestrator executes to pass control. This is a significant improvement as it separates the debate content from the control signal. We covered the fundamentals of tool calling in Module 1. - Structured Output (Recommended): The LLM is instructed to respond with a JSON object conforming to a Pydantic schema, such as
{"response": "...", "next_agent": "..."}. This is the most robust and production-ready pattern. It provides a clean, machine-readable separation of concerns and eliminates parsing errors. As noted in Module 1, this capability is a powerful tool for building reliable agentic workflows.
For a production system, Structured Output is the preferred method for managing state transitions in a debate, as it provides the most reliable contract between the agent's reasoning and the orchestration logic.
4. Advanced Patterns and Considerations
The basic debate pattern can be extended and refined for more complex scenarios.
Moderated Debates
The example in the blog post implements a "peer-to-peer" debate where agents hand off to each other directly. An alternative is a hierarchical or moderated debate. In this topology, a Moderator agent acts as the orchestrator.
- The
Moderatorinitiates the debate and collects the initial responses. - It then distributes the responses and prompts the debaters for critiques.
- It collects the critiques and initiates the revision round.
- The
Moderatoris responsible for checking for convergence, enforcing debate rules (e.g., preventing repetitive arguments), summarizing the state of the debate, and making the final decision if no consensus is reached.
This pattern centralizes control, which can be useful for complex debates or when you need to ensure the discussion remains productive. This relates back to the Arbiter component we discussed in the blackboard lesson.
Grounding Debates with External Tools
A debate based solely on the internal knowledge of LLMs can devolve into plausible fictions. A more powerful approach is to allow agents to ground their arguments in external reality by using tools.
The following video, while using a specific library (PydanticAI), demonstrates this concept well. It builds two agents with opposing political views and gives each one a tool to search the internet.
I Made AI Agents DEBATE Each Other! [PydanticAI Tutorial]
This video from the Eric Roby channel, "I Made AI Agents DEBATE Each Other!", shows how to build a multi-agent system where each agent can use a web search tool to gather evidence for its arguments.
Focus on the architecture, not the specific library syntax: Watch how a researcher agent with a DuckDuckGo search tool is created from political view. Then, see the final result where each agent's response is backed by information it found online from work life balance.
By equipping your debating agents with tools—such as the web search shown in the video, a vector database for RAG (Module 5), or a code interpreter (Module 6)—you transform the debate from a philosophical discussion into a collaborative research and analysis process. Each agent's critique can be backed by retrieved evidence, dramatically improving the quality and factuality of the final output.
Conclusion
In this lesson, we have designed and specified the implementation of a multi-agent debate pattern, a powerful protocol for collaborative problem-solving. This moves us beyond simple agent chains to a more dynamic and robust form of interaction.
Key Takeaways:
- Debate as a Refinement Process: Multi-agent debate is a technique to improve the accuracy and robustness of LLM outputs through iterative critique and self-correction.
- Structured Workflow: A successful debate follows a clear workflow: initial generation, critique, revision, and a finalization/decision step.
- State Transition is Key: The mechanism for turn-taking is the core of the implementation. While regex or basic tool-calling can work for prototypes, structured output provides the most reliable control flow for production systems.
- Integration with Blackboard: The debate's shared state (message history) is a perfect use case for the blackboard architecture. Each turn corresponds to a new entry on the blackboard.
- Advanced Patterns: The basic debate can be enhanced with a
Moderatoragent for better control and by providing agents withToolsto ground their arguments in external data.
Preview of the Next Lesson:
The debate pattern we explored today is inherently sequential—agents take turns speaking. However, many complex tasks can be broken down into independent subtasks that can be executed concurrently. In our next and final lesson of this module, we will explore how to orchestrate the parallel execution of multiple agents and implement a structured result aggregation strategy, moving from sequential collaboration to parallel processing.