Avoiding Common Pitfalls When Using LLMs to Generate Desktop Audio/Video Conversion Tools

    This article uses a batch audio-extraction tool for videos as a running example to show how to turn vague, conversational requirements into clear specifications when using large language models (LLMs) to build desktop GUI applications. It walks through five core practices: writing layered prompts that convert adjectives like "no lag" into verifiable architectural constraints; running long conversions in a background thread and reporting status through a queue; checking external dependencies before execution; asking follow-up questions to make implicit defaults explicit; and reviewing generated code through static checks, runtime validation, and security review. It also includes a symptom-to-root-cause-to-fix reference table and advice on turning these practices into a repeatable team workflow.

    1. The Problem: Generating Code Is Easy; Generating a Usable Desktop Tool Is Not

    Many developers who use large language models (LLMs) to build small desktop utilities have run into a familiar scenario. You describe a need to “batch-extract audio tracks from videos,” and within minutes the model produces a complete piece of code. But when you actually run it, several hidden problems surface:

    • Vague requirements: The output directory isn’t specified, so files with the same name are silently overwritten;
    • Poor interaction: A long-running conversion runs on the main thread, the interface freezes, and the only option is to force-kill the process;
    • Missing dependencies: When the audio/video conversion component isn’t installed, the software crashes on startup without any friendly message.

    Any one of these is enough to push a tool from “usable” to “too risky to use.”

    The common root cause is this: models are good at filling in missing code snippets, but software quality also depends on whether requirements are expressed accurately, whether implicit constraints are made explicit, and whether the generated result is verified. Using a “batch video-audio extraction tool” as an example, this article breaks a vague, conversational description into a specification-style prompt, then walks through four steps in order: background execution, dependency pre-checks, follow-up clarification, and code review.

    Note: Different models produce code in different styles. The practices described below come from general development experience with this class of GUI tools and are not specific to any particular product.

    2. Specifying Requirements: Turning “No Lag” into Verifiable Architectural Constraints

    2.1 The Gap Between Verbal Requirements and Implicit Constraints

    The original requirement was roughly: support common video formats, export mainstream audio formats, keep the interface friendly and lag-free, and show a message when something goes wrong. These descriptions are clear enough for a human reader, but they lack two kinds of information for the model:

    1. Implicit architectural constraints: long-running tasks must not run on the main thread;
    2. Implicit business rules: where output goes, how same-named files are handled, and whether a single file failure aborts the whole batch.

    If you leave all of this for the model to infer, the result tends to fluctuate between “mostly works” and “full of small problems.” Making each implicit constraint explicit, one by one, is the first step in prompt design.

    2.2 Layered Prompts: Role, Task, Features, Non-Functional Needs, and Boundaries

    It helps to split the prompt into five layers:

    • Role: state the tech stack and engineering-quality expectations;
    • Task: one sentence describing what the tool should do;
    • Functional requirements: enumerable and verifiable;
    • Non-functional requirements: constraints on performance, interaction, reliability, and so on;
    • Boundaries and exceptions: invalid input, special paths, single-item failures, and similar cases.

    Here’s a template you can adapt:

    1. Role: You are a senior Python desktop application developer who writes GUI programs with clear structure and thorough exception handling.
    2. Task: Using Python's built-in GUI library, build a desktop tool that batch-extracts audio tracks from videos and saves them.
    3. Functional requirements:
    4. 1. Import files with common video extensions and recursively import directories; support clearing and removing list items;
    5. 2. Configure output format, sample rate, channels, and other parameters, and choose an output directory;
    6. 3. Provide Start Conversion and Exit buttons, plus a progress bar and status bar.
    7. Non-functional requirements:
    8. 1. Conversion runs in a background thread; the UI stays responsive throughout;
    9. 2. Progress and results are passed back to the main thread via a queue to refresh the UI; never manipulate widgets directly from the worker thread;
    10. 3. A single file failure does not affect subsequent tasks; errors are written to a log and shown in the UI;
    11. 4. When an output file with the same name exists, append a number automatically; never overwrite existing files;
    12. 5. On startup, check whether the audio conversion command-line tool is available; if it is missing, show a clear message.
    13. Boundaries and exceptions:
    14. 1. Prompt the user when the file list is empty or the output directory is empty;
    15. 2. Handle paths that contain Chinese characters or spaces;
    16. 3. On exit, if tasks are running, ask for confirmation and cancel them first.
    17. Output requirements: Complete, runnable code, along with dependency notes, startup instructions, and known limitations.

    There’s one key lesson here: rather than only saying “friendly interface, smooth operation,” it’s better to write out “conversion runs in a background thread and never manipulates widgets from the worker thread.” The former is an adjective the model can only guess at; the latter is a concrete architectural constraint the model can implement line by line, and one the developer can verify item by item.

    2.3 An Acceptance Checklist: Make Every Requirement Verifiable

    The essence of specification is translating requirements into acceptance conditions:

    Requirement Implicit Constraint Acceptance Check
    No lag in the UI Conversion runs in a background thread Dragging the window and switching tabs work normally during conversion
    Show messages on error Exceptions are caught per item and written to a log Feed in a corrupted file that can’t be parsed; the UI shows a message and the task continues
    Complete features Covers the full import → convert → exit flow Exercise import, removal, parameter settings, and exit one by one
    Reasonable layout Widgets adapt as the window resizes After resizing, no widget is hidden or out of bounds

    During testing, if no one can click through and verify each item manually, you can ask the model to generate an automated check script that batch-processes sample files from the command line, then confirm the output count, format, and naming against the program’s logs. Replacing “looks fine” with an executable result is the most reliable way to test generated code.

    3. Keeping the UI Responsive: Separating Long-Running Work from Worker Threads

    3.1 Why the UI Freezes

    A desktop GUI program is typically driven by a single event loop. Events such as user clicks and drags enter a queue and are handled one by one by the main thread, and UI painting also depends on the main thread. As a result, everything the main thread handles must return as quickly as possible — a principle stressed repeatedly in GUI development: never put any long-running operation on the main thread. Audio/video transcoding consumes both CPU and heavy disk I/O, taking anywhere from a few seconds to a few minutes. Once it’s written into a button callback, the event loop is occupied for a long time, which shows up as an unresponsive window and a frozen progress bar, leaving force-killing the process as the only option.

    3.2 Sample Code: Background Execution with Queue-Based Reporting

    The code below uses placeholder names to express the idea and doesn’t depend on a specific implementation:

    1. import queue
    2. import subprocess
    3. import threading
    4. MESSAGE_QUEUE = queue.Queue() # The single communication channel between the worker thread and the main thread
    5. class ConvertWorker(threading.Thread):
    6. """Background thread: only runs the conversion and reports status; never touches UI widgets directly."""
    7. def __init__(self, tasks, converter):
    8. super().__init__(daemon=True) # Ends with the process when the main program exits
    9. self.tasks = tasks # [(source path, target path), ...]
    10. self.converter = converter # Externally injected converter function, easy to replace and test
    11. def run(self):
    12. total = len(self.tasks)
    13. for index, (src, dst) in enumerate(self.tasks, start=1):
    14. try:
    15. self.converter(src, dst) # The time-consuming work happens only in the worker thread
    16. MESSAGE_QUEUE.put(("progress", index, total))
    17. except Exception as exc: # A single failure is only logged; it does not abort the whole batch
    18. MESSAGE_QUEUE.put(("error", src, str(exc)))
    19. MESSAGE_QUEUE.put(("done", total))

    The main thread pulls messages at a fixed interval and refreshes the progress bar and status bar, as shown:

    1. def poll_messages(self):
    2. while True:
    3. try:
    4. message = MESSAGE_QUEUE.get_nowait()
    5. except queue.Empty:
    6. break # No new messages right now; the next timer callback will check again
    7. kind, *payload = message
    8. if kind == "progress":
    9. index, total = payload
    10. self.progress_var.set(int(index * 100 / total))
    11. self.status_var.set(f"Completed {index}/{total}")
    12. elif kind == "error":
    13. self.status_var.set(f"Conversion failed: {payload[0]} ({payload[1]})")
    14. elif kind == "done":
    15. self.status_var.set(f"All finished, processed {payload[0]} files in total")
    16. # Check back on the main thread every 100 milliseconds; timer usage varies slightly across GUI libraries
    17. self.root.after(100, self.poll_messages)

    Here, self.root.after(100, self.poll_messages) means the main thread runs the check every 100 milliseconds. Timer usage differs across GUI libraries, but the “worker produces, main thread consumes” pattern stays the same.

    This design brings three benefits:

    1. The UI stays responsive: you can still drag the window and check status during conversion;
    2. Exception isolation: a single file failure is recorded as one error, while the rest continue converting;
    3. Controllable state: to “cancel,” you only need to set a stop flag for the worker thread, and the loop checks it after each completed task.

    3.3 Three Details That Are Easy to Overlook

    • Don’t update widgets from the background thread: most GUI libraries require widgets to be updated only on the main thread, and calling widget methods directly from a background thread may cause undefined behavior. Queue-based reporting exists precisely to avoid this.
    • Overall progress can make the progress bar “look stuck”: if each file takes a different amount of time, progress computed by file count will speed up and slow down. In scenarios with many long files, you can parse the processed duration and total duration from the underlying tool’s output, convert it to a percentage, and report that. Note that output formats can change between versions, so the parsing logic needs to tolerate errors.
    • Define exit and cancel behavior explicitly: if the window is closed while a task is running, confirm first and cancel unfinished tasks; the background thread should end with the main program to avoid leaving a stray process behind.

    4. Checking Dependencies Up Front: Surfacing Environment Problems Before Use

    Tools that batch-extract audio from video commonly depend on an additional command-line conversion component, which isn’t installed by default with the language. If a user’s machine doesn’t have it, the program often throws an error only when the first task runs — a poor experience. The sensible approach is to complete the check before conversion starts, or even at startup. Sample code:

    1. import shutil
    2. REQUIRED_TOOLS = ["converter"] # Placeholder name for the actual command-line conversion component
    3. def check_dependencies():
    4. """Check external dependencies at startup; tell the user clearly if any are missing."""
    5. missing = [name for name in REQUIRED_TOOLS if shutil.which(name) is None]
    6. if missing:
    7. raise RuntimeError("Missing required conversion component(s): " + ", ".join(missing))

    Combined with two practices, this can reduce environment-related problems to a minimum:

    1. Put the check first: run it at startup or before the user clicks “Start Conversion,” and provide installation guidance through the status bar or a dialog;
    2. Avoid injection risk when invoking external tools: pass paths as an argument list (e.g., subprocess.run([...], capture_output=True)) rather than concatenating paths directly into a command string. This naturally supports paths with Chinese characters and spaces, and avoids special characters being misparsed.

    5. Asking Follow-Up Questions: Turning “Default Behavior” into Explicit Rules

    After the first version of the code is generated, one valuable follow-up question is: “By default, which directory do the converted files go to?” This seems trivial, but it exposes the default behavior the model filled in on its own. When information is incomplete, generative models tend to insert a default value based on the most common pattern, and that value may not match the user’s expectation.

    The output directory is just one example. The following kinds of questions should all be confirmed before acceptance:

    • Default path: is the output directory the program’s directory, the user’s home directory, or the last-used directory?
    • Same-name policy: if the target file already exists, should it skip, overwrite, or append a number automatically?
    • Partial failure: if an individual file fails to convert, should the remaining files still be processed?
    • Failure information: is the error message enough to locate the problem, and is it also written to a log?
    • Cancel and interrupt: after canceling mid-task, how are completed results and temporary files handled?

    Once expectations are clear, you can turn the answers into configuration items or UI options. For example, default the output directory to the program’s directory and let users change it, append a number to same-named files by default, and let users choose to skip or overwrite. Defaults should be “safety-first”: better to prompt once more than to silently overwrite an existing file without the user knowing.

    6. Code Review: Four Checks to Run After Generation

    Code that runs is not the same as code that can be delivered. Review it in this order:

    1. Static checks: first check syntax and imports to confirm there are no syntax errors and every module imports correctly;
    2. Runtime validation: prepare small, medium, and large sample files (including corrupted files) to cover normal, boundary, and error paths;
    3. Security and robustness checks:
      • Does path handling use a cross-platform join method?
      • Is the encoding specified explicitly for file reads and writes?
      • Are exceptions isolated at the task level?
      • Are there cases where temporary files are left on disk?
    4. Maintainability checks: are modules split by responsibility (UI, conversion logic, configuration management), are logs complete and able to output by level, and do key pieces of logic carry necessary comments?

    A sample modular split looks like this:

    1. audio_extractor/
    2. ├── ui.py # UI layout, event callbacks, status refresh
    3. ├── worker.py # Background thread, progress and error reporting
    4. ├── converter.py # Conversion logic, dependency checks, naming policy
    5. ├── config.py # Defaults, list of supported formats
    6. └── tests/ # Sample files and automated check scripts

    Separating the conversion logic from the UI has a benefit: the core logic can be tested independently of the GUI, and when you later swap out the UI library or adjust the conversion implementation, the scope of changes is easier to control.

    7. Quick Reference: From Symptom to Root Cause to Fix

    Symptom Root Cause Fix Direction
    The UI freezes during conversion The long-running task runs on the main thread Run it in a background thread; the main thread only refreshes the UI
    The UI misbehaves after a background thread updates a widget Widget operations aren’t executed on the main thread Report messages through a queue; the main thread updates everything uniformly
    Output files are silently overwritten The same-name handling policy isn’t defined Append a number by default and let users choose the policy
    One file’s failure aborts the whole batch Exceptions aren’t caught within a single task Catch exceptions at the file level and record them to a log
    The software won’t start or conversion errors out The command-line conversion component is missing Check dependencies at startup and provide installation guidance
    Conversion fails when the filename contains Chinese characters Improper path encoding or command concatenation Use cross-platform path joins and argument-list invocation
    The progress bar sits at one value for a long time Progress is averaged by file count Parse output durations and report a percentage

    What these cases have in common is that the problem isn’t that the model “can’t write code,” but that the requirement didn’t state the constraints clearly. Turning common pitfalls into a checklist and reviewing each item after every generation can significantly reduce rework.

    8. From Personal Productivity to Team Process

    Individual productivity gains are only the starting point. For a team to use LLM-assisted development long-term, consider the following:

    • Turn prompts into assets: distill validated requirement templates into shared team assets that new projects can reuse directly, adding project-specific constraints as needed;
    • Establish a code-quality baseline: generated code should still go through code review, static scanning, and unit tests — don’t lower the bar just because “it was generated by a model”;
    • Build up an acceptance checklist: organize typical failures into a checklist to serve as the basis for regression testing;
    • Connect build and operations: build artifacts can be archived and distributed uniformly through cloud products such as object storage; once packaged as container images, they can be deployed to test or production environments through a container platform. Runtime logs can be routed into a logging service for centralized search, retention, and auditing. Combined with monitoring and alerting, you can set thresholds on metrics such as error counts and response times to catch problems early and trace them back.

    On top of these general capabilities, Baidu AI Cloud offers products such as object storage, containers, logging, and monitoring, and supports the development and deployment of large-model applications. Teams can evaluate their choices based on their own network environment, data-compliance requirements, and cost budget.

    9. Summary

    Using a “batch video-audio extraction tool” as a sample, the key to LLM-assisted desktop tool development isn’t how much code the model generates in one shot, but turning vague requirements into clear specifications, writing implicit constraints as explicit architectural requirements, and placing the generated result inside a verifiable loop. Specifically:

    1. Organize prompts in layers, converting adjectives like “no lag” into verifiable technical constraints;
    2. Run long-running tasks in the background and report status through a queue so the UI always stays responsive;
    3. Check external dependencies in advance to avoid environment problems surfacing only at runtime;
    4. Actively ask about default behavior, turning implicit rules into explicit configuration;
    5. After generation, run static checks, runtime validation, and security review;
    6. Turn prompt templates, pitfall lists, and quality checks into a team process, and connect them to general cloud capabilities such as build, logging, and monitoring.

    With this approach, developers can more confidently use LLMs to shorten the path from idea to a usable tool when facing similar needs, while holding the line on quality and maintainability.