Automating Data Trend Analysis with an AI Agent: 7 Days of Pitfalls and Fixes

    This article breaks down a seven-day effort to turn a repetitive data trend analysis workflow into a fully automated agent pipeline. It explains why fixed, structured, verifiable tasks are good candidates for automation, then examines three major failure modes—teaching UI automation through natural language, relying on general-purpose multimodal models for chart reading, and the correct-and-forget loop—along with practical fixes such as explicit selectors, deterministic image processing, and storing knowledge in a repository. It also covers reliability engineering for unattended runs and three transferable lessons for anyone building similar automation.

    1. Background: Time Lost to Mechanical Work

    Anyone doing data trend analysis knows the routine: log into several business systems at fixed times every day, screenshot trend charts one by one, judge the direction by eye, read key values, apply a fixed algorithm dictionary to convert them into conclusions, and compile everything into a table. The work requires little technical skill but depends heavily on human attention. It can consume four to six hours a day, leaving your eyes sore, your judgment drifting, and making it easy to miss or misread charts among hundreds of images.

    This kind of work has three traits: a fixed process, structured input, and verifiable output. Any step that meets all three is a good candidate for an AI agent. Over a seven-day break, I rebuilt this pipeline from “semi-automatic” to “fully automatic,” and hit enough pitfalls along the way to write a case study in what not to do. This article breaks down the failure modes and fixes stage by stage.

    2. Overall Architecture: A Seven-Step Pipeline and Its Weak Points

    The automated pipeline can be abstracted into seven stages:

    1. Session establishment and login state retention
    2. Conditional search and task location
    3. Main chart region capture
    4. Auxiliary metrics region capture
    5. Structuring the image into a numeric matrix
    6. Calculating conclusions using the algorithm dictionary
    7. Aggregating and saving results

    The reliability of a pipeline does not depend on its strongest link but on its weakest. When seven steps run in sequence, even at 99% success per step, the overall rate is only about 93%; run ten charts back to back and an interruption is almost inevitable. So the first design principle is not “raise the ceiling of each step” but make every step retryable, verifiable, and resumable from a checkpoint.

    3. Pitfall 1: Teaching UI Automation Like a Conversation

    The first mistake was repeatedly describing the intended actions in natural language and expecting the model to figure out the right way to locate elements. The result: wrong locators, incorrect search results, and spinning in place whenever a popup, captcha, or loading overlay appeared. Told to “close the popup,” it sometimes clicked the wrong button and sometimes closed the entire tab.

    The root cause is that the determinism required by UI automation conflicts with the ambiguity of natural language. The right approach is to downgrade “description” to “suggestion” and upgrade “selectors” to “contracts”:

    1. # Bad: relying on the model's on-the-spot guessing
    2. # prompt: "close the popup and then search"
    3. # Good: explicit selectors + explicit waiting + fail loudly
    4. def dismiss_overlay(page, timeout_ms=3000):
    5. for sel in OVERLAY_SELECTORS: # candidate selector list maintained by the team
    6. loc = page.locator(sel)
    7. if loc.count() and loc.first.is_visible():
    8. loc.first.click()
    9. page.wait_for_timeout(200)
    10. return True
    11. return False # no popup is a normal case, not an error

    Three engineering rules go with this:

    • Wait for conditions, not for time: use element visibility, network idle, or specific text appearing as signals; use a fixed sleep only as a fallback.
    • Externalize login state: keep credentials and cookies in environment variables or a secret manager, never in scripts; when a session expires, raise SessionExpired uniformly and let the scheduler trigger re-login instead of scattering checks through business code.
    • Idempotent design: rerunning any step produces no side effects; name screenshot files by “task + timestamp + index” and overwrite rather than append.

    4. Pitfall 2: Trusting General-Purpose Multimodal APIs for Visual Reading

    The most expensive and frustrating step was sending screenshots to a general-purpose vision language model for reading values. In practice, performance fell into three tiers: lightweight models misidentified even colors, ruining the entire numeric matrix; mid-tier models hallucinated noticeably, reading 5 as 3 and red as blue; high-end models improved accuracy, but the per-image cost multiplied by hundreds of images a day made the monthly bill unacceptable.

    The more important judgment is this: a trend chart is a deterministic rendered graphic, not a natural image. Legend colors, axes, gridlines, and data point positions are all generated by a plotting library according to rules, so solving them with geometry and color rules is more appropriate than guessing with a probabilistic model.

    1. import cv2, numpy as np
    2. def read_series(img_path, palette, plot_box):
    3. img = cv2.imread(img_path)
    4. roi = img[plot_box[1]:plot_box[3], plot_box[0]:plot_box[2]]
    5. hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
    6. out = {}
    7. for name, (h, s, v) in palette.items(): # color thresholds come from one manual calibration
    8. mask = cv2.inRange(hsv, (h-8, 60, 60), (h+8, 255, 255))
    9. ys, xs = np.where(mask > 0)
    10. out[name] = {"points": int(len(xs)), "x_ratio": float(xs.mean()/roi.shape[1]) if len(xs) else None}
    11. return out

    After the change, the local script makes zero network calls and consumes zero tokens, reads values stably, and can be unit tested—regress against twenty manually annotated samples, and any change immediately reveals a drop in accuracy. The general principle here: if a deterministic algorithm can solve it, don’t hand it to a probabilistic model; use the model only as a fallback for edge cases the rules can’t cover.

    5. Pitfall 3: The “Correct-and-Forget” Loop and Knowledge Retention

    The most mentally draining pattern: point out an error and it fixes it on the spot, then the same error reappears two days later, caught in a loop of “err—correct—remember—err again.” This isn’t a bad memory on the model’s part; the knowledge was stored in the conversation context, and once the context is compressed, the experience evaporates.

    The fix is to move knowledge from “conversation” to a “repository,” forming three layers:

    • Rule layer: hard constraints written as configuration and validators, for example values must fall within the axis range, and a missing-point ratio above a threshold fails the run.
    • Sample layer: all historical failure screenshots and manual annotations go into a database as a regression test set, running the same cases before and after changes.
    • Process layer: build “generate—validate—retry—escalate” into the scheduler instead of relying on human watching.
    1. retry:
    2. max_attempts: 3
    3. backoff: exponential
    4. escalate:
    5. on_failure: notify_and_hold # on repeated failures, hold and alert; never silently output wrong data
    6. validation:
    7. range_check: true
    8. missing_ratio_max: 0.05

    6. Reliability Engineering: Making Full Automation Safe to Run Unattended

    The prerequisite for unattended operation is that errors can be detected. At least four things should be in place: structured logging across the whole pipeline (an input summary, duration, and result fingerprint for each step); key metrics feeding monitoring and alerts, with repeated failures automatically held rather than skipped; raw screenshots and structured results archived together to object storage for traceability and recomputation; and containerized compute and scheduling for consistent environments, horizontal scaling, and queue-based peak shaving.

    If data volume keeps growing, the heavy work can be split into “collection” and “computation” stages, decoupled with a message queue, with compute-intensive steps like visual recognition scaled independently. This combination is a common industry practice, independent of any specific vendor.

    7. Retrospective: Three Transferable Lessons

    First, quantify before automating. Measure the time and failure rate of each step, and the optimization order becomes obvious, avoiding polishing where it hurts least. Second, determinism first. Never outsource what rules, geometry, and color can cover to a large model; the model only handles fallback and anomaly attribution. Third, write experience into code, not memory. Validators, regression sets, and retry policies are the assets; “got it” in a conversation is not.

    What seven days bought was not some magic tool but a set of engineering constraints that let the machine find its own errors, retry on its own, and alert on its own. Get these three points right, and repetitive work is truly handed off.