Model Layering Practices in Multi-Agent Programming

    Using a single AI model for all multi-agent programming tasks ties task difficulty, context length, and cost together. This article explores how to optimize efficiency and quality by dividing responsibilities across four model layers: lead, execution, lightweight, and planning. It covers routing rules, context budgeting, acceptance criteria, and a practical collaboration workflow to prevent common anti-patterns.

    Using a single model “for everything” seems convenient, but it actually ties task difficulty, context length, and invocation cost together. File name retrieval, log categorization, test output organization, and cross-module refactoring or API contract design do not consume the same type of capabilities. If you route everything through the strongest model, simple steps will consume high-price reasoning quotas and stuff irrelevant text into the same context, diluting subsequent decisions. If you replace everything with a lightweight model, planning and acceptance will easily distort at boundary conditions. A more robust approach is to layer by responsibility rather than picking an “omnipotent model” based on branding or slogans.

    Distinguish Four Types of Responsibilities

    Layering is not about copying the same prompt four times; it is about ensuring each model type only sees the inputs it can handle well and only produces the results necessary for the next handoff.

    The Lead is responsible for judgment. It receives goals, constraints, and existing evidence, breaking down requirements into parallelizable and verifiable subtasks. It decides which steps must be serial and which can be distributed. Core algorithms, permission boundaries, data consistency, and the final merge decision are finalized by the Lead. The Lead’s value lies in preventing large-scale generation in the wrong direction, rather than rewriting every line itself.

    The Execution Layer is responsible for implementation. Subtasks should have clear inputs, outputs, allowed modification paths, and forbidden modules. The Execution Layer can process independent features in parallel, such as adding parameter validation to an API, adding boundary tests to existing functions, or migrating a call according to a set plan. It does not reinterpret product goals or arbitrarily expand the scope of changes.

    The Lightweight Layer is responsible for perception and organization. Codebase search, log slicing, error categorization, dependency list extraction, and test result comparison are mostly high-recall, low-creativity tasks. Delegating these to models with smaller context windows and faster responses significantly reduces the number of times the Lead needs to read raw materials. The Lightweight Layer’s output should be short evidence: file paths, symbol names, failed assertions, key log lines, and confidence scores, rather than lengthy rewrites.

    The Planning Layer is responsible for a few high-leverage decisions. The split order for large-scale refactoring, module boundaries, compatibility strategies, and conflict arbitration between multiple agents are suitable for intervention at the start of a task or when structural disagreements arise. The Planning Layer should not become a bottleneck for every minor step; it outputs constraints, milestones, and risk lists, and then returns execution control to the Lead.

    You can understand this as an evidence pipeline: the Lightweight Layer collects facts, the Planning Layer delineates boundaries, the Execution Layer modifies within those boundaries, and the Lead performs acceptance using tests and diff reviews.

    Routing Rules Matter More Than Model Names

    Model selection should be written as a checkable policy rather than relying on a conversationalist’s ad-hoc judgment. Practical rules usually only look at task characteristics:

    • Whether the input is structured and the output can be programmatically verified. Tasks that can be judged right or wrong by rules or tests should be prioritized for the Execution Layer or Lightweight Layer.
    • Whether reading a wide range of the repository is required to locate the issue. Retrieve first, then read. Never let the Lead perform an aimless scan of the entire repository.
    • Whether the cost of failure is irreversible. For data migration, permissions, release scripts, and public APIs, raise the review level, serialize if necessary, and require manual confirmation.
    • Whether there are write conflicts between subtasks. Steps that modify the same file or the same state machine should not be parallelized; read-only retrieval can be parallelized as much as possible.
    • Whether the context has exceeded the budget. When over budget, summarize and trim first, instead of switching to a larger window to continue stacking raw text.

    The illustrative scheduling pseudocode only expresses control flow and does not bind to any vendor API:

    1. on task(goal, repo, constraints):
    2. plan = planner.draft(goal, constraints) if is_architectural(goal) else empty
    3. facts = lightweight.search_and_extract(repo, plan.hints)
    4. subtasks = lead.decompose(goal, plan, facts)
    5. for batch in lead.parallel_batches(subtasks):
    6. patches = workers.run(batch, write_scope=batch.paths)
    7. report = lightweight.summarize_tests(run_tests(patches))
    8. if not lead.accept(patches, report, constraints):
    9. lead.repair_or_escalate(report)
    10. return lead.final_diff()

    The key here is not the function names, but that the input for each call is trimmed: the Execution Layer does not see irrelevant directories, the Lightweight Layer is not asked to “incidentally rewrite the architecture,” and the Lead only consumes evidence summaries and patch diffs.

    Treat Context as a Budget

    A large part of the cost in agent programming comes from repetitive reading. If the same error is read by the Lead, Execution Layer, and Planning Layer, the cost stacks up based on context length. You should set a budget for each role: the Lightweight Layer only returns the minimum lines needed for location; the Execution Layer only receives relevant file fragments, API signatures, and failed test cases; the Planning Layer works only at the level of goals, constraints, and module maps; the Lead retains decision records, unresolved risks, and the latest diffs, but not all historical tool outputs.

    The budget must be accompanied by eviction rules. When a tool returns more than a threshold, the Lightweight Layer should first perform structured compression: retain paths, symbols, line numbers, assertions, and conclusions, discarding repetitive stacks and irrelevant warnings. The compression result must be traceable; raw logs should be stored in object storage or build artifacts, and retrieved by line number when needed, rather than being permanently kept in the conversation.

    Parallelism is also constrained by the budget. If you spin up a large number of execution agents that share the same overly long context, or all modify the same hot file, the saved unit cost will be eaten up by lock conflicts, duplicate generation, and rework. The degree of parallelism should be determined alongside whether the write sets intersect and whether tests can run independently. Read-only searches can be more aggressive; write operations should be in small batches, short cycles, and rollable.

    Acceptance Criteria Determine If “Downgrading” is Possible

    Whether layering maintains quality depends on whether acceptance is independent of the generation process. When the Lead accepts a patch, it should at least verify four things: whether the changes fall within authorized paths; whether the public behavior is consistent with the task description; whether new or existing tests cover failure paths; and whether unexplained configuration, dependency, or permission changes have been introduced. Test results are organized into a comparison table by the Lightweight Layer, but pass/fail is based on the exit code and assertions of the actual test process, not just on the model’s repetition.

    For changes that are difficult to cover with tests, such as semantic adjustments beyond naming refactoring, the Execution Layer should be required to submit “what was changed, why, and what was not changed.” If the Lead finds insufficient evidence, it should send it back for supplementary retrieval rather than merging based on impression. The Planning Layer should only step in when there is continuous rework, API conflicts, or cross-module assumptions fail, to avoid escalating every formatting issue.

    A common industry observation is that after moving search, classification, and result organization away from the main chain, the number of calls to strong models decreases. The overall cost is often lower than “using the same high-capability model for all steps,” while the correctness of key decisions is still protected by acceptance gates. The specific ratio depends on the repository size, test speed, and task granularity, and cannot be treated as a fixed return. What is worth monitoring is the token composition per task, the number of reworks, and whether the final diff passes the same set of tests.

    A Practical Collaboration Workflow

    1. Define the task card. Clearly state the goal, non-goals, allowed modification directories, APIs that must be maintained, and the definition of done. Do not parallelize without boundaries.
    2. Retrieve before modifying. Use the Lightweight Layer to produce candidate files and symbols, and let the Lead confirm the scope before dispatching.
    3. Split into independently verifiable batches. Each batch should ideally correspond to a set of tests; if it fails, only rerun that batch.
    4. The Execution Layer generates the minimal diff within the write scope. Prohibit incidentally formatting the entire repo or upgrading unrelated dependencies.
    5. Use real tests and static checks to collect results, then hand them to the Lightweight Layer for categorization.
    6. The Lead performs acceptance against the task card. If it fails, provide failure evidence and restrict the scope of the next modification.
    7. Only call the Planning Layer when structural assumptions fail, and update milestones instead of discarding all patches.
    8. Log routing decisions: which layer handled which type of task, how much context was consumed, and how many reworks occurred. These records are more useful than swapping models based on gut feeling later.

    When running in the cloud, the scheduler, build environment, and logs can be stored separately. For example, use a container platform to host isolated execution environments, object storage to save raw logs and patches, and logging services with monitoring and alerting to observe timeouts, retries, and cost anomalies. If your team is already using general capabilities on Baidu AI Cloud, you only need to configure different quotas and timeouts for model calls by role, without hardcoding the orchestration logic into a single conversation.

    Common Anti-Patterns

    Using the strongest model as the only entry point and having it “play” other roles internally usually does not save context, because all tool outputs are still piled up in the same session. Conversely, delegating acceptance to a lightweight model to cut costs will lead to hidden semantic errors entering the main branch. Another failure mode is parallel agents sharing a writable workspace, where patches written later overwrite those written earlier, while tests independently show as passed. Write isolation, clear file ownership, and unified testing before merging are more important than increasing the number of agents.

    It is also not advisable to interpret layering as a fixed four-seat arrangement. Minor changes might only need lightweight retrieval plus one execution step; architectural tasks require planning. Roles are policy labels, not a roster that must be online simultaneously.

    Conclusion

    The efficiency of agent programming increasingly depends on collaboration methods, not on how strong a single call is. The Lead is responsible for judgment and acceptance, the Execution Layer implements in parallel within clear boundaries, the Lightweight Layer handles retrieval and summarization, and the Planning Layer only resolves structural issues. By designing routing, context budgeting, write conflict control, and repeatable test gates well, cost optimization does not have to rely solely on swapping for cheaper models, and quality will not be dragged down by irrelevant context because “everything is handed to the strongest model.”