Multi-Agent Collaboration and Iterative Code Generation: A Practical Checklist

    A practical checklist for using long-context models, coordinating multiple agents, and managing code-generation loops. It covers retrieval, token costs, task states, idempotent retries, access controls, validation, rollback, and iteration limits, with findings from small-scale tests that require independent verification.

    Introduction

    Large language models can handle a range of tasks involving long-document comprehension, code generation, and multi-agent collaboration. However, applying a demonstration directly to a working system can lead to problems.

    This checklist focuses on capability limits, orchestration workflows, loop safeguards, and cost considerations. The observations and practices come from small-scale tests; validate them against your own data before relying on them.

    1. Long-Context Processing: Use Retrieval Within the Context Window

    The context window determines how many tokens a model can accept in a single call. Tokens are the basic units used to process text. A Chinese character typically corresponds to one or two tokens, depending on the tokenizer. Content that exceeds the window may be truncated, or the request may be rejected.

    A large codebase will typically exceed the capacity of a single context window. A practical approach is to:

    1. Split code along file and function boundaries, preserving import relationships and type definitions.
    2. Use retrieval-augmented generation (RAG) to select files relevant to the question, and include only the retrieved passages in the context.
    3. Use prompt caching for fixed system prompts and project conventions to reduce repeated billing.

    Long contexts also increase costs. Both input and output are billed by token, and conversation history is sent again with each call. Including an entire report may be convenient, but it increases the cost of subsequent turns.

    In a financial-report analysis example, the test used publicly disclosed quarterly reports covering the two most recent fiscal years. The model identified metrics such as revenue, gross margin, and net income, and produced year-over-year comparisons. However, the sample was limited and was not exhaustively checked. Each finding therefore needs to be verified against the original statements before use.

    2. Multi-Agent Orchestration: State, Messages, and Failure Rollback

    A multi-agent architecture commonly includes a coordinating agent, retrieval agent, cleaning agent, metric-extraction agent, summarization agent, and review and testing agents. Dividing responsibilities reduces the context complexity of individual calls. Role definitions alone, however, are not enough to make the system reliable without state management.

    Define an explicit state machine for each subtask:

    State Meaning Allowed Next States
    pending Waiting to execute running
    running Execution in progress succeeded, failed
    failed The current attempt failed retrying, dead_letter
    retrying Retrying according to a backoff policy running
    succeeded The result has passed validation Terminal state
    dead_letter Retry limit exceeded; requires manual handling Terminal state

    Messages between agents should include these fields:

    • task_id
    • step
    • payload_ref: A reference to a file or database record rather than the raw source content.
    • status
    • attempt: The attempt number.
    • idempotency_key: The key used to identify repeat executions of the same operation.

    Make Retries Idempotent

    Before performing a write operation, check whether the operation associated with the same idempotency_key has already completed. If it has, return the existing result.

    This prevents repeated calls after a network timeout from generating duplicate reports.

    Isolate Permissions, Validate Results, and Support Rollback

    • Permission isolation: Restrict retrieval agents to allowlisted domains and file writes to a designated working directory. Do not give them production credentials.
    • Result validation: Before summarization, check that the expected metrics, units, and reporting periods are present. Route missing items to manual review.
    • Failure rollback: Version intermediate artifacts. If a task fails, revert to the most recent version that passed validation.

    3. Iterative Code Generation: Limit Loops and Isolate Execution

    Self-iteration in AI coding tools is essentially a loop: generate code, run tests, read errors, and revise the code.

    In the tested example, the tool generated a product plan and sample data from the requirements. The frontend was relatively complete, and its interactions generally matched the requirements. Backend logic and exception handling still required manual work.

    The loop must have explicit limits. The intended pseudocode example covers a maximum iteration count, a timeout, failure classification, and escalation to a human. The functions classify_failure and escalate are illustrative and must be implemented for the target system.

    The available source excerpt ends partway through the function signature:

    1. MAX_ITERATIONS = 5
    2. TIMEOUT_SECONDS = 120
    3. def agent_self_iteration(task, sandb