How I Tamed an Automation Agent in 7 Days: Deterministic Code Over Model Reasoning

    This article breaks down a seven-step web data extraction pipeline that was handed to an AI agent and took seven days of debugging to stabilize. It explains why login and popup handling should be moved out of model reasoning into deterministic guard functions, why general-purpose vision models are a poor fit for pixel-level reading in controlled rendering environments, and how to replace conversational error correction with externalized rules, schema validation, and regression tests. You will find practical engineering patterns, Python and YAML examples, an architecture recommendation that prioritizes deterministic code with the model as fallback, and a checklist of pitfalls to avoid. The core takeaway: an agent's value comes from how much uncertainty you convert into determinism, not from how much it can reason.

    1. Background: A Seven-Step Pipeline That Looked Simple

    The goal of this project was to hand a repetitive manual web data collection workflow over to an agent. The chain was split into seven stages: log in to the target site, search with precise conditions, capture a screenshot of the root node, capture screenshots of the boot-number-related elements, map those screenshots into a numeric matrix, produce results according to a predefined algorithm dictionary, and finally aggregate statistics.

    On paper, none of these seven steps is complex. The real difficulty is that every single step involves a large amount of non-determinism. Page structures change, popups change, visual presentation changes, and the agent can introduce new errors at each step. The end result: a task that should have finished in ten minutes took seven days and nights of debugging.

    The sections below review the problems stage by stage and give the corresponding engineering fixes.

    2. Stage 1: Simulated Login and Popup Handling — Don’t Expect the Model to “Learn”

    The earliest failures were concentrated in the login and page interaction layer. Two patterns were typical. First, element location failed: search conditions were typed into the wrong field, and the returned content had nothing to do with expectations. Second, whenever a captcha, an ad overlay, or an onboarding mask appeared, the flow stalled and the agent simply waited in place, repeatedly.

    The debugging process was even more absurd. To get the agent to master the single action of “close the popup,” I corrected it more than fifty times, and every time it produced a new mistake: clicking the wrong close button, hitting an adjacent icon, or closing the entire tab.

    Root cause: handing interface operations entirely to the model’s real-time reasoning means treating a volatile page structure as stable knowledge to be memorized. The model’s context is limited, and once the page gets slightly complex, instruction priorities get scrambled.

    Engineering fix:

    1. Strip “popup handling” out of model reasoning and turn it into a deterministic pre-guard function. Poll for overlay layers, try several closing strategies in priority order, and only escalate when all of them fail.
    2. Never hardcode a single selector for element location. Maintain a candidate selector list and fall back through it in order.
    3. Wrap every interaction in an atomic operation with a timeout. On failure, throw a structured exception instead of letting the model improvise.
    1. def dismiss_overlays(page, timeout=5.0):
    2. """Deterministic overlay guard: try closing in priority order, no model reasoning"""
    3. strategies = ["[class*=close]", "[aria-label*=close]", "text=关闭", "text=知道了"]
    4. deadline = time.time() + timeout
    5. while time.time() < deadline:
    6. for sel in strategies:
    7. el = page.query_selector(sel)
    8. if el and el.is_visible():
    9. el.click()
    10. time.sleep(0.3)
    11. if not page.query_selector("[class*=mask], [class*=modal]"):
    12. return True
    13. raise OverlayError("Overlay could not be dismissed, manual intervention required")

    3. Stage 2: Visual Recognition — Don’t Use a General Vision Model for Pixel-Level Reading

    The core stage, “screenshot to numeric matrix,” initially relied entirely on a cloud vision model API, and this was the source of the cost blowup.

    The trial-and-error path went roughly like this. Start with a free-tier model: it misjudged even basic colors, and the matrix results were almost entirely wrong. Switch to a mid-tier model and things improved slightly, but there was obvious hallucination — reading 5 as 3, red as blue. Upgrade to a high-tier model and accuracy went up, but each image cost several tenths of a yuan; three hundred images a day meant tens of yuan per day, and the monthly cost was completely unacceptable.

    Root cause: this kind of task is essentially deterministic reading in a controlled environment, not open-domain semantic understanding. The screenshots come from a fixed rendering template, so colors, positions, and font sizes are relatively stable. Using a probabilistic generative model here means paying a high cost to solve a low-entropy problem.

    Engineering fix: switch to a local image processing pipeline — locate first, then read.

    1. Extract color regions with color space conversion plus threshold segmentation, which is more resistant to lighting and compression noise than direct RGB comparison.
    2. For digit regions, run template matching first to determine candidate boxes, then normalize and binarize, and finally compare against a fixed mapping table.
    3. The whole pipeline runs offline, with zero API call cost, and recognition results are reproducible and unit-testable.
    1. def color_to_digit(roi_hsv):
    2. """Local color rendering recognition: HSV thresholds + fixed mapping, replacing a vision model"""
    3. masks = {
    4. "red": [(0, 120, 70), (10, 255, 255)],
    5. "blue": [(100, 120, 70), (130, 255, 255)],
    6. "green": [(40, 80, 70), (80, 255, 255)],
    7. }
    8. scores = {k: cv2.countNonZero(cv2.inRange(roi_hsv, lo, hi))
    9. for k, (lo, hi) in masks.items()}
    10. best = max(scores, key=scores.get)
    11. return COLOR_DICT[best] if scores[best] > MIN_PIXELS else None

    After the rewrite, recognition accuracy held steady at 100% (given the fixed template and resolution), and there were no more usage-based charges at all.

    4. Stage 3: The Correction Loop — Externalize Rules Instead of Repeating the Conversation

    The most draining stage was “training” the agent. The original expectation was simple: tell it what went wrong, and it won’t do it again. In practice, this fell into a loop of “make a mistake — correct it — remember it — make it again — correct it again,” commonly described as being trapped in a triangle: the same error keeps resurfacing across a long-running task.

    Root cause: conversational correction only affects short-term context and carries no persistent binding force across sessions. The model has no versioned knowledge artifact, so correction information is lost as context is evicted.

    Engineering fix:

    1. Externalize the rules: write constraints as configuration files and validators, not as reminders in a chat. Every output must pass the validator; anything non-compliant is rejected outright and retried.
    2. Regression case set: turn every historical error into an assertion case, replay the full set after every change, and build a no-regression baseline.
    3. Structured output: force the model to return JSON with a schema; a missing field is a failure, which avoids natural language ambiguity.
    4. Layered retries: retry lightweight errors automatically, escalate repeated failures to a manual queue, and attach an on-site snapshot and logs.
    1. # rules.yaml — externalized constraints, effective across sessions
    2. retry:
    3. max_attempts: 3
    4. backoff: exponential
    5. validation:
    6. schema: result.schema.json
    7. reject_on_missing_field: true
    8. regression:
    9. cases: tests/regression/*.yaml # one assertion per historical error

    5. Architecture Recommendation: Determinism First, Model as Fallback

    The core conclusion from seven days of practice: anything that can be solved with deterministic code must never be handed to model reasoning. The recommended division of labor is as follows.

    • Deterministic layer: login, popups, pagination, screenshots, image reading, and statistics aggregation, all implemented in ordinary code — testable and reproducible.
    • Model layer: only semantic judgment and failure attribution, for example understanding search intent and summarizing why something failed.
    • Governance layer: unified logging with monitoring and alerting, recording per-step latency, failure codes, and retry counts; artifacts and screenshots written to object storage for traceability.
    • Scheduling layer: tasks decoupled with a message queue, executors hosted on a container platform, enabling horizontal scaling and failure isolation.

    On cost control: after local image algorithms replaced the usage-based vision API, marginal cost approaches zero. If cloud vision capability is genuinely needed, it should be used only for manual review of a small proportion of difficult samples, not for the entire main chain.

    6. Pitfall Checklist

    1. Don’t treat a volatile UI as the model’s long-term memory; interaction logic must be code.
    2. Don’t use a general vision model for precise reading in controlled rendering scenarios — you lose on both cost and accuracy.
    3. Don’t rely on conversational correction; constraints belong in configuration and validators.
    4. Don’t skip regression cases, or fixed problems will inevitably come back.
    5. Don’t ignore observability; without per-step logs you cannot tell which stage broke.
    6. Don’t chase a fully automated closed loop; keeping a manual fallback queue is what makes a solution production-grade.

    After refactoring along these lines, the seven-step pipeline went from “needing someone to watch it every time” to running unattended and stable, and debugging cost dropped from days to hours. An agent’s value lies not in how much it can reason, but in how much uncertainty we have converged into determinism.