Engineering AI for Science: Practical Lessons for Building Large Model Applications
This article explains why deploying large language models in scientific research requires engineering discipline rather than simply larger models. It walks through a typical single-cell transcriptomics workflow, shows how to constrain model output with tool whitelists and parameter validation, and describes a plan-execute-review pattern for long-running agent tasks. It also covers closed-loop generation and evaluation in drug and materials discovery, the data and compute infrastructure needed for reproducibility, a three-layer evaluation framework, common pitfalls, and a phased adoption roadmap.
1. Why AI for Science Needs Engineering, Not Bigger Models
Scientific discovery tasks differ fundamentally from general-purpose chat. Their inputs are high-dimensional, noisy experimental data without unified labels, and their outputs must be verifiable by peers. Chat inputs are natural language, and outputs only need to hold up semantically. Connecting a general-purpose large model directly to a research workflow usually runs into three problems: conclusions that cannot be reproduced, intermediate steps that cannot be audited, and a high cost per exploration that rarely converges.
The goal of engineering is to constrain the model’s intuition inside a verifiable process. A practical approach is to layer the system: data and compute at the bottom, feature extraction and statistical testing in the middle, and the large model on top, responsible for hypothesis generation, experimental design, and result interpretation. The large model does not replace statistical methods. It ranks and filters candidates in a vast hypothesis space, focusing human attention on a few high-value directions.
2. A Typical Scenario: From Single-Cell Atlas to a Candidate Gene List
Take the construction of a developmental atlas from single-cell gene expression. A robust pipeline usually includes these stages:
- Data ingestion and QC: unify the expression matrix format, filter out low-quality cells and low-expression genes, and record every filtering threshold.
- Dimensionality reduction and clustering: select highly variable genes, reduce dimensions with principal component analysis, then build a graph and cluster to obtain cell subpopulations.
- Trajectory inference: construct differentiation paths between subpopulations, marking start and end states and branch points.
- Differential expression and enrichment analysis: identify stage-specific marker genes along the trajectory, run functional enrichment, and form a candidate list.
- Hypothesis generation and ranking: the large model combines literature semantics with pathway priors to provide mechanistic explanations and priorities for the candidate genes.
Step 5 is where the large model delivers real value. It does not “compute” genes. It translates statistical results into testable biological hypotheses and points to the kind of validation experiment to run next. Illustrative agent tool registration code:
TOOLS = {"qc_filter": {"desc": "Filter cells and genes by thresholds", "schema": {"min_genes": "int", "max_mito": "float"}},"cluster": {"desc": "Dimensionality reduction and clustering", "schema": {"n_pcs": "int", "resolution": "float"}},"trajectory": {"desc": "Build differentiation trajectory", "schema": {"root": "str", "method": "str"}},"diff_exp": {"desc": "Differential expression test", "schema": {"group_a": "str", "group_b": "str"}},"enrichment": {"desc": "Pathway enrichment", "schema": {"gene_set": "list", "db": "str"}},}def run_agent(plan, executor):for step in plan: # plan is generated by the model but must come from the TOOLS whitelistassert step["tool"] in TOOLS, f"Illegal tool: {step['tool']}"yield executor(step["tool"], step["args"])
The key is the whitelist and parameter validation: the model can only propose a call intent, while execution authority and parameter boundaries stay on the engineering side. This preserves flexibility for exploration while preventing uncontrolled behavior.
3. Agent Orchestration: Making Long-Running Tasks Controllable
Research tasks often take tens of minutes to hours, far beyond the patience threshold of a single request. A reliable pattern is plan-execute-review in three stages. The planning stage produces structured steps. The execution stage runs computation as asynchronous tasks and writes state to persistent storage. The review stage aggregates logs, charts, and intermediate artifacts, then hands them to the model to produce conclusions and a statement of uncertainty.
Four things must be enforced in engineering. First, idempotency: repeating a step produces no side effects. Second, resumability: persist intermediate artifacts and recover from the most recent checkpoint after a failure. Third, observability: record an input summary, elapsed time, resource usage, and random seed for every step. Fourth, cost control: use smaller parameter configurations for small-scale trials and scale up only after a direction is confirmed. Illustrative state machine:
def step(state, tool, args, executor, store):key = f"{state.run_id}:{tool}:{hash(str(sorted(args.items())))}"if store.exists(key):return store.load(key) # Idempotency: return the cached result on a hitout = executor(tool, args)store.save(key, out, seed=state.seed) # Persist to disk: enables resumability and reproducibilityreturn out
4. Drug and Materials Discovery: Closing the Loop Between Generation and Evaluation
In molecular and formulation design, the common paradigm is a generate-evaluate-filter loop: the model proposes candidate structures or compositions, physics and chemistry constraints score them, and only candidates that satisfy stability, synthesizability, and cost constraints move to the next round. The most common mistake here is letting the model act as both generator and judge, which inflates scores. The correct approach is to introduce an independent evaluator and to define evaluation metrics as computable quantities, such as energy, stability window, and number of synthesis steps.
Convergence of the loop should not rely on the model’s self-assessment either. Set explicit stopping conditions: candidate diversity below a threshold, no improvement in the best score for several consecutive rounds, or an exhausted budget.
5. A Common Architecture for the Data and Compute Foundation
The foundation supporting these pipelines is usually a combination of general capabilities: object storage holds raw data and intermediate artifacts, a message queue decouples long-running tasks, a container platform provides reproducible runtime environments, and logging plus monitoring and alerting track the input, output, and resource levels of every step. Baidu AI Cloud can support end-to-end data and compute orchestration across these general categories, letting research teams focus on the methods themselves.
Data governance should emphasize three points: versioning, tagging datasets together with code; traceable lineage, so any conclusion can be traced back to a specific data slice and parameters; and least privilege, isolating sensitive experimental data by project.
6. Evaluation, Reproducibility, and Common Pitfalls
Evaluation should have three layers. The process layer looks at success rate and average elapsed time. The result layer checks whether metrics significantly outperform a random baseline. The science layer checks whether conclusions can be validated by independent experiments. A missing random baseline is the most common pitfall in practice; many reported “improvements” are just data leakage or selection bias.
Other frequent problems include treating correlation as causation, ignoring batch effects, tuning on the test set, and reporting only successful cases. The way to avoid them is to include baselines, random seeds, and failed samples in the report, so negative results carry information too.
7. A Phased Roadmap for Adoption
A four-stage progression is recommended. Start with offline reproduction, running the full pipeline on public datasets. Then pursue single-point efficiency gains, choosing the most labor-intensive step for intelligent literature retrieval and hypothesis ranking. Next, close the loop by connecting the evaluator to the generation stage. Finally, move to platformization, accumulating the tool whitelist, templates, and monitoring system. Set quantifiable acceptance criteria at each stage to avoid the cycle of a demo that looks impressive but is unusable in production.
