Building AI Agents for Complex Software Engineering: A Practical Guide
Putting a general-purpose LLM into a real development workflow is rarely limited by whether it can write a single function. The hard parts are long task horizons, messy context, vague acceptance criteria, and the fact that once output enters a codebase, it creates ongoing costs. This article explains how to treat an engineering agent as a constrained working system: defining where it applies, writing clear task contracts, planning and self-verification, using multimodal inputs effectively, setting up automated triggers and security boundaries, interpreting benchmarks, managing token costs, and following a production readiness checklist. It is a practical guide for engineering teams that want agents to handle more complex, long-running coding tasks while keeping errors discoverable and reversible.
Beyond Code Generation: A Constrained Working System
When you put a general-purpose large model into a real development workflow, the difficulty is usually not “can it write a function.” The real challenges are long task horizons, complex context, ambiguous acceptance criteria, and the fact that once output enters the codebase, it carries ongoing costs. An agent built for complex software engineering is fundamentally a constrained working system: it receives goals and constraints, plans steps, invokes tools, produces changes, and proves the result with repeatable checks—rather than just returning a plausible-looking block of text.
Where These Systems Fit
This kind of system suits scenarios where requirements are reasonably describable, the repository structure is stable, and tests and static checks already exist—for example, bug fixes, filling in API implementations, drafting documentation and UI mockups, and repetitive refactoring. It is not suitable as the sole responsible party for safety-critical changes, unclarified business rules, or legacy systems that lack regression safeguards.
Human oversight should scale with risk, not be eliminated across the board. Low-risk, automatically revertible changes can get lighter spot-checking; changes involving permissions, money, data leaving a boundary, or production configuration should retain review and release gates. “Reducing supervision” means shifting it from line-by-line code reading to defining goals, constraints, and acceptance criteria up front.
Task Contracts
Most long-horizon coding failures trace back to unclear contracts. Before work begins, write down at least four things:
- Goal: The user-visible behavior or internal invariant to change.
- Scope: Directories that may be modified, modules that are off-limits, compatibility requirements.
- Evidence: Tests, type checking, builds, UI screenshots, or metric comparisons—at least one that is automatically repeatable.
- Stop conditions: Passed; blocked (missing permissions or information); or over budget (steps, time, tokens).
A sample task description can be short, but must be executable:
Goal: Add pagination to the order query API, 20 items per page by default, 100 max.Scope: Only modify the query interface and its tests; do not change the database schema.Evidence: New tests pass; no regression in existing cases; out-of-range page numbers return a clear error.Stop: Stop when tests are green, or after two consecutive failed fix attempts—then report the blocker.
The agent should restate the constraints before starting work. When the restatement disagrees with the human’s contract, the human’s contract wins—not the model’s “reasonable inference.”
Planning, Execution, and Self-Verification
Complex tasks should be split into small, revertible steps: read the relevant code, list assumptions, make the minimal change, run checks, and iterate based on failure information. Each step should introduce only one major change, which makes regressions easier to localize.
Self-verification is not generating the answer again—it means designing checks before delivery. Effective checks typically include:
- Comparing against the requirements line by line and flagging uncovered items.
- Running existing and new tests, recording the commands and a summary of results.
- Testing boundary inputs side by side: null values, extreme values, insufficient permissions, duplicate submissions.
- Checking whether the diff goes out of scope—unexpected reformatting, dependency upgrades, secrets or internal addresses leaking into output.
When verification fails, the agent should return a blocker description and the paths it already tried, not a longer explanation that papers over failed checks. The verification design itself can be part of the deliverable: a plan, a diff, and evidence—the three together are easier to review than a single block of code.
Using Multimodal Inputs
Professional tasks often mix interfaces, slides, scanned documents, and code. Higher resolution helps with small fonts, thin borders, and table lines, but raising resolution increases visual tokens and processing latency. In practice: crop the relevant region first and strip decorative backgrounds before sending an image to the model; for multiple rounds of questions about the same image, reuse the structured results already extracted rather than re-uploading the original.
Visual capability is good for generating UI sketches, proofreading layouts, and recovering fields from screenshots—but it is not suitable as the sole basis for pixel-level acceptance. Final acceptance should still rely on component-library constraints, accessibility checks, and human review. The same applies to documents and slides: the model handles structure and key points, while brand guidelines, data definitions, and external commitments are approved by people.
Automated Triggers
Turning a model into an “on-duty cloud assistant” hinges on triggers and permissions, not slogans. Three common trigger types can be combined:
- Scheduled: dependency audits, license expirations, periodic reports.
- API-based: ticket status changes, pipeline failures, monitoring alerts.
- Repository events: merge request opened, changes to specified paths, release tags created.
Every trigger should carry minimal context: repository version, relevant log fragments, and the list of permitted operations. Default to read-only; restrict write access to branches or draft directories. Execution records should preserve input summaries, tool calls, diffs, and conclusions for post-hoc auditing. Scheduled tasks also need re-entrancy protection so the same fault isn’t repeatedly “fixed.”
Companies deploying this pipeline on their own cloud can use general-purpose container platforms, object storage, message queues, and logging/monitoring infrastructure to host queues, artifacts, and traces. General cloud infrastructure such as Baidu AI Cloud can carry the compute and storage, but model policy, repository permissions, and release gates should still be defined by the deploying organization—these should not be defaulted to an outsourced, custom-consulting arrangement.
Security and Network Capability Boundaries
A coding agent has access to code, secrets, and runtime environments, so security design must come before capability demos. Differentiating network offensive/defensive capabilities in training or policy preserves defensive use cases—vulnerability fixing, configuration hardening, log investigation—while reducing the risk of unauthorized intrusion, malware, and availability attacks. On the product side, the common approach is request classification with refusal policies: when a prohibited or high-risk cybersecurity use is detected, block it outright rather than offering “half” a set of steps.
When implementing, apply these controls in parallel:
- Tool allowlists—no arbitrary host commands or outbound connections.
- Secret scanning, with sensitive data masked in output and logs.
- Persistent refusal of high-risk intent, without relaxing it because the request is framed as “research” or “an exercise.”
- Track security metrics separately from functional metrics: refusal accuracy, false-block rate, and unauthorized tool-call attempts.
Different versions may trade off along these metrics—no single score means “safer.” After any change, run a regression set: legitimate development requests should not be broadly blocked, and clearly offensive requests should not be completed.
How to Read Benchmarks
Software engineering benchmarks typically give a model a real or realistic ticket and require it to change the repository until tests pass. Scores reflect a specific problem set, time budget, and tool environment—they cannot be directly converted into team productivity. When reading results, check at least: whether multiple attempts are allowed, whether the model can see the tests, whether failures are counted, and whether tasks skew toward one language or framework.
Agent benchmarks for financial analysis or office documents work the same way: they test the ability to gather information per instruction, compute, and form verifiable conclusions. Being ahead or behind only holds within that benchmark’s definition. Before adopting an agent, a more useful approach is a small sample from your own repository: fix 20–50 historical tickets and compare pass rate, average lines of manual correction, and rework count.
A knowledge cutoff date determines what library versions, regulations, and product interfaces a model recognizes by default. Information after the cutoff should come from retrieval or the repository itself, and answers should cite the source—never present memorized knowledge as current fact.
Cost and Tokens
Pricing is usually per input and output token. After a tokenizer change, the same source code, Chinese comments, or logs may map to more tokens, and the bill rises even at an “unchanged unit price.” Before launch, estimate with real samples: how much goes to system prompts, repository excerpts, tool responses, and multi-round fixes. Effective cost controls are shrinking context, caching stable prefixes, limiting retries, and stopping when verification fails instead of looping in endless self-dialogue.
Visual inputs, long logs, and full diffs are the biggest sources of bloat. If you can cite line numbers and symbol names, don’t paste entire files.
Launch Checklist
- Write clear task contracts and stop conditions.
- Open only the tools and directories needed to complete the task.
- Enforce tests or checks and attach evidence to the result.
- Have humans review high-risk diffs; auto-merge only low-risk, revertible items.
- Record traces and regularly audit refusals, false blocks, and unauthorized actions.
- Re-test with your own tickets; don’t base procurement or release decisions on external leaderboards.
Organized this way, an agent can handle more complex, more time-consuming coding and professional deliverables, while keeping errors within a discoverable, revertible range. Better capability should show up as fewer wasted round-trips and more complete evidence—not as less accountability.
