Long-Task Code Iteration and Multi-Agent Collaboration: LLM Application Practices

    This article explores the practices of long-task code iteration and multi-agent collaboration using Large Language Models (LLMs). It covers core mechanisms such as task decomposition, feedback loops, and context management, along with multi-agent collaboration patterns. Additionally, it provides insights on evaluation methods, cost and quota considerations, risk control, and practical steps for implementation.

    1. Background: Why Focus on Long-Task Code Iteration

    Early code generation was mostly limited to single-turn Q&A: provide a requirement, get a piece of code, and manually debug it. With the improvement of LLMs’ reasoning and tool-calling capabilities, the industry has started to focus on another type of scenario: allowing models to autonomously perform multi-step operations over a longer task cycle, including reading code, modifying files, running tests, and making further modifications based on errors.

    This scenario is typically referred to as long-task code iteration. Its value lies in reducing developers’ repetitive labor in the “execute-feedback-correct” loop. Developers can focus their energy on requirement definition, solution trade-offs, and result verification.

    To determine if a solution is suitable for a team, three questions must be clarified first:

    1. Can the model maintain a consistent understanding of the goal after multiple rounds of modifications?
    2. Can the model correct its direction based on real runtime feedback, rather than repeatedly outputting similar erroneous code?
    3. Can the overall cost be accepted by the team?

    The following sections revolve around these three questions.

    2. Core Mechanisms of Long-Task Code Iteration

    2.1 Task Decomposition

    A common reason for long-task failure is that the goal is too vague. For example, a description like “build a monitoring system” lacks boundaries, forcing the model to assume many details, often resulting in deviations from expectations. An effective approach is to break the goal down into verifiable subtasks, each with clear inputs, outputs, and acceptance criteria.

    When decomposing, the following principles can be followed:

    • Each subtask should only modify one module or one type of file;
    • Each subtask should correspond to at least one automated check;
    • Dependencies between subtasks should be explicitly recorded.

    2.2 Feedback Loop

    The core of iteration capability lies in the feedback loop. The model proposes changes, the system applies the changes and executes validation, and then passes the validation results back to the model as new context. Without real feedback, the model can only rely on its own judgment, easily falling into a state of “looking correct.”

    Below is a simplified iteration loop diagram, intended only to illustrate the structure, not an interface of a specific tool:

    1. def iterate_until_pass(task, agent, run_tests, apply_patch, max_rounds=5):
    2. context = task.build_context()
    3. for round_no in range(1, max_rounds + 1):
    4. patch = agent.propose_change(context)
    5. apply_patch(patch)
    6. report = run_tests(task.test_suite)
    7. if report.passed:
    8. return {"status": "done", "rounds": round_no}
    9. # Append failure information to the context to drive the next round of corrections
    10. context = context.append(report.summary())
    11. return {"status": "needs_review", "rounds": max_rounds}

    The loop sets a maximum number of rounds. After exceeding the limit, the task should be handed over to manual processing rather than retrying indefinitely. This not only controls costs but also prevents the model from continuously consuming resources in the wrong direction.

    2.3 Context Management

    Long tasks generate a large amount of logs, diffs, and error messages. If everything is stuffed into the context, the model’s attention will be diluted, and key constraints may be ignored. Common practices include:

    • Maintaining a short task description file recording the goals, constraints, and completed items;
    • Keeping only the failure summary from the most recent round, with historical details written to external storage;
    • Truncating logs and extracting key lines, retaining error types, top of the stack trace, and relevant file paths.

    3. Multi-Agent Collaboration Patterns

    A single agent can easily lose track of complex tasks. Assigning responsibilities to multiple roles can reduce the burden of single inferences and facilitate parallel progression.

    3.1 Role Division

    A common division includes three types of roles:

    Role Responsibility Output
    Planner Decomposes requirements, formulates subtasks and dependencies Task list
    Executor Completes code modifications for a single subtask Code changes and self-test results
    Reviewer Checks whether changes meet acceptance criteria Approval or rejection feedback

    The planner is responsible for the global perspective, the executor focuses on local implementation, and the reviewer provides independent judgment. The reviewer should ideally use a different context than the executor to avoid adopting the executor’s assumptions.

    3.2 Dependency Management and Parallelism

    Subtasks without dependencies can be executed in parallel, while those with dependencies need to be queued. The task list can be described in a structured format:

    1. {
    2. "goal": "Build a frontend prototype for financial report monitoring",
    3. "subtasks": [
    4. {"id": "layout", "owner": "executor", "depends_on": [], "accept": "Page structure renders without errors"},
    5. {"id": "filter", "owner": "executor", "depends_on": ["layout"], "accept": "Filter conditions can correctly filter data"},
    6. {"id": "review", "owner": "reviewer", "depends_on": ["layout", "filter"], "accept": "Pass component tests"}
    7. ]
    8. }

    After the scheduler reads the dependencies, it can decide which subtasks can be started simultaneously. This approach is more stable than having a single agent complete all work sequentially and makes it easier to locate which step caused a problem.

    3.3 Typical Scenario: Financial Report Information Organization

    Taking the organization of listed company financial report information as an example, the task can be broken down into four parts: data acquisition, field standardization, metric calculation, and interface display. There is a dependency between data acquisition and field standardization, while interface display can be developed in parallel with the first two once the API contract is determined.

    The key to this type of task lies in data validation. For instance, whether the currency units are unified, whether the reporting periods are aligned, and how missing values are marked. These rules should be written into test cases and backed by automated checks, rather than relying on the model’s common sense.

    4. Frontend Prototyping and Backend Completion

    In actual projects, agents often first produce a visual frontend prototype. The prototype can quickly confirm interaction forms and information hierarchy, but it usually lacks real data services and exception handling.

    The recommended progression is as follows:

    1. Confirm the page structure and core interactions with stakeholders;
    2. Use mock data to complete frontend rendering and basic interactions;
    3. Define the API contract, including field names, types, and error codes;
    4. Have the executor complete the backend service, and verify frontend-backend consistency using contract tests;
    5. Before introducing real data sources, perform regression tests with sample data first.

    The API contract is crucial in this process. As long as the contract is stable, the frontend and backend can be iterated separately without blocking each other.

    5. Evaluation Methods: Don’t Just Look at Single-Item Benchmarks

    Model capability evaluation typically relies on public benchmark tests, but the correlation between these scores and actual development outcomes is limited. Teams should pay more attention to their own task sets. It is recommended to establish the following metrics:

    • First-time pass rate: The proportion of tasks that pass all acceptance tests after the first execution;
    • Average iteration rounds: The average number of corrections required to reach a passing state;
    • Manual intervention rate: The proportion of tasks requiring manual modification or re-describing requirements;
    • Regression rate: The proportion of tasks introducing new defects after fixing an issue;
    • Unit cost: The total cost spent to complete a task.

    When evaluating, fix the task set, fix the acceptance scripts, and record the complete logs of each run. This allows for comparing whether results have genuinely improved after changing models, adjusting prompt structures, or modifying tool configurations.

    6. Comprehensive Consideration of Cost and Quotas

    In model selection, unit price is only part of the cost. A more meaningful metric is the cost per unit of effective output:

    Cost per unit of effective output = Total expenditure within the cycle ÷ Number of tasks passing acceptance

    If a model is cheap per call but requires more rounds to pass, the final cost may be higher. Conversely, a model with a higher unit price that passes on the first try may yield better overall efficiency.

    When using subscription or quota-based services, the following aspects should also be noted:

    • The refresh cycle and measurement method of quotas to avoid running out of limits during critical periods;
    • The peak resource consumption of long tasks, where a single task may consume a large amount of quota in a short time;
    • The waste ratio of failed tasks, which should be tracked separately.

    Teams can reserve stronger models for high-value tasks and assign highly repetitive tasks to lower-cost solutions. Tiered usage is generally more economical than uniformly using a single model.

    7. Risk and Boundary Control

    Automated code execution introduces additional risks that need to be controlled at the design stage.

    7.1 Permissions and Sandboxing

    Agents should run in an isolated environment with access only to the directories and services required for the task. Write permissions, network permissions, and deployment permissions should be granted separately, adhering to the principle of least privilege. For high-risk operations involving deletion, publishing, or modifying permissions, manual confirmation should be required.

    7.2 Keys and Sensitive Information

    Keys, tokens, and personal data should not appear in prompts or logs. They can be injected through environment variables or key management services and masked before log output.

    7.3 Stability and Exception Handling

    When evaluating agents, in addition to the completion rate, the following capabilities should also be checked:

    • Can it strictly adhere to constraints, such as not modifying files outside the specified directory?
    • When encountering missing dependencies, network timeouts, or test environment anomalies, can it stop and report rather than bypassing them arbitrarily?
    • Can it correctly perceive the current runtime environment, such as the operating system, available commands, and version information?
    • Can it maintain task state after running for a long time, and can it resume after an interruption?

    These test items can be written into fixed cases and re-run every time the model is changed or the tool is upgraded.

    8. Implementation Recommendations

    When introducing long-task code iteration capabilities, teams can proceed with the following steps:

    1. Select three to five real, medium-complexity tasks to form an internal benchmark set;
    2. Write clear acceptance tests for each task to ensure results can be automatically judged;
    3. Set a maximum number of iteration rounds and a budget cap, handing over to humans if exceeded;
    4. Record the first-time pass rate, iteration rounds, and unit cost, and review them weekly;
    5. Determine the model tiering strategy based on the data, and gradually expand the scope of application.

    By following this process, teams can use quantifiable results to determine whether a tool is worth investing in, rather than relying on a single experience or marketing claims to make decisions.