AI-Assisted Programming: From a Single Prompt to a Disk Cleanup Tool

    Large language models can quickly generate practical developer utilities from natural-language descriptions. This article uses a disk analysis and cleanup tool as an example to explain how to design safer prompts, validate generated code, handle latency and failures in remote inference services, and choose between cloud-based and local deployment. The central principle is simple: generated code can reduce development effort, but it still requires testing, permission controls, and careful review.

    1. Problem Background

    Running out of disk space is a common problem for developers. Storage usage is often spread across build caches, container images, virtual environments, log files, download directories, and temporary files. Investigating these locations manually requires running multiple disk-usage commands, which is inefficient and can lead to accidentally deleting useful data.

    The code-generation capabilities of large language models provide a new way to build small utilities like these. A developer only needs to describe the goal, and the model can produce a runnable script. This significantly reduces the cost of writing scripts, but it also introduces new engineering questions: How should the generated code be validated? How can response times be kept acceptable when a model service is under heavy load? How should the workflow continue when the service is unavailable? This article focuses on these three issues.

    2. Generating a Disk Analysis Tool with Natural Language

    2.1 Prompt Design Principles

    A one-sentence prompt can produce a usable result, but the more specific the prompt, the more reliable the output is likely to be. A practical prompt generally includes the following elements:

    • Runtime environment: Operating system, programming language, and version
    • Functional scope: Which directories to scan and which metrics to calculate
    • Output format: Terminal table, sorting rules, and unit conversion
    • Safety constraints: Whether deletion is allowed and whether confirmation is required
    • Error handling: What to do when permissions are insufficient, symbolic links are encountered, or files are in use

    Safety constraints are the easiest part to overlook. Cleanup scripts should be read-only by default. Deletion should require an explicit option and should list the objects to be removed before execution.

    2.2 Example: Scanning Large Files in the Home Directory

    The following script calculates the total space used by the home directory and lists several of its largest files. It uses a min-heap to keep the top N results, so memory usage is independent of the total number of files. This makes it suitable for scanning large directory trees.

    1. import os
    2. import heapq
    3. def human_size(num):
    4. for unit in ["B", "KB", "MB", "GB", "TB"]:
    5. if num < 1024:
    6. return f"{num:.1f}{unit}"
    7. num /= 1024
    8. return f"{num:.1f}PB"
    9. def scan(root, top_n=20):
    10. largest = [] # Min-heap containing (size, path)
    11. total = 0
    12. for dirpath, _, filenames in os.walk(root):
    13. for name in filenames:
    14. path = os.path.join(dirpath, name)
    15. try:
    16. if os.path.islink(path):
    17. continue
    18. size = os.path.getsize(path)
    19. except OSError:
    20. continue # Skip files that cannot be accessed or no longer exist
    21. total += size
    22. if len(largest) < top_n:
    23. heapq.heappush(largest, (size, path))
    24. elif size > largest[0][0]:
    25. heapq.heapreplace(largest, (size, path))
    26. return total, sorted(largest, reverse=True)
    27. if __name__ == "__main__":
    28. total, files = scan(os.path.expanduser("~"))
    29. print(f"Total usage: {human_size(total)}")
    30. for size, path in files:
    31. print(f"{human_size(size):>10} {path}")

    This code includes three notable design choices. First, os.walk does not follow symbolic links to directories by default, while the islink check also prevents linked files from being counted again. Second, exception handling is limited to individual files, so an error affecting one file does not terminate the entire scan. Third, the output only reports usage and contains no deletion logic.

    2.3 How to Add Cleanup Capabilities

    If cleanup functionality is required, it should be implemented in two stages. The first stage generates a candidate list, grouping items by category—such as caches, logs, and temporary files—and displaying their sizes. The second stage performs deletion only after user confirmation and records the deleted paths for later review. Deletion logic should be separated from scanning logic, and dry-run mode should be enabled by default.

    3. Validating the Correctness of Generated Code

    Model-generated code should not be used directly for deletion operations. The following review process can significantly reduce risk:

    1. Read before running: Check path construction, loop boundaries, and exception branches line by line.
    2. Test in a dedicated directory: Create a sample directory containing nested directories, symbolic links, and files with insufficient permissions, then verify the reported results.
    3. Compare with system tools: Use existing disk-usage commands to validate the total. Significant discrepancies require further investigation.
    4. Restrict the deletion scope: Allow deletion only under approved paths, and reject system directories and user document directories.
    5. Keep deletion reversible: Prefer moving files to the operating system’s trash or recycle bin instead of calling an irreversible delete operation directly.

    Validating model output is essentially the same as reviewing code submitted by another developer. Faster generation does not eliminate the need for review.

    4. Latency and Reliability in Remote Inference Services

    4.1 How Latency Affects the Workflow

    The response speed of a remote large language model service depends on several factors, including network conditions, server-side queueing, model size, output length, and current system load. The same service may perform very differently at different times. In practice, slower output during peak periods can directly delay interactive programming, especially when a task requires multiple rounds of revisions.

    Developers can reduce the impact in several ways:

    • Use streaming output so that content can be read while it is being generated, reducing perceived waiting time.
    • Split long tasks into several smaller requests, processing one function or module at a time.
    • Cache the results of frequently used prompts locally to avoid generating the same code repeatedly.

    4.2 Reliability and Fault-Tolerance Design

    Network interruptions and service timeouts cannot be completely avoided when using remote services. The caller should include fault-tolerance logic rather than assuming that every request will succeed.

    1. import time
    2. def call_with_retry(fn, retries=3, base_delay=1.0):
    3. for attempt in range(retries):
    4. try:
    5. return fn()
    6. except (TimeoutError, ConnectionError):
    7. if attempt == retries - 1:
    8. raise
    9. time.sleep(base_delay * (2 ** attempt)) # Exponential backoff

    Exponential backoff prevents the client from sending a large number of retries as soon as a service begins recovering, which could increase pressure on the server. For non-real-time tasks such as code generation, completed output should also be saved so that an interrupted task can resume from a checkpoint instead of starting over.

    4.3 Multiple Backends and Fallback Strategies

    If a workflow depends heavily on model services, multiple inference backends can be configured with predefined fallback rules. For example, the workflow could switch to a secondary backend when the primary one is unavailable, or use a less capable but more stable local model for simple tasks. Fallback rules should be defined in configuration ahead of time to avoid ad hoc decisions during an incident.

    5. Choosing Between Remote Inference and Local Deployment

    Remote services and local deployments are suitable for different scenarios. The following dimensions should be considered:

    Dimension Remote Service Local Deployment
    Model capability Usually stronger and upgraded by the service provider Limited by available hardware and model size
    Response stability Depends on network conditions and provider workload Depends on local resources
    Data privacy Code and prompts must be transmitted externally Data remains on the local system
    Hardware cost Usage-based payment or subscription Requires investment in GPUs, memory, and electricity
    Maintenance cost Almost none Requires model updates and environment configuration

    For sensitive code or internal data, local deployment offers a clear privacy advantage. For workloads that require the strongest coding capabilities and have reliable network connectivity, remote services may be more appropriate. Many teams use a hybrid strategy: simple daily utilities run locally, while more complex tasks are sent to remote services.

    6. Engineering Practices for Production Use

    The following principles can help when integrating large language models into everyday development:

    • Treat the model as a draft generator: Generated results must be tested and reviewed before entering a formal workflow.
    • Standardize prompt templates: Store validated prompts in version control for reuse and comparison.
    • Track invocation metrics: Record request duration, failure rate, and output length to support backend selection.
    • Define permission boundaries: Restrict which directories generated scripts can access and which operations they can execute.
    • Review the system regularly: Periodically evaluate model quality and service performance, then adjust backend configuration as needed.

    7. Conclusion

    Large language models can greatly reduce the effort required to build a small tool for a specific problem, and disk analysis and cleanup is a typical example. However, these efficiency gains depend on control. Generated code must be validated, deletion operations must require confirmation, and remote services need fault-tolerance mechanisms.

    There is no universally superior choice between remote inference and local deployment. The right decision depends on data sensitivity, reliability requirements, and available hardware. Once these boundaries are clearly defined, large language models can become a reliable part of everyday development workflows.