How to Build a Disk Space Analysis and Cleanup Tool with an LLM

    Learn how to use a large language model to quickly create a Python tool for analyzing disk usage and identifying cleanup candidates. This guide covers prompt design, recursive directory scanning, large-file detection, safe deletion workflows, model selection, API performance, and local deployment strategies.

    1. Background and Requirements: What to Do When a Disk Is Full

    Insufficient disk space is a common and frustrating problem in both software development and everyday computer use. Typical causes include ever-growing build caches, unbounded log files, accumulated virtual environments and dependency directories, and temporary files scattered throughout download folders. Traditional approaches rely on built-in operating system tools or require manually checking directory sizes one level at a time. Both methods are inefficient and can easily miss important files.

    An effective disk space analysis tool should provide the following capabilities:

    1. Recursively scan a specified directory, calculate the space used by each immediate child directory, and sort the results by size;
    2. Identify large files, such as files exceeding a configurable threshold, to quickly locate the main sources of disk usage;
    3. Recognize commonly cleanable directories, including cache, temporary, and build-output directories;
    4. Generate a visual or easy-to-read report that makes the distribution of disk usage clear at a glance;
    5. Handle deletion operations carefully, providing a preview and confirmation step before removing anything.

    Because the requirements are well-defined and have clear boundaries, this type of utility is a good candidate for generating an initial implementation with a large language model.

    2. Prompt Design: Why a Single Sentence Can Be Enough

    When using an LLM for code generation, many developers tend to write very long prompts. For small tools with clearly defined requirements, however, a concise prompt can be more effective. A practical prompt template might look like this:

    1. Write a disk space analysis and cleanup utility with the following requirements:
    2. 1. Recursively calculate the space used by each child directory under a specified path and print the results in sorted order;
    3. 2. List the N largest files;
    4. 3. Support filtering candidate cleanup files by file extension;
    5. 4. Require a file list and a second confirmation before any deletion;
    6. 5. Use only the standard library and no external dependencies.

    Three principles are especially important when writing a high-quality prompt:

    • Define the inputs and outputs, such as the target directory and report format;
    • Define constraints, such as using only the standard library or supporting multiple platforms;
    • Define safety boundaries, such as requiring confirmation before deletion.

    The last point is particularly important. Any tool that deletes files should be instructed to preview the targets first, request confirmation, and provide a reversible alternative when possible, such as moving files to a recycle bin or renaming them. Otherwise, the generated code may perform irreversible deletion directly.

    3. Core Implementation and Example Code

    Using Python as an example, the core task is to recursively calculate directory sizes. A simplified implementation is shown below:

    1. import os
    2. from pathlib import Path
    3. def dir_size(path: Path) -> int:
    4. total = 0
    5. for p in path.rglob('*'):
    6. try:
    7. if p.is_file():
    8. total += p.stat().st_size
    9. except (PermissionError, OSError):
    10. continue # Skip inaccessible entries so the scan can continue
    11. return total
    12. def analyze(root: str, top_n: int = 10):
    13. root_path = Path(root)
    14. results = []
    15. for child in root_path.iterdir():
    16. if child.is_dir():
    17. results.append((str(child), dir_size(child)))
    18. else:
    19. results.append((str(child), child.stat().st_size))
    20. results.sort(key=lambda x: x[1], reverse=True)
    21. for name, size in results[:top_n]:
    22. print(f"{size / 1024 / 1024:10.1f} MB {name}")
    23. if __name__ == "__main__":
    24. analyze(input("Enter the directory to analyze: "))

    A production-ready version could add several improvements:

    • Use multithreading or os.scandir to speed up traversal;
    • Deduplicate symbolic links to avoid cycles;
    • Display progress information when scanning large directories;
    • Export results to JSON or CSV for tracking changes over time.

    These enhancements can also be implemented incrementally through additional conversations with the model. This is one of the main advantages of LLM-assisted development: start with a runnable minimum version, then refine it according to actual requirements.

    4. Two Important Model Selection Factors: Reasoning Depth and Response Speed

    When using an LLM to build this type of utility, two factors have a direct impact on the development experience.

    First, the length of the reasoning process should match the complexity of the task. Some models spend a substantial amount of time on reasoning. For a simple task such as writing a disk analysis script, lengthy reasoning can significantly increase waiting time without providing proportional benefits. A better approach is to select models according to task complexity: use fast, lightweight models for simple scripting tasks, and switch to models with stronger reasoning capabilities for architecture design or complex debugging. In intelligent coding tools and command-line coding assistants, this switch often only requires changing a configuration setting.

    Second, API throughput and stability affect iteration speed. The same model may feel noticeably different when used through an API in a coding tool compared with its official interactive environment. If responses are slow or connections are interrupted, several approaches can help:

    • Reduce the maximum output length for each request;
    • Break large tasks into smaller steps and use multiple short conversations instead of one long generation;
    • Enable streaming output so results arrive earlier and direction problems can be detected sooner;
    • Monitor provider rate limits and retry policies, and implement automatic reconnection in the client.

    5. Local Deployment: Reducing Dependence on Networks and Rate Limits

    If response speed and data privacy are both important, local deployment is worth considering. Many models are available in different parameter sizes. After quantization, smaller and medium-sized models can run on consumer GPUs or even CPU-only systems. A general-purpose local inference framework can then expose an API compatible with the coding tool.

    A typical local deployment process includes:

    1. Evaluate the hardware: Confirm that available GPU memory or system memory can accommodate the target quantized model;
    2. Choose a quantized version: Balance model quality against resource usage;
    3. Start a local inference service: Expose a local API endpoint;
    4. Update the coding tool configuration: Point the endpoint to the local service and set the model name to the locally loaded model.

    After deployment, generation speed is no longer affected by network conditions or server-side load. Prompts and code also remain on the local machine, which can be reassuring when working with sensitive path information.

    However, smaller local models generally have a lower capability ceiling on complex tasks than leading cloud-based models. For many users, a hybrid strategy offers the best balance: run a lightweight local model for routine tasks and use a more capable cloud model when handling difficult problems.

    6. Conclusion

    Using a single well-designed prompt to generate a disk space analysis and cleanup utility is a high-value example of AI-assisted development. The key practices are:

    • Clearly specify the expected outputs, constraints, and safety boundaries in the prompt;
    • Match the model to the complexity of the task instead of using extended reasoning for simple scripts;
    • Improve the development experience by optimizing task size, streaming output, and API reliability;
    • Consider local deployment when speed and privacy are important.

    Once this workflow becomes familiar, the same approach can be applied to many other one-off utilities, including disk cleanup, log analysis, and batch file renaming.