Beyond One Model for All: A Layered Multi-Agent Workflow for AI Coding

    Many teams still rely on a single model for the entire AI coding workflow, which drives up costs, creates errors, and limits parallelism. This article introduces a layered collaboration pattern: an orchestrator model handles planning and verification, execution models write code in parallel, and lightweight models take on retrieval and organization tasks. It also covers task card templates, routing code, and an implementation checklist, supported by a public benchmark in which a team scheduled up to 25 execution workers to complete roughly 22 million tokens of defect search at similar quality while reducing costs by about one-third.

    1. The Problem: Why Using One Model for Everything Doesn’t Pay Off

    In AI coding tools, a common pattern is to use the same model for everything: understanding requirements, searching code, writing implementations, and checking results. This approach is easy to get started with, but as task size grows, several problems emerge.

    1.1 Costs Are Inflated by Low-Value Work

    A flagship model offers broad capabilities and deep reasoning, but its per-token cost is also the highest. In real codebase tasks, reading files, searching for symbols, scanning logs, and organizing results consume a lot of tokens without demanding much reasoning power. Having a flagship model handle these steps is like using your most expensive resource for basic grunt work.

    1.2 Long Contexts Dilute Information

    Stuffing all related files, logs, and intermediate results into the model at once looks complete, but doesn’t necessarily work well. It is widely observed that the longer the context, the more likely the model is to miss mid-context details, drift from initial constraints, and produce less stable output or follow formatting less reliably. The effect is especially pronounced on complex tasks with multiple subtasks.

    1.3 Serial Execution Inflates Wait Time

    A single model that reads files, edits code, and runs checks one step after another means any blocked step holds up everything downstream. Yet many subtasks are independent and could run at the same time.

    1.4 Self-Review Has Blind Spots

    When the same model writes and verifies its own code, it tends to fall into confirmation bias: “this looks fine.” Edge cases and error paths often get overlooked.

    Takeaway: The root of the cost problem is often not which model you use, but how you organize those models.

    2. The Core of Layered Collaboration: Match Each Task to the Right Model

    Industry practice suggests the question worth exploring is not “which model is strongest,” but “how can different models work together.” One principle matters especially: don’t make the most expensive model do all the work.

    2.1 Role Tiers

    You can group models across general-purpose coding tools and platforms into four roles:

    Tier Role Capability Focus Typical Tasks Parallel Strategy
    Orchestrator Flagship model / orchestrator agent Task decomposition, complex decisions, core code, final acceptance Root-cause analysis, critical-path coding, change review Serial, globally unique
    Execution Execution worker Implementing against clear constraints Independent, well-scoped feature work, parallel defect fixes Multiple in parallel
    Lightweight Lightweight worker Processing large volumes of input quickly File and symbol search, log reading, classification and tagging, information extraction, result organization Many in parallel
    Coordination High-level coordination role Long-horizon reasoning, cross-domain synthesis Large-scale refactoring, architecture planning, complex research, high-difficulty multi-agent tasks Use sparingly, single checkpoint

    Not every team needs the coordination tier. It suits problems that resist decomposition and demand a global view; in day-to-day iteration, a flagship orchestrator plus execution and lightweight tiers usually cover most scenarios.

    2.2 The Key to Layering: Assign a Complexity Level to Each Task

    Whether layering works depends on making accurate judgments about tasks. You can draw on cognitive load theory from software engineering (Sweller, 1988):

    • Intrinsic load: the inherent difficulty of the task itself. Fixes requiring cross-module reasoning or trade-offs among multiple approaches carry high intrinsic load naturally.
    • Extraneous load: the extra burden introduced by how a task is organized and presented. Having to scan dozens of files to locate a target symbol is a classic case of extraneous load.

    Under this framework, the orchestrator model can tag each subtask as it decomposes the work:

    1. complexity:
    2. cross_module_reasoning: true # Requires cross-module reasoning
    3. uncertainty: high # Multiple possible approaches; trial and error needed
    4. verifiability: programmatic # Whether tests or tools can decide automatically: programmatic / semi / manual
    5. change_scope: files # Scope of impact
    6. risk: low # Reversibility of a failure

    Among these, verifiability is the most valuable dimension:

    • Tasks a test, compile step, or static check can decide automatically—such as function-level bug fixes—are good candidates to push down to execution models, even if they carry some difficulty.
    • Tasks that only a human can judge—“is this design sound?” “is this trade-off appropriate?”—should be pulled up to the orchestrator model.

    Also, don’t split fix tasks evenly by file. The better approach is to have each worker independently reproduce and locate the same batch of defects, produce its own complete fix, and then let the orchestrator model evaluate them centrally. This preserves the relationships among defects and lets you pick the best of several candidate solutions.

    2.3 What Tiered Coding Really Buys You

    Many developers have seen the same thing with coding tools: the same request passes in one shot today, yet takes repeated edits to barely work tomorrow. Beyond task difficulty, a major reason is that every conversation starts from zero—nothing preserves what has been validated as effective, and nothing remembers the pitfalls already hit.

    Tiers offer a way out by reserving precious reasoning capacity for the moments that matter:

    1. Simple mechanical changes—renaming, filling in parameters, replacing deprecated calls—can go directly to a lightweight model: fast and cheap.
    2. Medium changes that touch interfaces or data models go to an execution model, with clear context and constraints.
    3. Design trade-offs, performance bottlenecks, concurrency, and consistency problems go to the flagship model for deep analysis.
    4. Optimization tasks that look “clearly hard” to you can go to a high-level coordination model for exploratory analysis.

    In one sentence: Reasoning tier depends on problem difficulty, not lines of code.

    3. Orchestration in Practice: Orchestrator Decomposition + Worker Parallelism

    Take “batch-fixing defects in a large codebase” as an example. A typical controlled multi-agent workflow has five stages.

    3.1 Preparation and Decomposition

    The orchestrator model first reads the defect list and clusters defects using directory structure and module dependencies. For example, by functional module:

    • Login timeouts in the authentication module;
    • Amount rounding issues in the payment module;
    • Null-handling issues in the export module.

    Defects within the same module often share the same code context even when symptoms differ. Packaging them for the same worker reduces repeated searching and helps keep the fix style consistent.

    3.2 Dispatch and Parallel Execution

    Each subtask is packaged into a “task card” for a worker. A task card is a self-contained description that lets the worker start without going back to the orchestrator with questions:

    • Goal: the specific problem to fix;
    • Constraints: files that must not be touched, interfaces that must be preserved;
    • Acceptance criteria: tests or checks that must pass;
    • Budget: token and turn limits.
    1. # Task card example: the worker can start without asking the orchestrator
    2. task_id: auth-timeout-001
    3. role: worker
    4. goal: Fix an intermittent login timeout under high concurrency
    5. context:
    6. - src/auth/session.go
    7. - src/middleware/timeout.go
    8. constraints:
    9. - Do not change the public fields or interface signatures of Session
    10. - Only modify files under src/auth/ and src/middleware/
    11. acceptance:
    12. - go test ./src/auth/... ./src/middleware/... passes completely
    13. - New cases cover the timeout scenario
    14. budget:
    15. max_tokens: 120000
    16. max_turns: 15

    If you want auxiliary models to handle searching and organizing, you can split out two more roles:

    • Retriever: only returns relevant file paths and code snippets for given keywords; makes no changes.
    • Synthesizer: consolidates each worker’s fix notes, affected files, and test results into a structured report.

    This way, a worker’s context contains only code directly relevant to the task—shortening context and lowering the risk of attention being pulled off track by unrelated information.

    3.3 Orchestrator Review and Acceptance

    After workers return their patches, the orchestrator model reviews them centrally:

    1. Run tests and static checks uniformly. This is the objective gate and comes first.
    2. Review the changes that pass: whether they stay within constraints, introduce new coupling, or stay consistent with other modules.
    3. Return failed tasks with error logs to the original worker to retry, or merge them with neighboring defects and hand them to the flagship model.
    4. Merge accepted changes in dependency order, running regression tests after each merge.

    3.4 Scheduling Code Example

    The pseudocode below highlights five key points: capability abstraction, task routing, concurrency limits, budget control, and failure escalation.

    1. import asyncio
    2. # Describe models by capability, not by a specific vendor's model name
    3. MODELS = {
    4. "orchestrator": "reasoning-strong", # Orchestrator: planning and verification
    5. "worker": "coding-balanced", # Execution: well-scoped coding
    6. "utility": "lightweight", # Lightweight: search and organization
    7. }
    8. ROLE_LIMITS = {
    9. "orchestrator": {"max_parallel": 1, "max_tokens": 500_000},
    10. "worker": {"max_parallel": 25, "max_tokens": 120_000},
    11. "utility": {"max_parallel": 50, "max_tokens": 30_000},
    12. }
    13. def route(task) -> str:
    14. """Pick a role from the complexity tags; fall back to the orchestrator when in doubt, letting it decide whether to push work down"""
    15. if task.cx.programmatic and not task.cx.cross_module_reasoning:
    16. return "worker"
    17. if task.kind in ("search", "classify", "summarize"):
    18. return "utility"
    19. return "orchestrator"
    20. async def run_agent(plan):
    21. sems = {r: asyncio.Semaphore(c["max_parallel"])
    22. for r, c in ROLE_LIMITS.items()}
    23. done, failed = [], []
    24. async def one(task):
    25. role = route(task)
    26. async with sems[role]: # Rate-limit per role; lightweight tasks can run at higher concurrency
    27. budget = ROLE_LIMITS[role]["max_tokens"]
    28. for attempt in range(3): # Bounded retries to avoid infinite loops
    29. result = await call_model(MODELS[role], task, max_tokens=budget)
    30. if not result.tool_calls_error:
    31. return result
    32. if attempt == 1 and role != "orchestrator":
    33. # Escalate after repeated failure: hand the failed task back to the orchestrator
    34. task.cx.cross_module_reasoning = True
    35. role = "orchestrator"
    36. async with sems[role]:
    37. result = await call_model(MODELS[role], task,
    38. max_tokens=500_000)
    39. budget = min(budget * 2, ROLE_LIMITS[role]["max_tokens"])
    40. return result
    41. results = await asyncio.gather(*(one(t) for t in plan.tasks),
    42. return_exceptions=True)
    43. for task, res in zip(plan.tasks, results):
    44. (done if not isinstance(res, Exception) else failed).append((task, res))
    45. # Hand results back to the orchestrator for centralized acceptance; re-queue failed tasks with their logs
    46. return await call_model(MODELS["orchestrator"],
    47. summarize(done, failed), verify=True)

    Two points to keep in mind:

    • Budgets and retries: always set an explicit token cap per call and a total retry limit. Automatic retries without a cap can push costs out of control.
    • Layered acceptance: tests, compilation, and static checks are deterministic verification and should be run by programs, with their results as the source of truth. The model’s job is to make code pass tests—not to judge whether it passes. That is how you minimize the blind spots of self-written, self-verified code.

    4. Evidence: Smarter Collaboration Beats Cheaper Models

    To decide whether an orchestration approach is worth adopting, look at two metrics: cost and quality.

    4.1 A Publicly Disclosed Comparison

    A team publicly shared a comparison: on a defect search task across a codebase of roughly 22 million tokens, using a high-performance flagship model as orchestrator and scheduling up to 25 mid-tier execution models as workers:

    • The final score was essentially the same as the control group;
    • Cost was about one-third lower.

    The exact mapping varies by task design, but the shift in cost structure is clear:

    • The control group’s cost was roughly “N × full-codebase context × flagship model price.”
    • In the new approach, the flagship model only handles decomposition and a slimmed-down summary, while full-codebase searching runs through many low-cost calls in parallel.

    4.2 Why Quality Didn’t Drop

    Defect search depends less on how deep a single inference is and more on whether coverage is broad enough. Multiple workers scanning different areas in parallel actually catch hidden defects more easily. The orchestrator model then de-duplicates and ranks candidate defects during synthesis and hands deterministic checks to programs, keeping the final result solid.

    4.3 Where the Savings Come From

    Cost Item Single Model for Everything Layered Collaboration
    Search and filtering Flagship model reads files one by one Lightweight models pre-filter in parallel; flagship model only reviews
    Fix implementation All fixes done serially Multiple execution models run in parallel by module
    Acceptance checks Self-written, self-verified; easy to miss issues Programs run deterministic checks + orchestrator review
    Context length Everything stuffed in: long and noisy Trimmed per task and supplied on demand
    Failure retries Redo everything Retry locally per task, escalate level by level

    4.4 Important Caveats

    This conclusion does not hold unconditionally. When subtasks are strongly dependent, or when deep cross-module reasoning is required, over-parallelizing can lower quality by fragmenting context.

    Adding more agents blindly is not a good idea. Research on multi-agent systems (such as the 2025 survey by Cemri et al.) points out that failures in multi-agent systems often stem from coordination problems rather than the capabilities of any single model. Typical issues include:

    • Specification divergence: members describe and understand task goals differently;
    • Duplicate steps: multiple members repeat the same subtask;
    • Insufficient verification: without a unified acceptance standard, errors propagate from member to member.

    Agent count must follow how well a task can be split: parallelism is worth it only when the task can be decomposed and verified.

    5. Engineering Implementation Checklist

    5.1 Task Splitting

    • Split by “module + verifiable goal,” not evenly by file.
    • Write scopes must not overlap; read-only search tasks are exempt.
    • Each task card is self-contained: goal, constraints, acceptance criteria, and budget.
    • Tag dependencies among subtasks and schedule in topological order.

    5.2 Context Supply

    • The orchestrator model keeps a “repository map”: directory structure, module responsibilities, and key interfaces.
    • Workers receive only code and notes directly relevant to their task.
    • Set a separate context budget per role; for example, return only paths and key snippets for search results rather than pasting whole blocks.

    5.3 Quality Assurance

    • Tests first: add or fix test cases before workers start fixing.
    • Layered acceptance: programs run deterministic checks; the orchestrator model reviews semantics and design soundness.
    • Independent review: for high-risk changes, spin up a separate review role apart from the implementer to avoid path dependence.
    • Regression protection: run regression tests after every merge to confirm existing functionality is intact.

    5.4 Cost and Observability

    • Log each task’s routing decision, token usage, elapsed time, and retry count to analyze cost distribution and keep tuning routing rules.
    • Set alerts on metrics such as cost and error rate; downgrade or pause automatically when anomalies appear.
    • In the cloud, a message queue can smooth out traffic spikes for task dispatch; object storage suits code snapshots, patches, and intermediate artifacts for traceability and replay; a container platform provides isolation and elastic scaling for concurrent execution environments; and logging plus monitoring support runtime observation. On Baidu AI Cloud, for example, you can deploy this kind of orchestration as a workload on a container platform and combine it with general-purpose capabilities such as object storage, message queues, logging, and monitoring, with specific choices evaluated against your own scale and compliance requirements.

    5.5 When Not to Use Multi-Agent Collaboration

    • Architecture design where subtasks are tightly coupled and require holistic trade-offs;
    • Migrations where changes conflict and must complete atomically;
    • Exploratory tasks that need long-term context continuity;
    • Cases where testing and verification are missing, leaving no objective way to judge worker output.

    In these cases, having a flagship model drive things solo, or pushing only searching and organizing to auxiliary models, is usually safer.

    6. Conclusion: From “Single-Model Capability” to “Team Collaboration Efficiency”

    Back to the original question: optimizing AI coding costs doesn’t necessarily require switching to a cheaper model. Redesigning how agents collaborate often yields more. The approach boils down to three principles:

    1. Tier by capability: the orchestrator decides, executors build, and lightweight models handle bulk processing;
    2. Route by task: push simple, verifiable tasks down; pull complex decisions up;
    3. Verify as a safety net: let programs run deterministic checks and let the orchestrator model do the final sign-off.

    For teams, start small:

    1. Inventory daily tasks and flag the parts that are “repetitive, low on judgment”;
    2. Push those parts to lightweight models and watch cost and quality;
    3. Then gradually parallelize independent development tasks.

    Future competitiveness may depend not only on how strong a single model is, but on whether you can organize a group of models into a team with clear division of labor and smooth collaboration.