Automating Scientific Computing Script Generation and Iterative Refinement with Local LLMs

    This article explains how to build a practical local tool that uses a locally deployed lightweight LLM to generate and iteratively refine scientific computing scripts from natural-language descriptions. It covers the overall architecture, system prompt design, multi-turn context management, safe code extraction and execution, interactive command design, the iterative debugging workflow, capability limits of small models, and practical usage recommendations, helping readers reduce repetitive scripting work at zero inference cost while keeping data on their own machine.

    Automating Scientific Computing Script Generation and Iterative Refinement with Local LLMs

    1. Background

    In engineering computation, data processing, and teaching demonstrations, a large amount of time is spent repeatedly writing basic scripts. Tasks such as reading data, plotting curves, performing matrix transformations, or setting up simulation workflows are usually not logically complex, yet writing them from scratch still requires looking up syntax and debugging step by step. LLMs can generate code from natural-language descriptions, which makes it possible to lower this barrier.

    Calling cloud-based LLM services directly typically requires applying for access credentials and paying per request. For learners, small teams, or scenarios involving sensitive data, both points can be obstacles. Deploying the model locally reduces calling costs and prevents data from leaving the machine. The trade-off is that you must bear certain hardware resource costs and accept compromises in model capability.

    2. Overall Architecture

    A usable local code-generation tool generally consists of four parts:

    1. Local model runtime: loads a lightweight open-source model and exposes inference through a local network port.
    2. Script-side interaction layer: receives user input, maintains conversation history, sends requests, and parses responses.
    3. Code extraction and execution module: extracts code blocks from model replies and runs them in the current workspace after user confirmation.
    4. Persistence module: saves satisfactory code as script files for later reuse.

    The benefit of this layering is that each part can be replaced independently. When switching models, you only need to change the model name configuration, without touching the interaction logic. Similarly, if you later want a different interface, you only need to rewrite the interaction layer.

    3. System Prompt Design

    Small models have limited instruction-following ability, so the system prompt needs to be as specific and unambiguous as possible. A qualified prompt should include at least:

    • Role definition: clearly state that the model acts as an expert in a particular programming language, so its output style matches the domain.
    • Output form: require complete, directly runnable scripts rather than fragments or pseudocode.
    • Structural constraints: for example, forbid function definitions so the code can run as a whole in the command window, reducing execution complexity.
    • Format conventions: require code to be placed in a unified code block so it can be extracted programmatically.

    An illustrative example:

    1. system_prompt = [ ...
    2. 'You are an expert in scientific computing scripting.', ...
    3. 'Generate a complete, directly runnable script. Do not define functions.', ...
    4. 'Put the code in a code block, with only one brief sentence of explanation before the block.'];

    Forbidding function definitions is an explicit trade-off. Script-style code is easier to run directly and suits rapid generation, but it is less reusable and harder to test piece by piece. For one-off tasks and prototype validation, this trade-off is reasonable. If the code matures into a long-term tool, it can be refactored into functions later.

    4. Multi-Turn Dialogue and Context Management

    The key to multi-turn dialogue is that every request must include the full message history in order. Each user input and each model reply should be appended to the history. Only then can the model understand references like “modify it based on the previous version.”

    As the conversation grows, the input can exceed the model’s context window. Early requirements may then be ignored, and reply quality degrades. Three common mitigation strategies are:

    • Sliding window: keep only the most recent turns. Simple to implement, but early requirements are lost.
    • Summary compression: periodically ask the model to condense the history into a short summary that replaces the raw records. Preserves more information, but the summary itself may introduce errors.
    • Manual reset: the user actively clears the history via a command, suitable when switching tasks.

    This tool uses a manual clear command combined with retaining a limited number of turns. The advantage is predictable behavior: users know exactly when memory will be lost and can decide themselves when to start a new task.

    5. Code Extraction and Safe Execution

    Model-generated code is unverified and cannot be assumed correct or safe. In engineering practice, follow these principles:

    1. Show first, execute later: display the generated code to the user, who decides whether to run it.
    2. Extract only code blocks: locate code by finding the start and end markers of the code block and ignore the surrounding explanatory text.
    3. Limit execution impact: generated code may delete files, access the network, or modify system settings. Untrusted content should run in an isolated environment, or key statements should be manually reviewed before execution.
    4. Keep the raw reply: makes it easier for users to compare, troubleshoot, and roll back.

    Illustrative extraction logic:

    1. % Pseudocode: locate the content between the first pair of code fence markers
    2. [start_pos, end_pos] = locate_fence_pair(reply);
    3. code_text = reply(start_pos:end_pos);

    Avoid feeding model output directly into dynamic evaluation mechanisms without inspection. This is the most important safety difference between a local tool of this kind and an ordinary script.

    6. Interactive Command Design

    Interactive commands should be clearly distinguishable from ordinary questions, so that control commands are not mistakenly sent to the model as natural-language requests. This tool defines the following commands:

    • /run: run the most recently generated code.
    • /save: save the most recently generated code to a file.
    • /clear: clear the conversation memory and start a new task.
    • exit or q: quit the program.

    Command detection should happen before sending any request. The program first checks whether the input is a command; only non-command content enters the model inference flow. This saves inference time and guarantees deterministic control behavior.

    7. Iterative Refinement Workflow

    In practice, the first generated code usually satisfies only most of the requirements. The recommended iteration process is:

    1. Run the code and observe the output or error messages.
    2. Feed the error message, together with the original code, back to the model, and describe the expected correct behavior.
    3. Ask the model to modify only the faulty part and output the complete code.

    Because the history retains the original code, the model can locate where changes are needed. Asking it to “modify only the faulty part” reduces unrelated changes and makes line-by-line manual comparison easier. If the same problem recurs, consider breaking the task into smaller steps and validating each step.

    8. Capability Limits and Improvement Directions

    Small-parameter models typically perform weakly in the following areas:

    • Complex algorithms and multi-step logical reasoning: the model tends to miss boundary conditions or make mistakes in intermediate steps.
    • Obscure functions and newer syntax: incomplete memory may lead to nonexistent parameters or incorrect calling conventions.
    • Global consistency in long code: the longer the code, the higher the risk of inconsistent variable naming and data structures.

    Mitigations include: splitting large tasks into smaller steps; providing example inputs and expected outputs in the prompt; and manually verifying critical results. If hardware permits, you can also switch to a larger local model. Model selection should be based on task complexity and hardware constraints, not parameter count alone.

    9. Practical Recommendations

    1. Start with well-defined, localized tasks—such as a single plot or a single data-processing step—and expand requirements gradually.
    2. Keep a version of every usable generation result for easy rollback and comparison.
    3. Review line by line any code involving file writes, deletions, or system calls before running it.
    4. Organize frequently used prompts into templates to reduce repetitive description and keep output style consistent.

    Through local deployment and careful interaction design, you can obtain a practical coding assistant at zero calling cost. Its main value lies in reducing repetitive scripting work, not in replacing your own understanding and verification of program logic.