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.

    1. # organize.py — usage: python organize.py ./inbox ./out --dry-run
    2. import argparse, hashlib, json, shutil
    3. from pathlib import Path
    4. TEXT_EXT = {".md", ".txt", ".csv", ".log", ".json"}
    5. def sha256_of(path: Path) -> str:
    6. h = hashlib.sha256()
    7. with path.open("rb") as f:
    8. for chunk in iter(lambda: f.read(65536), b""):
    9. h.update(chunk)
    10. return h.hexdigest()
    11. def classify(src: Path) -> str:
    12. return "text" if src.suffix.lower() in TEXT_EXT else "other"
    13. def safe_target(out_dir: Path, src: Path, index: int) -> Path:
    14. folder = out_dir / classify(src)
    15. folder.mkdir(parents=True, exist_ok=True)
    16. candidate = folder / f"{index:04d}_{src.name}"
    17. n = 1
    18. while candidate.exists(): # Overwrite policy: never overwrite, auto-avoid
    19. candidate = folder / f"{index:04d}_{n}_{src.name}"
    20. n += 1
    21. return candidate
    22. def run(src_dir: Path, out_dir: Path, dry_run: bool = False) -> list:
    23. files = sorted(p for p in src_dir.rglob("*") if p.is_file())
    24. manifest = []
    25. for index, path in enumerate(files, 1):
    26. record = {"src": str(path), "bytes": path.stat().st_size,
    27. "sha256": sha256_of(path)}
    28. target = safe_target(out_dir, path, index)
    29. record["dst"] = str(target)
    30. if not dry_run:
    31. tmp = target.with_suffix(target.suffix + ".tmp")
    32. shutil.copy2(path, tmp) # Write to a temp file first
    33. tmp.replace(target) # Atomic rename into place
    34. manifest.append(record)
    35. return manifest
    36. if __name__ == "__main__":
    37. ap = argparse.ArgumentParser()
    38. ap.add_argument("src", type=Path); ap.add_argument("out", type=Path)
    39. ap.add_argument("--dry-run", action="store_true")
    40. a = ap.parse_args()
    41. rows = run(a.src, a.out, a.dry_run)
    42. if not a.dry_run:
    43. (a.out / "manifest.json").write_text(
    44. json.dumps(rows, ensure_ascii=False, indent=2), encoding="utf-8")
    45. 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.

    1. # pip install playwright==1.44.1 && playwright install chromium
    2. from playwright.sync_api import sync_playwright
    3. def collect(keyword: str, limit: int = 20) -> list:
    4. with sync_playwright() as p:
    5. browser = p.chromium.launch(headless=True)
    6. ctx = browser.new_context(
    7. user_agent="MyOfficeBot/1.0 (+contact: ops@example.com)",
    8. locale="zh-CN")
    9. page = ctx.new_page()
    10. try:
    11. page.goto("https://example.com/search", timeout=30_000)
    12. page.fill("#q", keyword)
    13. page.click("button[type=submit]")
    14. page.wait_for_selector(".result", timeout=15_000)
    15. rows = page.eval_on_selector_all(
    16. ".result", "els => els.map(e => ({t: e.innerText, u: e.href}))")
    17. return rows[:limit]
    18. finally:
    19. 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.

    1. # pip install python-pptx==0.6.23 openpyxl==3.1.2
    2. from pptx import Presentation
    3. from openpyxl import Workbook
    4. def build_deck(outline, path):
    5. prs = Presentation("template.pptx") # Template defines the layouts
    6. layout = prs.slide_layouts[1] # Title + content
    7. for title, bullets in outline:
    8. s = prs.slides.add_slide(layout)
    9. s.shapes.title.text = title
    10. s.placeholders[1].text_frame.text = "\n".join(f"• {b}" for b in bullets)
    11. prs.save(path + ".tmp"); __import__("os").replace(path + ".tmp", path)
    12. def build_sheet(rows, path):
    13. wb = Workbook(); ws = wb.active
    14. ws.append(["Date", "Item", "Hours(h)"])
    15. for r in rows: ws.append(r)
    16. ws["D2"] = "=SUM(C2:C1000)"
    17. 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):

    1. job:
    2. name: daily_brief
    3. cron: "0 7 * * *"
    4. timezone: Asia/Shanghai
    5. timeout_sec: 600
    6. max_retries: 2
    7. retry_backoff_sec: 60
    8. max_instances: 1
    9. input_dir: ./data/in
    10. output_dir: ./out/briefs
    1. # pip install apscheduler==3.10.4
    2. from apscheduler.schedulers.blocking import BlockingScheduler
    3. from apscheduler.triggers.cron import CronTrigger
    4. s = BlockingScheduler(timezone="Asia/Shanghai")
    5. s.add_job(daily_brief, CronTrigger.from_crontab("0 7 * * *"),
    6. id="daily_brief", max_instances=1, coalesce=True,
    7. misfire_grace_time=300)
    8. 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

    1. Module interfaces: does each of the five modules have its own entry function, with inputs and outputs as serializable structures;
    2. Prerequisites: is the Python version pinned, are dependencies version-locked, is a --dry-run provided;
    3. Write safety: no overwrites, backups present, a manifest available for rollback;
    4. Least privilege: directory allow-list, credentials via environment variables/keychain;
    5. Logging and monitoring: are all fields present, and do failures raise alerts rather than fail silently;
    6. Idempotency: does a repeated trigger produce only one result;
    7. Manual spot check: sample 5%–10% of each batch’s artifacts for manual review;
    8. 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.