Agent Automation in Practice: From Repeated Pitfalls to Reliable Delivery
This article offers a practical guide to building reliable agent-assisted automation for repetitive data-processing workflows. It covers workflow decomposition, data contracts, state-based web interaction, image-to-matrix processing, regression testing, executable algorithm definitions, idempotent pipelines, cost and security considerations, and a phased rollout. The goal is to help teams move from constant supervision and repeated fixes to measurable, recoverable production operations.
1. Change the Goal: Build a Reliable Process, Not “Teach the Agent”
Logging in to a business website every day, searching for specified objects, saving hundreds of trend charts, and then judging each trend, marking data, and calculating results is a typical repetitive data-processing task. The steps are relatively fixed, but they contain many details: whether pages load completely, whether screenshot areas are correct, whether legends change, whether data is duplicated, and whether statistical definitions remain consistent.
Handing the entire job to an agent may look like a quick way to free people from manual work, but it often creates another situation: the person moves from executor to full-time supervisor. The agent occasionally locates the wrong element, misrecognizes an image, or skips a step, which means explaining requirements again, fixing scripts, and checking results.
The root cause is that automation cannot rely only on natural language understanding. It also needs explicit inputs and outputs, executable constraints, and verification mechanisms independent of the agent.
A more reasonable goal is:
Let the agent assist with development and handle exceptions, let deterministic programs perform high-frequency execution, and let verification rules determine whether a task is truly complete.
For trend-chart analysis, the business workflow can be reconstructed into seven stages:
Authorized login → precise search → base-view collection → grouped-view collection → image structuring → rule-based calculation → summary acceptance.
Informal screenshot names from the original business process should be mapped to formal data categories and collection specifications rather than written directly into scripts. Only when each stage can be tested independently does the complete workflow have a foundation for stable operation.
2. Define Data Contracts Before Writing Automation Code
The most common mistake in automation development is to let the agent generate a script that “runs,” then keep patching it. Systems built this way usually lack boundaries: what input a step requires, what output it produces, and whether it can continue after failure are all unclear.
Define a data contract for each stage.
For example, the input for a screenshot task should include at least:
- task ID;
- business object identifier;
- query conditions and statistics date;
- screenshot category;
- expected chart area;
- page layout or collection rule version.
The output should include at least:
- actual query conditions;
- collection time;
- image location;
- image dimensions;
- page status;
- completeness check result;
- failure reason.
These fields are not meant to add documentation overhead. They prevent “a file exists” from being treated as success. Even if a screenshot is saved successfully, it may show a login page, a loading placeholder, or the wrong business object.
Likewise, the image-recognition stage should not output only a numeric matrix. It should also include matrix dimensions, invalid cell positions, quality metrics, and recognition rule version. Only then can downstream algorithms judge whether the input is worth using.
Business identifiers should also remain explicit data fields. If an identifier contains leading zeros, it must not be casually converted to an integer, because that may change its business meaning.
3. Web Operations: Replace Repeated Trial and Error with State Checks
1. Element location should express business meaning
Clicking based on fixed screen coordinates is vulnerable to window size, zoom level, and page layout changes. A more robust approach is to locate targets by semantics, visible labels, and stable attributes, and to check whether the match is unique.
When multiple candidates exist for a search box, the program should not simply choose the first one. It should consider the surrounding region, visibility, and context. If it cannot determine the target, it should stop the task and record page evidence rather than continue generating potentially incorrect screenshots.
2. Page waits should be tied to business states
Fixed waits of a few seconds can be an auxiliary measure, but they should not be the main basis for deciding that a page has finished loading.
A more reliable process should confirm in sequence:
- whether the login success marker appears;
- whether the search control is operable;
- whether query conditions are correctly entered;
- whether the loading state has ended;
- whether the current result corresponds to the target object;
- whether the chart area contains collectable content.
This is effectively a finite-state machine for the page. The program enters the next stage only when preconditions are satisfied, avoiding execution before the page is ready.
3. Popups and verification should be handled by category
Ordinary prompt dialogs, session expiry, and security verification should not share one handling logic.
Known ordinary popups can be closed by explicit rules; session expiry should enter the authorized login flow; when a CAPTCHA or additional identity verification appears, it should be completed by a human or replaced with an officially supported data-access method. Security mechanisms should not be bypassed.
Access frequency should also follow website rules. Read-only tasks should limit permissions and access rates, so data collection automation does not become unnecessary pressure on the business system.
4. Retries must be bounded
Retries are suitable for temporary failures such as network jitter or page-load timeouts. However, if a locating rule has already failed, repeating the same operation will not recover automatically.
Distinguish between:
- Retryable errors: brief connection anomalies, load timeouts;
- Errors requiring fixes: layout changes, missing fields, non-unique locators;
- Errors requiring human intervention: identity verification, insufficient authorization, unclear business conditions.
Retry counts, waiting strategies, and exit conditions should all be defined in advance. The agent must not be allowed to click in an infinite loop.
4. Image Structuring: Prefer Fixed Rules, Use Vision Models for Exceptions
Converting trend charts into numeric matrices is the most critical quality gate in the entire workflow. If recognition results are wrong, even a perfectly correct downstream calculation is only processing incorrect input precisely.
1. First determine whether screenshot recognition is really necessary
If the business system provides authorized data export or an official data API, structured data should be preferred. Compared with recovering values from images, structured data is usually easier to verify and less affected by page styles.
Only when the business can present information only as charts should the image-processing workflow be used.
2. Fixed layouts are suitable for deterministic image processing
Local image processing can be considered when charts have the following characteristics:
- grid rows and columns are basically fixed;
- colors have a stable mapping to business states;
- legend and coordinate areas can be clearly separated;
- screenshot source, zoom level, and theme are relatively consistent.
A common processing chain is:
region cropping → grid localization → cell segmentation → valid pixel filtering → color classification → symbol or number recognition → matrix validation.
Color recognition should not compare whether a single pixel equals one fixed color value. Anti-aliasing, compression, and transparency overlays all introduce deviations. First filter out backgrounds and borders, then calculate the dominant color distribution inside each cell, and classify using an appropriate color space and tolerance.
Numbers, lines, and text annotations require separate handling. Recognizing color is not the same as recognizing values, and the two problems should not be conflated.
3. Vision-language models should not handle all fixed calculations
Vision-language models are suitable for interpreting complex images, handling layout changes, or providing anomaly diagnosis. However, when reading fixed charts cell by cell, they may miss cells, confuse values, or produce outputs that do not match the required format.
A layered strategy can therefore be used:
- Use local deterministic rules for standard charts;
- Move images that fail quality checks into an exception queue;
- Use vision models to assist with exceptions;
- Keep human review or independent verification for critical results.
The value of this design is not simply reducing model calls. It lets different technologies handle the work they are best suited for.
4. Do not promise unconditional 100% accuracy
A batch of samples being fully correct only shows the result on that batch. It does not prove that all future screenshots will be accurate.
Acceptance should at least track:
- cell recognition accuracy;
- the proportion of matrices that are completely correct as a whole;
- detection rate for anomalous images;
- human review rate;
- performance under different layouts, themes, and zoom levels.
Whole-image correctness deserves special attention. For example, suppose each cell has an independent 99.9% chance of being recognized correctly, and one image contains 300 cells. The probability that the entire image is correct is approximately 0.999 to the power of 300, or about 74%. Real errors may not be independent, but this example shows that high local accuracy does not equal a reliable whole image.
5. Turn Repeated Corrections into Persistent Rules and Regression Tests
If an agent repeatedly makes the same mistake, it does not necessarily mean it has completely failed to understand the requirement. A more common problem is that the correction exists only in the conversation context and never enters executable system assets.
After a long interaction, context may be compressed, omitted, or conflict with new requirements. “Remember it next time” alone cannot establish engineering reliability.
Every correction should produce four outputs:
- Failure sample: preserve the corresponding image, page state, or input data;
- Cause explanation: identify the stage where the error occurred;
- Rule update: modify code, configuration, or data definitions;
- Regression test: confirm that the same error will not be triggered again under the same conditions.
For example, if a legend is misrecognized as matrix data, do not simply tell the agent “do not recognize the legend.” Define the crop range or exclusion area explicitly, and add a test image that contains a legend.
It is important to distinguish three kinds of changes:
- changing prompts adjusts the model’s task instructions;
- changing rules and code changes system execution logic;
- training a model with data updates model parameters.
These three should not all be called “training the agent.” For fixed business processes, rule engineering and testing are usually more important than endlessly extending prompts.
6. Algorithm Dictionaries Should Be Executable and Traceable
Deriving trend judgments or statistical results from a matrix must rely on explicit algorithm definitions, not on a model interpreting business rules on the fly.
Each rule should specify:
- the orientation and dimensions of the input matrix;
- the business meaning of each value or state;
- how missing values are handled;
- how boundary conditions are calculated;
- the priority when multiple rules match;
- output fields and explanation format;
- rule version and applicable scope.
For example, “continuous rise” must clarify whether it means strictly increasing across several consecutive positions or whether equality is allowed. “Abnormal change” must clarify the comparison window and the source of the threshold. If definitions are incomplete, the program can only guess.
Result records should also include an input summary, collection rule version, recognition rule version, and algorithm version. In this way, when statistical results change, it is possible to determine whether the raw data changed or the processing logic changed.
For decision-making metrics, also distinguish between “describing historical trends” and “predicting future outcomes.” Automation can improve processing efficiency and consistency, but it cannot give an algorithm predictive capability out of nowhere.
7. Make the Pipeline Support Failure Recovery and Repeated Execution
When processing hundreds of images per day, individual task failures are normal. The system should not rerun the entire workflow from the beginning because one image is anomalous.
A simplified flow can be:
Process a single task:Check task identity and input versionIf a valid result already exists for the same version:Return completed statusCollect target chartValidate page object, chart area, and image completenessIf collection validation fails:Record reason and move to pending queueStop this taskExtract numeric matrixValidate dimensions, value range, and missing positionsIf matrix does not meet quality requirements:Save evidence and mark for reviewStop this taskExecute algorithm with specified versionSave detail results and audit informationMark task complete
There are two key mechanisms here.
The first is idempotency: executing the same task repeatedly should not produce duplicate statistical records. Task identity can be determined by the business object, date, screenshot category, and processing version.
The second is checkpoints: artifacts from stages that have passed validation should be retained. When an algorithm is updated, the matrix can be recalculated without revisiting the website; when recognition rules are updated, saved images can be reprocessed without repeating collection.
The summary stage must separately reconcile:
- expected task count;
- actual completed count;
- failed count;
- pending review count;
- duplicate record count.
Unrecognized data must not default to zero. Otherwise, “no data” will be incorrectly interpreted as “value is zero.”
8. Cost, Security, and Operations Are Part of the Solution
1. Calculate cost across the complete chain
Do not compare only the price of a single model call. Total cost also includes compute resources, failure retries, human review, rule maintenance, and business losses caused by incorrect results.
Local image processing reduces external model calls, but it still has compute and maintenance costs. A model-based approach may start development faster, but it may also add ongoing call and review costs. The choice should be based on actual chart complexity and measurable quality performance, not on a blanket claim that one technology is always cheaper.
2. Tighten permissions and sensitive data handling
Account credentials should not be written into prompts, source code, or ordinary logs. Screenshots may contain internal business information, so data authorization and retention requirements should be confirmed before storage, transmission, or calls to external services.
The automation execution environment should also follow the principle of least privilege. Read-only collection tasks do not need permission to modify business data. Scripts generated by an agent should be reviewed and tested in isolation before entering the production environment.
3. Monitoring should focus on quality, not just process liveness
A script that keeps running does not mean the business results are correct. At minimum, monitor success rate, stage latency, retry count, anomaly recognition ratio, pending review volume, and summary completeness.
If the pending review ratio suddenly rises on a given day, the page theme may have changed or the chart layout may have been updated. The system should raise an alert rather than lowering validation standards just to complete tasks.
9. Rollout Order: Close the Loop First, Then Scale
A four-stage rollout is recommended:
Stage 1: Standardize the business process. Define fields, chart categories, algorithm definitions, and acceptance criteria, and collect samples that include both normal and abnormal cases.
Stage 2: Build the smallest closed loop. Start with a small number of tasks and complete collection, recognition, calculation, and summarization. Verify the results of each stage step by step.
Stage 3: Add reliability. Introduce state machines, bounded retries, idempotent writes, checkpoints, quality thresholds, and a human review queue.
Stage 4: Scale gradually. First run under human supervision, then increase task volume according to quality metrics. Concurrency and access frequency must be constrained by the rules of the business system.
The final acceptance criterion is not that the agent claims “the task is complete.” It is that artifacts are complete, calculations are traceable, errors are discoverable, and failures are recoverable.
Truly reliable automation does not mean letting the model improvise more. It means placing the model’s capabilities in the right positions: helping understand requirements, generate implementations, and analyze exceptions, while programs, rules, and tests guard the boundaries of the results. Only then can repetitive work move from “watching the agent correct errors every day” to “managing a sustainable production process by metrics.”
