After Seven Days of Failures, I Turned an AI Agent into a Fully Automated Data Pipeline

    Repetitive chart-trend analysis looks simple but fails easily when an AI agent drives the browser alone. This article explains a seven-step pipeline with acceptance criteria, a session state machine, deterministic chart parsing with model review only for low-confidence cases, regression testing, a six-layer architecture, and quality, observability, and security gates.

    Repetitive data-trend analysis usually involves a chain of steps that look simple but are easy to lose control of: establish a login session, search by conditions, capture full-page and regional views, turn chart readings into a numeric matrix, calculate metrics from an algorithm dictionary, and produce a statistical summary. When people do this work, experience and attention barely keep the chain together. Once an AI agent takes over, a single popup, a page redesign, or a small coordinate shift can quietly produce wrong results across the whole pipeline.

    After several days of trial and error, the core conclusion was clear: do not expect a conversational AI agent to complete every step “in passing.” Agents are well suited to task planning, tool selection, exception explanation, and review of low-confidence samples. Actual collection, parsing, calculation, and aggregation must be pushed down into deterministic components that can be tested, replayed, and observed. The following is a reproducible engineering approach.

    1. Define the problem first: a seven-step chain and acceptance criteria

    Before writing any prompt, break the business process into explicit states and artifacts. Otherwise the agent will improvise on the page, and failures will be hard to locate.

    Step Main inputs Main outputs Common problems Acceptance criteria
    1. Session setup Entry URL, authorization credentials Valid session, login evidence Selector changes, popup occlusion, human verification Session is reusable; failure types are distinguishable
    2. Precise search Date, object, filters Target result list Query conditions drift; async loading is incomplete Query parameters are traceable; result counts can be checked
    3. Full-view screenshot Stable page state Raw page snapshot Animation not finished; resolution changes Fixed viewport; state is consistent before and after capture
    4. Subregion screenshot Snapshot, region template Chart region, local evidence Fixed coordinates fail; scale differs Region config is versioned and replayable
    5. Map graphics to a numeric matrix Local image, palette, axes Digitized reading matrix Anti-aliasing, occlusion, theme changes Golden-sample regression passes
    6. Rule-dictionary calculation Numeric matrix, algorithm version Metric results Mixed units; inconsistent null handling Unit tests cover boundary conditions
    7. Statistical summary Multi-batch results Report, evidence chain Duplicate runs; missed batches Idempotent; checksums match

    The point of this table is that every step needs inputs, outputs, and acceptance criteria. It is not enough to say “let the agent operate the website.” The agent may only call these defined tools. It must not bypass validation and invent a business conclusion.

    2. Login and popups: teach the agent to recognize state, not “close the popup”

    The most common mistake in simulated login is relying on a single selector, or teaching the agent to keep learning “click the close button in the upper right.” A small redesign or a slight popup shift makes that old experience useless. A better approach is a state machine: first classify the current page state, then take the matching action.

    The logic can be abstracted as:

    1. function ensureSession(siteKey):
    2. if session.exists(siteKey) and session.healthCheck(siteKey):
    3. return session.load(siteKey)
    4. page = open(entryUrl[siteKey])
    5. state = classifyPage(page)
    6. if state == "overlay":
    7. dismissKnownOverlays(page, kinds = ["announcement", "permission prompt", "subscription popup"])
    8. state = classifyPage(page)
    9. if state == "loginForm":
    10. fillCredentials(secrets.get(siteKey))
    11. submit(page)
    12. saveEvidence(page, "after_submit")
    13. state = classifyPage(page)
    14. if state == "humanCheck":
    15. saveEvidence(page, "human_check")
    16. return NeedHuman("human_check_required")
    17. if state != "loggedIn":
    18. saveEvidence(page, "unexpected_state")
    19. return NeedHuman("unexpected_state")
    20. return session.persist(siteKey)

    Four points matter.

    First, selectors need a fallback strategy. Prefer stable semantic attributes, then structural paths, and use visual positioning last. Do not rely on one absolute coordinate.

    Second, popup handling must be classified. Announcements that can be closed automatically, permission prompts that can be ignored, and human checks that require a person should follow different branches. Do not force-close an unknown popup. Save the screenshot and page structure and send it to human review.

    Third, keep evidence before and after every action. Screenshots, key state, timestamps, and the current step should be persisted together. Otherwise a failure at night can only be guessed at.

    Fourth, reuse sessions and health-check them. Logging in from scratch on every job increases both failure rate and risk-control exposure. When a session expires, the system should still fall back to logging in again.

    3. Visual recognition: do not send every image to a multimodal API

    Turning chart readings into numbers is where cost and accuracy most easily fall out of balance. Multimodal models are good at complex semantics and open-ended scenes, but on large numbers of charts with fixed templates, palettes, and axes they can confuse colors, misread scales, or hallucinate values. Worse, one API call per image becomes a continuous cost, and failed retries amplify it further.

    A more stable design is local deterministic parsing first, with the model as a fallback reviewer:

    1. Normalize images for a fixed template, including crop, scale, denoising, and color-space conversion.
    2. Quantize pixels into masks using the template palette, and detect bars, lines, legends, and similar elements.
    3. Use axis tick points for linear or piecewise mapping, converting graphic positions into values.
    4. Validate with confidence, boundary ranges, and business rules.
    5. Call a vision-language model or OCR only for low-confidence, heavily occluded, or unknown-template samples.
    6. Review results must still enter golden-sample regression. They must not be hard-coded into production rules.

    Pseudocode:

    1. function parseChart(image, templateVersion):
    2. roi = normalize(image, template[templateVersion].cropBox)
    3. palette = loadPalette(template[templateVersion].palette)
    4. masks = quantizeToColorMasks(roi, palette)
    5. marks = findConnectedComponents(masks, minArea = template.minMarkArea)
    6. axis = calibrateAxis(roi, template[templateVersion].axisPoints)
    7. values = mapMarksToValues(marks, axis)
    8. result = {
    9. values: values,
    10. templateVersion: templateVersion,
    11. evidence: saveArtifact(roi),
    12. confidence: scoreConfidence(marks, axis, template)
    13. }
    14. if result.confidence < template.reviewThreshold:
    15. result.needsReview = true
    16. return result

    Do not casually claim “100 percent recognition.” For fixed templates, stable palettes, and controlled screenshots, deterministic pixel parsing can keep misreads very low. As soon as the page theme, resolution, chart type, or occlusion changes, regression tests are required. The engineering goal is detectable low confidence and replayable error samples, not a vague high-accuracy slogan.

    The lesson that vision models can be inaccurate and expensive can be stated as a principle: if a deterministic algorithm can solve the problem, do not hand it to a probabilistic model. If a model must judge, constrain the input, the output format, and the review path.

    4. From correction loops to regression tests: turn experience into assets

    The most frustrating agent behavior is “make a mistake, correct it, appear to remember, then make the same mistake days later.” On the surface, context was lost. Underneath, the correction was never turned into an executable specification. “Be careful next time” in a chat is not an engineering constraint. Test cases and configuration versions are.

    Treat every error as a closed loop:

    1. Save the failure scene: screenshot, page structure, input parameters, tool-call sequence, and model output.
    2. Classify the problem: session, selector, wait timing, image parsing, or business rule.
    3. Turn it into a failing test: the same input must fail before the fix and pass after it.
    4. Let the agent propose a fix, but generate candidate patches only in a sandbox.
    5. Run the full golden-sample set and check for regressions.
    6. After human or rule review, enter a canary rollout, then increase volume gradually.
    7. Version prompts, region templates, palettes, algorithm dictionaries, and test sets.

    This replaces “make the model remember” with “make the system verify.” The agent may help locate issues and suggest fixes, but it must not change production rules without tests and review.

    A stable automation pipeline can be split into six layers.

    The first layer is scheduling and the task queue. Build idempotent job keys from date, object, and template version, and support retries, dead letters, and human intervention.

    The second layer is an orchestration state machine. Define login, search, screenshot, parsing, calculation, and aggregation as explicit states. Each state has entry conditions, exit conditions, timeouts, and evidence.

    The third layer is a deterministic tool set: session management, page navigation, stable screenshots, region cropping, color parsing, axis calibration, rule calculation, and report generation. Tools communicate through structured data, not free text.

    The fourth layer is evidence and artifact storage. Raw screenshots, cropped images, parsed matrices, calculation results, logs, and version numbers should be stored as a group. If the deployment is on Baidu AI Cloud, object storage can archive evidence, a log service can centralize search, and monitoring alerts can track anomalies. These are general capabilities; the core remains the data contract and the audit trail.

    The fifth layer is a human review console. Send only low-confidence samples, unknown popups, human checks, and abnormal values to people, so reviewers do not redo the whole flow.

    The sixth layer is monitoring and alerting. Watch success rate, retry count, human-check trigger rate, low-confidence ratio, model-fallback count, time per job, result drift, and cost.

    Orchestration example:

    1. function runAnalysis(date, templateVersion):
    2. jobKey = idempotentKey(date, templateVersion)
    3. ctx = trace.start(jobKey)
    4. session = ensureSession(siteKey)
    5. query = buildQuery(date, filters)
    6. resultPage = performSearch(session, query)
    7. pages = listResultPages(resultPage)
    8. matrix = []
    9. evidence = []
    10. for page in pages:
    11. snapshot = captureStableViewport(page)
    12. regions = sliceRegions(snapshot, templateVersion)
    13. for region in regions:
    14. parsed = parseChart(region, templateVersion)
    15. validateAgainstSchema(parsed)
    16. matrix.add(parsed)
    17. evidence.add(parsed.evidence)
    18. assertPageComplete(page)
    19. results = compute(matrix, algorithmDict[version])
    20. report = aggregate(results)
    21. persist(report, evidence, matrixHash = hash(matrix))
    22. return report

    The point of this pseudocode is not syntax. It encodes two design choices: every critical step produces a structured artifact, and every parse result must pass schema and business validation. Model output must not be written into the report directly.

    6. Quality gates, monitoring, and security boundaries

    An automated pipeline should be accepted like a production system.

    For data quality, check field completeness, numeric ranges, unit consistency, unusual period-over-period and sequential changes, whether summary totals match detail totals, and whether nulls and duplicate records are handled correctly.

    For runtime quality, measure login success rate, popup-handling success rate, search hit rate, screenshot failure rate, low-confidence parse rate, human review rate, API fallback rate, time per job, and the distribution of failed retries.

    For observability, every job needs a searchable job ID, step logs, key screenshots, tool-call records, and version numbers. Alerts should be based on consecutive failures, structural errors, and business anomalies, not on discovering wrong numbers only after the report is generated.

    For security, credentials belong in a controlled secrets facility and should be granted with least privilege. Screenshots may contain sensitive information, so set retention periods, access control, and redaction policies. Calls to external models should limit the data scope so full pages or unrelated personal information are not sent out unnecessarily. Also follow the target system’s access terms and rate limits.

    7. A reproducible rollout path

    To reproduce this from scratch, proceed in this order:

    1. Pick one fixed template and one date range, and run the seven-step chain manually.
    2. Define inputs, outputs, and acceptance criteria for each step.
    3. Implement deterministic tools first. Do not let the agent operate the page directly.
    4. Build a golden-sample set covering normal charts, occluded charts, abnormal palettes, empty data, and boundary values.
    5. Let the agent handle only orchestration and exception suggestions. Every fix goes through tests and a canary.
    6. Run in shadow mode, compare with human results, then switch the main flow.
    7. Expand templates and objects gradually. Keep a version and a rollback path for every change.

    The payoff is not only “saving half a day of manual work.” Personal experience becomes a maintainable production line: errors can be located, results can be replayed, cost can be controlled, and changes can be verified. The valuable role of an AI agent is not to replace every engineering implementation. It is to manage uncertain cases so deterministic code can reliably do most of the repetitive work.