Building a Disk Space Analysis and Cleanup Tool with LLM Assistance

    Large language models can speed up utility development, but tasks like disk cleanup demand careful control over destructive operations. This article walks through turning a vague one-line request into a working, verifiable Python tool that scans disk usage, identifies large files, and performs deletion only with explicit confirmation. It covers requirement breakdown, prompt design with safety boundaries, a heap-based scanning implementation, staged cleanup strategy, handling LLM API latency, and result validation.

    1. Background: Why Disks Silently Fill Up

    Disk usage on personal dev machines and work servers usually grows slowly. By the time the system warns you about low space, the problem has been building for a long time. Common culprits include: build artifacts and dependency caches that are never cleaned up, container images and virtual environments regenerated over and over, unrotated log files, neglected download and temp directories, and duplicate copies left behind by sync tools.

    Manual investigation is inefficient. Running statistics commands directory by directory is slow, and hidden directories are easy to miss. A more practical approach is to write a small tool that answers three questions: which directories are consuming space, which files are the largest, and which contents can be safely deleted.

    This article uses that scenario to show how to turn a one-sentence requirement into a runnable, verifiable tool—while keeping deletion under control throughout the process.

    2. Requirement Breakdown: Turning a Vague Idea into Verifiable Features

    Asking an LLM to “help me clean up my disk” often produces results that miss the mark. A more reliable approach is to break the requirement into concrete feature points, each of which can be confirmed with a test or manual review.

    At minimum, split the work into these four items:

    1. Scanning: Walk a target directory, measure every file’s size, and ignore symbolic links to avoid loops and double counting.
    2. Sorting and aggregation: Output the largest files, and summarize usage by first-level subdirectory.
    3. Classification suggestions: Identify cleanup candidates based on paths and extensions—cache directories, build artifacts, old logs—without actually deleting anything.
    4. Controlled cleanup: Preview only by default. Execute deletion only after the user explicitly confirms, and prefer moving files to a recycle mechanism over permanent deletion.

    Once broken down, each feature point can be generated separately by the model and verified one at a time. The benefits are a small blast radius when something goes wrong and faster problem isolation.

    3. Prompt Design: Constraining Output Structure and Safety Boundaries

    The purpose of a prompt is to limit the model’s output scope. Here is a reusable prompt framework:

    1. Implement a disk space analysis script using the Python standard library. Requirements:
    2. 1. Accept a directory path as an argument, defaulting to the current directory;
    3. 2. Output the 20 largest regular files with human-readable sizes;
    4. 3. Do not follow symbolic links;
    5. 4. Skip directories without read permission, count them, and keep running;
    6. 5. The script must be read-only by default and delete nothing;
    7. 6. Include function docstrings and describe ideas for two test cases.

    This prompt contains four types of constraints: input format, output content, exception behavior, and safety boundaries. Without the safety boundary, the model may add deletion logic on its own—code like that needs especially careful review.

    4. Core Implementation: Scanning for Large Files

    The key in the scanning phase is controlling memory usage. Collecting all file info into a list and then sorting puts heavy pressure on memory in directories with enormous file counts. A fixed-capacity min-heap keeps only the current top N files.

    1. import heapq
    2. import os
    3. def find_large_files(root, top_n=20):
    4. """Return the top_n largest regular files under root as a list of (bytes, path)."""
    5. heap = [] # min-heap, holds at most top_n items
    6. errors = []
    7. def on_error(err):
    8. errors.append(err)
    9. for dirpath, _, filenames in os.walk(root, onerror=on_error):
    10. for name in filenames:
    11. path = os.path.join(dirpath, name)
    12. try:
    13. if os.path.islink(path):
    14. continue
    15. size = os.path.getsize(path)
    16. except OSError as err:
    17. errors.append(err)
    18. continue
    19. if len(heap) < top_n:
    20. heapq.heappush(heap, (size, path))
    21. elif size > heap[0][0]:
    22. heapq.heapreplace(heap, (size, path))
    23. result = sorted(heap, reverse=True)
    24. return result, errors
    25. def format_size(num_bytes):
    26. """Convert a byte count into a human-readable unit."""
    27. for unit in ("B", "KB", "MB", "GB", "TB"):
    28. if num_bytes < 1024:
    29. return f"{num_bytes:.1f}{unit}"
    30. num_bytes /= 1024
    31. return f"{num_bytes:.1f}PB"
    32. if __name__ == "__main__":
    33. import sys
    34. target = sys.argv[1] if len(sys.argv) > 1 else "."
    35. files, errors = find_large_files(target)
    36. for size, path in files:
    37. print(f"{format_size(size):>10} {path}")
    38. print(f"{len(errors)} items could not be read and were skipped.")

    Three design decisions here are worth explaining. First, the onerror callback of os.walk handles directories without permission, so traversal is not interrupted by a single failed directory. Second, the islink check prevents large files pointed to by symbolic links from being counted twice, and keeps the scan from running out of control when a link points outside the target tree. Third, the min-heap runs in O(n log k) time, where n is the total file count and k is the number of results to keep—very efficient when k is small.

    5. Cleanup Strategy: Preview First, Confirm, Then Allow Undo

    Scan results are only clues; actual cleanup decisions require human judgment. Split the cleanup into three phases.

    Phase 1: Classified preview. Generate a candidate list based on path rules—directories named cache, files ending in .log older than a threshold, build output directories, and so on. Write the preview results to a text file for item-by-item review.

    Phase 2: User confirmation. The script should require the user to confirm each category or provide an explicit confirmation argument. Never offer a silent-delete default.

    Phase 3: Reversible deletion. Operating systems typically provide a recycle bin mechanism, and programs can move files there through the corresponding system APIs. If no such API is available in your environment, at minimum move files destined for deletion into a date-stamped quarantine directory, keep them for a period, then clean them up in a batch.

    The cost of an error in a cleanup script is far higher than in a scanning script. A single mistaken deletion may make data unrecoverable, so no delete function should be invoked before Phase 2.

    6. Latency and Stability When Calling LLMs

    When LLMs sit inside a workflow, you will often see fluctuating response times, long stretches with no output, or dropped connections. These issues stem mainly from network paths, server-side queuing, and the model’s own inference speed—switching to a cleverer prompt won’t fix them.

    Common engineering countermeasures include:

    • Timeouts: Set an upper limit on each request and abort on timeout so the process doesn’t hang indefinitely.
    • Exponential backoff retries: After a failure, wait a fixed multiple longer before retrying, with a cap on total attempts.
    • Streaming output: Enable streaming responses so users see partial results sooner, easing the wait.
    • Task splitting: Break large tasks into smaller requests so a single failure only affects part of the result.
    • Local caching: Cache generation results for identical requests to avoid redundant calls.

    Example code:

    1. import time
    2. def call_with_retry(request_fn, max_retries=3, base_delay=2.0):
    3. """Retry an unstable call with exponential backoff. request_fn is a zero-argument callable."""
    4. for attempt in range(max_retries):
    5. try:
    6. return request_fn()
    7. except TimeoutError:
    8. if attempt == max_retries - 1:
    9. raise
    10. time.sleep(base_delay * (2 ** attempt))

    If your team has stricter requirements around data privacy and stability, consider deploying an open-source model on your internal network. The main costs are GPU memory, system memory, and operations overhead—evaluate against your actual hardware and concurrency needs rather than assuming local deployment is automatically faster.

    7. Validation and Iteration

    Generated scripts must be validated before being used in real environments. Follow these steps:

    1. Run in a test directory: Create a sample directory containing large files, symbolic links, and permission-restricted subdirectories, and confirm the output matches expectations.
    2. Compare against a baseline: Compute the same directory’s totals with built-in system commands and check them against the script’s results.
    3. Check edge cases: Verify that inaccessible directories are skipped and counted correctly, and that symbolic links are not counted.
    4. Audit the deletion logic: Confirm that no deletion calls exist in default mode and that the user-confirmation flow cannot be bypassed.

    Once validated, iterate based on issues found in real usage. Common directions include adding exclusion rules, filtering by modification time, and exporting CSV reports. Change exactly one feature point per iteration and rerun the validation steps.

    8. Summary

    The keys to using LLMs to build tools are three stages: requirement breakdown, prompt constraints, and result validation. For deletion-involving tasks like disk cleanup, keep scanning and deletion strictly separated, stay read-only by default, and preserve a reversible path. The same workflow applies just as well to other operations scripts.