From Repeated Failures to Stable Operation: A Practical Guide to AI Agent Automation

    This article explains how to build reliable automation with AI agents for high-volume, low-tolerance tasks such as trend-chart analysis. It covers splitting responsibilities between the agent, deterministic programs, and humans; designing a verifiable pipeline; state-driven browser automation; screenshot capture; converting images into structured matrices; versioned business rules; persisting lessons into the system; building recovery into batch jobs; and measuring reliability with layered acceptance metrics. Readers will learn why "reminding the model to be careful" fails and how engineering constraints turn fragile scripts into sustainable automation.

    1. Define the Goal First: Automation Is Not About Letting the Model Do Everything

    Logging into a business site every day, searching for target records, capturing hundreds of trend charts, and then recognizing and tallying each one is a classic high-repetition, low-tolerance task. It may look like “just a few clicks,” but it actually combines page interaction, image understanding, business-rule execution, and result validation all at once.

    Handing the entire task to an agent to operate freely usually runs into three problems:

    First, page state is unstable. Session expiry, pop-up prompts, asynchronous loading, and layout changes can all push subsequent actions off course.

    Second, image recognition cannot aim only for “looking reasonable.” A single misread digit or color can corrupt an entire matrix and then contaminate the final tally.

    Third, a correction in conversation does not mean the capability has been fixed into the system. The model understanding a problem in one exchange does not guarantee that later runs will honor the same constraints.

    So the reliable approach is not to “keep reminding the model to be more careful,” but to redraw responsibilities:

    The agent assists with development, explains anomalies, and proposes fixes; deterministic programs handle collection, recognition, computation, and validation; humans handle edge cases that cannot be confirmed automatically.

    This division does not weaken the agent’s value; it puts the agent where it fits best.

    2. Break Business Operations into a Verifiable Pipeline

    For trend-chart analysis, the full workflow can be split into seven stages:

    1. Verify authorization status and enter the business page.
    2. Search for target records based on the task list.
    3. Retrieve the primary trend chart.
    4. Retrieve the numbered or auxiliary chart that corresponds to the primary one.
    5. Convert the image into a structured numeric matrix.
    6. Compute results using versioned rule algorithms.
    7. Aggregate the output and retain evidence.

    What matters is not the number of steps but that each step defines its input, output, and success condition.

    For example, “search complete” should not mean the search button was clicked, but that the page displayed results matching the target conditions; “screenshot complete” should not mean an image file was generated, but that the file is readable, its dimensions match expectations, and it contains the target chart.

    It is worth creating an independent record for each task:

    1. Task record
    2. Task ID
    3. Business date
    4. Query conditions
    5. Current stage
    6. Primary chart location
    7. Auxiliary chart location
    8. Recognition result location
    9. Rule version
    10. Execution count
    11. Error reason

    The primary and auxiliary charts should be bound through a stable task ID rather than relying on file generation order. Otherwise, a single retry can cause a mismatch: the image itself is fine, but a different record is being analyzed.

    3. Browser Automation: From Coordinate Clicks to State-Driven

    3.1 Locate by Business Semantics, Not Fixed Positions

    Fixed screen coordinates are easily affected by window size, zoom level, and page layout. A more robust approach is to locate elements by their accessible names, label associations, stable attributes, or container structure.

    Before acting, also verify the target element:

    • Does it exist;
    • Is it visible;
    • Is it in an interactive state;
    • Is there exactly one clear match;
    • Is it within the expected business region.

    If multiple matches appear, do not arbitrarily pick the first one; instead, narrow the locator further or mark the task as a page-structure anomaly.

    3.2 Wait for Business Conditions, Not Blind Delays

    A fixed wait of a few seconds cannot adapt to both fast and slow networks. A more reliable approach is to wait for an observable business condition, such as the results table appearing, the loading indicator disappearing, or the target chart finishing its draw.

    Note that a page stopping its requests does not necessarily mean the chart has finished drawing. For dynamic drawing regions, also judge by loading markers, chart dimensions, or short-term visual stability.

    Every wait must have an upper bound. On timeout, save the current state, then decide whether to retry or abort, rather than waiting indefinitely.

    3.3 Define Explicit Rules for Pop-ups

    Classifying pop-ups by type avoids misoperations:

    • Known non-critical prompts can be dismissed following confirmed rules;
    • Session-expiry prompts should enter the re-authorization flow;
    • CAPTCHAs or multi-factor authentication should be handed to a human;
    • Unknown pop-ups should save the page state and pause the current task.

    Do not let the program “try clicking every suspected close button.” That strategy can close the business page, cancel operations, or even trigger buttons with real consequences.

    3.4 Respect Access Boundaries

    Automation should run within authorized scope and follow the site’s terms of use. When facing CAPTCHAs, rate limits, or anti-automation prompts, do not bypass security controls.

    Login credentials should also not be written into scripts, ordinary logs, or conversation records. Use a controlled credential-management approach and restrict the permissions of the running account.

    4. Screenshot Capture: Recognition Quality Starts with Input Quality

    Many recognition problems are not caused by the algorithm but by inconsistent screenshot scope and image state.

    It is best to capture the chart element or a confirmed business region rather than the entire desktop. Page titles, ads, notification bars, and toolbars add irrelevant noise and may also expose unnecessary business information.

    At a minimum, the capture stage should check:

    1. Whether the image was fully generated and can be read normally;
    2. Whether the chart region’s dimensions fall within the expected range;
    3. Whether there are blanks, occlusions, or loading prompts;
    4. Whether the target identifier on the page matches the task;
    5. Whether the primary and auxiliary charts belong to the same record.

    If a fixed layout changes, first judge whether it can be reliably normalized before cropping or scaling. Do not stretch images arbitrarily just to fit the recognition program, or character shapes and grid proportions may be distorted.

    Also keep both the original and the processed images. The former is for traceability and the latter for recognition; the two serve different purposes and should not overwrite each other.

    5. Image to Matrix: Don’t Make the Model Guess What Can Be Computed Deterministically

    5.1 Why a Vision Model May Not Suit Cell-by-Cell Reading

    Vision models are good at understanding open-ended images, such as summarizing a trend, explaining an anomaly pattern, or grasping a complex layout. But recognizing charts with clear rules and fixed styling demands cell-by-cell consistency and reproducibility.

    If the task is to recognize digits, colors, and positions within a fixed grid, local image processing is often easier to control for cost, localize errors, and build tests.

    However, “local processing” is not automatically accurate. Color drift, compression noise, font changes, zoom level, and occlusion all affect results. The correct goal is verified reliability within a clearly supported range, not a claim that any image can be recognized perfectly.

    5.2 First Check for an Authorized Structured Data Source

    Before designing image recognition, confirm whether the page offers a permitted data export, table content, or structured data interface.

    If the raw data can be obtained legally, it should generally be preferred, with screenshots serving as audit evidence. Only when no suitable data source exists should image recognition become the primary path.

    5.3 Build a Layered Recognition Flow

    A general approach is as follows:

    1. Raw image
    2. → Chart region localization
    3. → Size and layout check
    4. → Grid division
    5. → Cell color and character feature extraction
    6. → Value mapping
    7. → Matrix structure validation
    8. → Accept result or send to manual review

    For color classification, use range checks in a suitable color space rather than comparing whether a pixel equals a fixed color value. For each cell, sample from multiple positions and avoid text and borders as much as possible to reduce interference from anti-aliasing and compression.

    For character recognition, template matching can be tried when the font is fixed and the character set is small; when fonts and backgrounds vary widely, a general character-recognition method may be needed. Either way, clearly define the supported range of styles.

    5.4 Uncertain Results Must Be Exposed Explicitly

    The recognition program should be allowed to output “cannot confirm” rather than forcibly filling in the closest-looking digit.

    For example, if a cell’s color falls in the boundary region between two categories, or a character’s difference from multiple candidate templates is close, it should be flagged for review.

    Metrics like template similarity or color distance are not necessarily statistical probabilities and cannot be treated directly as accuracy. They can serve as a basis for accepting or rejecting a result, but thresholds must be calibrated with representative samples.

    After the matrix is generated, also check row and column counts, value ranges, nulls, and business relationships. Passing a structure check only means the result satisfies constraints; it does not mean the recognition is correct, so a sampling-review mechanism must still be retained.

    6. Business Algorithms: Turn Natural-Language Rules into Testable Computation

    Recognition and computation must be separated.

    The recognition module only answers “what is in the image”; the rule module answers “what these data mean under the business definition.” Mixing the two makes errors hard to localize.

    The rule algorithm must at least define:

    • The orientation of the input matrix;
    • How blanks, missing values, and invalid values are handled;
    • How a continuous trend is defined;
    • Whether the statistical window includes boundaries;
    • The priority when multiple rules conflict;
    • Whether the aggregation denominator uses successful tasks or all tasks.

    Here is language-agnostic illustrative logic:

    1. Process a single task:
    2. Read and validate task info
    3. Get primary and auxiliary charts
    4. Check image quality and correspondence
    5. Recognize matrix
    6. If matrix fails validation:
    7. Save evidence
    8. Move to review queue
    9. End current task
    10. Load specified rule version
    11. Compute result
    12. Save matrix, result, and rule version
    13. Mark task complete

    Rule changes must produce a new version. If historical results used an old rule, retain version information to avoid mixing data computed under different definitions in the same tally.

    7. Avoid Repeated Corrections: Write Experience into the System, Not the Conversation

    Repeatedly telling the agent “don’t do that again” is usually less effective than adding a single check condition.

    Each time an error is found, answer three questions:

    1. At which stage did the error occur?
    2. Why did the existing check fail to catch it?
    3. How can the same class of error be detected automatically if it recurs?

    The corresponding fix should generally land in four kinds of persistent assets:

    • Operating specs: record stage order, inputs and outputs, and prohibited actions;
    • Configuration rules: record page locators, image layout, and recognition mappings;
    • Test samples: preserve known problems and their correct results;
    • Regression checks: verify that a fix did not break existing flows.

    For example, if the program once treated an auxiliary chart as the primary one, add an image-type check; if the program once missed the last record, add a task-count reconciliation; if a rule once misjudged a boundary value, add a test for that boundary.

    This does not necessarily involve training model parameters; more precisely, it turns temporary experience into repeatable software constraints.

    8. Make Batch Tasks Recoverable

    When one run processes hundreds of records, partial failures should be treated as normal, not as a reason for the whole batch to crash.

    8.1 Support Resume-from-Checkpoint

    Persist task state so that on restart only incomplete or retry-allowed tasks are processed. When saving files, write to a temporary file first and replace the official result only after successful validation, reducing the risk of leaving half-finished output after an interruption.

    8.2 Ensure Repeated Runs Do Not Double-Count

    When the same task is rerun, it should update the corresponding result rather than keep appending. The task ID can be generated from the business date and record identifier, and the final aggregation should deduplicate by task ID.

    8.3 Distinguish Retry from Repair

    Temporary network errors can be retried a limited number of times; page-structure changes, rule conflicts, and recognition uncertainty usually will not resolve themselves by running a few more times.

    Define strategies by error type and set a maximum number of attempts to avoid endless clicking, requests, or model calls.

    8.4 Control Concurrency by Stage

    Concurrency for page collection must consider the site’s allowed access rate and session behavior; concurrency for local image processing depends on processor, memory, and disk resources. The two should not share the same simple limit.

    On older devices especially, limit the number of pages open at once and monitor memory usage. Otherwise, increasing concurrency may bring more timeouts and screenshot failures.

    9. Acceptance Metrics: Don’t Just Look at “The Flow Finished”

    Whether the automation is reliable must be measured in layers:

    • Collection success rate: whether target records were correctly obtained;
    • Image qualification rate: whether screenshots meet recognition requirements;
    • Cell recognition accuracy: whether it matches manual annotation;
    • Whole-image full-correctness rate: whether an image contains any recognition error;
    • Auto-pass rate: the proportion of tasks needing no human intervention;
    • End-to-end correctness rate: whether the final result matches review;
    • Cost per task: computation, storage, model calls, and review costs;
    • Recovery time: how long it takes to recover after an anomaly.

    High cell accuracy does not mean the whole image is reliable. The more cells an image has, the greater the chance of at least one error, so whole-image correctness must be evaluated separately.

    The test set should cover normal samples, different layouts, color shifts, occlusions, empty data, and session expiry. Debug samples and final acceptance samples should also be kept separate to avoid performing well only on familiar images.

    A three-step rollout is recommended: first validate the flow with a small number of tasks, then run in parallel with manual results for comparison, and finally expand the scope of automatic execution gradually. For high-impact results, retain manual review or sampling review rather than skipping validation outright.

    10. Conclusion: Reliable Automation Comes from Engineering Constraints

    When handing repetitive work to an agent, the truly hard part is not generating the first script, but keeping the flow controllable when pages change, recognition is uncertain, and tasks are interrupted.

    The core of a reliable solution can be summarized in five points: business state is verifiable, recognition results can be rejected, computation rules are traceable, task execution is recoverable, and historical errors are regression-tested.

    Once these mechanisms are in place, the agent is no longer a temporary assistant that needs constant reminding, but a collaborating role within the automation system. Humans no longer need to inspect every image, and can focus their attention on anomaly review, rule maintenance, and business judgment. That is the truly sustainable efficiency gain of batch trend analysis.