Multi-Agent Development: Controlled Workflows for Cost-Effective Code Delivery
Multi-agent development splits a software project across AI-driven roles—researcher, architect, developer, and tester—coordinated by an orchestrator that assigns tasks, merges results, and enforces quality gates. This article explains how to structure such a system, how to calculate its real costs, which mistakes are most common, and when the approach is worth adopting. It includes a runnable orchestration skeleton in Python, a cost model based on tokens and retries, a comparison of single-agent versus multi-agent setups, and guidance on enterprise constraints such as tenant isolation, data sanitization, and mandatory human review points.
Multi-Agent Development: Controlled Workflows for Cost-Effective Code Delivery
Multi-agent collaborative development means splitting a software project into multiple AI-driven roles, with an orchestrator assigning tasks, collecting results, and controlling quality. Its value lies in parallel processing and reduced human waiting time, but it does not automatically guarantee quality or lower costs. This article explains how to build this pattern, how to calculate costs, what common mistakes look like, and under what conditions it is worth adopting.
Some public reports mention teams generating large volumes of code with multi-agent pipelines, but these cases usually lack complete information about project scope, human effort, and acceptance criteria. Before citing such cases, verify the original sources and run your own calculations based on your team’s data.
How Multi-Agent Development Works
The core of a multi-agent system is division of labor. A single coding tool working on a large project can easily exceed its context window and struggles to handle cross-module logic at the same time. Splitting tasks across roles, where each role only processes the information it needs, reduces the burden on any single call.
1. Role Design
Common roles include the following.
- Researcher agent: collects requirements, reviews official documentation and comparable open-source solutions, and produces a technology selection report. The report should cite sources and dates to avoid outdated material.
- Architect agent: designs module boundaries, interface specifications, and data models based on the research report. Interface specifications are the foundation of subsequent parallel development and should be written in machine-verifiable formats such as OpenAPI or JSON Schema.
- Developer agents: implement the modules assigned to them according to the interface specification. Each developer agent may only modify its assigned files, preventing multiple agents from editing the same file concurrently.
- Test and debug agent: writes unit and integration tests, performs code review, and packages failure information into repair tasks that go back to the developer agents.
More roles are not better. Each additional role increases handoff cost and adds another point of failure. Small projects typically need only three to four roles.
2. Orchestration and State Management
The orchestrator does three things: splits tasks, allocates resources, and records state.
When splitting tasks, divide along module boundaries rather than by lines of code. Each subtask needs a clear input, output, and acceptance condition. Concurrency must be capped, because both rate limits and cost of model services grow with parallelism.
The focus of state management is conflict prevention. Common practices include the following.
- Each developer agent works on an independent branch; the tester agent runs interface contract tests before merging.
- Shared files have defined ownership; only one agent may modify a file at a time.
- A code snapshot is saved at the end of each stage, so failures can roll back to the last version that passed tests.
- Interface changes must update the architecture specification first, then notify the affected developer agents.
Message queues can decouple task distribution, and object storage can hold code snapshots and intermediate documents. These solve transport and storage problems, but they do not replace a conflict strategy.
3. The Quality Loop
The test loop is the most underestimated part of a multi-agent system. Run tests immediately after code is generated; on failure, hand the error stack and relevant code to the developer agent for repair, then retest. This loop catches many routine errors, such as null handling, boundary conditions, and obvious type errors.
But it has clear limits. The tester agent can only find problems covered by its test cases. If the tests themselves are incomplete, or if the requirements were misunderstood, the loop will repeatedly pass incorrect tests. Therefore, a passing loop only proves the code satisfies the given tests—not that it matches business intent.
The repair loop must have a maximum retry count. Once exceeded, automatic repair should stop and the task should be handed to a human. Otherwise the system may keep consuming tokens without converging.
A Runnable Orchestration Skeleton
The code below shows the basic structure of the orchestration logic. It requires Python 3.10+ and uses only the standard library asyncio. You need to implement Agent.run yourself, typically by calling a model API or a coding tool.
import asynciofrom dataclasses import dataclass@dataclassclass Task:kind: strpayload: strclass Agent:"""Wraps a single model call. A real implementation should includetimeouts, retries, and token counting."""def __init__(self, role: str):self.role = roleasync def run(self, task: Task) -> str:raise NotImplementedError("Connect your model or coding tool here")class Orchestrator:def __init__(self, agents: dict[str, Agent], max_parallel: int = 5, max_retries: int = 3):self.agents = agentsself.semaphore = asyncio.Semaphore(max_parallel)self.max_retries = max_retriesasync def _call(self, role: str, payload: str) -> str:async with self.semaphore:return await self.agents[role].run(Task(kind=role, payload=payload))def human_review(self, stage: str, artifact: str) -> None:# Placeholder. A real system should write an approval record and# block until the responsible reviewer confirms.print(f"[Awaiting human approval] {stage}: {artifact[:80]}")async def _repair(self, code: dict[str, str], report: str) -> dict[str, str]:fixed = {}for module, source in code.items():fixed[module] = await self._call("developer", f"Fix request:\n{report}\nCode:\n{source}")return fixedasync def execute_project(self, spec: str, modules: list[str]) -> dict[str, str]:report = await self._call("researcher", spec)design = await self._call("architect", report)self.human_review("Architecture design", design)sources = await asyncio.gather(*(self._call("developer", f"Interface spec:\n{design}\nAssigned module: {m}") for m in modules))code = dict(zip(modules, sources))for _ in range(self.max_retries):test_report = await self._call("tester", str(code))if test_report.strip() == "PASS":breakcode = await self._repair(code, test_report)else:raise RuntimeError("Max repair attempts exceeded; escalate to a human")self.human_review("Final code", str(code))return code# Usage example# agents = {role: MyAgent(role) for role in ["researcher", "architect", "developer", "tester"]}# result = asyncio.run(Orchestrator(agents).execute_project(spec, ["user", "order"]))
Before running this code, note the following.
- Each agent should use its own API key or permission scope, and may only write to sandbox branches—never push directly to the main branch.
- Keys are read from environment variables or a secrets management service; they must not be written into code or logged.
human_reviewin this example only prints a message. In production it must block the pipeline until the responsible person confirms in an approval system.- The
"PASS"check is illustrative. Real projects should parse structured test framework output, such as exit codes and coverage reports.
How to Calculate Costs
The cost of multi-agent development comes mainly from model-call tokens. Count every agent’s calls, not just the final code output.
The basic formula for total cost is:
Total cost = Σ (input tokens per call × input price + output tokens per call × output price)
“Each call” here includes all research, design, development, testing, and repair calls. Retry counts significantly affect cost. If a module needs three repair rounds on average, the development stage’s token consumption can be several times that of a single generation.
A practical estimation procedure:
- Count the average number of calls per role.
- Record the average input and output tokens per call.
- Multiply by the current model pricing, then add a retry multiplier.
- Add the time cost of human review. Human review is usually a major cost component and must not be omitted.
Cost calculation should also include quality costs. If generated code has defects after going live, the cost of fixing and rolling back can far exceed the development savings. A reasonable metric is “total cost per accepted feature point,” not “generation cost per thousand lines of code.”
Choosing Between Single-Agent and Multi-Agent
Multi-agent is not always the better choice. The table below compares the two approaches across common dimensions.
| Dimension | Single Agent | Multi-Agent |
|---|---|---|
| Suitable scale | Single modules, small features, scripts | Multi-module, cross-service, larger projects |
| Context pressure | Easily exceeds the window as the project grows | Each role handles only local information |
| Cost | Fewer calls, simpler structure | More calls; requires orchestration and monitoring |
| Latency | Serial execution; slower per task | Parallelizable; overall time may shrink |
| Conflict risk | Low | Higher; requires branching and interface contracts |
| Quality risk | Depends on the reliability of a single output | Errors between roles can amplify; needs independent testing |
When choosing, ask yourself a few questions. Can the task be cleanly split along module boundaries? Are the interfaces stable? Does the team have the capacity to maintain an orchestration system? If two of these answers are no, a single agent with human review is the safer starting point.
Common Mistakes
In practice, the following problems occur most frequently.
- Vague requirements amplify errors: the researcher agent’s misunderstanding of requirements propagates to the architect and developers. Every layer looks “reasonable,” but the whole deviates from business goals.
- No interface contracts: developer agents each assume their own interface formats, and type mismatches surface only at merge time. The fix is to write machine-verifiable interface specifications first and enforce them in tests.
- Tests cover only happy paths: test cases generated by the tester agent tend to focus on normal inputs, while exceptional inputs, concurrency scenarios, and permission checks are easily missed.
- Repair loops that never converge: without a retry limit, the system repeatedly modifies the same code while token consumption keeps growing.
- Sensitive information leakage: agents write keys or customer data into prompts, logs, or vector databases.
- Excessive parallelism: concurrency exceeds the team’s review capacity, leaving generated code unreviewed and merge conflicts unresolved.
Constraints for Enterprise Adoption
In enterprise environments, long-term memory is usually implemented with a vector database. When an agent needs historical code or documents, it retrieves relevant fragments through semantic search instead of placing the entire codebase in the prompt. This controls token costs but introduces new problems.
First, tenant isolation. Data from different projects and customers must live in separate indexes or namespaces, and the caller’s permissions must be verified during retrieval. Second, sensitive data handling. Keys, personal information, and internal domains in the code should be sanitized before ingestion. Third, retrieval quality. Maintain a set of human-annotated query samples and periodically evaluate hit rate and recall, rather than assuming retrieval results are reliable.
On the infrastructure side, multi-agent systems need a container platform to elastically scale execution environments, a logging service to trace the input, output, and latency of every call, and object storage for code snapshots. Teams can choose any cloud service or self-hosted solution with these capabilities; the key is whether it meets requirements for permission isolation, auditing, and cost monitoring.
Human checkpoints are the bottom line for enterprise adoption. Mandatory human review is recommended at three points: architecture design sign-off, core interface changes, and final code merge. The human role shifts from writing code line by line to reviewing architecture, checking risks, and adjusting the workflow. Review must not be a formality—reviewers need visibility into each agent’s inputs, outputs, and test results.
Conclusion
Multi-agent collaborative development splits research, design, coding, testing, and repair into stages that can run in parallel and be tracked. It suits larger projects with clear module boundaries and relatively stable interfaces. Its cost is determined jointly by tokens, retries, and human review, and all three must be included in any estimate.
In controlled scenarios where quality, security, and cost can all be assessed, this pattern can improve delivery efficiency. Teams should start with small-scale pilots, record the cost and acceptance outcome of every call, and then decide whether to expand based on the data.
