A Guide to Engineering AI Agents with General Multimodal Models
This article provides a comprehensive engineering guide for building and deploying AI agent applications using general multimodal models. It covers key aspects including transitioning from question-answering to task completion, defining model capability boundaries, designing robust agent workflows, optimizing code generation, managing costs and efficiency, establishing evaluation systems, ensuring security governance, and adopting a phased implementation strategy.
1. From “Answering Questions” to “Completing Tasks”
The value of a general model lies not just in generating fluent text, but in its ability to help users complete tasks with clear goals, constraints, and acceptance criteria. Tasks such as organizing materials, analyzing screenshots, modifying code, comparing candidate solutions, and executing multi-step workflows can all be initiated via natural language, yet their engineering complexity varies significantly.
Simple Q&A relies primarily on the model’s inherent knowledge and current context. Complex tasks, however, require managing intermediate states, accessing external information, invoking tools, and checking execution results. When building such applications, the model should be treated as a reasoning and generation component within the system, rather than an autonomous execution entity with unlimited permissions that guarantees correct outcomes.
From an engineering perspective, evaluating general models should cover three dimensions:
- Task Quality: Is the final result correct, complete, and compliant with user constraints?
- Execution Efficiency: How many interaction rounds, tool calls, and generated tokens are required to complete the task?
- Operational Controllability: When errors occur, can they be located, halted, recovered, or escalated to human operators?
These three dimensions must be optimized together. Pursuing only natural expression can compromise factual and execution accuracy; pursuing only response speed may eliminate necessary verification steps.
2. Defining Capability Boundaries: Avoiding Confusion Between Model and System Capabilities
2.1 Multimodal Understanding Does Not Equal Multimodal Generation
Models supporting text and image inputs can explain visible information in pictures, such as identifying UI layouts, describing chart trends, extracting document fields, or locating anomalies in screenshots. However, input and output capabilities are independent issues; the ability to understand images does not mean the model can directly generate images, audio, or video.
Image analysis is also affected by resolution, shooting angle, occlusion, text size, and compression quality. When processing scanned contracts, device screenshots, or business charts, the original materials should be retained, and the output should distinguish between “directly observable information” and “inferences based on context.” For key fields like amounts, dates, and units, adding rule-based validation or manual review is recommended.
2.2 Information Retrieval is an Application Pipeline, Not an Inherent Ability
Whether a model can access the latest information depends on whether the application integrates retrieval capabilities (e.g., RAG), as well as the retrieval scope, access permissions, and content quality. The fact that a model can discuss a topic does not mean it has accessed relevant materials.
A reliable information retrieval pipeline typically includes: clarifying the question, forming a query, fetching materials, determining relevance, extracting evidence, and generating a conclusion. Conclusions should be traceable to the materials used, with retrieval timestamps noted. For time-sensitive information, the time of the event, the publication time of the material, and the retrieval time should be clearly distinguished.
2.3 Computer Operation Relies on a Controlled Execution Environment
While a model can analyze operational targets and propose steps, actions like clicking UI elements, modifying files, or submitting forms must be performed by external execution components. Permissions, session states, and execution results must be managed by the system.
Therefore, applications should clearly distinguish between “suggest execution,” “approved execution,” and “executed.” Generating operational instructions does not mean the action has been successfully completed; the task status should only be updated to success when the execution component returns a valid result and passes inspection.
3. Agent Workflows: Constraining Uncertainty with Deterministic Mechanisms
Multi-step agents are suitable for tasks with clear goals that require cross-stage collaboration. For example, extracting changes from a set of requirements, locating related code, proposing modifications, running tests, and compiling delivery notes.
The following basic workflow is recommended:
Receive Task → Clarify Constraints → Formulate Plan → Execute Actions → Verify Results → Decide to Continue, End, or Escalate
3.1 Task Descriptions Must Include Acceptance Criteria
“Fix this issue” is usually not specific enough. A more effective task description should state the expected behavior, current anomalies, impact scope, immutable parts, and verification methods.
For data organization tasks, acceptance criteria might include having all specified fields, citing sources for each conclusion, and explicitly marking missing information. For code tasks, it could mean passing target tests, maintaining API compatibility, introducing no extra dependencies, and aligning the change scope with requirements.
Clearer acceptance criteria make it easier for the system to determine task completion and prevent infinite revision loops.
3.2 Plans Should Update with Evidence, Not Execute Rigidly
An initial plan is merely a set of assumptions to be verified. If a tool returns information that contradicts expectations, the system should reassess the next step rather than mechanically executing the original plan.
However, re-planning must be subject to budget constraints. Applications can set maximum steps, longest execution time, and tool call limits based on business requirements. These limits are application-level policies and should not be misunderstood as inherent model parameters.
3.3 Explicitly Save Task States
Long-running tasks should not rely entirely on chat history to save progress. The system should record completed actions, key evidence, failure reasons, pending items, and the current version.
State records should be concise to avoid dumping excessive raw logs into the context. Important original text can be stored in external storage, with the model receiving only necessary fragments and reference IDs. When summarizing key constraints, care must be taken to prevent omissions, especially regarding user authorization scope and acceptance criteria.
3.4 Design Idempotency Protection for Execution Actions
Tasks may be retried due to network interruptions or service anomalies. If the same step is executed repeatedly, it may cause duplicate submissions, duplicate messages, or file overwrites.
Therefore, the execution layer should check if an action has already been completed and adopt idempotent designs where applicable. For operations that are difficult to undo, a pending execution list should be formed and submitted only after confirmation.
4. Code Development: Generation is the Starting Point, Verification is the Loop
The core of an AI programming application is not generating more code, but completing correct changes with lower manual effort.
4.1 Establish Minimal Sufficient Context
The model needs to understand the target code, related APIs, test requirements, and necessary dependencies, but it does not necessarily need to read the entire project. Adding irrelevant files to the context increases costs and may interfere with judgment.
You can first locate the error position and call chain, then gradually supplement related context. For large projects, provide module responsibilities, build methods, and constraint specifications so the model understands the boundaries where modifications should fall.
4.2 Prioritize Reviewable, Small-Scale Modifications
Changing multiple modules at once may seem efficient, but it expands the verification scope and increases rollback difficulty. A safer approach is to form the minimal change first, explain the reason, and then execute targeted tests.
If the issue involves public APIs, data structures, or persistence logic, compatibility must also be analyzed. Code that runs successfully does not mean it will not break existing callers or historical data.
4.3 Replace Self-Evaluation with Execution Results
“The code is fixed” is not acceptable verification evidence. Valid evidence should include actual test results, static analysis results, build outputs, and necessary runtime logs.
The following closed loop is recommended:
Understand Problem → Propose Hypothesis → Modify Code → Execute Checks → Analyze Failure → Limited Fixes → Output Change Report
The change report should state what was modified, what was verified, and what conditions remain unverified. If the environment cannot execute tests, the limitations should be explicitly stated rather than describing expected results as facts.
5. Efficiency and Cost: Measuring by Successful Tasks
The cost of model applications cannot be judged solely by single-call pricing or output length. Factors that truly impact the budget include input size, failed retries, tool execution, wait times, and manual review.
The following general metric can be used:
Cost per Successful Task = Total Investment During Evaluation Period ÷ Number of Tasks Meeting Acceptance Criteria
Here, total investment can include model call fees, external tool fees, runtime resource costs, and manual processing costs. For critical business operations, potential losses caused by errors should also be considered.
5.1 Less Output is Not Necessarily More Efficient
Reducing repetitive descriptions and verbose explanations usually helps lower overhead, but if critical verifications, source citations, or risk warnings are omitted simultaneously, the overall rework cost may actually increase.
When optimizing output, compress invalid repetitions rather than necessary information. For example, code tasks can prioritize outputting change summaries, check results, and residual risks without repeatedly reiterating all requirements.
5.2 Tiered Task Processing
Simple classification, field extraction, and formatting can use shorter pipelines, while cross-document reasoning, complex code modifications, and high-risk decisions require more sufficient context and verification.
Tiering should be based on actual evaluation, not whether “the task looks simple.” Some short questions may contain complex business constraints, while some long document tasks are just rule-based extraction.
5.3 Distinguish Response Speed from Completion Speed
The user-perceived first response time is not the same as the actual task completion time. Quickly providing a plan does not mean finishing the work faster.
Therefore, you should simultaneously observe first response latency, total completion latency, tool wait time, and rework frequency. Optimization can start by eliminating invalid serial steps, but operations with dependencies should not be blindly parallelized for speed.
6. Evaluation Systems: Turning Abstract Capabilities into Business Evidence
General evaluations provide references but cannot directly replace an enterprise’s own validation. Different tasks have different data distributions, prompt formats, tool environments, and scoring rules, so evaluation results often cannot be simply cross-calculated.
When building an internal evaluation set, it should cover normal cases, missing information cases, abnormal inputs, and high-risk edge cases, while retaining independent validation samples.
It is recommended to track at least the following metrics:
- Task success rate and key field accuracy;
- Tool call success rate and failure recovery capability;
- Average cost, completion latency, and tail latency;
- Evidence integrity of results;
- Manual takeover ratio and rework frequency;
- Unauthorized operations and sensitive information leakage.
For complex tasks, execution traces should be retained to determine whether failures stem from model understanding, retrieval quality, tool anomalies, or unclear acceptance rules. Without error classification, optimization can easily degrade into repeatedly adjusting prompts.
7. Security Governance: Stronger Capabilities Demand Clearer Authorization Boundaries
The fact that a model can understand or generate highly complex content does not mean it can unconditionally execute related tasks. Especially in cybersecurity, life sciences, and sensitive data scenarios, capability level, usage authorization, and business compliance are distinct issues.
7.1 Enforce Least Privilege Configuration
Tools should only have the permissions required for the current task. Reading data, modifying data, and sending data externally should be controlled separately. For actions involving deletion, payment, permission changes, or public release, independent confirmation steps should be set up.
7.2 Treat External Content as Untrusted Data
Web pages, files, and retrieval results may contain text that induces the model to alter its task objectives. Applications should not automatically elevate such content to system instructions, let alone allow it to expand tool permissions.
Risk control must be implemented at the execution layer, including allowed resource access scopes, action type checks, and interception of sensitive operations. You cannot rely solely on the model to judge whether external content is trustworthy.
7.3 Establish Audit and Rollback Capabilities
Critical tasks should record input summaries, authorization scope, executed actions, approval records, and result statuses. Sensitive content in logs also requires access control and retention period management.
For changes that can be rolled back, a recovery plan should be prepared before execution; for irreversible operations, confirmation requirements should be heightened. Audit records are used to track facts; the model’s generated explanations should not be treated as actual execution logs.
8. Implementation Path: Validate First, Then Expand
Enterprises can start with low-risk, easily verifiable tasks, such as internal data organization, non-critical copy drafting, or read-only code analysis. After verifying task quality and cost on a small scale, controlled writes, cross-system collaboration, and long-process execution can be gradually introduced.
The launch process should adopt a phased strategy: conduct offline evaluations first, then limited trials, followed by gradual scaling by business scope. When the model version, prompt templates, retrieval configuration, or tool permissions change, regression tests should be performed, and a rollback plan should be retained.
Ultimately, whether a general model application is reliable depends on whether the complete system can continuously provide verifiable results. The model handles understanding and generation, tools handle real execution, processes manage permissions and states, and evaluation proves effectiveness. Only by designing these components together can multimodal understanding, code assistance, and agent capabilities be transformed into stable productivity.
