Taming Automation Agents: 7 Days of Pitfalls and Engineering Fixes
This article documents a seven-day effort to automate a repetitive data-trend analysis workflow with browser automation, task orchestration, and LLM reasoning. It breaks the pipeline into seven stages, explains why end-to-end success is the product of per-stage success, and walks through six concrete failure modes—model-improvised interaction logic, selector drift and bad waits, costly and inaccurate general-purpose vision recognition, lost context and state, missing idempotency and rate limits, and poor observability—along with the engineering fixes that resolved each one. Readers will find reusable patterns and a checklist for building automation where deterministic code and probabilistic models each do the job they are best at.
1. Background: The Time Eaten by Repetitive Work
Anyone doing data-trend analysis gets stuck on the same mechanical task every day: log in to a fixed site, search for the target objects, capture more than three hundred trend charts, read each chart’s direction, annotate key values, apply a fixed algorithm, and aggregate everything into a table. The work requires no creativity but demands intense focus. Half a day disappears, eyes get sore, attention scatters, and there is barely time to drink water.
This kind of work has a clear signature: the flow is fixed, the inputs are well defined, the outputs can be verified, and there is little room for error. That is exactly the part an automation agent should take over. So I combined browser automation, task orchestration, and LLM reasoning on an old laptop and spent seven days pushing it through. Along the way I switched models six times and scrapped three architecture versions before the full chain finally ran end to end. Below is every pitfall I hit, with the engineering fix that worked.
2. Understand the Chain First: Seven Stages, Seven Classes of Risk
The full workflow abstracts into seven steps:
- Session login
- Conditional search
- Root chart capture
- Detail chart capture
- Image-to-number-matrix conversion
- Calculation against an algorithm dictionary
- Result aggregation and archiving
One engineering fact has to be accepted: the longer the chain, the more the end-to-end success rate is the product of the per-stage success rates. At 95% per stage, seven stages in series leave roughly 70%. So the core of automation is not “make one step smarter” but “make every step more deterministic.”
3. Pitfall 1: Handing Interaction Logic to the Model to Improvise
At first I had the model generate the login script directly, and the results were all over the place: wrong selectors for the search box, returned content unrelated to the target, scripts spinning in place when a captcha or promotional overlay appeared. I repeatedly told it to “close the popup first,” and sometimes it clicked the wrong button, sometimes it closed the whole tab.
Root cause: deterministic logic was handed to probabilistic reasoning.
Fix: split the layers. Hard-code the deterministic parts; give only the probabilistic parts to the model.
# Anti-pattern: let the model decide where to click at every step# agent.decide(page.screenshot(), "close the popup and log in")# Recommended: explicit state machine + limited fallbackSTATES = ["open", "dismiss_overlay", "fill_form", "submit", "verify"]def dismiss_overlay(page):for sel in OVERLAY_CLOSE_SELECTORS: # multiple candidate selectorsloc = page.locator(sel)if loc.count() and loc.first.is_visible():loc.first.click(timeout=2000)return Truereturn False # no popup is a normal case, not an error
Three points matter: prepare multiple candidate selectors and degrade by priority; treat “no popup” as a normal branch rather than a failure; verify page state after each action instead of blindly moving to the next step.
4. Pitfall 2: Selector Drift and Wrong Waiting Strategy
Page redesigns, dynamic rendering, and lazy loading all break fixed selectors. Meanwhile, waiting a fixed number of seconds for an element is either too short and yields an empty screenshot, or too long and inflates total runtime.
Fix: wait on an observable state, and add a self-healing mechanism.
async def wait_ready(page, marker_text, timeout=15000):await page.wait_for_load_state("domcontentloaded")await page.get_by_text(marker_text).first.wait_for(timeout=timeout)# Key point: wait for a business marker, not for a number of seconds
When locating elements fails several times in a row, trigger a one-off “structure probe”: collect the tag, text, and position features of candidate controls, have the model output new selector suggestions, write them into the configuration, and run a regression check. The model then intervenes only on anomalies, which saves cost and keeps stability intact.
5. Pitfall 3: Trusting a General-Purpose Vision Model, Blowing Up Cost and Still Missing Accuracy
The most expensive step was “screenshot to numbers.” I first sent every image to a general-purpose vision model, the bill climbed fast, and recognition quality was poor: axis ticks misread, legends confused, and ambiguous attribution where two lines cross.
Root cause: a general model is built to “understand an image,” while the business needs “read a value inside a known coordinate system.” The difficulty and the cost do not match.
Fix: three moves to cut cost and raise accuracy.
- Get structured data first: if the site offers an export, an API, or the chart’s underlying data, take the data directly. Zero cost, highest accuracy.
- Crop and upscale: keep only the plotting area, drop titles and decoration; upscale the tick region and boost contrast before recognition.
- Rule-based fallback and cross-checking: recognize the same chart at two crop scales, and flag it for human review if the deviation exceeds a threshold.
Illustrative reconciliation logic:
def reconcile(a, b, tol=0.02):if abs(a - b) / max(abs(a), 1e-6) > tol:return None, "NEED_REVIEW" # do not guess, send to a humanreturn (a + b) / 2, "OK"
The engineering principle is plain: if you can fetch data, do not look at the image; if you can look at a region, do not look at the whole image; if you can verify, do not trust blindly.
6. Pitfall 4: Broken Context and Lost State
When a long run failed at step five and restarted, login and search were redone from scratch, which was slow and more likely to trip anti-abuse controls. After many turns the model also forgot the established rules, and its output format gradually drifted.
Fix: externalize the state.
- Persist session and page state, and resume retries from the latest checkpoint.
- Write rules, the field dictionary, and algorithm definitions into external configuration, injecting only the necessary fragment on each call to control context length.
- Enforce strict output structure (such as a structured object with fixed fields), and retry on parse failure instead of guessing.
{ "series_id": "A-1024", "points": [[0, 12.3], [1, 13.1]], "unit": "pct", "confidence": 0.91 }
7. Pitfall 5: No Idempotency or Rate Limiting, Tasks Avalanche
With too much concurrency across three hundred plus images, I saw duplicate submissions, duplicate counts, and sessions being kicked. Automation stability often fails on “retry.”
Fix: give every task an idempotency key and check for duplicates before writing; cap concurrency and add exponential backoff; set a timeout ceiling on all external calls so threads do not hang.
if store.exists(task_key): # idempotency check firstreturn store.get(task_key)result = run_pipeline(task)store.put(task_key, result, ttl=86400)
8. Pitfall 6: No Observability, Nothing to Do but Stare
An automation system needs a black box. I kept an input summary, elapsed time, status code, and screenshot for every step, together with a logging service and monitoring alerts, and set thresholds on success rate, cost per task, and average duration, with automatic notification on anomalies. Diagnosis time dropped from hours to minutes.
9. Final Architecture: Dividing Labor Between Determinism and Intelligence
The working shape is: the orchestration layer owns the state machine and retries, the code layer owns interaction and data extraction, the model layer handles only fuzzy judgment and anomaly self-healing, and the validation layer owns cross-checking and human fallback. If elastic compute and unified operations are needed, the task queue, containerized execution, object-storage archiving, logging, and monitoring can be carried by general-purpose cloud products, leaving only a lightweight scheduler locally, so old hardware runs stably too.
10. Reusable Pitfall Checklist
- If a data API exists, skip image recognition.
- Code the interaction logic; use reasoning only for fuzzy cases.
- Wait on business markers, not fixed seconds.
- Use multiple candidate selectors with fallback, and trigger structural self-healing on anomalies.
- Externalize state, resume from checkpoints, enforce strict output constraints.
- Idempotency key + capped concurrency + exponential backoff.
- Log the whole chain, and put metric alerts in place early.
- Cross-check key results two ways; when unsure, hand off to a human.
Seven days produced a single conclusion: the ceiling of automation does not depend on how smart the model is, but on how large a cage you build for uncertainty. Build the cage well, and repetitive work truly becomes the machine’s job.
