Multi-Agent LLM Systems: Layered Collaboration Patterns and Cost Optimization

    This article explores how to build LLM applications with multi-agent layered collaboration to balance cost and quality. It defines four agent roles—orchestrator, executor, lightweight, and specialist—and explains how to divide responsibilities, schedule tasks with dependencies and state machines, scope context per role, and control costs through escalation thresholds, batching, and fail-fast rules. It also covers quality governance, common anti-patterns, and a phased implementation path.

    1. Why You Shouldn’t Give Every Task to a Single LLM

    As LLM-based applications spread, many teams building intelligent coding assistants, automated repair systems, code comprehension tools, or complex task execution platforms rely on a single high-capability model for every step. This approach is common in early prototypes because it is simple to implement, involves short call chains, and results in a clear system structure. However, as task size grows, steps become longer, and codebases grow more complex, having a single model handle all the work gradually reveals a series of problems.

    First, cost becomes unbalanced. High-capability models typically have stronger reasoning, generation, and comprehensive judgment abilities. But if low-risk tasks like file retrieval, log reading, result formatting, and simple classification are also assigned to them, resources are consumed unnecessarily. This is especially true in scenarios such as large-scale codebase analysis, batch task execution, and long-running automated operations, where the number of calls rises quickly and costs expand accordingly.

    Second, latency and throughput become insufficient. Complex tasks are rarely completed in one shot; they consist of multiple steps. If every step serially calls the same model, overall system response slows down. In contrast, if some tasks can be processed in parallel by lighter roles while the main agent handles only key decisions, overall execution efficiency improves.

    Third, context management becomes difficult. When a model must simultaneously understand requirements, retrieve code, read logs, modify files, run tests, and analyze results, the context expands rapidly. The longer the context, the more easily the model loses critical information and produces inconsistent judgments. Layered collaboration allows each role to handle only the context relevant to its responsibilities, reducing the comprehension burden.

    Fourth, errors propagate. If the model both makes decisions and executes them, a wrong judgment midway may cause subsequent steps to continue along the incorrect path, with no independent verification or correction mechanism. Multi-agent layered collaboration can use acceptance, testing, and auditing roles to create cross-checks, reducing the chain effects of single-point failures.

    Therefore, the key focus is not simply pursuing a single “strongest model” but designing a stable agent collaboration mechanism where roles of different capability levels each fulfill their duties, balancing cost and quality.

    2. Core Idea: Assign Different Duties to Different Agents

    The core principle of multi-agent layered collaboration can be summarized as: high-capability models make judgments, lightweight models execute, simple tasks are not escalated, and complex decisions are not delegated downward.

    Here, “high-capability model” does not refer to a specific product but to a model role with strong reasoning, good long-text comprehension, strong code understanding, and solution planning abilities. It is better suited for tasks requiring comprehensive judgment, such as task decomposition, risk analysis, architecture selection, final acceptance, and conflict resolution.

    “Execution agents” are suited for tasks with clear boundaries, explicit inputs, and verifiable outputs, such as implementing a function, modifying a specified file, adding tests, generating patches, and handling local defects in a module. These tasks do not require extensive global reasoning but do require stable execution and accurate adherence to constraints.

    “Lightweight agents” are suited for high-frequency, low-difficulty, batch-executable tasks, such as searching code snippets, reading logs, extracting key fields, organizing test results, categorizing error types, and generating structured summaries. Their value lies not in complex reasoning but in low cost, low latency, and concurrency.

    In addition, a “specialist coordination agent” can be set up to handle highly complex tasks such as large-scale refactoring, architecture planning, complex research, and cross-module impact analysis. Such tasks usually require longer thinking time and stronger consistency control, so they cannot simply be handed to lightweight roles.

    3. Typical Role Division: From Execution Chain to Governance Chain

    A relatively complete multi-agent collaboration system can be divided into four layers by responsibility.

    Role Type Main Responsibilities Suitable Tasks Key Constraints
    Orchestrator Agent Requirement understanding, task decomposition, decision-making, acceptance Complex goal setting, risk assessment, final merge Highest permissions, fewest calls
    Execution Agent Code modification, test supplementation, module implementation Development tasks with clear boundaries Operates only within authorized scope
    Lightweight Agent Retrieval, reading, classification, organization Log search, field extraction, result aggregation No complex inference
    Specialist Agent Refactoring, architecture analysis, research reasoning Large-scale modifications, solution comparison Requires human or orchestrator review

    3.1 Orchestrator Agent

    The orchestrator agent is the decision-making center of the system. It must translate user goals into executable tasks and decide task priorities, dependencies, and execution order. It should not directly perform large amounts of small work but should focus on whether goals are clear, results are verifiable, and risks are controllable.

    Key outputs of the orchestrator agent include:

    • Task decomposition results
    • Acceptance criteria for each subtask
    • Sets of tasks that can be executed in parallel
    • Approval requirements for high-risk tasks
    • Final integration and regression conclusions

    3.2 Execution Agent

    Execution agents are the main producers. Their characteristics are clear task boundaries, explicit output formats, and quantifiable verification methods. Tasks such as “fix an incorrect return value in a function,” “add tests for exception branches,” and “locate the source of a null pointer from logs” are all suitable for execution agents.

    To avoid execution deviations, execution agents must follow strict input-output conventions. They cannot arbitrarily expand the task scope or modify files outside their permissions without confirmation.

    3.3 Lightweight Agent

    The value of lightweight agents lies in scale. They can process large numbers of low-complexity tasks in parallel, such as:

    • Searching for relevant symbols in a codebase
    • Extracting error codes and timestamps from logs
    • Classifying test results
    • Converting natural language requirements into structured fields
    • Aggregating multiple execution results into a concise summary

    The design focus of lightweight agents is stability, retryability, and low context consumption. They should not undertake tasks requiring multi-step reasoning and cross-module judgment.

    3.4 Specialist Coordination Agent

    When tasks involve large-scale refactoring, architecture upgrades, complex research, or cross-system impact analysis, a specialist coordination agent can be introduced. It requires stronger context integration abilities and outputs auditable analysis processes. Because such tasks are high-risk, they usually require secondary confirmation by the orchestrator agent or a human.

    4. Scheduling Mechanism: Making Task Flow Clear and Traceable

    Layered collaboration is not simply assigning tasks to different roles; it requires a clear scheduling mechanism. “Multi-agent” systems without scheduling mechanisms easily degenerate into a stack of isolated calls and struggle to produce stable benefits.

    4.1 Task Object Design

    Each task should have a clear structured description to facilitate scheduling, tracking, and acceptance. A general task object can include the following fields:

    1. task = {
    2. id: "T-102",
    3. goal: "Fix initialization exception in a module",
    4. level: "execute",
    5. dependencies: ["T-101"],
    6. inputs: ["repo_snapshot", "test_log"],
    7. constraints: ["only_touch_auth_module"],
    8. outputs: ["patch", "test_report", "summary"],
    9. acceptance: ["unit_pass", "static_check_pass", "review_ok"]
    10. }

    Through the task object, the system can determine which layer of agent should handle a task and record its dependencies and acceptance status.

    4.2 Task Dependencies and Parallel Execution

    Complex tasks can usually be organized as a directed acyclic graph (DAG). A main goal can be decomposed into multiple subtasks with defined dependencies between them. Tasks without dependencies can be executed in parallel, while tasks with dependencies must wait for prerequisite results.

    For example:

    • Retrieve relevant files
    • Analyze failed tests
    • Generate a fix patch
    • Run regression tests
    • Aggregate conclusions

    Retrieval and failed test analysis can run in parallel, patch generation must wait for analysis to complete, and regression tests must wait for the patch to be generated. Such a structure can significantly improve overall throughput.

    4.3 State Machine Management

    It is recommended to define clear states for each task:

    1. pending -> running -> waiting_for_review -> passed / failed -> rolled_back

    The state machine helps the system identify stuck tasks, repeatedly executed tasks, and tasks requiring human intervention. For failed tasks, avoid infinite retries; instead, set a maximum retry count and degradation strategy.

    5. Context Management: The Key to Reducing Call Costs and Error Rates

    In multi-agent collaboration, context transfer is the most easily overlooked issue. Many system failures are not caused by insufficient model capability but by stuffing too much irrelevant information into the context, causing roles to misunderstand task goals.

    5.1 Trim Context by Role

    The orchestrator agent needs to see global goals, the task tree, and risk summaries, but does not need to see all raw logs. Execution agents need to see specific tasks, file snippets, constraints, and acceptance criteria, but do not need to see the complete project history. Lightweight agents only need to process the current retrieval or classification object.

    This context trimming significantly reduces invalid input and improves execution accuracy.

    5.2 Use Structured Intermediate Results

    Agents should not only pass natural language long texts to each other but should pass structured results as much as possible, such as:

    • Defect lists
    • Change lists
    • Test pass rates
    • Risk alerts
    • Pending confirmation items

    Structured intermediate results are easy for machines to parse and for humans to audit.

    5.3 Summaries and Compression

    For long logs, long documents, or long code snippets, lightweight agents can first generate summaries before handing them to upstream roles. Summaries should not be simple truncation but should retain key information, such as error types, impact scope, trigger conditions, related modules, and reproduction paths.

    6. Cost Control: Not Simply Switching to a Cheaper Model, but Reducing Invalid Calls

    In intelligent programming and automated tasks, cost optimization cannot be understood only as lowering the unit price per call. More effective approaches include reducing the number of calls, shortening contexts, improving task success rates, and avoiding invalid repeated executions.

    6.1 Push High-Frequency Simple Tasks Down

    Tasks like file search, log classification, and result formatting will significantly increase costs if all are assigned to high-capability roles. Assigning these tasks to lightweight roles is the first step in cost optimization.

    6.2 Set Escalation Thresholds

    Not all failures need to be immediately escalated to higher-capability roles. A tiered strategy can be set:

    • Allow a retry after one lightweight call failure
    • Escalate to an execution role after multiple failures
    • Escalate to the orchestrator role if the execution role cannot solve it
    • High-risk changes must enter human confirmation

    This avoids premature use of high-cost resources.

    6.3 Batching and Caching

    For similar tasks, batch processing should be used as much as possible. For example, retrieve multiple symbols at once, read multiple log snippets at once, and generate multiple test conclusions at once. For results that have already been computed, short-term caching can be set to avoid repeated calls.

    6.4 Fail Fast

    When inputs do not meet minimum conditions, the task should be terminated directly instead of letting the model guess repeatedly. For example, if necessary files are missing, permissions are insufficient, dependencies are missing, or log information is incomplete, inputs should be supplemented first instead of continuing to generate potentially unreliable results.

    7. Quality Governance: Multi-Agent Systems Must Have Acceptance and Rollback

    Multi-agent collaboration improves efficiency but also increases chain complexity. Without a quality governance mechanism, the system may appear to complete tasks but actually introduce new problems.

    7.1 Define Acceptance Criteria Upfront

    Each task should define acceptance criteria at creation time rather than judging after results come out. Acceptance criteria should be quantifiable as much as possible, such as:

    • Whether relevant unit tests pass
    • Whether static checks show no new serious warnings
    • Whether changes involve only the authorized scope
    • Whether necessary documentation is generated
    • Whether there are unhandled exceptions

    7.2 Independent Acceptance Role

    Although the orchestrator agent can perform acceptance, a more reliable approach is to have an independent role or human participate in key acceptance. Independent acceptance reduces the bias of “self-generated, self-approved.”

    7.3 Versioning and Rollback

    All changes should have version records to ensure they can be rolled back when problems occur. For code modifications, configuration changes, and task strategy adjustments, change descriptions and rollback paths should be retained.

    7.4 Audit Logs

    Multi-agent systems need to record key logs, including task initiation, role assignment, context summaries, tool calls, result outputs, exception information, and acceptance conclusions. Logs are not only for troubleshooting but also for subsequent optimization of role division and cost control strategies.

    8. Common Anti-Patterns: Practices That Weaken the Value of Multi-Agent Systems

    In practical implementation, some common mistakes can make multi-agent collaboration meaningless.

    1. Using the same high-capability role for all tasks. This leads to out-of-control costs and fails to leverage the advantages of layered collaboration.
    2. The orchestrator role directly completes all small work. The value of the orchestrator role lies in judgment and scheduling, not in replacing all execution roles.
    3. Lightweight roles undertake complex reasoning. Lightweight roles are suitable for small tasks with clear boundaries. If forced to undertake architecture design, complex debugging, or cross-module refactoring, they easily produce unstable results.
    4. No acceptance loop. With only generation and no verification, the system accumulates hidden errors.
    5. Indiscriminate context passing. Every role receiving complete historical information increases noise and reduces accuracy.
    6. Lack of failure handling strategy. Without retry limits, degradation paths, or human intervention mechanisms, the system may continuously consume resources under abnormal conditions.

    9. Implementation Path: Start from Low-Risk Scenarios and Expand Gradually

    When enterprises or individuals implement multi-agent layered collaboration, they are advised not to build an overly complex system from the start but to advance in a gradual manner.

    Step 1: Pilot in low-risk scenarios. Examples include log summarization, test case generation, code comment completion, and simple defect localization. These tasks have clear boundaries and are easy to verify.

    Step 2: Define roles and output contracts. Clarify the inputs, outputs, permissions, and acceptance criteria of the orchestrator, execution, lightweight, and specialist roles to avoid ambiguous responsibilities.

    Step 3: Establish a task tracking mechanism. Track tasks from creation, assignment, and execution to acceptance to ensure every result has a source.

    Step 4: Gradually introduce parallelism and escalation mechanisms. After task scale expands, add dependency graphs, parallel scheduling, failure escalation, and human confirmation processes.

    Step 5: Continuously evaluate effectiveness. Focus not only on completion rates but also on metrics such as cost, latency, error rate, rollback rate, human intervention rate, and change quality.

    10. Conclusion: Future Competition Lies in Agent Collaboration Efficiency

    In intelligent programming and automated task execution scenarios, the upper limit of single-model capability is important, but system-level efficiency often depends on whether role division is clear, scheduling is reasonable, context is controllable, and acceptance is closed-loop. Rather than pursuing a single model to handle all work, it is better to build a layered collaboration system: the orchestrator agent handles judgment, execution agents handle production, lightweight agents handle high-frequency tasks, and specialist agents tackle high-complexity challenges.

    The core value of this approach lies in breaking down complex problems into manageable small tasks, concentrating high-risk decisions in a few key steps, and spreading low-cost execution across a larger set of tasks. Through role layering, context trimming, task dependency management, cost threshold control, and acceptance rollback mechanisms, the system can significantly reduce resource consumption while maintaining quality. Future agent engineering is not just about improving single-model capability but about designing an efficient, governable, and continuously evolving agent collaboration network.