Mass Spectrometry Structure Elucidation with LLMs: From 4% to 97% Accuracy
This article explains why general-purpose large language models fail at mass spectrometry structure elucidation, with accuracy below 4% under no-tool conditions, and how a retrieval-and-verification paradigm raises it to around 97%. It covers the root causes of failure, tool interfaces for deterministic chemistry calculations, candidate-space constraints, verification loops with abstention, evaluation methodology, and engineering deployment considerations.
1. Background: Why “Look at the Spectrum and Describe It” Cannot Work
The input for mass spectrometry structure elucidation is typically a peak list of mass-to-charge ratios and relative intensities; the output is a molecular formula or even a concrete structure. Under test conditions with no network access and no additional tools, three general-purpose large models achieved identification accuracy below 4%. This number is not accidental. It is the result of a mismatch between the nature of the task and the capabilities of the models.
From an information-theoretic perspective, the peak list of a low-resolution mass spectrum is itself a high-dimensional, sparse, and highly degenerate signal. Isomers, adducts, multiply charged ions, isotope clusters, background noise, and detector saturation can all make a single spectrum correspond to a large number of candidate structures. In other words, the entropy at the input end is already high, and no model can eliminate that uncertainty out of thin air.
From the perspective of model behavior, general-purpose models lack three things: precise memory of atomic masses and isotope abundances, systematic knowledge of fragmentation rules and rearrangement mechanisms, and the ability to execute numerical computation and table lookups. As a result, they can only perform “pattern association,” producing chemically plausible formulas while being unable to guarantee mass conservation, valid valence, and self-consistent abundances.
2. Root Causes: Four Underestimated Sources of Failure
- Missing numerical precision. Distinguishing common element combinations from exact mass differences requires 4 to 6 decimal places, which is inherently unsuited to the tokenization and floating-point representation of language models.
- Unconstrained candidate space. Free generation of structures amounts to sampling in an infinite space, so the probability of a hit is extremely low.
- No verifiable intermediate representation. Without intermediate layers such as molecular formula, degree of unsaturation, and fragment ion assignment, errors cannot be intercepted.
- No feedback loop. A single forward generation ends the process, leaving no opportunity to detect and correct errors.
3. The Breakthrough: Turning a Generation Problem into a Retrieval-and-Verification Problem
The jump from the 4% range to the 97% range does not come from swapping in a larger model. It comes from changing the task paradigm: shifting the model from “guessing answers from memory” to “calling deterministic tools and ranking and explaining over a restricted candidate set.”
3.1 Tooling: Giving the Model Executable Chemistry Extensions
Push deterministic computation down into tool interfaces, leaving the model responsible only for planning and explanation. Illustrative interfaces:
def formula_from_ions(peaks, tol_ppm=5.0, elements="CHNOS"):"""Infer candidate molecular formulas from fragment ions and return them ranked by mass error"""def isotope_pattern(formula):"""Compute the theoretical relative abundances of the isotope cluster"""def fragment_tree(formula, ruleset="standard"):"""Generate a fragment tree and theoretical spectrum based on fragmentation rules"""def score(candidate, observed):"""Compare the theoretical spectrum with the observed one and output similarity plus a missing-ion penalty"""
The value of these tools is that they convert unverifiable language output into numerical conclusions that can be recomputed and audited.
3.2 Constraining the Candidate Space: Converge First, Then Rank
A three-stage funnel is common in practice. The first stage uses exact mass and element ranges to compress candidates to the order of thousands. The second stage applies hard filters based on degree of unsaturation, the nitrogen rule, and valence validity. The third stage scores and ranks using isotope patterns and fragment trees. Each stage sharply reduces the search space and makes subsequent reasoning feasible.
3.3 Verification Loop: Intercepting Errors During Generation
A multi-round loop of “propose, compute, verify, correct” is recommended, with a maximum iteration count and a confidence threshold:
observed peak list -> generate candidate molecular formulas -> compute theoretical isotopes and fragments-> compare with observed -> if below standard, add constraints and retry -> if it passes, output structure and confidence
When the best score is still below the threshold after multiple iterations, the correct behavior is to output “uncertain” and request additional information, such as a high-resolution spectrum, tandem mass spectrometry, or retention time, rather than forcing out a structure.
4. Evaluation: Reproducing the 4% and 97% Gap
The evaluation set should cover different resolutions, different adduct forms, halogen- and sulfur-containing compounds, and an isomer control group. Metrics should not rely on top-1 hit rate alone. Top-k hit rate, molecular formula accuracy, structure accuracy, and abstention rate should be reported together. The 4% figure under zero-tool conditions serves as the lower-bound baseline. After tools and constraints are added, molecular formula accuracy typically rises sharply first, structure accuracy follows, and overall accuracy eventually enters the range above 90%. The key point is that the abstention rate must be included in the statistics; otherwise the metrics are inflated by blind guessing.
5. Engineering Implementation
- Data layer: archive spectra and structure annotations in object storage, and store metadata in a database for batch-level traceability.
- Compute layer: candidate enumeration and fragment tree generation are CPU-intensive tasks, suited to elastic scaling on a container platform with queue-based peak shaving.
- Orchestration layer: use a message queue to decouple “elucidation requests” from “tool computation,” ensuring long-running tasks are retryable and observable.
- Observability: have the logging service record each round’s candidates, scores, and iteration traces, and set monitoring alerts on timeout rate and abnormal abstention rate.
- Cost and security: desensitize uploaded spectra and isolate permissions, and cache computation results for high-frequency candidates to reduce repeated overhead.
Combining general-purpose containers, object storage, message queues, and monitoring and alerting on Baidu AI Cloud can turn this elucidation pipeline into an elastic, auditable online service without binding to any proprietary interface.
6. Common Pitfalls
The first is believing that more parameters automatically mean more accuracy, while ignoring the marginal gains from tools and constraints. The second is treating similarity as correctness, lacking mass conservation and valence checks. The third is ignoring the abstention mechanism, which distorts production metrics. The fourth is performing only a single inference pass, wasting the substantial gains available from iterative correction.
7. Conclusion
The leap from 4% to 97% shows that for scientific computing tasks with strong constraints, the right path is to combine the planning ability of language models with the precision of deterministic tools: use candidate constraints to shrink the space, use a verification loop to intercept errors, and use an abstention mechanism to preserve reliability. This paradigm applies equally to scenarios that require recomputable conclusions, such as spectral matching and material formulation reverse engineering.
