Multi-Model AI Agent Collaboration for Backend System Optimization
An 8–10-hour backend optimization exercise illustrates how an execution agent, a review agent, and human oversight can work together on an existing codebase. This article examines file-level task definitions, context caching, tool-based verification, defect handling, and quality gates, while explaining why low inference costs do not eliminate the need for clear acceptance criteria and engineering review.
Multi-Model AI Agent Collaboration for Backend System Optimization
1. Why Backend Optimization Needs Collaborative Agents
Optimizing a backend administration system rarely means starting from scratch. More often, developers must extend a partially completed application or maintain an older codebase. Common challenges include unclear module boundaries, incomplete API contracts, undocumented legacy logic, insufficient coverage of failure paths, lengthy validation workflows, and fragmented requirements.
Asking an AI coding agent to complete a large feature through a single, open-ended prompt can lead to context drift, uncontrolled changes, and inadequate verification.
During an intensive exercise lasting approximately 8–10 hours, we optimized a partially completed backend administration system using a multi-model workflow with two roles:
- Execution agent: Read code, modify files, and run verification tools.
- Review agent: Examine diffs, identify edge cases, and flag potential defects.
The exercise involved approximately 820 messages and 660,000 context tokens, with about 659,900 cached tokens and a reported cache hit rate of roughly 99%. Using a general context-cache pricing estimate, the model usage cost was approximately CNY 10.
Assistant messages accounted for about 50% of the interaction, tool messages for 42.3%, and other messages for 7.7%. This distribution suggests that the workflow centered on agent execution and tool-based verification rather than conversation alone.
The main lesson is not that low costs justify unlimited trial and error. Rather, agents can take on substantial repetitive editing and debugging work when task boundaries are clear, context is stable, and verification forms a closed feedback loop. Quality still depends on human task decomposition, acceptance criteria, and review.
2. Dividing Responsibilities Between Execution and Review Agents
The execution agent works best on narrowly defined tasks: read specified files, understand local logic, make a change, run checks, and repair failures based on feedback. Its strengths are speed, frequent tool use, and direct execution of explicit instructions.
In this exercise, however, it was less reliable at discovering implicit requirements, anticipating edge cases, and adding defensive checks. Typical gaps included insufficient input validation, missed exception paths, and incomplete consideration of idempotency and authorization boundaries.
The review agent’s role was therefore not to write the same code again. It focused on diff review and risk-oriented questions:
- Does the change exceed the task’s defined scope?
- Are API contracts still consistent?
- Are null values, boundary values, exception branches, concurrency, and authorization paths handled?
- Are logs, error codes, and audit records complete?
- Do tests cover both successful and failing paths?
- Can the execution agent provide reproduction steps and a repair explanation for suspicious behavior?
This division lets the execution agent maintain momentum while the review agent supplies a second perspective, reducing blind spots that can develop during long-context work.
A review agent does not replace human acceptance testing. Critical logic involving data consistency, authorization, billing, or settlement still requires human spot checks and business validation.
3. Replace Vague Requests with File-Level Task Cards
The most effective control during rapid iteration was not a longer prompt. It was breaking work down to specific files or functions and defining verifiable acceptance criteria.
We used task cards containing background, objectives, constraints, acceptance criteria, verification methods, and prohibited changes.
Example task cardModule: User authorizationBackground:Role checks are scattered across multiple entry points,resulting in duplicated logic.Objective:Extract a shared authorization function and update thespecified entry points to use it.Constraints:Preserve the existing API response structure.Do not add external dependencies.Maintain compatibility with existing error codes.Acceptance criteria:The successful path passes.Unauthorized requests return the existing error code.Logs include the user identifier and operation type.Verification:Run relevant unit tests, static checks, and API contract checks.Prohibited changes:Do not modify the database schema.Do not change unrelated modules.
The defining feature of a useful task card is testability. “Optimize the authorization module” is not an actionable acceptance criterion. “Extract a shared authorization function in the specified files, preserve error-code compatibility, and add tests for unauthorized requests” is.
Specific tasks are easier for the execution agent to complete and easier for the reviewer to assess for scope violations.
4. Manage Context with Stable Prefixes and Concise Tool Output
The high cache hit rate came from reusing stable context. We organized context into three layers:
- Stable prefix: Project conventions, directory structure, architectural constraints, API contracts, error-code conventions, and coding style. This material changed infrequently and appeared near the beginning of the context to support cache reuse.
- Task context: The current task card, relevant code excerpts, recent diffs, and summaries of failures. This followed the stable prefix and changed with each task.
- Tool output: Search results, test output, static-analysis findings, and log analysis. These were summarized to retain error locations, relevant stack traces, expected versus actual behavior, and the affected scope, without carrying forward large volumes of irrelevant logs.
A high cache hit rate does not guarantee high-quality context. If the stable prefix contains outdated rules, caching can reproduce the same mistakes consistently. Project conventions and API contracts need regular maintenance: stability must rest on correctness.
The approximately CNY 10 cost was an observation from one exercise, not a general price expectation. Total engineering cost must also include the time spent on human task decomposition, review, and acceptance testing.
5. Build a Tool-Based Verification Loop
Tool messages represented 42.3% of the interaction, reflecting a workflow dominated by code inspection, editing, analysis, and verification rather than text generation.
An effective execution loop includes:
- Search: Locate relevant files, call sites, data models, and error codes.
- Read: Inspect local code and API contracts rather than loading the entire codebase into context.
- Modify: Make small changes and identify the files changed and the reasons.
- Verify: Run static checks, unit tests, API contract checks, and the regression checklist.
- Analyze: Diagnose failures with the smallest necessary investigation.
- Repair: Fix the failing behavior without expanding into unrelated refactoring.
The workflow can be summarized with the following pseudocode:
def run_task(task_card):context = build_stable_context(project_rules, architecture, interface_contracts)plan = executor.plan(task_card, context)for step in plan.steps:patch = executor.edit(step, context)result = tools.verify(patch, checks=task_card.checks)if not result.passed:feedback = diagnose(result)patch = executor.repair(step, feedback, context)review = reviewer.review(patch, task_card.acceptance)if review.has_risk:executor.repair(step, review.feedback, context)return summary_with_diff_and_checks()
The governing principle is that every step must be verifiable. If repeated repair attempts still fail, stop expanding the prompt. Instead, narrow the task or have a developer investigate the underlying issue.
6. Turn Repeated Corrections into Quality Gates
Some defects became apparent only during review by the second agent or a human. The productive response was not simply to ask the execution agent to “try again.” Feedback needed to describe reproduction steps, expected behavior, actual behavior, and the smallest acceptable repair scope.
For example:
- Reproduction: An entry point receives a request with a required parameter missing and enters an exception path.
- Expected behavior: Return the existing error code and write an audit log.
- Actual behavior: An uncaught exception is raised.
- Repair scope: Modify only the specified validation function and its call sites; preserve the response structure.
At a minimum, quality gates should include:
- Diff review
- Static checks
- Unit tests
- API contract checks
- A regression checklist
- Human spot checks
Critical paths involving authorization, auditing, data consistency, idempotency, and concurrency need additional defensive-programming checks. These should address input validation, boundary values, exception paths, duplicate submissions, unauthorized access, and log completeness.
7. Evaluate Cost and Efficiency Without Confusing Them with Quality
The exercise recorded approximately 820 messages, 660,000 context tokens, a reported 99% cache hit rate, and an estimated model usage cost of CNY 10. These figures suggest that repeated agent execution can be economical when stable context is reused.
Low execution cost, however, means that iteration is inexpensive—not that delivery quality is automatically high.
The responsibilities remain distinct:
- Execution agent: Carry out explicit tasks quickly and reduce repetitive manual work.
- Review agent: Add an independent review perspective.
- Humans: Define objectives and acceptance criteria, and judge critical risks.
Agents are best treated as a high-throughput execution layer, not an autonomous decision-making layer. Clear boundaries, reliable verification tools, and an established review process can improve iteration efficiency. Vague requirements, unclear contracts, and missing validation can instead turn inexpensive execution into additional rework.
8. Operationalize the Workflow with Observability
In an enterprise environment, collect tool calls, verification results, failure reasons, and cost metrics into a unified, auditable record of each iteration.
The original implementation recommendations referenced Baidu AI Cloud’s logging, monitoring and alerting, and container services as possible supporting infrastructure. Any use of these services should be assessed against the deployment environment and applicable service availability.
Useful metrics include:
- Task-card completion rate
- First-pass verification rate
- Review finding density
- Regression failure rate
- Context cache hit rate
- Human intervention time per task
These measurements help teams determine which tasks are suitable for agent execution and which still require human-led implementation.
9. Conclusion
Effective multi-model collaboration for backend optimization depends less on choosing a stronger model than on building an executable, verifiable, and reviewable engineering process.
File-level task cards control scope. Stable context and caching help control model usage costs. Tool-based verification supports quality. Review agents and human acceptance checks manage risk.
The execution agent contributes speed and focused implementation. The review agent contributes a second perspective. Humans define goals, decompose work, and enforce critical quality gates. Together, these roles can deliver more consistent, auditable improvements within a limited budget.
