Applying LLM Agents to Scientific Research: Architecture and Pitfalls of a Single-Cell Analysis Agent

    This article explains how to bring LLM-based agents into scientific computing workflows, using single-cell RNA sequencing (scRNA-seq) analysis as a concrete example. It covers why agent-driven workflows improve reproducibility and auditability over manual scripting, presents a four-layer architecture with sandboxed execution and deterministic validation, walks through the standard single-cell analysis pipeline with its human review checkpoints, and provides a reference scheduling implementation with retry limits, timeouts, tool whitelists, and audit logging. It also outlines the boundaries of LLM usage in drug and materials discovery, where every model output must be backed by deterministic tools.

    1. Why Hand Research Workflows Over to an Agent

    Traditional scientific computing relies on experts manually writing scripts, configuring environments, and interpreting data one step at a time. The process is driven by accumulated experience, and results are hard to reproduce. The AI4S (AI for Science) agent approach delegates this orchestration to a large language model: the model interprets the research goal, generates an analysis plan and code, and then adjusts the next step based on execution results.

    The two approaches differ mainly in three ways:

    • Recordability: every piece of code and every error the agent produces can be written to a log, whereas a manual workflow often leaves only the final result.
    • Reproducibility: an agent workflow is reproducible only after code and dependency versions are pinned. The LLM’s output itself is not guaranteed to be identical every time.
    • Verifiability: any number the agent outputs must be traceable back to the raw computation produced by a deterministic tool.

    Agents are well suited to repetitive, clearly defined analysis tasks. For exploratory judgments whose results cannot be verified, they should not be the sole basis for decisions.

    2. Agent Architecture for Single-Cell Analysis

    This scenario is typically divided into four layers:

    • Interaction layer: researchers state their analysis needs in natural language, for example, “analyze the developmental trajectory of mouse embryonic pancreatic cells.”
    • Agent orchestration layer: the LLM decomposes the request into steps such as quality control, normalization, dimensionality reduction, clustering, and differential gene analysis.
    • Compute execution layer: the agent generates Python scripts and runs standard libraries such as Scanpy in an isolated sandbox.
    • Data and knowledge layer: raw sequencing data is read from authorized storage, while the LLM provides background biological knowledge to assist interpretation — it does not replace computation.

    2.1 Prerequisites

    Before starting a run, the following conditions must be met:

    • The Python version and the versions of libraries such as Scanpy and anndata are pinned in the project dependency file and covered by regression tests.
    • The sandbox has no external network access, mounts only authorized directories, and enforces CPU, memory, and execution-time limits.
    • The LLM API’s inputs and outputs have explicit structural definitions. Plan steps should be returned as JSON, and any format mismatch should raise an error immediately.
    • Raw data has passed authorization review and de-identification checks.

    2.2 Analysis Pipeline and Human Checkpoints

    The standard single-cell analysis pipeline includes the following steps, each with boundaries that require human confirmation:

    1. Quality control: filter out low-quality cells by gene count, UMI count, and mitochondrial gene fraction. Thresholds should be set per dataset rather than copied from fixed values.
    2. Doublet detection and removal: use tools such as Scrublet or DoubletFinder to remove false cells formed when two cells are mistakenly merged.
    3. Normalization and highly variable gene selection: correct for sequencing depth differences and select genes with pronounced variation for downstream analysis.
    4. Batch correction: when samples come from different batches, use methods such as Harmony or scVI. After correction, check that real biological differences have not been over-smoothed.
    5. Dimensionality reduction and clustering: use UMAP for visualization. Scan multiple clustering resolutions and judge whether the results are reasonable based on marker genes.
    6. Cell type annotation: annotate based on marker genes or reference atlases. Annotations suggested by the LLM are only candidates and must be confirmed by domain experts.
    7. Differential gene analysis: define comparison groups first, then apply tests such as Wilcoxon. Correct for multiple testing with the Benjamini–Hochberg method and set a log fold-change threshold. FDR < 0.05 is a common starting point, but the exact value should be chosen based on the data.
    8. Candidate gene output: state the filtering criteria in the list and note that candidate genes require wet-lab validation.

    The analysis plan generated by the agent requires human review before critical steps are executed.

    2.3 Scheduling Logic Example

    The following pseudocode shows the basic structure of the orchestration layer, including an iteration cap, timeout control, a tool whitelist, audit logging, and deterministic validation:

    1. ALLOWED_TOOLS = {"read_h5ad", "run_qc", "normalize", "cluster", "find_markers"}
    2. MAX_ROUNDS = 3 # Max auto-repair attempts per step; prevents infinite loops
    3. STEP_TIMEOUT_S = 600 # Per-step execution timeout in seconds
    4. class AgentError(Exception):
    5. """Expected workflow error that must be escalated to a human."""
    6. class BioResearchAgent:
    7. def __init__(self, llm, sandbox, audit_log):
    8. self.llm = llm
    9. self.sandbox = sandbox
    10. self.audit = audit_log
    11. def analyze_scrna(self, dataset_uri, research_goal):
    12. plan = self.llm.plan(goal=research_goal, dataset=dataset_uri,
    13. allowed_tools=ALLOWED_TOOLS)
    14. self._validate_plan(plan)
    15. results = {}
    16. for step in plan.steps:
    17. results[step.name] = self._run_step(step)
    18. self.audit.record("plan_done", [s.name for s in plan.steps])
    19. # The LLM only summarizes; it does not make numeric judgments
    20. return self.llm.summarize(results)
    21. def _validate_plan(self, plan):
    22. unknown = [s.tool for s in plan.steps if s.tool not in ALLOWED_TOOLS]
    23. if unknown:
    24. raise AgentError(f"Plan contains unauthorized tools: {unknown}")
    25. def _run_step(self, step):
    26. code = self.llm.generate_code(step)
    27. for attempt in range(1, MAX_ROUNDS + 1):
    28. self.audit.record("code", step.name, attempt, code)
    29. try:
    30. result = self.sandbox.run(code, timeout=STEP_TIMEOUT_S)
    31. except TimeoutError:
    32. raise AgentError(f"Step {step.name} timed out and was stopped")
    33. if result.ok:
    34. self._check_result(result, step)
    35. return result.data
    36. if attempt < MAX_ROUNDS:
    37. code = self.llm.fix_code(code, result.error_summary)
    38. raise AgentError(f"Step {step.name} still failed after {MAX_ROUNDS} attempts")
    39. def _check_result(self, result, step):
    40. # Deterministic check: empty output is a hard failure, not an LLM judgment
    41. if result.data is None or len(result.data) == 0:
    42. raise AgentError(f"Step {step.name} produced empty output")

    Key points of the code:

    • MAX_ROUNDS caps automatic repair attempts. If the model keeps generating faulty code, the workflow stops and hands off to a human.
    • Execution is aborted on timeout to avoid tying up compute resources for long periods.
    • The tool whitelist validates the plan before execution, blocking calls to unauthorized functions.
    • Every piece of generated code and every error message is written to the audit log for later troubleshooting.
    • Validation of numeric results is performed by deterministic code.

    3. Tool Boundaries in Drug and Materials R&D

    In drug discovery and new materials research, LLMs can handle literature processing and interpretation work, but every step must be backed by deterministic tools:

    • Literature mining: the LLM can extract molecular structure information such as SMILES strings from papers and patents. Extraction results must be checked for syntax and chemical validity by chemistry parsing libraries such as RDKit.