Engineering AI for Science: A Practical Guide to Verifiable LLM Workflows

    This article explains how to move large language models from a Q&A assistant role into scientific research workflows where conclusions must be verifiable. It breaks a runnable system into five layers: turning a research question into a machine-executable specification, wrapping code generation in a validation loop, controlled invocation of specialized tools, data and environment reproducibility management, and layered quality evaluation with human-in-the-loop checkpoints. It also lists common anti-patterns and outlines how the model, the engineering framework, and the researcher should split responsibilities.

    1. The Trend: LLMs Enter the Research Workflow, and the Hard Part Is Verification, Not Writing

    The most visible change of the past two years is that LLMs are shifting from a “Q&A assistant” to a “workflow owner” in research settings. The early pattern was a researcher pasting an error message and a snippet of code into a chat box and getting back a suggested fix. The current pattern is different: the model reads the research goal, decomposes it into executable steps, writes the analysis code itself, calls specialized tools for statistics and visualization, and finally produces conclusions together with an evidence chain.

    The engineering implications of this shift matter far more than the capability upgrade. The fundamental difference between research analysis and general text generation is that conclusions must be verifiable: a bad marketing copy is merely ineffective, whereas a wrong significance decision or a misaligned sample label directly contaminates every downstream decision. So putting a model into a research workflow is not about “how good the generation is,” but about:

    • Reproducibility: can the same input produce the same result?
    • Auditability of intermediate artifacts: who changed which parameter, and when?
    • Controlled tool invocation: the model must not hold unrestricted execution rights.
    • Evidence attached to conclusions: every claim must trace back to specific data and run logs.

    The rest of this article walks through the layers of a runnable system.

    2. Layer 1: Turning a Research Question into a Machine-Executable Specification

    Research questions are inherently vague. “Check whether these two groups differ” is missing at least four categories of information from an engineering standpoint: which metric to compare, how samples are grouped, which test to use, and how the significance threshold and multiple-comparison correction are handled.

    The practical approach is to run a problem structuring step first, have the model emit an explicit specification, and only proceed to execution after the researcher confirms it. A simplified example:

    1. task: group_comparison
    2. dataset: expression_matrix_v2
    3. grouping:
    4. field: condition
    5. levels: [control, treated]
    6. metric: mean_difference
    7. test: welch_t_test
    8. alpha: 0.05
    9. multiple_testing: benjamini_hochberg
    10. outputs: [stats_table, volcano_plot, session_report]
    11. constraints:
    12. max_runtime_minutes: 20
    13. allowed_packages: [numpy, pandas, scipy, matplotlib]

    This specification is valuable for three reasons. First, it converts natural-language intent into checkable fields, so missing items surface immediately. Second, it becomes the “contract” for all later steps: code generation, tool selection, and result validation all take it as input. Third, it is naturally part of the experiment record, and combined with version control it makes runs reproducible.

    It is worth stressing that the structuring step should not be completed by the model alone. A safer division of labor is for the model to produce a draft plus a list of items needing confirmation, and for the researcher to confirm or correct them at minimal cost. This keeps the efficiency while preserving a clear boundary of responsibility.

    3. Layer 2: Code Generation Must Sit Inside a Verifiable Loop

    Having the model write analysis code is the core of this whole direction and also where risk concentrates. The reliable implementation wraps generation in a loop rather than delivering code in one shot:

    1. Generate: produce code from the specification, along with an “expected result shape” (for example, column names of the result table, order of magnitude of row counts, value ranges).
    2. Static checks: run syntax and dependency checks inside a controlled sandbox; implicit network access and out-of-bounds file access are prohibited.
    3. Small-scale trial run: execute on sampled data or the first few rows first, to quickly expose dimension mismatches and index errors.
    4. Assertion validation: express the expected shape as assertions and compare automatically after the run.
    5. Failure loop-back: feed the full error stack back to the model, with a cap on retries and budget to avoid unbounded consumption.
    6. Traceability: save the code version, dependency versions, random seed, and runtime environment identifier.

    A sketch of assertions and loop control:

    1. def validate(result_df, spec):
    2. assert list(result_df.columns) == spec["expected_columns"], "column structure mismatch"
    3. assert len(result_df) == spec["expected_rows"], "unexpected row count"
    4. assert result_df["p_value"].between(0, 1).all(), "p-value out of range"
    5. return True
    6. for attempt in range(MAX_RETRY):
    7. code = planner.generate(spec, feedback=feedback)
    8. ok, payload = sandbox.run(code, seed=FIXED_SEED, timeout=600)
    9. if ok and validate(payload, spec):
    10. break
    11. feedback = summarize_error(payload) # structured error summary, not the raw log
    12. else:
    13. raise BudgetExceeded("retry budget exhausted, escalate to a human")

    Two easily overlooked details here. First, what gets fed back to the model should be a structured error summary, not the entire log; an overly long log dilutes the key signal and actually lowers the repair success rate. Second, the random seed must be fixed and recorded, otherwise “reproducible” is just a slogan. Many small discrepancies in statistical pipelines come precisely from unfixed sampling and from parallel reduction order.

    4. Layer 3: Controlled Invocation of Specialized Tools

    Research analysis is rarely done with a single script; it usually involves statistical tests, sequence alignment, structure prediction, plotting, and other specialized capabilities. Letting the model “call tools” is, in engineering terms, giving it a restricted set of external interfaces. The design should follow a few principles:

    • Whitelisting: expose only wrapped tools, define parameters with schemas and validate them strictly, so the model cannot assemble arbitrary commands.
    • Idempotence and read-only first: design query tools as read-only and safely repeatable; write operations (modifying datasets, submitting long-running jobs) require a second confirmation.
    • Least privilege: containers mount no unrelated directories, credentials are issued per task with an expiry, and outbound network access is restricted by a domain whitelist.
    • Budget and timeouts: cap both individual calls and the overall task, so the model cannot fall into endless trial and error.
    • Unified accounting: the input summary, duration, and status of every call go into a logging service, which supports later auditing and cost attribution.

    A controlled tool description can be written as:

    1. {
    2. "name": "run_stat_test",
    3. "parameters": {
    4. "test": {"enum": ["t_test", "wilcoxon", "anova"]},
    5. "x": {"type": "array", "items": "number"},
    6. "y": {"type": "array", "items": "number"},
    7. "alpha": {"type": "number", "minimum": 0.0, "maximum": 1.0}
    8. },
    9. "side_effects": "none",
    10. "timeout_seconds": 120
    11. }

    An explicit annotation like side_effects looks tedious, yet it decides whether the system can safely let the model plan autonomously: only when the side effects of a call are declared clearly does the orchestration layer dare to parallelize or auto-retry unattended.

    5. Layer 4: Data, Environment, and Reproducibility Management

    The hard part of putting AI for Science into practice is often not the model but data governance. Reproducibility requires at least four things to hold at the same time: a fixed input data version, a fixed dependency environment, fixed parameters and seeds, and a trace of the run.

    The common engineering practice: raw data is written to object storage with versioning enabled, and intermediate artifacts are stored in per-task directories; dependencies are frozen as images or lock files and scheduled by a container platform; each run generates a manifest recording the data version, image digest, parameters, and random seed; the experiment record is archived together with the result tables, forming a traceable chain.

    One reminder: data compliance and privacy boundaries should be designed in up front. When sensitive data is involved, masking and access control must be completed before the data enters the pipeline, not patched on after results are produced. Cross-region compute scheduling also needs an assessment of the compliance impact of data leaving its domain.

    6. Layer 5: Quality Evaluation and Human in the Loop

    Evaluating this kind of system cannot rely only on “whether the final answer is correct”; metrics should be set per layer:

    • Specification layer: recall and precision of requirement extraction, and whether missing items are proactively questioned.
    • Execution layer: first-pass success rate, average number of retries, and the distribution of timeouts and failures.
    • Result layer: agreement with manual analysis conclusions, and the deviation range of key statistics.
    • Cost layer: average resource consumption and queue time per task.

    Human-in-the-loop design is equally critical. Three mandatory human confirmation points are recommended: confirmation of the research question and hypotheses, release approval for write operations or high-cost tasks, and external publication of final conclusions. Other steps can flow automatically, balancing efficiency and control.

    7. Common Anti-Patterns

    • One-shot delivery: no checkpoints and no loop, so a single model error wastes the entire round.
    • Raw log feedback: passing back the whole error message, where noise drowns the key signal.
    • Over-broad permissions: providing an environment that can execute arbitrary commands for convenience, which is an unacceptable risk.
    • Ignoring seeds: results cannot be reproduced, and review and collaboration costs rise sharply.
    • Single-metric evaluation: judging only by final-answer accuracy, which hides fragility in the execution layer.

    8. Conclusion

    Having LLMs take over research analysis workflows is essentially embedding “uncertain generative capability” into “research standards that demand certainty.” The viable path is not to pursue full automation, but to build a system that is specification-first, controlled in execution, verifiable in results, and traced end to end: the model handles decomposition and drafting, the engineering framework handles constraints and validation, and the researcher handles key decisions. If this foundation is built on general-purpose capabilities such as object storage, container platforms, logging services, and monitoring and alerting from Baidu AI Cloud, teams can focus their effort on the domain methods themselves rather than rebuilding infrastructure.