A Practical Guide to LLM Code Generation and Long-Running Agent Tasks
This guide covers evaluation methods and engineering practices for using large language models to generate code and run long-running Agent tasks. It explains how to build and validate frontend prototypes, how to structure an execute-feedback-repair loop for terminal coding Agents with iteration limits, timeouts, and rollback, how to measure token costs using cost-per-passing-task rather than per-call pricing, and how to organize multi-Agent collaboration with clear ownership and exception handling. It ends with a scoring checklist for model selection. All figures in this article are illustrative parameters, not real vendor pricing or performance data.
This article focuses on evaluation methods and engineering practices, not on ranking specific models. All numbers used here are illustrative parameters and do not represent any vendor’s actual pricing or performance.
When selecting a model, the evaluation criteria have shifted from benchmark scores to three questions: Is it stable on real engineering tasks? Can it fix its own errors based on failure logs? And how many deliverables that pass acceptance can you get per unit of cost?
1. Rapid Frontend Prototyping and Quality Acceptance
Quickly building a prototype is an effective way to validate product logic. Using a data-monitoring web application as an example, a typical workflow has four steps.
Step 1: Requirement parsing and architecture planning. The input is a natural-language requirement; the output is a feature list, page structure, and sample data schemas. Acceptance criteria: every item in the feature list maps to a page or an API endpoint, and the sample data fields match the requirement.
Step 2: Frontend generation. The input is the output of step 1; the output is runnable frontend code. Acceptance criteria: the project builds cleanly, the console shows no runtime errors, all pages render correctly at three common viewport widths, and key interactions (filtering, sorting, form validation) can be reproduced manually or via script.
Step 3: Backend integration preparation. The input is the list of APIs the frontend calls; the output is API definitions and mock data. Acceptance criteria: the frontend can walk through the main flows completely under the mock environment.
Step 4: Backend integration and logic completion. The input is the API definitions and the real backend; the output is a version that passes integration testing. Acceptance criteria: end-to-end test cases pass, and the frontend correctly handles API error codes.
Differences between models in frontend details can only be revealed by running the same set of test cases. It is recommended to fix a single requirements document and a fixed set of acceptance cases, then record for each candidate model whether the build passes, the case pass rate, and the number of lines requiring manual fixes. Without these records, never judge that a model “cuts corners” or “gets it right the first time” based on impressions.
2. The Execute–Feedback–Repair Loop for Terminal Agents
Terminal-side AI coding Agents follow an “execute, feedback, repair” loop: they run code, read error logs, generate a fix, and run again. This is conceptually close to test-driven development, where tests are the basis for judging whether code is acceptable.
The following pseudocode fixes common pitfalls: missing iteration limits and timeouts, and a non-isolated execution environment.
MAX_ITER = 5 # Maximum repair rounds, prevents infinite loopsTIMEOUT_SECONDS = 120 # Timeout for each rundef execute_task(prompt, project_context, sandbox):# project_context: read-only snapshot listing the file paths allowed to be modified# sandbox: isolated environment; blocks access to production credentials and external writessnapshot = sandbox.snapshot(project_context.paths)code = llm.generate_code(prompt, project_context)result = sandbox.run(code, timeout=TIMEOUT_SECONDS)for _ in range(MAX_ITER):if result.passed:break# Timeout and permission errors are usually beyond what the model can fix; escalate to a humanif result.timed_out or result.error_category == "permission":breakfix_prompt = build_fix_prompt(result.error_logs, result.error_category)code = llm.generate_code(fix_prompt, project_context, previous=code)result = sandbox.run(code, timeout=TIMEOUT_SECONDS)if not result.passed:sandbox.restore(snapshot) # Roll back on failure; leave no half-finished changes behindreturn {"status": "needs_human", "logs": result.error_logs}# After tests pass, output only the diff for human review before mergingreturn {"status": "ready_for_review", "diff": sandbox.diff()}
When deploying this in practice, teams should check the following:
- Log capture: Persist the command, output, and exit code of every round in full.
- Error classification: Distinguish syntax errors, missing dependencies, failed test assertions, timeouts, and permission issues, and define a handling path for each.
- Repair verification: After every fix, rerun all relevant tests—never judge success by the changed line alone.
- Rollback: When failures repeat or changes exceed the allowed scope, restore from the snapshot.
- Human takeover: When the iteration limit is reached, a permission error occurs, or data deletion is involved, stop immediately and notify the owner.
Code generated by an Agent must never run directly in production, nor be merged without review. Changes involving database writes, payments, or permission configuration must be confirmed by a human.
3. Token Cost and Productivity ROI
Token cost determines whether an Agent can be used long term. Comparing price per million tokens alone does not reflect real cost, because failed attempts are billed too. A better metric is cost per passing task:
- Cost per call = input tokens × input price + output tokens × output price
- Cost per task = cost per call × average number of calls
- Cost per passing task = cost per task ÷ task pass rate
Here is a hypothetical example. Assume an input price of 1 unit per million tokens and an output price of 4 units per million tokens, with each call averaging 20,000 input tokens and 2,000 output tokens.
- Model A: Cost per call ≈ 0.028 units, 8 calls on average, 60% pass rate. Cost per task ≈ 0.224 units; cost per passing task ≈ 0.37 units.
- Model B: Cost per call also ≈ 0.028 units, 5 calls on average, 50% pass rate. Cost per task ≈ 0.14 units; cost per passing task ≈ 0.28 units.
In this hypothetical scenario, Model B—the one with the lower pass rate—has the lower unit cost, because it needs fewer repair rounds. Real conclusions require recalculating with your own tasks and prices.
Beyond cost, check these limits: weekly or daily usage quotas, concurrent request limits, and context window size. If a quota runs out mid-task, the task gets interrupted and prior work may be wasted. Long-context capability also needs testing. A simple method: embed a fixed marker at different positions in a long file, ask the model to retrieve it, and record the success rate at each position.
4. Multi-Agent Collaboration: Division of Work and Exception Handling
A single Agent has a capability ceiling. Multi-Agent collaboration splits a task across roles such as architect, frontend developer, backend developer, and test engineer. The hard part is not the number of roles but communication and conflict handling.
For a data-monitoring system, you could assign four Agents: a scraping Agent collects data, a cleaning Agent normalizes formats, an analysis Agent computes metrics, and a presentation Agent handles the frontend. Each Agent may only write to the directories it owns, preventing two Agents from modifying the same file simultaneously.
There are three common collaboration topologies:
| Topology | Characteristics | When to Use |
|---|---|---|
| Central orchestration | One coordinator assigns tasks and aggregates results | Clear task boundaries; a single gatekeeper is needed |
| Pipeline | Each Agent’s output is the next Agent’s input | Fixed step order, e.g., collection to presentation |
| Peer-to-peer | Agents exchange messages directly | Complex dependencies, but stronger protocol constraints are needed |
Messages should follow a fixed structure, for example containing a task ID, role, input location, output location, and status. Keep shared state in a single queryable task board to simplify troubleshooting.
Basic rules for exception handling:
- Set a timeout and a maximum retry count per task; beyond that, hand off to the coordinator or a human.
- Failures caused by network flakiness can be retried; failures caused by dependency conflicts should first switch to a fallback dependency version or stop.
- When two Agents modify the same file, the Agent that owns the file takes precedence; the other must resubmit.
- When the model cannot determine the current OS or dependency version, it should run a check command rather than guess.
Whether a multi-Agent architecture improves efficiency depends on whether the task can be cleanly partitioned. If the resulting modules have heavy interdependencies, coordination costs may outweigh the benefits. Validate this with a small-scale pilot.
5. Selection and Rollout Checklist
Developers can score candidates along the following dimensions, recording the test method for each:
- Frontend generation: Build pass rate, acceptance case pass rate, and manual-fix volume on the same requirement.
- Self-repair: Average repair rounds, test pass rate after repairs, and the proportion of tasks requiring human takeover.
- Cost: Cost per passing task, computed with your own tasks and prices.
- Quotas and context: Whether weekly usage is sufficient, and the success rate of the long-context position test.
- Security: Sandbox isolation, permission controls, and a working code review process.
The scope of this article is small-to-medium web projects and script-based engineering. For embedded systems, high-concurrency trading systems, or projects involving personal data, additional security review and compliance assessment are required; the practices here cannot be applied directly.
Three takeaways: First, model selection should be based on measured results on the same set of test cases, not on marketing numbers. Second, an Agent must have iteration limits, rollback, and human takeover to safely handle long-running tasks. Third, calculate cost based on tasks that pass, not on the number of calls.
