LLM Agents in Drug Discovery: A Practical Guide to Marker Gene Analysis
Large language model (LLM) agents can break down complex research tasks, such as marker gene analysis in single-cell RNA sequencing, into automatable and verifiable steps for drug discovery teams. This guide explores why stepwise automation fits scientific computing and details the six key stages of the marker gene analysis pipeline, from data quality control to biological plausibility evaluation. It provides a runnable Python code framework, key parameter configurations, and the four core responsibilities of AI agents (planning, execution, checking, and reporting). Additionally, it includes a troubleshooting checklist and a risk assessment list to help research teams apply AI agents safely and efficiently while maintaining rigorous human oversight.
1. Why Stepwise Automation Fits Scientific Computing
Over the past two years, LLM agents have primarily been applied in code generation, document processing, and customer service. The inputs and outputs in these scenarios are clearly defined and easy to verify—for instance, whether code compiles or tests pass usually yields an answer within seconds.
Research tasks are more challenging to verify. Researchers must simultaneously handle experimental data, domain literature, and causal hypotheses, assessing the reliability of conclusions when evidence is insufficient. For drug discovery teams, the return on investment from automation depends on whether the workflow can be decomposed into small, individually inspectable steps.
An anonymous case study indicated that a team integrated a general-purpose LLM agent and reduced the preliminary results of marker gene calculation, ribosome-related gene filtering, and biological plausibility assessment from a 4-to-8-hour manual task to roughly the duration of a meal. The original report did not specify the type of research institution, data scale, or the measurement criteria for the time taken, so this figure only indicates a direction and should not be treated as a universal conclusion. Teams should re-measure this on their own specific data.
2. Inputs, Outputs, and Checks for the Six Stages
To determine whether a stage can be handed over to an agent first, three criteria apply: whether the inputs and outputs are clear, whether the results can be independently checked, and whether the system can quickly roll back in case of errors. The table below lists the six stages of marker gene analysis.
| Stage | Input | Output | Verification Metrics | Common Failures | Can it be Automated First? |
|---|---|---|---|---|---|
| Data QC | Count matrix and cell metadata | Filtered matrix and QC stats | Genes per cell, mitochondrial percentage, doublet detection rate | Inappropriate threshold application, accidental deletion of a cell type | Yes, results are quantifiable |
| Gene Filtering | Filtered matrix and gene set | Matrix after removal, downweighting, or regression correction | Proportion of affected genes, clustering stability before and after | Excessive removal, loss of cell state information | Execute plan comparison only; final plan selection requires manual confirmation |
| Normalization & Dimensionality Reduction | Matrix | Low-dimensional embedding and neighborhood graph | Variance explained by PCs, parameter sensitivity | Inappropriate selection of HVGs or number of PCs | Yes, requires comparing 2-3 sets of settings |
| Clustering | Low-dimensional embedding | Cluster labels across multiple resolutions | Cluster stability, cluster size distribution | Excessive resolution leading to cluster fragmentation | Yes, save results for all resolutions |
| Marker Gene Calculation | Cluster labels | Ranked genes per cluster | Adjusted p-value, effect size, detection rate | Inappropriate test method, ignoring multiple testing correction | Yes, thresholds must be written into config beforehand |
| Biological Plausibility Evaluation | Ranked genes and reference marker genes | Cell type annotations and evidence | Marker gene hit rate, pathway support | Relying on a single marker gene, ignoring tissue context | Generate candidate annotations only; final annotation requires manual review |
Each stage can be tested independently. Teams should prioritize automating QC statistics and marker gene ranking, as their metrics are clear and errors are easily spotted. Stages involving cell type judgment must retain manual review.
3. A Runnable Workflow Skeleton
The following code uses the Scanpy library and can serve as a starting point. The thresholds are placeholder values and need to be adjusted based on data distribution.
import randomimport numpy as npimport scanpy as scdef set_seed(seed: int) -> None:random.seed(seed)np.random.seed(seed)def run_qc(adata, min_genes=200, max_mt_pct=15.0):adata.var["mt"] = adata.var_names.str.startswith("MT-")sc.pp.calculate_qc_metrics(adata, qc_vars=["mt"], inplace=True)keep = ((adata.obs["n_genes_by_counts"] >= min_genes)& (adata.obs["pct_counts_mt"] <= max_mt_pct))return adata[keep].copy()def filter_ribosomal(adata, mode="remove"):# mode: "remove" for removal, "none" for no processing# "downweight" and "regress" need to be implemented separately after normalizationif mode == "remove":rp = adata.var_names.str.match(r"^RP[SL]\d+")return adata[:, ~rp].copy()return adata.copy()def normalize_and_reduce(adata, n_hvg=2000, n_pcs=30):sc.pp.normalize_total(adata, target_sum=1e4)sc.pp.log1p(adata)sc.pp.highly_variable_genes(adata, n_top_genes=n_hvg)adata.raw = adataadata = adata[:, adata.var["highly_variable"]].copy()sc.pp.scale(adata, max_value=10)sc.tl.pca(adata, n_comps=50, random_state=0)sc.pp.neighbors(adata, n_pcs=n_pcs, random_state=0)return adatadef cluster(adata, resolution=0.5):sc.tl.leiden(adata, resolution=resolution, random_state=0,key_added=f"leiden_r{resolution}")return adatadef rank_markers(adata, groupby, method="wilcoxon"):sc.tl.rank_genes_groups(adata, groupby=groupby, method=method,use_raw=True, corr_method="benjamini-hochberg")return sc.get.rank_genes_groups_df(adata, group=None)def run_pipeline(path, config, out_dir):set_seed(config["seed"])adata = sc.read_h5ad(path) # Mount raw data as read-onlyadata = run_qc(adata, config["min_genes"], config["max_mt_pct"])adata = filter_ribosomal(adata, config["ribo_mode"])adata = normalize_and_reduce(adata, config["n_hvg"], config["n_pcs"])results = {}for r in config["resolutions"]: # Save separately for each resolutionadata = cluster(adata, r)results[r] = rank_markers(adata, f"leiden_r{r}")results[r].to_csv(f"{out_dir}/markers_r{r}.csv", index=False)return results
Before running, record the following information: Python version, exact versions of all dependencies, random seeds, and the hash value of the configuration file. Raw data should be mounted read-only, and results should only be written to the designated directory.
4. How to Configure Key Parameters
Mitochondrial Gene Proportion. Thresholds vary by tissue type. A common starting point is between 5% and 20%, but the final value should be determined by examining the cell distribution plot and confirming whether the deleted cells are concentrated in a specific population. Do not directly copy numbers from literature.
Doublet Detection. You can use the Python tool Scrublet or the R tool scDblFinder. Detection results should be saved alongside QC statistics. The doublet rate generally increases with the number of loaded cells; check the detection rate against the expected values provided by the sequencing platform to ensure it is reasonable.
Normalization Method. Options include log-normalization, pooled size factor-based methods, or SCTransform. Different methods will affect the subsequent number of highly variable genes and principal components. Once a method is chosen, specify it clearly in the report.
Highly Variable Genes and Principal Components. The number of highly variable genes is typically trialed starting around 2000. The number of PCs can be determined by the inflection point on the variance explained plot. These two choices significantly impact clustering results; you should compare two to three sets of settings to observe cluster stability.
Clustering Resolution. It is recommended to set a range of resolutions, such as 0.2, 0.5, and 1.0, and save the results separately. Repeat clustering for the same resolution using different random seeds to calculate the Adjusted Rand Index (ARI). A low ARI indicates instability of the clusters at that resolution.
Marker Gene Testing. Options include the Wilcoxon rank-sum test or model-based methods. Regardless of the choice, adjusted p-values should be used. Set a minimum detection proportion and a lower bound for effect size to filter out genes expressed only in a few cells or with minimal differences. The specific lower bounds should be determined by the data scale and research question, and written into the configuration file.
Ribosomal Protein Genes. The expression levels of these genes are often related to translational activity; removing them directly may discard information relevant to cell state. A more robust approach is to compare three strategies: direct removal, downweighting, and regression correction. Comparison metrics include clustering stability (ARI or Normalized Mutual Information NMI), retention rate of reference marker genes, and consistency of annotations with the original plan. Once a strategy is selected, document the rationale in the report.
5. The Four Responsibilities of the Agent
In the research workflow, the agent assumes four types of responsibilities: planning, execution, checking, and reporting. Each responsibility must have clear inputs, outputs, manual review points, and rollback conditions.
Planning. Upon receiving an instruction like “identify the major cell types in a tissue and provide marker genes,” the agent must break down subtasks, list missing parameters, and ask researchers to confirm key choices, including mitochondrial thresholds, resolution ranges, and testing methods. The output is an execution plan with a parameter table. The manual review point is the parameter table. If researchers do not confirm, the agent should not begin execution.
Execution. The agent runs each stage according to the plan, writing only to the designated directory and not modifying raw data. Each stage must record the hash value of input files, configuration parameters, and software versions. If a step throws an error or the output exceeds predefined limits (e.g., filtering out more than a preset proportion of cells), the agent should stop and report rather than relaxing thresholds and continuing autonomously.
Checking. The agent runs checks on the output of each stage: whether the post-QC cell count is reasonable, whether the doublet rate aligns with platform expectations, whether the number of clusters falls within the expected range, and whether marker genes pass the adjusted p-value and effect size thresholds. Check results are saved in a tabular format. If a check fails, the agent should provide the failed item and possible causes, leaving the decision to rerun to the researchers.
Reporting. The report includes the methods used, key parameters, check results for each stage, and unresolved issues. Cell type annotations can only be written as candidate annotations, listing the marker genes and evidence upon which each annotation is based. Final annotations must be confirmed by researchers with relevant domain knowledge before adoption.
6. Troubleshooting Checklist
When issues arise, check in the following order:
- Sharp drop in cell count after QC: Check whether the mitochondrial threshold is appropriate for the current tissue and confirm the distribution of deleted cells.
- Doublet detection rate noticeably high or low: Verify the loaded cell count and the detection tool’s parameters.
- Number of clusters increases rapidly with higher resolution: Check the ARI to confirm if clusters are fragmenting; reduce resolution if necessary.
- Excessive number of significant marker genes: Check if adjusted p-values were used and whether effect size and detection proportion thresholds are in effect.
- A cluster has only one or two marker genes: Check whether the cluster is mixed with other cell types or consists of low-quality cells.
- Annotation relies on a single marker gene: Supplement with at least two independent marker genes and review pathway-level support.
7. Risk Checklist
- Raw data is mounted read-only, and results are only written to the designated directory.
- Configuration files, dependency versions, random seeds, and input file hashes are recorded.
- The agent only has the minimum permissions necessary to complete the task and cannot delete or overwrite existing results.
- If using an external LLM service, first confirm whether the data contains patient information or unpublished research data, and handle it according to institutional regulations.
- Every automatically generated conclusion is accompanied by check results and evidence sources.
- Cell type annotations, parameter choices, and method changes are all subject to manual confirmation.
Conclusion
In marker gene analysis, QC statistics and marker gene ranking have clear inputs and outputs, and their quantifiable results make them suitable for initial automation via agents. The selection of gene filtering strategies and cell type annotations, however, require researcher judgment. Teams should validate each step on their own data and maintain comprehensive records to enable tracing and rerunning in case problems occur.
