Skip to main content

04 - Multi-Agent Coding: LangGraph, CrewAI and AutoGen

When several agents are really needed for programming: two texts compared, a unit defect that was run, and a LangGraph graph with a reviewer that runs the code.

What do you think about this article?

04 - Multi-Agent Coding: LangGraph, CrewAI and AutoGen
Vibe CodingPhoto:SiddePexels

At a Glance

When several agents are really needed for programming: two texts compared, a unit defect that was run, and a LangGraph graph with a reviewer that runs the code.

04 - Multi-Agent Coding: LangGraph, CrewAI and AutoGen

For code, more agents are almost never the first choice: they add cost, and the defect they bring is harder to see than the one they solve. Those who defend them and those who criticize them, in two texts published a few days apart, agree on one thing: the problem is not how many agents you have, but whether they share the context and whether each result has a check. In this article you see why, run two examples that show the typical defect and the remedy, and understand when a second agent pays for itself.

The examples use LangGraph because it lets you write the path between agents and the cap on turns explicitly. For CrewAI and AutoGen you find in the text what matters for deciding, and pointers to the articles on this blog where their code was run. No model is called: the "agents" in the examples are scripted functions, because what is being studied is the structure around the model. Before this it helps to have read Agentic workflows: decomposing problems.

What the people who build them and the people who advise against them say, with their numbers

In the post on its own multi-agent research system (13 June 2025), Anthropic writes that in its data agents use on average about four times the tokens of a chat conversation, and multi-agent systems about fifteen times. From this it concludes that you need tasks of high enough value to pay for that consumption, and adds a point that directly concerns people who write software: domains where all agents must share the same context, or where there are many dependencies between agents, are not a good fit today, and most coding tasks have fewer truly parallelizable parts than research. The number holds for that system and that data, not for your project, but the order of magnitude says where to look: the cost of a second agent is not marginal.

Walden Yan, of Cognition, on 12 June 2025 reaches the same conclusion by another road, in a text titled Don't Build Multi-Agents. His two principles are that you must share context, including the full traces of the agents and not just individual messages, and that actions carry implicit decisions, so conflicting decisions carry bad results. For this reason he recommends, as a starting point, ruling out the architectures that violate them and starting from a single-threaded linear agent, which he says goes very far. He acknowledges the limit: for very long tasks the context fills up, and you need a way to compress the history, which is hard to get right.

To decide whether you need a second agent, the two positions boil down to three questions to ask in this order:

  • Are the parts truly independent, that is, does none depend on a decision made by another?
  • Does the value of the task justify token consumption of another order of magnitude?
  • Does each part have an automatic check that does not depend on the agent that produced it?

If even one answer is no, you do not need the second agent yet. The third question is the most neglected, and the one the rest of the article insists on: an agent that "reviews" another model's work, without running it, is an opinion, not a check, and two agreeing opinions do not make a proof.

The typical defect: two assumptions that go unseen

The principle of implicit decisions can be shown in thirty lines. Two "workers" write two files without seeing each other: the cart adds up prices and returns them in cents, the invoice formats an amount as euros with two decimals. Each has made a reasonable assumption about units, and each has its own unit test, which passes. The two workers are written by me as strings of code (they are not generated by a model): the defect is realistic, because unstated units are among the most common errors when two parts are written separately.

contract.py - two different assumptions, one contract that aligns them
# Two workers, two files, no shared contract: each one made an assumption.
CART = "def total(prices):\n    return sum(prices)\n"                      # prices in cents
INVOICE = "def format_amount(amount):\n    return f'{amount:.2f} EUR'\n"             # amount in euros
INVOICE_FIXED = "def format_amount(amount):\n    return f'{amount / 100:.2f} EUR'\n"  # amount in cents


def load(text):
    space = {}
    exec(text, space)
    return space


def checks(cart, invoice, own_input):
    """own_input: the value the invoice's unit test uses, according to ITS assumption."""
    results = {}
    results["cart unit"] = cart["total"]([1000, 250]) == 1250
    results["invoice unit"] = invoice["format_amount"](own_input) == "12.50 EUR"
    results["integration"] = invoice["format_amount"](cart["total"]([1000, 250])) == "12.50 EUR"
    return results


CASES = [("invoice with a different assumption", INVOICE, 12.5),
         ("invoice with the 'cents' contract", INVOICE_FIXED, 1250)]
for name, text, own_input in CASES:
    results = checks(load(CART), load(text), own_input)
    print(name + ":", {k: ("ok" if v else "FAILED") for k, v in results.items()})

# Output (python3 contract.py, two identical runs):
# invoice with a different assumption: {'cart unit': 'ok', 'invoice unit': 'ok', 'integration': 'FAILED'}
# invoice with the 'cents' contract: {'cart unit': 'ok', 'invoice unit': 'ok', 'integration': 'ok'}

In the output the two unit tests pass and the integration test fails: the invoice receives 1250, reads it as euros and prints a figure a hundred times larger. The fix is not a better agent but a line in the plan: "amounts are always whole cents", declared before the work and read by both. In the second line of the output the invoice divides by a hundred and the integration passes. It is the case Cognition calls conflicting implicit decisions, reduced to the bone: the remedy lies in the shared contract and in the test that crosses both parts, not in the number of reviewers.

LangGraph: the written path, the reviewer that runs, the cap on turns

LangGraph describes a workflow as a graph: a StateGraph with a shared state (here a TypedDict), nodes that are Python functions, fixed edges and conditional edges that decide the next node by looking at the state. It is a good choice when you want the path between agents to be readable and testable, and that is why I use it. It is not the only one: the article LangChain and LangGraph: agents with AgentExecutor and Tools shows other uses. Here the graph has three nodes: the developer (a script of two versions of the function pages, the first one wrong), the reviewer and a "human" node for when the attempts run out.

The reviewer is not a model: it runs the code against six cases and reports the first one that fails. This is the answer to the third question: the check is independent of whoever produced the code, and the message names the case (pages(1) = 0, expected 1), which is the information a real model would use to correct itself. The conditional edge after_review is the point where you decide the policy: outcome ok closes, attempts exhausted sends to the person, otherwise try again.

graph.py - developer, reviewer that runs, human node and turn limit
from typing import TypedDict

from langgraph.errors import GraphRecursionError
from langgraph.graph import END, START, StateGraph

TESTS = [(0, 0), (1, 1), (10, 1), (11, 2), (20, 2), (21, 3)]   # (items, pages) with 10 per page
CORRECT = "def pages(n, per_page=10):\n    return -(-n // per_page)\n"
TRUNCATED = "def pages(n, per_page=10):\n    return n // per_page\n"


class State(TypedDict):
    code: str
    outcome: str
    attempts: int


def build(versions, cap=None):
    """Developer -> reviewer graph. 'versions' is the worker's script: no model."""

    def developer(state: State):
        n = min(state["attempts"], len(versions) - 1)
        return {"code": versions[n], "attempts": state["attempts"] + 1}

    def reviewer(state: State):
        space = {}
        exec(state["code"], space)          # the reviewer really runs it: it does not opine
        for items, expected in TESTS:
            got = space["pages"](items)
            if got != expected:
                return {"outcome": f"pages({items}) = {got}, expected {expected}"}
        return {"outcome": "ok"}

    def human(state: State):
        return {"outcome": "a person is needed: " + state["outcome"]}

    def after_review(state: State):
        if state["outcome"] == "ok":
            return END
        if cap is not None and state["attempts"] >= cap:
            return "human"
        return "developer"

    g = StateGraph(State)
    g.add_node("developer", developer)
    g.add_node("reviewer", reviewer)
    g.add_node("human", human)
    g.add_edge(START, "developer")
    g.add_edge("developer", "reviewer")
    g.add_conditional_edges("reviewer", after_review, ["developer", "human", END])
    g.add_edge("human", END)
    return g.compile()


empty = {"code": "", "outcome": "", "attempts": 0}

r = build([TRUNCATED, CORRECT], cap=3).invoke(empty)
print("1) fixes on the second turn:", r["outcome"], "| attempts:", r["attempts"])

r = build([TRUNCATED], cap=3).invoke(empty)
print("2) never fixes, cap 3      :", r["outcome"], "| attempts:", r["attempts"])

try:
    build([TRUNCATED]).invoke(empty, config={"recursion_limit": 8})
except GraphRecursionError as error:
    print("3) no cap, limit 8         :", type(error).__name__, "-", str(error)[:46])

# Output (python3 graph.py with langgraph 1.2.21, two identical runs):
# 1) fixes on the second turn: ok | attempts: 2
# 2) never fixes, cap 3      : a person is needed: pages(1) = 0, expected 1 | attempts: 3
# 3) no cap, limit 8         : GraphRecursionError - Recursion limit of 8 reached without hitting a

Three runs, three behaviors. In the first, the second turn fixes it and the graph ends with ok after two attempts. In the second the worker never fixes it: the cap of three attempts sends the case to the human node, and the outcome carries the last error, so whoever receives the case knows where to start. The third is the one not to forget: without a cap written by you, a loop that does not converge goes on, and the LangGraph documentation says the default recursion limit is 10,007 supersteps since version 1.1.4. With recursion_limit at 8, passed as a top-level key of the configuration, the run stops with GraphRecursionError. You get it only if you set it, and with a developer-reviewer loop on a real model every turn costs tokens.

A note on the execution: I used a virtual environment outside the repository, already set up by another batch of this series of work, with Python 3.14.4 and langgraph 1.2.21 from PyPI. The reviewer uses exec because the code under test is mine and sits in the example; with code generated by a model it must be run in a separate process and with permissions reduced to the bare minimum, as in the article Claude Code: agentic development from the terminal.

CrewAI, AutoGen and Claude Code subagents: what you need to know to choose

CrewAI models the work as a team of agents with roles and tasks, and the processes documentation lists two modes, sequential and hierarchical. The code of a complete example, with a crew run without a model, is in the article CrewAI: teams of collaborating agents. AutoGen is the case in which verification changes the recommendation: the stable documentation declares the project archived and no longer maintained by Microsoft, with no bug or security fixes, still advises against production use and points new users to the Microsoft Agent Framework. Whoever starts today should not choose it; whoever already has it must plan the migration, as the article on AutoGen and AG2 explains.

Claude Code subagents are Markdown files with a YAML header, each with its own prompt, its own tools and a separate context; the tool that launches them is called Agent. If you limit a subagent to Read, Grep, Glob, you get a reviewer that cannot modify anything, and that is the case where it is worth it: separation of permissions, more than of "roles". The trade-off is Cognition's: what the subagent discovers comes back to you as a summary, and the decisions it made along the way you do not see. That is why a read-only subagent is a good use, and a subagent that writes code in parallel with another on the same module is not.

Anyone who wants the complete architecture, with a supervisor, memory and error recovery, will find it in Multi-agent orchestration: production architectures; the limits above (shared context, independent checks, cap on turns) hold for any framework you choose.

When not to use more agents

A single agent with a good plan and a check per step is the right answer more often than it seems: Cognition's post says so and, for programming tasks, Anthropic itself confirms it. You add a second agent when one context is truly not enough (a big job with independent parts, for example modules without shared interfaces), when you want a read-only reviewer with different permissions, or when the task has enough value to pay for the increase in cost. You do not add it to "specialize" a role with a label such as "senior reviewer with 15 years of experience": a biography in the prompt does not add a check.

A cost rule you can measure yourself, without trusting my figures or anyone's: run the same task with one agent and with two, and compare the tokens consumed (if your tool reports them) and the number of human interventions. It is your own number, from your project. Checking the code that comes out of these systems is the subject of Testing AI-generated code.

Frequently asked questions

When is it worth using several agents to program?

When the parts are truly independent, the value of the task pays for much higher token consumption and every part has an automatic check. Anthropic observes that programming tasks have fewer parallelizable parts than research, so the common case is a single agent.

Is AutoGen still a good choice?

According to the official stable documentation, not for new projects: the project is archived and no longer maintained by Microsoft, and the documentation points those starting out to the Microsoft Agent Framework.

How do I keep a review loop from running forever?

With a cap written by you in the state (the number of attempts) and with LangGraph's recursion_limit as a safety net. The default limit stated by the documentation is very high (10,007 supersteps since version 1.1.4).

What you can do now

You can assess whether a second agent is needed with three questions (independence of the parts, value of the task, independent check) and you have two figures with sources for the cost, with their limit. You have seen a unit defect between two separately written parts pass the unit tests and fail integration, and the remedy, a contract declared in the plan. You have a LangGraph graph that runs the code under review, has a cap on attempts and a turn limit. And you know that AutoGen is archived. The next step is testing AI-generated code, and if you want the overall picture start again from the first article of the series.

For prompts and instructions see Prompt Engineering for IDEs and Code Generation, for security Security in vibe coding, for the close of the series The future of agentic software development.

Sources

The two programs were run twice each with identical output (cmp): contract.py with Python 3.14, graph.py with Python 3.14.4 and langgraph 1.2.21 in a virtual environment outside the repository. The "agents" are scripted functions: no model was called, and the token cost of a real system was not measured here.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects