Multi-Agent Coding Collaboration: Model Selection, Task Orchestration, and Cost Control

    This article covers three problems teams face when deploying coding agents: choosing a model, splitting tasks, and controlling cost. It explains how to benchmark candidate models on your own codebase, when a master-worker architecture fits, and how to structure parallel execution with timeouts, retries, and result validation. It also covers common failure modes, cost metrics to monitor, and a pre-launch checklist. The performance and cost figures are illustrative only and should be verified in your own test environment.

    When teams deploy coding agents, they usually get stuck on three questions: which model to choose, how to split tasks, and how to control cost. This article is organized around these three questions. It provides scheduling code you can adapt and a pre-launch checklist. The performance and cost figures here are examples of an approach only. Verify them in your own test environment and do not reuse public leaderboard results directly.

    1. Evaluating Whether a Model Fits as the Foundation of a Coding Agent

    When choosing a model, compare intelligence, response speed, and overall cost on the same test set. Public leaderboards differ in task types, prompt formats, and scoring rules, so ranking alone can easily lead to the wrong choice.

    Follow these steps for a side-by-side evaluation:

    1. Extract 30 to 50 real tasks from your own codebase. Cover three categories: code comprehension, bug fixing, and unit test generation.
    2. Fix the prompt template, temperature, and context length. Run each candidate model under the same conditions.
    3. Record the pass rate, time to first token, output tokens per second, and total cost per task for each run.
    4. Run each task at least 3 times to observe variation. A lucky success does not demonstrate stable capability.

    Summarize the results in a table so the team can compare them:

    Task Type Sample Size Pass Rate Time to First Token (s) Output Tokens per Second Cost per Task (CNY) Variation Range
    Code comprehension 15 TBD TBD TBD TBD TBD
    Bug fixing 20 TBD TBD TBD TBD TBD
    Unit test generation 15 TBD TBD TBD TBD TBD

    Speed metrics must include their measurement conditions. The same model can show very different latency under different concurrency levels, regions, and network conditions. Record the concurrency, region, and time period for each measurement.

    Limits of Long Context

    Support for very long context means the model can accept more code. It does not mean you can load an entire project in one pass. In practice, keep three points in mind.

    First, a large context window does not equal effective comprehension. Information in the middle of long text may be used less reliably, so place key code close to the instruction.

    Second, longer input raises the cost of each call and increases latency.

    Third, cache hits depend on a stable prompt prefix. Frequently changing the system prompt, or inserting dynamic content near the start of the prompt, invalidates the cache.

    A safer approach is to narrow the scope first with retrieval or summarization, and include only the files relevant to the current sub-task. Place fixed coding standards and project documentation at the beginning of the prompt, and put dynamic content at the end. This raises the cache hit rate.

    2. Designing a Multi-Agent Collaboration Architecture

    A single agent handles small tasks well. For large projects that span multiple modules, it can exceed context limits and struggle to cover the distinct responsibilities of UI, interfaces, and testing at the same time. The master-worker scheduling pattern addresses this by dividing the work.

    Be clear about when to use it. Split large tasks that span modules, but keep small tasks with a single agent. Otherwise, the coordination overhead of splitting can outweigh the benefit.

    1. Master-Worker Scheduling Pattern

    The master agent understands the overall goal, splits it into sub-tasks, and assigns a role to each one, such as UI generation, API implementation, or test case generation. Each sub-agent receives only the context relevant to its role. This reduces interference from irrelevant information and makes it easier to troubleshoot each part on its own.

    The master agent must maintain a global state table. Each sub-task records at least the following fields:

    Field Meaning
    task_id Sub-task identifier
    role Role of the sub-agent responsible for the task
    input Reference to the input context, not the full code itself
    output Result returned by the sub-agent
    status pending, running, done, or failed
    retry_count Number of retries already performed
    deadline Latest completion timestamp

    After the sub-tasks finish, the master agent integrates the results and runs verification. Results can be merged only after they pass verification. Results that fail verification do not enter the main branch.

    2. Parallel Execution and Result Integration

    Sub-agents typically communicate through command-line calls, API requests, or message queues. The scheduling skeleton below includes timeout control, retries, result validation, and an overall timeout guard.

    Prerequisites:

    • Python 3.10 or later. The scheduling code uses only the standard library.
    • Sub-agent calls require your team’s own API client, for example httpx 0.27 or later.
    • Read the API key from the AGENT_API_KEY environment variable. Do not hardcode it.
    • Read the concurrency limit from the AGENT_MAX_WORKERS environment variable. The default is 4.
    • If you use pytest for verification, version 8.x is recommended.

    The four functions in the code are stubs. Running them as-is raises NotImplementedError. Replace them with your team’s implementations before the workflow can run end to end.

    1. import logging
    2. import os
    3. import random
    4. import time
    5. from concurrent.futures import ThreadPoolExecutor, as_completed
    6. from concurrent.futures import TimeoutError as FuturesTimeout
    7. from dataclasses import dataclass
    8. from typing import Any
    9. logger = logging.getLogger(__name__)
    10. MAX_WORKERS = int(os.environ.get("AGENT_MAX_WORKERS", "4"))
    11. MAX_RETRIES = 2
    12. SINGLE_CALL_TIMEOUT = 120 # Timeout for a single sub-agent call (seconds)
    13. OVERALL_TIMEOUT = 900 # Timeout for all sub-tasks combined (seconds)
    14. @dataclass
    15. class SubTask:
    16. task_id: str
    17. role: str
    18. payload: dict
    19. status: str = "pending"
    20. retry_count: int = 0
    21. output: Any = None
    22. def call_sub_agent(role: str, payload: dict, timeout: float) -> str:
    23. """Call a sub-agent and return its raw output text.
    24. Args: role is the role name. payload contains only the context this role needs.
    25. timeout is the per-call timeout in seconds.
    26. Returns: the model output string.
    27. Raises: TimeoutError on timeout, ConnectionError on network failure.
    28. """
    29. raise NotImplementedError("Replace with your team's sub-agent call implementation")
    30. def validate_output(role: str, output: str) -> bool:
    31. """Check whether a sub-agent output is acceptable.
    32. Examples: whether the JSON parses, whether the code passes a syntax check,
    33. whether required fields are present.
    34. Returns True if the check passes.
    35. """
    36. raise NotImplementedError("Replace with your team's output validation rules")
    37. def integrate_results(outputs: dict[str, str]) -> str:
    38. """Merge the outputs of each sub-task into one complete result.
    39. Args: outputs maps task_id to the validated output.
    40. Returns: the merged text or patch.
    41. Raises: ValueError if the parts conflict.
    42. """
    43. raise NotImplementedError("Replace with your team's result integration logic")
    44. def run_verification(merged: str) -> bool:
    45. """Verify the merged result, for example by applying the changes and running unit tests.
    46. Returns True if verification passes.
    47. Dependency: must run in an isolated temporary directory and must not modify the main branch directly.
    48. """
    49. raise NotImplementedError("Replace with your team's verification process")
    50. def run_subtask(task: SubTask) -> SubTask:
    51. """Run a single sub-task. Retry with exponential backoff on timeout or validation failure."""
    52. while task.retry_count <= MAX_RETRIES:
    53. task.status = "running"
    54. try:
    55. output = call_sub_agent(task.role, task.payload, SINGLE_CALL_TIMEOUT)
    56. if validate_output(task.role, output):
    57. task.output = output
    58. task.status = "done"
    59. return task
    60. logger.warning("Sub-task %s failed validation", task.task_id)
    61. except TimeoutError:
    62. logger.warning("Sub-task %s timed out", task.task_id)
    63. except ConnectionError:
    64. logger.warning("Sub-task %s connection failed", task.task_id)
    65. task.retry_count += 1
    66. if task.retry_count <= MAX_RETRIES:
    67. time.sleep(min(2 ** task.retry_count, 30) + random.uniform(0, 1))
    68. task.status = "failed"
    69. return task
    70. def orchestrate(subtasks: list[SubTask]) -> str:
    71. """Entry point for the master agent: run in parallel, integrate results, verify, then return."""
    72. pool = ThreadPoolExecutor(max_workers=MAX_WORKERS)
    73. futures = {pool.submit(run_subtask, t): t for t in subtasks}
    74. results: dict[str, SubTask] = {}
    75. try:
    76. for fut in as_completed(futures, timeout=OVERALL_TIMEOUT):
    77. task = fut.result()
    78. results[task.task_id] = task
    79. except FuturesTimeout:
    80. logger.warning("Overall timeout reached. Unfinished sub-tasks are marked as failed.")
    81. finally:
    82. pool.shutdown(wait=False, cancel_futures=True)
    83. for t in subtasks:
    84. if t.task_id not in results:
    85. t.status = "failed"
    86. results[t.task_id] = t
    87. failed = [tid for tid, t in results.items() if t.status != "done"]
    88. if failed:
    89. raise RuntimeError(f"The following sub-tasks failed and cannot be merged: {failed}")
    90. merged = integrate_results({tid: t.output for tid, t in results.items()})
    91. if not run_verification(merged):
    92. raise RuntimeError("The integrated result failed verification. The merge was blocked.")
    93. return merged

    Three points in this code need attention.

    • Set the per-call timeout and the overall timeout separately. The per-call timeout stops a single sub-agent from hanging. The overall timeout stops the whole scheduler from waiting indefinitely.
    • Set a cap on retries. Each retry is billed again, so retries can multiply cost.
    • After the overall timeout, threads that are already running cannot be forcibly stopped. They end on their own after the per-call timeout, and their results are discarded.

    3. Common Failure Modes and Cost Monitoring

    Most problems in multi-agent systems occur in three places