AI Office Automation in Practice: Runnable Code and an Acceptance Checklist
This article moves office automation past chatbot demos toward systems that run stably, reproducibly, and with a clear way to roll back. It walks through five capability modules—each with prerequisites, runnable code, failure handling, and safety boundaries—and covers an overall four-layer architecture, a browser-automation compliance checklist, scheduled-task design with idempotency keys and log fields, a pre-launch acceptance checklist, and an FAQ. Readers can use the examples to build a minimal local automation loop for file archiving and scheduled briefings, then harden security and monitoring module by module.
From “Can Chat” to “Can Run”: A Practical Local AI Office Automation Setup
Once large language models moved from conversation to execution, the hard part of office automation stopped being “can it be done?” and became “can it run stably, reproducibly, and with a way to roll back?” This article doesn’t restate concepts. Instead, it walks through five capability modules, giving the prerequisites, runnable code, failure handling, and safety boundaries for each. A pre-launch acceptance checklist and an FAQ close it out, so you can follow along directly.
1. Overall Architecture: Four Layers and Failure Handling
| Layer | Responsibility | Input | Output | Failure handling |
|---|---|---|---|---|
| Perception | Scan directories, capture page state, receive instructions | File paths, URLs, user natural language | Raw material and task list | Log unreadable paths and skip; do not interrupt the whole batch |
| Understanding | Break down goals, plan steps | Task list + prompts | Structured plan (JSON) | If plan validation fails, fall back to the template flow |
| Execution | Read/write files, drive the browser, render documents | Atomic actions from the plan | Persisted artifacts + run logs | Isolate single-file failures; write to a temp file, then atomically rename |
| Scheduling | Timed/event triggers, retry, alerting | cron config | Run records and alerts | Idempotency-key dedup + retry limit + escalate to human |
Key principle: leave decisions to the model, leave execution to deterministic code. The model only emits a plan; every side effect is carried out by testable functions. When something goes wrong, you can pinpoint the exact module instead of concluding “the model went off the rails again.”
2. Local File Processing: Make It Work First, Then Add Intelligence
Prerequisites: Python 3.9+ (the examples below were verified on Python 3.11 on Windows 11 and macOS 14, using only the standard library); read access to the input directory and write access to the output directory; the output directory must be kept separate from the input directory to avoid self-ingestion.
# organize.py — usage: python organize.py ./inbox ./out --dry-runimport argparse, hashlib, json, shutilfrom pathlib import PathTEXT_EXT = {".md", ".txt", ".csv", ".log", ".json"}def sha256_of(path: Path) -> str:h = hashlib.sha256()with path.open("rb") as f:for chunk in iter(lambda: f.read(65536), b""):h.update(chunk)return h.hexdigest()def classify(src: Path) -> str:return "text" if src.suffix.lower() in TEXT_EXT else "other"def safe_target(out_dir: Path, src: Path, index: int) -> Path:folder = out_dir / classify(src)folder.mkdir(parents=True, exist_ok=True)candidate = folder / f"{index:04d}_{src.name}"n = 1while candidate.exists(): # Overwrite policy: never overwrite, auto-avoidcandidate = folder / f"{index:04d}_{n}_{src.name}"n += 1return candidatedef run(src_dir: Path, out_dir: Path, dry_run: bool = False) -> list:files = sorted(p for p in src_dir.rglob("*") if p.is_file())manifest = []for index, path in enumerate(files, 1):record = {"src": str(path), "bytes": path.stat().st_size,"sha256": sha256_of(path)}target = safe_target(out_dir, path, index)record["dst"] = str(target)if not dry_run:tmp = target.with_suffix(target.suffix + ".tmp")shutil.copy2(path, tmp) # Write to a temp file firsttmp.replace(target) # Atomic rename into placemanifest.append(record)return manifestif __name__ == "__main__":ap = argparse.ArgumentParser()ap.add_argument("src", type=Path); ap.add_argument("out", type=Path)ap.add_argument("--dry-run", action="store_true")a = ap.parse_args()rows = run(a.src, a.out, a.dry_run)if not a.dry_run:(a.out / "manifest.json").write_text(json.dumps(rows, ensure_ascii=False, indent=2), encoding="utf-8")print(f"{len(rows)} files, dry_run={a.dry_run}")
Four rules of write safety: ① use copy rather than move, so the original files are always preserved; ② never overwrite by default—auto-append a sequence number on name collisions; ③ run with --dry-run first to print the plan, then do the real run; ④ manifest.json records the source/target paths and hashes, which is your rollback basis—read it in reverse to delete the artifacts and restore the originals. For directories holding customer contracts, finance, or HR files, run a permission check first (whether the current user has read access to the path), process only allow-listed subdirectories, and do not recursively scan the home directory.
3. Browser Automation: The Compliance Checklist Comes Before the Code
Option comparison:
| Option | Suitable scenarios | Boundaries and cost |
|---|---|---|
| Playwright/Selenium scripts | Structurally stable queries, form filling, exporting | Breaks on any redesign; selectors need maintenance |
| RPA tools (e.g., UiPath) | Desktop flows spanning multiple legacy systems | High licensing cost; debugging relies on record/replay |
| Cloud browser/remote execution | Unattended CI runs, centralized IP management | Login state and data egress need a compliance review |
| Local ephemeral context | One-off scraping, cases needing manual captcha handling | Not suitable for long-term unattended operation |
Risk-control checklist: read and note the target site’s robots.txt and terms of service; keep request intervals at ≥1–2 seconds and set a concurrency limit of 1; do not scrape personal data or non-public data behind a login; store login state only in the system keychain or environment variables—never hardcode it or write it to logs; stop immediately and hand off to a human on any captcha/risk control; retry with exponential backoff, no more than 3 times.
# pip install playwright==1.44.1 && playwright install chromiumfrom playwright.sync_api import sync_playwrightdef collect(keyword: str, limit: int = 20) -> list:with sync_playwright() as p:browser = p.chromium.launch(headless=True)ctx = browser.new_context(user_agent="MyOfficeBot/1.0 (+contact: ops@example.com)",locale="zh-CN")page = ctx.new_page()try:page.goto("https://example.com/search", timeout=30_000)page.fill("#q", keyword)page.click("button[type=submit]")page.wait_for_selector(".result", timeout=15_000)rows = page.eval_on_selector_all(".result", "els => els.map(e => ({t: e.innerText, u: e.href}))")return rows[:limit]finally:ctx.close(); browser.close() # Ensure release to avoid process leaks
4. Deep Research: Making Conclusions Traceable
The execution order is fixed: problem breakdown → multi-source retrieval → cross-verification → structured synthesis. First have the model output a research plan (what to look up, where to look, what the acceptance criteria are), have a human confirm it, then execute. Write each step’s output back to a file so that any conclusion can be traced back to its source.
Suggested source grading: Tier A is official documentation, regulatory announcements, and original papers; Tier B is first-line media and vendor technical blogs; Tier C is aggregator sites and secondhand summaries; Tier D is unsigned content. A core conclusion needs at least two Tier A/B sources, and when sources conflict, present them side by side rather than averaging them. Use a uniform citation format: “title + publisher + date + URL + retrieval time”; mark missing dates as “undated.”
5. Slide Deck and Spreadsheet Generation: Separate the Template from the Data
Tools and verification conditions: python-pptx 0.6.23 produces editable PPTX files, and openpyxl 3.1.2 produces XLSX files with formulas and conditional formatting; both passed on Python 3.11 plus the system versions above.
# pip install python-pptx==0.6.23 openpyxl==3.1.2from pptx import Presentationfrom openpyxl import Workbookdef build_deck(outline, path):prs = Presentation("template.pptx") # Template defines the layoutslayout = prs.slide_layouts[1] # Title + contentfor title, bullets in outline:s = prs.slides.add_slide(layout)s.shapes.title.text = titles.placeholders[1].text_frame.text = "\n".join(f"• {b}" for b in bullets)prs.save(path + ".tmp"); __import__("os").replace(path + ".tmp", path)def build_sheet(rows, path):wb = Workbook(); ws = wb.activews.append(["Date", "Item", "Hours(h)"])for r in rows: ws.append(r)ws["D2"] = "=SUM(C2:C1000)"wb.save(path + ".tmp"); __import__("os").replace(path + ".tmp", path)
Write safety: output to a new version-numbered file (e.g., report_v20826.pptx) rather than overwriting last week’s file; back up any existing file with the same name to .bak before writing; set the template file to read-only so the script can’t rewrite it.
6. Scheduled Tasks and Dispatch: Idempotency Keys and Log Fields
Minimal config (job.yaml):
job:name: daily_briefcron: "0 7 * * *"timezone: Asia/Shanghaitimeout_sec: 600max_retries: 2retry_backoff_sec: 60max_instances: 1input_dir: ./data/inoutput_dir: ./out/briefs
# pip install apscheduler==3.10.4from apscheduler.schedulers.blocking import BlockingSchedulerfrom apscheduler.triggers.cron import CronTriggers = BlockingScheduler(timezone="Asia/Shanghai")s.add_job(daily_brief, CronTrigger.from_crontab("0 7 * * *"),id="daily_brief", max_instances=1, coalesce=True,misfire_grace_time=300)s.start()
Idempotency key = sha256(job_name + input_hash + scheduled_date). Embed this key in the artifact filename; on a duplicate trigger, if a file with that name already exists, return immediately, avoiding duplicate generation and duplicate notifications.
Log fields (one JSON object per line): job_name, run_id, trigger_type, scheduled_time, start_time, duration_ms, input_hash, output_path, item_count, status, retry_count, error_code, operator.
7. Pre-Launch Acceptance Checklist
- Module interfaces: does each of the five modules have its own entry function, with inputs and outputs as serializable structures;
- Prerequisites: is the Python version pinned, are dependencies version-locked, is a
--dry-runprovided; - Write safety: no overwrites, backups present, a manifest available for rollback;
- Least privilege: directory allow-list, credentials via environment variables/keychain;
- Logging and monitoring: are all fields present, and do failures raise alerts rather than fail silently;
- Idempotency: does a repeated trigger produce only one result;
- Manual spot check: sample 5%–10% of each batch’s artifacts for manual review;
- Rollback drill: have you actually deleted an artifact once and restored the source files.
8. Frequently Asked Questions
Q: Do you have to bring in a large language model? Not necessarily. Deterministic flows like file archiving and report filling are more stable in pure code; the model’s value is in unstructured understanding and plan orchestration, so it’s worth introducing only at the “understanding” and “summarization” stages.
Q: Run locally or in the cloud? Use local when you need access to local files, internal network systems, or a GUI; pure web scraping and scheduled dispatch can go to the cloud, but first assess data-egress compliance.
Q: What’s the most common mistake? One is doing batch rewrites of original files without a dry-run; second is hardcoding account credentials; third is a task without an idempotency key causing duplicate notifications; fourth is selectors/templates without version control, so they silently produce wrong results after a redesign.
Q: How do you measure the payoff? Use three manual metrics: per-batch processing time, manual spot-check failure rate, and the share that needs human intervention—then compare after two full weeks.
Following this architecture, an individual can get a minimal loop running—file archiving plus a scheduled brief—within a day; a team can then tighten security and monitoring module by module on top of it, forming an intelligent office pipeline that fits its own workflow.
